Menu

[r1586]: / trunk / GoogleContactsSync / GoogleServices.cs  Maximize  Restore  History

Download this file

167 lines (148 with data), 6.2 kB

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
using Google.Apis.Calendar.v3;
using Google.Apis.Http;
using Google.Apis.PeopleService.v1;
using Google.Apis.Requests;
using Google.Apis.Services;
using Google.Apis.Util;
using Serilog;
using System;
using System.Net;
using System.Threading.Tasks;
namespace GoContactSyncMod
{
internal class GoogleServices
{
// TODO(obelix30): it is workaround for open issue here: https://github.com/google/google-api-dotnet-client/issues/608
/// <summary>
/// Creates CalendarService with custom back-off handler.
/// </summary>
/// <param name="initializer">The service initializer.</param>
/// <returns>Created CalendarService with custom back-off configured.</returns>
public static CalendarService CreateCalendarService(BaseClientService.Initializer initializer)
{
CalendarService service = null;
try
{
initializer.DefaultExponentialBackOffPolicy = ExponentialBackOffPolicy.None;
service = new CalendarService(initializer);
var backOffHandler = new BackoffHandler(service, new ExponentialBackOff());
service.HttpClient.MessageHandler.AddUnsuccessfulResponseHandler(backOffHandler);
return service;
}
catch
{
if (service != null)
{
service.Dispose();
}
throw;
}
}
public static PeopleServiceService CreatePeopleService(BaseClientService.Initializer initializer)
{
PeopleServiceService service = null;
try
{
initializer.DefaultExponentialBackOffPolicy = ExponentialBackOffPolicy.None;
service = new PeopleServiceService(initializer);
var backOffHandler = new BackoffHandler(service, new ExponentialBackOff());
service.HttpClient.MessageHandler.AddUnsuccessfulResponseHandler(backOffHandler);
return service;
}
catch
{
if (service != null)
{
service.Dispose();
}
throw;
}
}
/// <summary>
/// Check if error returned from Google API is transient, i.e. could be retried.
/// </summary>
/// <param name="statusCode">Status code returned from API (e.g. 403, 500).</param>
/// <param name="reqError">Server error.</param>
/// <returns>If error is transient.</returns>
public static bool IsTransientError(HttpStatusCode statusCode, RequestError reqError)
{
if ((int)statusCode >= (int)HttpStatusCode.InternalServerError)
{
return true;
}
if (statusCode == HttpStatusCode.Forbidden)
{
if (reqError.Errors[0].Reason == "rateLimitExceeded")
{
return true;
}
if (reqError.Errors[0].Reason == "userRateLimitExceeded")
{
return true;
}
if (reqError.Errors[0].Reason == "dailyLimitExceeded")
{
return true;
}
if (reqError.Errors[0].Reason == "quotaExceeded")
{
return true;
}
}
return false;
}
public const int BatchRequestSize = 50;
public const int BatchRequestBackoffDelay = 1000;
private static readonly Random random = new Random();
public static TimeSpan GetExpotentialBackoffDelay(int currentRetry)
{
var v = (Math.Pow(2.0, (double)currentRetry - 1) * 1000) + random.Next(0, 250);
return TimeSpan.FromMilliseconds(v);
}
/// <summary>
/// Specific back-off implementation.
/// </summary>
public class BackoffHandler : IHttpUnsuccessfulResponseHandler
{
private readonly IBackOff _backoff;
private readonly IClientService _service;
private readonly TimeSpan _maxTimeSpan;
/// <summary>
/// Constructs a new custom back-off handler
/// </summary>
/// <param name="service">Client service</param>
/// <param name="backoff">Back-off strategy (e.g. exponential backoff)</param>
public BackoffHandler(IClientService service, IBackOff backoff)
{
_service = service;
_backoff = backoff;
_maxTimeSpan = TimeSpan.FromHours(1);
}
/// <summary>
/// Handler for back-off, if retry is not possible it returns <c>false</c>. Otherwise it blocks for some time (miliseconds)
/// and returns <c>true</c>, so call is retried.
/// </summary>
/// <param name="args">The arguments object to handler call.</param>
/// <returns>If request could be retried.</returns>
public async Task<bool> HandleResponseAsync(HandleUnsuccessfulResponseArgs args)
{
if (!args.SupportsRetry || _backoff.MaxNumOfRetries < args.CurrentFailedTry)
{
return false;
}
if (IsTransientError(args.Response.StatusCode, _service.DeserializeError(args.Response).Result))
{
var delay = _backoff.GetNextBackOff(args.CurrentFailedTry);
if (delay > _maxTimeSpan || delay < TimeSpan.Zero)
{
return false;
}
await Task.Delay(delay, args.CancellationToken);
Log.Debug("Back-Off waited " + delay.TotalMilliseconds + "ms before next retry...");
return true;
}
return false;
}
}
}
}
Want the latest updates on software, tech news, and AI?
Get latest updates about software, tech news, and AI from SourceForge directly in your inbox once a month.