Skip to content

Commit

Permalink
Fix hedging being cancelled too early
Browse files Browse the repository at this point in the history
  • Loading branch information
martintmk committed Jun 22, 2023
1 parent 18171df commit 7f98d79
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 2 deletions.
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 @@ private async ValueTask<Outcome<T>> ExecuteCoreAsync<TState>(
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

0 comments on commit 7f98d79

Please sign in to comment.