|
| 1 | +namespace SendGrid.Helpers.Reliability |
| 2 | +{ |
| 3 | + using System; |
| 4 | + using System.Collections.Generic; |
| 5 | + using System.Net; |
| 6 | + using System.Net.Http; |
| 7 | + using System.Threading; |
| 8 | + using System.Threading.Tasks; |
| 9 | + |
| 10 | + /// <summary> |
| 11 | + /// A delegating handler that provides retry functionality while executing a request |
| 12 | + /// </summary> |
| 13 | + public class RetryDelegatingHandler : DelegatingHandler |
| 14 | + { |
| 15 | + private static readonly List<HttpStatusCode> RetriableServerErrorStatusCodes = |
| 16 | + new List<HttpStatusCode>() |
| 17 | + { |
| 18 | + HttpStatusCode.InternalServerError, |
| 19 | + HttpStatusCode.BadGateway, |
| 20 | + HttpStatusCode.ServiceUnavailable, |
| 21 | + HttpStatusCode.GatewayTimeout |
| 22 | + }; |
| 23 | + |
| 24 | + private readonly ReliabilitySettings settings; |
| 25 | + |
| 26 | + /// <summary> |
| 27 | + /// Initializes a new instance of the <see cref="RetryDelegatingHandler"/> class. |
| 28 | + /// </summary> |
| 29 | + /// <param name="settings">A ReliabilitySettings instance</param> |
| 30 | + public RetryDelegatingHandler(ReliabilitySettings settings) |
| 31 | + : this(new HttpClientHandler(), settings) |
| 32 | + { |
| 33 | + } |
| 34 | + |
| 35 | + /// <summary> |
| 36 | + /// Initializes a new instance of the <see cref="RetryDelegatingHandler"/> class. |
| 37 | + /// </summary> |
| 38 | + /// <param name="innerHandler">A HttpMessageHandler instance to set as the innner handler</param> |
| 39 | + /// <param name="settings">A ReliabilitySettings instance</param> |
| 40 | + public RetryDelegatingHandler(HttpMessageHandler innerHandler, ReliabilitySettings settings) |
| 41 | + : base(innerHandler) |
| 42 | + { |
| 43 | + this.settings = settings; |
| 44 | + } |
| 45 | + |
| 46 | + protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) |
| 47 | + { |
| 48 | + if (this.settings.MaximumNumberOfRetries == 0) |
| 49 | + { |
| 50 | + return await base.SendAsync(request, cancellationToken).ConfigureAwait(false); |
| 51 | + } |
| 52 | + |
| 53 | + HttpResponseMessage responseMessage = null; |
| 54 | + |
| 55 | + var numberOfAttempts = 0; |
| 56 | + var sent = false; |
| 57 | + |
| 58 | + while (!sent) |
| 59 | + { |
| 60 | + var waitFor = this.GetNextWaitInterval(numberOfAttempts); |
| 61 | + |
| 62 | + try |
| 63 | + { |
| 64 | + responseMessage = await base.SendAsync(request, cancellationToken).ConfigureAwait(false); |
| 65 | + |
| 66 | + ThrowHttpRequestExceptionIfResponseCodeCanBeRetried(responseMessage); |
| 67 | + |
| 68 | + sent = true; |
| 69 | + } |
| 70 | + catch (TaskCanceledException) |
| 71 | + { |
| 72 | + numberOfAttempts++; |
| 73 | + |
| 74 | + if (numberOfAttempts > this.settings.MaximumNumberOfRetries) |
| 75 | + { |
| 76 | + throw new TimeoutException(); |
| 77 | + } |
| 78 | + |
| 79 | + // ReSharper disable once MethodSupportsCancellation, cancel will be indicated on the token |
| 80 | + await Task.Delay(waitFor).ConfigureAwait(false); |
| 81 | + } |
| 82 | + catch (HttpRequestException) |
| 83 | + { |
| 84 | + numberOfAttempts++; |
| 85 | + |
| 86 | + if (numberOfAttempts > this.settings.MaximumNumberOfRetries) |
| 87 | + { |
| 88 | + throw; |
| 89 | + } |
| 90 | + |
| 91 | + await Task.Delay(waitFor).ConfigureAwait(false); |
| 92 | + } |
| 93 | + } |
| 94 | + |
| 95 | + return responseMessage; |
| 96 | + } |
| 97 | + |
| 98 | + private static void ThrowHttpRequestExceptionIfResponseCodeCanBeRetried(HttpResponseMessage responseMessage) |
| 99 | + { |
| 100 | + if (RetriableServerErrorStatusCodes.Contains(responseMessage.StatusCode)) |
| 101 | + { |
| 102 | + throw new HttpRequestException(string.Format("Http status code '{0}' indicates server error", responseMessage.StatusCode)); |
| 103 | + } |
| 104 | + } |
| 105 | + |
| 106 | + private TimeSpan GetNextWaitInterval(int numberOfAttempts) |
| 107 | + { |
| 108 | + var random = new Random(); |
| 109 | + |
| 110 | + var delta = (int)((Math.Pow(2.0, numberOfAttempts) - 1.0) * |
| 111 | + random.Next( |
| 112 | + (int)(this.settings.DeltaBackOff.TotalMilliseconds * 0.8), |
| 113 | + (int)(this.settings.DeltaBackOff.TotalMilliseconds * 1.2))); |
| 114 | + |
| 115 | + var interval = (int)Math.Min(this.settings.MinimumBackOff.TotalMilliseconds + delta, this.settings.MaximumBackOff.TotalMilliseconds); |
| 116 | + |
| 117 | + return TimeSpan.FromMilliseconds(interval); |
| 118 | + } |
| 119 | + } |
| 120 | +} |
0 commit comments