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

Adopt Alpha 2 in samples #1338

Merged
merged 2 commits 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
2 changes: 1 addition & 1 deletion Directory.Packages.props
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
<Project>
<PropertyGroup>
<ManagePackageVersionsCentrally>true</ManagePackageVersionsCentrally>
<PollyVersion>8.0.0-alpha.1</PollyVersion>
<PollyVersion>8.0.0-alpha.2</PollyVersion>
</PropertyGroup>
<ItemGroup>
<PackageVersion Include="coverlet.msbuild" Version="6.0.0" />
Expand Down
6 changes: 3 additions & 3 deletions samples/DependencyInjection/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@
// You can also register result-based (generic) resilience strategies
// First generic parameter is the key type, the second one is the result type
// This overload does not use the context argument (simple scenarios)
.AddResilienceStrategy<string, HttpResponseMessage>("my-strategy", builder =>
.AddResilienceStrategy<string, HttpResponseMessage>("my-http-strategy", builder =>
{
builder.AddTimeout(TimeSpan.FromSeconds(1));
})
Expand All @@ -35,10 +35,10 @@
ResilienceStrategyProvider<string> strategyProvider = serviceProvider.GetRequiredService<ResilienceStrategyProvider<string>>();

// Retrieve the strategy by name
ResilienceStrategy strategy = strategyProvider.Get("my-strategy");
ResilienceStrategy strategy = strategyProvider.GetStrategy("my-strategy");

// Retrieve the generic strategy by name
ResilienceStrategy<HttpResponseMessage> genericStrategy = strategyProvider.Get<HttpResponseMessage>("my-strategy");
ResilienceStrategy<HttpResponseMessage> genericStrategy = strategyProvider.GetStrategy<HttpResponseMessage>("my-http-strategy");

try
{
Expand Down
9 changes: 2 additions & 7 deletions samples/Extensibility/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -118,18 +118,13 @@ protected override async ValueTask<Outcome<TResult>> ExecuteCoreAsync<TResult, T
public static class MyResilienceStrategyExtensions
{
// Add new extension that works for both "ResilienceStrategyBuilder" and "ResilienceStrategyBuilder<T>"
public static TBuilder AddMyResilienceStrategy<TBuilder>(this TBuilder builder, MyResilienceStrategyOptions options)
where TBuilder : ResilienceStrategyBuilderBase
{
builder.AddStrategy(
public static TBuilder AddMyResilienceStrategy<TBuilder>(this TBuilder builder, MyResilienceStrategyOptions options) where TBuilder : ResilienceStrategyBuilderBase
=> builder.AddStrategy(
// Provide a factory that creates the strategy
context => new MyResilienceStrategy(context.Telemetry, options),

// Pass the options, note that the options instance is automatically validated by the builder
options);

return builder;
}
}


26 changes: 6 additions & 20 deletions samples/GenericStrategies/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -14,12 +14,10 @@
ResilienceStrategy<HttpResponseMessage> strategy = new ResilienceStrategyBuilder<HttpResponseMessage>()
.AddFallback(new FallbackStrategyOptions<HttpResponseMessage>
{
FallbackAction = async _ =>
FallbackAction = _ =>
{
await Task.Delay(10);

// Return fallback result
return new Outcome<HttpResponseMessage>(new HttpResponseMessage(System.Net.HttpStatusCode.OK));
return Outcome.FromResultAsTask(new HttpResponseMessage(HttpStatusCode.OK));
},
// You can also use switch expressions for succinct syntax
ShouldHandle = outcome => outcome switch
Expand All @@ -33,22 +31,10 @@
})
.AddRetry(new RetryStrategyOptions<HttpResponseMessage>
{
ShouldRetry = outcome =>
{
// We can handle specific result
if (outcome.Result?.StatusCode == HttpStatusCode.InternalServerError)
{
return PredicateResult.True;
}

// Or exception
if ( outcome.Exception is HttpRequestException)
{
return PredicateResult.True;
}

return PredicateResult.False;
},
// You can use "PredicateBuilder" to configure the predicates
ShouldHandle = new PredicateBuilder<HttpResponseMessage>()
.HandleResult(r => r.StatusCode == HttpStatusCode.InternalServerError)
.Handle<HttpRequestException>(),
// Register user callback called whenever retry occurs
OnRetry = outcome => { Console.WriteLine($"Retrying '{outcome.Result?.StatusCode}'..."); return default; },
BaseDelay = TimeSpan.FromMilliseconds(400),
Expand Down
15 changes: 6 additions & 9 deletions samples/Intro/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -41,16 +41,14 @@
// Add retries using the options
.AddRetry(new RetryStrategyOptions
{
ShouldRetry = outcome =>
// To configure the predicate you can use switch expressions
ShouldHandle = args => args.Exception switch
{
// We want to retry on this specific exception
if (outcome.Exception is TimeoutRejectedException)
{
// The "PredicateResult.True" is shorthand to "new ValueTask<bool>(true)"
return PredicateResult.True;
}
TimeoutRejectedException => PredicateResult.True,

return PredicateResult.False;
// The "PredicateResult.False" is just shorthand for "new ValueTask<bool>(true)"
// You can also use "new PredicateBuilder().Handle<TimeoutRejectedException>()"
_ => PredicateResult.False
},
// Register user callback called whenever retry occurs
OnRetry = args => { Console.WriteLine($"Retrying...{args.Arguments.Attempt} attempt"); return default; },
Expand All @@ -65,7 +63,6 @@
// Register user callback called whenever timeout occurs
OnTimeout = args =>
{

Console.WriteLine($"Timeout occurred after {args.Timeout}!");
return default;
}
Expand Down
22 changes: 22 additions & 0 deletions samples/Retries/ExecuteHelper.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
using System.Net;

namespace Retries;

internal class ExecuteHelper
{
public bool Fail { get; set; } = true;

public HttpResponseMessage ExecuteUnstable()
{
if (Fail)
{
Fail = false;
Console.WriteLine($"{DateTime.UtcNow}: Execute failed");
throw new InvalidOperationException();
}

Fail = true;
Console.WriteLine($"{DateTime.UtcNow}: Executed");
return new HttpResponseMessage(HttpStatusCode.OK);
}
}
77 changes: 28 additions & 49 deletions samples/Retries/Program.cs
Original file line number Diff line number Diff line change
@@ -1,44 +1,31 @@
using Polly;
using Polly.Retry;
using Retries;
using System.Net;

var helper = new ExecuteHelper();

// ------------------------------------------------------------------------
// 1. Create a retry strategy that only handles invalid operation exceptions
// 1. Create a retry strategy that handles all exceptions
// ------------------------------------------------------------------------

ResilienceStrategy strategy = new ResilienceStrategyBuilder()
.AddRetry(new RetryStrategyOptions
{
// Specify what exceptions should be retried
ShouldRetry = outcome =>
{
if (outcome.Exception is InvalidOperationException)
{
return PredicateResult.True;
}

return PredicateResult.False;
},
})
// Default retry options handle all exceptions
.AddRetry(new RetryStrategyOptions())
.Build();

Console.WriteLine("---------------------------------------");
strategy.Execute(helper.ExecuteUnstable);

// ------------------------------------------------------------------------
// 2. Customize the retry behavior
// ------------------------------------------------------------------------

strategy = new ResilienceStrategyBuilder()
.AddRetry(new RetryStrategyOptions
{
// Specify what exceptions should be retried
ShouldRetry = outcome =>
{
if (outcome.Exception is InvalidOperationException)
{
return PredicateResult.True;
}

return PredicateResult.False;
},
// Specify what exceptions should be retried using PredicateBuilder
ShouldHandle = new PredicateBuilder().Handle<InvalidOperationException>(),
RetryCount = 4,
BaseDelay = TimeSpan.FromSeconds(1),

Expand All @@ -48,24 +35,22 @@
})
.Build();

Console.WriteLine("---------------------------------------");
strategy.Execute(helper.ExecuteUnstable);

// ------------------------------------------------------------------------
// 3. Register the callbacks
// ------------------------------------------------------------------------

strategy = new ResilienceStrategyBuilder()
.AddRetry(new RetryStrategyOptions
{
// Specify what exceptions should be retried
ShouldRetry = outcome =>
// Specify what exceptions should be retried using switch expressions
ShouldHandle = args => args.Exception switch
{
if (outcome.Exception is InvalidOperationException)
{
return PredicateResult.True;
}

return PredicateResult.False;
InvalidOperationException => PredicateResult.True,
_ => PredicateResult.False,
},

OnRetry = outcome =>
{
Console.WriteLine($"Retrying attempt {outcome.Arguments.Attempt}...");
Expand All @@ -74,6 +59,9 @@
})
.Build();

Console.WriteLine("---------------------------------------");
strategy.Execute(helper.ExecuteUnstable);

// ------------------------------------------------------------------------
// 4. Create an HTTP retry strategy that handles both exceptions and results
// ------------------------------------------------------------------------
Expand All @@ -82,22 +70,10 @@
.AddRetry(new RetryStrategyOptions<HttpResponseMessage>
{
// Specify what exceptions or results should be retried
ShouldRetry = outcome =>
{
// Now, also handle results
if (outcome.Result?.StatusCode == HttpStatusCode.InternalServerError)
{
return PredicateResult.True;
}

if (outcome.Exception is InvalidOperationException)
{
return PredicateResult.True;
}

return PredicateResult.False;
},

ShouldHandle = new PredicateBuilder<HttpResponseMessage>()
.Handle<HttpRequestException>()
.Handle<InvalidOperationException>()
.HandleResult(r=>r.StatusCode == HttpStatusCode.InternalServerError),
// Specify delay generator
RetryDelayGenerator = outcome =>
{
Expand All @@ -112,3 +88,6 @@
}
})
.Build();

Console.WriteLine("---------------------------------------");
httpStrategy.Execute(helper.ExecuteUnstable);