-
Notifications
You must be signed in to change notification settings - Fork 19
Fix: Polly retry policy not retrying CTS-triggered timeouts in PackageUploader #127
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
Merged
Merged
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
9e48b63
Use the caller's cancellation token directly instead of a scoped CTS
elahmed-microsoft b575886
Added the comment above the SendAsync call in InitializeAssetAsync cl…
elahmed-microsoft 64fff6c
Unit tests for polly retry policy fix with cts
elahmed-microsoft File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
125 changes: 125 additions & 0 deletions
125
src/PackageUploader.ClientApi.Test/XfusRetryPolicyTests.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,125 @@ | ||
| // Copyright (c) Microsoft Corporation. | ||
| // Licensed under the MIT License. | ||
|
|
||
| using Microsoft.Extensions.DependencyInjection; | ||
| using Microsoft.Extensions.Logging; | ||
| using Microsoft.Extensions.Logging.Abstractions; | ||
| using Polly; | ||
| using Polly.Contrib.WaitAndRetry; | ||
| using Polly.Extensions.Http; | ||
|
|
||
| namespace PackageUploader.ClientApi.Test; | ||
|
|
||
| /// <summary> | ||
| /// Verifies that the Polly retry policy in XfusExtensions retries | ||
| /// TaskCanceledException thrown by HttpClient.Timeout (non-canceled outer token) | ||
| /// rather than treating it as intentional cancellation. | ||
| /// </summary> | ||
| [TestClass] | ||
| public class XfusRetryPolicyTests | ||
| { | ||
| private const string TestClientName = "xfus-retry-test"; | ||
|
|
||
| /// <summary> | ||
| /// Simulates the behavior of HttpClient.Timeout: throws TaskCanceledException | ||
| /// with the inner exception being a TimeoutException, while the caller's | ||
| /// CancellationToken remains non-canceled. | ||
| /// </summary> | ||
| private sealed class TimeoutSimulatingHandler : DelegatingHandler | ||
| { | ||
| public int CallCount; | ||
|
|
||
| protected override Task<HttpResponseMessage> SendAsync( | ||
| HttpRequestMessage request, CancellationToken cancellationToken) | ||
| { | ||
| Interlocked.Increment(ref CallCount); | ||
|
|
||
| // HttpClient.Timeout throws TaskCanceledException wrapping TimeoutException. | ||
| // The key detail: cancellationToken (the caller's token) is NOT canceled. | ||
| throw new TaskCanceledException( | ||
| "The request was canceled due to the configured HttpClient.Timeout of 100 seconds elapsing.", | ||
| new TimeoutException("A task was canceled.")); | ||
| } | ||
| } | ||
|
|
||
| /// <summary> | ||
| /// Builds the same Polly retry policy used in XfusExtensions.AddXfusService | ||
| /// to test it in isolation without requiring IConfiguration or the full DI graph. | ||
| /// </summary> | ||
| private static IAsyncPolicy<HttpResponseMessage> BuildXfusRetryPolicy(int retryCount) | ||
| { | ||
| var delay = Backoff.DecorrelatedJitterBackoffV2(TimeSpan.FromMilliseconds(1), retryCount); | ||
| return HttpPolicyExtensions | ||
| .HandleTransientHttpError() | ||
| .OrResult(response => (int)response.StatusCode >= 500) | ||
| .OrInner<TimeoutException>() | ||
| .OrInner<TaskCanceledException>() | ||
| .WaitAndRetryAsync(delay, (_, _, _, _) => Task.CompletedTask); | ||
| } | ||
|
|
||
| private static (IHttpClientFactory Factory, TimeoutSimulatingHandler Handler) BuildTestFactory(int retryCount) | ||
| { | ||
| var handler = new TimeoutSimulatingHandler(); | ||
| var services = new ServiceCollection(); | ||
| services.AddLogging(b => b.AddProvider(NullLoggerProvider.Instance)); | ||
|
|
||
| services.AddHttpClient(TestClientName) | ||
| .AddPolicyHandler(BuildXfusRetryPolicy(retryCount)) | ||
| .ConfigurePrimaryHttpMessageHandler(() => handler); | ||
|
|
||
| var sp = services.BuildServiceProvider(); | ||
| return (sp.GetRequiredService<IHttpClientFactory>(), handler); | ||
| } | ||
|
|
||
| [TestMethod] | ||
| public async Task PollyRetries_WhenHttpClientTimeoutThrowsTaskCanceledException() | ||
| { | ||
| // Arrange | ||
| const int retryCount = 3; | ||
| var (factory, handler) = BuildTestFactory(retryCount); | ||
| var httpClient = factory.CreateClient(TestClientName); | ||
|
|
||
| // Act — send a request with a non-canceled token | ||
| using var cts = new CancellationTokenSource(); | ||
| try | ||
| { | ||
| await httpClient.SendAsync(new HttpRequestMessage(HttpMethod.Get, "http://localhost/test"), cts.Token); | ||
| } | ||
| catch (Exception) when (!cts.Token.IsCancellationRequested) | ||
| { | ||
| // Expected — the final attempt throws after all retries exhausted. | ||
| // Polly may rethrow the inner TimeoutException or the outer TaskCanceledException. | ||
| } | ||
|
|
||
| // Assert — initial attempt + retryCount retries = retryCount + 1 total calls | ||
| Assert.AreEqual(retryCount + 1, handler.CallCount, | ||
| $"Expected {retryCount + 1} total attempts (1 initial + {retryCount} retries), " + | ||
| $"but got {handler.CallCount}. Polly may be treating the timeout as intentional cancellation."); | ||
| } | ||
|
|
||
| [TestMethod] | ||
| public async Task PollyDoesNotRetry_WhenCallerCancelsToken() | ||
| { | ||
| // Arrange — verify that actual user cancellation is NOT retried | ||
| var (factory, handler) = BuildTestFactory(retryCount: 3); | ||
| var httpClient = factory.CreateClient(TestClientName); | ||
|
|
||
| // Act — cancel the token before sending (simulates user Ctrl+C) | ||
| using var cts = new CancellationTokenSource(); | ||
| cts.Cancel(); | ||
|
|
||
| try | ||
| { | ||
| await httpClient.SendAsync(new HttpRequestMessage(HttpMethod.Get, "http://localhost/test"), cts.Token); | ||
| } | ||
| catch (OperationCanceledException) | ||
| { | ||
| // Expected | ||
| } | ||
|
|
||
| // Assert — should not retry when caller intentionally canceled | ||
| Assert.IsTrue(handler.CallCount <= 1, | ||
| $"Expected at most 1 attempt when caller cancels, but got {handler.CallCount}. " + | ||
| "Polly should not retry intentional cancellation."); | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.