Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

SimpleRetryHandler - sleep now uses CancellationToken #1032

Merged
merged 1 commit into from
Mar 31, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
45 changes: 45 additions & 0 deletions SpotifyAPI.Web.Tests/RetryHandlers/SimpleRetryHandlerTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -182,6 +182,51 @@ public async Task HandleRetry_DirectSuccess()
setup.Sleep.Verify(s => s(TimeSpan.FromMilliseconds(50)), Times.Exactly(0));
}

[Test]
public async Task HandleRetry_CancellationTokenHonoredInSleep()
{
var setup = new Setup();
setup.Response.SetupGet(r => r.StatusCode).Returns(HttpStatusCode.TooManyRequests);
setup.Response.SetupGet(r => r.Headers).Returns(new Dictionary<string, string> {
{ "Retry-After", "5" }
});

var retryCalled = 0;
setup.Retry = (request, ct) =>
{
retryCalled++;
return Task.FromResult(setup.Response.Object);
};

var handler = new SimpleRetryHandler()
{
TooManyRequestsConsumesARetry = true,
RetryTimes = 0,
RetryAfter = TimeSpan.FromSeconds(1)
};

var cancellationTokenSource = new CancellationTokenSource();

var startTime = DateTimeOffset.UtcNow;
try
{
var attemptTask = handler.HandleRetry(setup.Request.Object, setup.Response.Object, setup.Retry, cancellationTokenSource.Token);

// Wait enough that we're probably in the sleep
await Task.Delay(TimeSpan.FromMilliseconds(100));

cancellationTokenSource.Cancel();

await attemptTask;
}
catch (OperationCanceledException)
{
//Expected
}

Assert.That(DateTimeOffset.UtcNow - startTime, Is.LessThan(TimeSpan.FromSeconds(4)));
}

private class Setup
{
public Mock<Func<TimeSpan, Task>> Sleep { get; set; } = new Mock<Func<TimeSpan, Task>>();
Expand Down
15 changes: 8 additions & 7 deletions SpotifyAPI.Web/RetryHandlers/SimpleRetryHandler.cs
Original file line number Diff line number Diff line change
Expand Up @@ -10,10 +10,10 @@ namespace SpotifyAPI.Web
{
public class SimpleRetryHandler : IRetryHandler
{
private readonly Func<TimeSpan, Task> _sleep;
private readonly Func<TimeSpan, CancellationToken, Task> _sleep;

/// <summary>
/// Specifies after how many miliseconds should a failed request be retried.
/// Specifies after how many milliseconds should a failed request be retried.
/// </summary>
public TimeSpan RetryAfter { get; set; }

Expand All @@ -38,10 +38,11 @@ public class SimpleRetryHandler : IRetryHandler
/// the Retry-After header
/// </summary>
/// <returns></returns>
public SimpleRetryHandler() : this(Task.Delay) { }
public SimpleRetryHandler(Func<TimeSpan, Task> sleep)
public SimpleRetryHandler() : this(sleepWithCancel: Task.Delay) { }
public SimpleRetryHandler(Func<TimeSpan, Task> sleep) : this((t, _) => sleep(t)) { }
public SimpleRetryHandler(Func<TimeSpan, CancellationToken, Task> sleepWithCancel)
{
_sleep = sleep;
_sleep = sleepWithCancel;
RetryAfter = TimeSpan.FromMilliseconds(50);
RetryTimes = 10;
TooManyRequestsConsumesARetry = false;
Expand Down Expand Up @@ -88,15 +89,15 @@ private async Task<IResponse> HandleRetryInternally(
var secondsToWait = ParseTooManyRetries(response);
if (secondsToWait != null && (!TooManyRequestsConsumesARetry || triesLeft > 0))
{
await _sleep(secondsToWait.Value).ConfigureAwait(false);
await _sleep(secondsToWait.Value, cancel).ConfigureAwait(false);
response = await retry(request, cancel).ConfigureAwait(false);
var newTriesLeft = TooManyRequestsConsumesARetry ? triesLeft - 1 : triesLeft;
return await HandleRetryInternally(request, response, retry, newTriesLeft, cancel).ConfigureAwait(false);
}

while (RetryErrorCodes.Contains(response.StatusCode) && triesLeft > 0)
{
await _sleep(RetryAfter).ConfigureAwait(false);
await _sleep(RetryAfter, cancel).ConfigureAwait(false);
response = await retry(request, cancel).ConfigureAwait(false);
return await HandleRetryInternally(request, response, retry, triesLeft - 1, cancel).ConfigureAwait(false);
}
Expand Down
Loading