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

Fix hedging being cancelled too early #1340

Merged
merged 1 commit into from
Jun 22, 2023
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
8 changes: 6 additions & 2 deletions src/Polly.Core/Hedging/HedgingResilienceStrategy.cs
Original file line number Diff line number Diff line change
Expand Up @@ -67,12 +67,16 @@ internal sealed class HedgingResilienceStrategy<T> : OutcomeResilienceStrategy<T
ResilienceContext context,
TState state)
{
// Capture the original cancellation token so it stays the same while hedging is executing.
// If we do not do this the inner strategy can replace the cancellation token and with the concurrent
// nature of hedging this can cause issues.
var cancellationToken = context.CancellationToken;
var continueOnCapturedContext = context.ContinueOnCapturedContext;

var attempt = -1;
while (true)
{
attempt++;
var continueOnCapturedContext = context.ContinueOnCapturedContext;
var cancellationToken = context.CancellationToken;
var start = _timeProvider.GetTimestamp();
if (cancellationToken.IsCancellationRequested)
{
Expand Down
22 changes: 22 additions & 0 deletions test/Polly.Core.Tests/Hedging/HedgingResilienceStrategyTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -104,6 +104,28 @@ public void ExecutePrimaryAndSecondary_EnsureAttemptReported()
attempts[1].Attempt.Should().Be(1);
}

[Fact]
public async Task ExecutePrimary_Cancelled_SecondaryShouldBeExecuted()
{
_options.MaxHedgedAttempts = 2;

ConfigureHedging(o => o.Result == "primary", args => () => Outcome.FromResultAsTask("secondary"));
var strategy = Create();

var result = await strategy.ExecuteAsync(
context =>
{
var source = new CancellationTokenSource();
source.Cancel();
context.CancellationToken = source.Token;

return new ValueTask<string>("primary");
},
ResilienceContext.Get());

result.Should().Be("secondary");
}

[InlineData(-1)]
[InlineData(-1000)]
[InlineData(0)]
Expand Down