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

Handle CancellationToken for Retry #2396

Open
wants to merge 3 commits into
base: main
Choose a base branch
from

Conversation

peter-csala
Copy link
Contributor

@peter-csala peter-csala commented Nov 18, 2024

Pull Request

The issue or feature being addressed

#2375

Details on the issue fix or feature implementation

  • Retry: handle cancelled CancellationToken as OperationCanceledException
  • Assessment
    • Hedging: handles cancelled CancellationToken as OperationCanceledException
    • Timeout: does not handle cancelled CancellationToken as OperationCanceledException
      • We might want to tackle that as a separate PR

Confirm the following

  • I started this PR by branching from the head of the default branch
  • I have targeted the PR to merge into the default branch
  • I have included unit tests for the issue/feature
  • I have successfully run a local build

@peter-csala
Copy link
Contributor Author

It seems like the timeout strategy also does not handle the linked CancellationToken's cancellation as OperationCanceledException

The following code prints 1 as a result

var cts = new CancellationTokenSource();
var p = new ResiliencePipelineBuilder<int>().AddTimeout(TimeSpan.FromSeconds(1)).Build();
var r = await p.ExecuteAsync(async token =>
{
	await Task.Delay(500, token);
	cts.Cancel();
	return 1;
}, cts.Token);

Console.WriteLine(r); // 1

@peter-csala
Copy link
Contributor Author

peter-csala commented Nov 18, 2024

For hedging it seems like we are getting OperationCanceledException at the next attempt.

var options = new HedgingStrategyOptions<int>
{
	ShouldHandle = _ => PredicateResult.True(),
	MaxHedgedAttempts = 3,
	Delay = TimeSpan.FromMilliseconds(100),
	OnHedging = static args =>
	{
		Console.WriteLine("Hedging...");
		return default;
	}
};

var cts = new CancellationTokenSource();
var p = new ResiliencePipelineBuilder<int>().AddHedging(options).Build();
var r = await p.ExecuteAsync(async token =>
{
	await Task.Delay(200);
	cts.Cancel();
	return 3;
}, cts.Token);

Console.WriteLine(r);

Output:

Hedging...
Unhandled exception. System.OperationCanceledException: The operation was canceled.
   at Polly.Utils.ExceptionUtilities.TrySetStackTrace[T](T exception) in /_/src/Polly.Core/Utils/ExceptionUtilities.cs:line 23
   ...

@peter-csala peter-csala marked this pull request as ready for review November 18, 2024 14:36
@peter-csala peter-csala changed the title [DRAFT] Handle CancellationToken for Retry Handle CancellationToken for Retry Nov 18, 2024
@@ -53,6 +53,15 @@ protected internal override async ValueTask<Outcome<T>> ExecuteCore<TState>(Func
{
var startTimestamp = _timeProvider.GetTimestamp();
var outcome = await StrategyHelper.ExecuteCallbackSafeAsync(callback, context, state).ConfigureAwait(context.ContinueOnCapturedContext);
try
{
context.CancellationToken.ThrowIfCancellationRequested();
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

How about just checking for context.CancellationToken.IsCancellationRequested() and then constructing the exception manually?

Alternatively, you can do the same check inside ExecuteCallbackSafeAsync and it will apply everywhere where it is used.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I tried to follow the same pattern what we already have for the _timeProvider.DelayAsync:

try
{
await _timeProvider.DelayAsync(delay, context).ConfigureAwait(context.ContinueOnCapturedContext);
}
catch (OperationCanceledException e)
{
return Outcome.FromException<T>(e);
}

But yes for sure, I can rewrite the code to avoid try catch. Do you want?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants