Spotify.NET/SpotifyAPI.Web/RetryHandlers/SimpleRetryHandler.cs

108 lines
3.7 KiB
C#
Raw Normal View History

2022-11-27 12:29:35 +00:00
using System;
using System.Collections.Generic;
2020-05-12 16:53:17 +01:00
using System.Linq;
using System.Net;
2022-11-27 12:29:35 +00:00
using System.Threading;
2020-05-12 16:53:17 +01:00
using System.Threading.Tasks;
2020-06-03 16:44:13 +01:00
using SpotifyAPI.Web.Http;
2020-05-12 16:53:17 +01:00
2020-06-03 16:44:13 +01:00
namespace SpotifyAPI.Web
2020-05-12 16:53:17 +01:00
{
public class SimpleRetryHandler : IRetryHandler
{
2020-06-03 18:12:12 +01:00
private readonly Func<TimeSpan, Task> _sleep;
2020-05-12 16:53:17 +01:00
/// <summary>
/// Specifies after how many miliseconds should a failed request be retried.
/// </summary>
2020-06-03 18:12:12 +01:00
public TimeSpan RetryAfter { get; set; }
2020-05-12 16:53:17 +01:00
/// <summary>
/// Maximum number of tries for one failed request.
/// </summary>
public int RetryTimes { get; set; }
/// <summary>
/// Whether a failure of type "Too Many Requests" should use up one of the allocated retry attempts.
/// </summary>
public bool TooManyRequestsConsumesARetry { get; set; }
/// <summary>
/// Error codes that will trigger auto-retry
/// </summary>
public IEnumerable<HttpStatusCode> RetryErrorCodes { get; set; }
/// <summary>
/// A simple retry handler which retries a request based on status codes with a fixed sleep interval.
/// It also supports Retry-After headers sent by spotify. The execution will be delayed by the amount in
/// the Retry-After header
/// </summary>
/// <returns></returns>
public SimpleRetryHandler() : this(Task.Delay) { }
2020-06-03 18:12:12 +01:00
public SimpleRetryHandler(Func<TimeSpan, Task> sleep)
2020-05-12 16:53:17 +01:00
{
_sleep = sleep;
2020-06-03 18:12:12 +01:00
RetryAfter = TimeSpan.FromMilliseconds(50);
2020-05-12 16:53:17 +01:00
RetryTimes = 10;
TooManyRequestsConsumesARetry = false;
RetryErrorCodes = new[] {
HttpStatusCode.InternalServerError,
HttpStatusCode.BadGateway,
HttpStatusCode.ServiceUnavailable
};
}
2020-06-03 18:12:12 +01:00
private static TimeSpan? ParseTooManyRetries(IResponse response)
2020-05-12 16:53:17 +01:00
{
2020-05-16 17:48:32 +01:00
if (response.StatusCode != (HttpStatusCode)429)
2020-05-12 16:53:17 +01:00
{
return null;
}
if (
(response.Headers.ContainsKey("Retry-After") && int.TryParse(response.Headers["Retry-After"], out int secondsToWait))
|| (response.Headers.ContainsKey("retry-after") && int.TryParse(response.Headers["retry-after"], out secondsToWait)))
2020-05-12 16:53:17 +01:00
{
2020-06-03 18:12:12 +01:00
return TimeSpan.FromSeconds(secondsToWait);
2020-05-12 16:53:17 +01:00
}
throw new APIException("429 received, but unable to parse Retry-After Header. This should not happen!");
}
public Task<IResponse> HandleRetry(IRequest request, IResponse response, IRetryHandler.RetryFunc retry, CancellationToken cancel = default)
2020-05-12 16:53:17 +01:00
{
Ensure.ArgumentNotNull(response, nameof(response));
2020-11-13 13:43:00 +00:00
Ensure.ArgumentNotNull(retry, nameof(retry));
2020-05-12 16:53:17 +01:00
return HandleRetryInternally(request, response, retry, RetryTimes, cancel);
2020-05-12 16:53:17 +01:00
}
2020-06-03 16:44:13 +01:00
private async Task<IResponse> HandleRetryInternally(
IRequest request,
IResponse response,
IRetryHandler.RetryFunc retry,
int triesLeft,
CancellationToken cancel)
2020-05-12 16:53:17 +01:00
{
cancel.ThrowIfCancellationRequested();
2020-06-03 18:12:12 +01:00
var secondsToWait = ParseTooManyRetries(response);
2020-05-12 16:53:17 +01:00
if (secondsToWait != null && (!TooManyRequestsConsumesARetry || triesLeft > 0))
{
await _sleep(secondsToWait.Value).ConfigureAwait(false);
response = await retry(request, cancel).ConfigureAwait(false);
2020-05-12 16:53:17 +01:00
var newTriesLeft = TooManyRequestsConsumesARetry ? triesLeft - 1 : triesLeft;
return await HandleRetryInternally(request, response, retry, newTriesLeft, cancel).ConfigureAwait(false);
2020-05-12 16:53:17 +01:00
}
while (RetryErrorCodes.Contains(response.StatusCode) && triesLeft > 0)
{
await _sleep(RetryAfter).ConfigureAwait(false);
response = await retry(request, cancel).ConfigureAwait(false);
return await HandleRetryInternally(request, response, retry, triesLeft - 1, cancel).ConfigureAwait(false);
2020-05-12 16:53:17 +01:00
}
return response;
}
}
}