-
-
Notifications
You must be signed in to change notification settings - Fork 1.3k
Introduce samples folder
#1295
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
Introduce samples folder
#1295
Changes from all commits
Commits
Show all changes
8 commits
Select commit
Hold shift + click to select a range
49603af
Introduce `samples` folder
martintmk 6f0e641
Polish release notes.
martintmk cddd37d
Use the Polly package
martintmk 5128d73
clenaup
martintmk 4b01125
PR comments
martintmk ef71c62
Improvements
martintmk 2f7fe4a
PR comments
martintmk 58b662a
PR comments
martintmk 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
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
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
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,3 @@ | ||
| { | ||
| "dotnet.defaultSolution": "Samples.sln" | ||
| } |
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,16 @@ | ||
| <Project Sdk="Microsoft.NET.Sdk"> | ||
|
|
||
| <PropertyGroup> | ||
| <OutputType>Exe</OutputType> | ||
| <TargetFramework>net7.0</TargetFramework> | ||
| <ImplicitUsings>enable</ImplicitUsings> | ||
| <Nullable>enable</Nullable> | ||
| </PropertyGroup> | ||
|
|
||
| <ItemGroup> | ||
| <PackageReference Include="Microsoft.Extensions.Logging.Console" /> | ||
| <PackageReference Include="Microsoft.Extensions.DependencyInjection" /> | ||
| <PackageReference Include="Polly.Extensions" /> | ||
| </ItemGroup> | ||
|
|
||
| </Project> |
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,53 @@ | ||
| using Microsoft.Extensions.DependencyInjection; | ||
| using Microsoft.Extensions.Logging; | ||
| using Polly; | ||
| using Polly.Registry; | ||
| using Polly.Timeout; | ||
|
|
||
| // ------------------------------------------------------------------------ | ||
| // 1. Register your resilience strategy | ||
| // ------------------------------------------------------------------------ | ||
|
|
||
| var serviceProvider = new ServiceCollection() | ||
| .AddLogging(builder => builder.AddConsole().SetMinimumLevel(LogLevel.Debug)) | ||
| // Use "AddResilienceStrategy" extension method to configure your named strategy | ||
| .AddResilienceStrategy("my-strategy", (builder, context) => | ||
| { | ||
| // You can resolve any service from DI when building the strategy | ||
| context.ServiceProvider.GetRequiredService<ILoggerFactory>(); | ||
|
|
||
| builder.AddTimeout(TimeSpan.FromSeconds(1)); | ||
| }) | ||
| // 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 => | ||
| { | ||
| builder.AddTimeout(TimeSpan.FromSeconds(1)); | ||
| }) | ||
| .BuildServiceProvider(); | ||
|
|
||
| // ------------------------------------------------------------------------ | ||
| // 2. Retrieve and use your resilience strategy | ||
| // ------------------------------------------------------------------------ | ||
|
|
||
| // Resolve the resilience strategy provider for string-based keys | ||
| ResilienceStrategyProvider<string> strategyProvider = serviceProvider.GetRequiredService<ResilienceStrategyProvider<string>>(); | ||
|
|
||
| // Retrieve the strategy by name | ||
| ResilienceStrategy strategy = strategyProvider.Get("my-strategy"); | ||
|
|
||
| // Retrieve the generic strategy by name | ||
| ResilienceStrategy<HttpResponseMessage> genericStrategy = strategyProvider.Get<HttpResponseMessage>("my-strategy"); | ||
|
|
||
| try | ||
| { | ||
| // Execute the strategy | ||
| // Notice in console output that telemetry is automatically enabled | ||
| await strategy.ExecuteAsync(async token => await Task.Delay(10000, token), CancellationToken.None); | ||
| } | ||
| catch (TimeoutRejectedException) | ||
| { | ||
| // The timeout strategy cancels the user callback and throws this exception | ||
| Console.WriteLine("Timeout!"); | ||
| } | ||
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,8 @@ | ||
| <Project> | ||
| <PropertyGroup> | ||
| <RunAnalyzers>true</RunAnalyzers> | ||
| <RunAnalyzersDuringBuild>true</RunAnalyzersDuringBuild> | ||
| <EnforceCodeStyleInBuild>true</EnforceCodeStyleInBuild> | ||
| <AnalysisLevel>latest</AnalysisLevel> | ||
| </PropertyGroup> | ||
| </Project> |
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,3 @@ | ||
| <Project> | ||
| <!-- Intentionally empty to not include Directory.Build.targets in the root. --> | ||
| </Project> |
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,14 @@ | ||
| <Project Sdk="Microsoft.NET.Sdk"> | ||
|
|
||
| <PropertyGroup> | ||
| <OutputType>Exe</OutputType> | ||
| <TargetFramework>net7.0</TargetFramework> | ||
| <ImplicitUsings>enable</ImplicitUsings> | ||
| <Nullable>enable</Nullable> | ||
| </PropertyGroup> | ||
|
|
||
| <ItemGroup> | ||
| <PackageReference Include="Polly.Core" /> | ||
| </ItemGroup> | ||
|
|
||
| </Project> |
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,135 @@ | ||
| using Polly; | ||
| using Polly.Telemetry; | ||
|
|
||
| // ------------------------------------------------------------------------ | ||
| // Usage of custom strategy | ||
| // ------------------------------------------------------------------------ | ||
| var strategy = new ResilienceStrategyBuilder() | ||
| // This is custom extension defined in this sample | ||
| .AddMyResilienceStrategy(new MyResilienceStrategyOptions | ||
| { | ||
| OnCustomEvent = args => | ||
| { | ||
| Console.WriteLine("OnCustomEvent"); | ||
| return default; | ||
| } | ||
| }) | ||
| .Build(); | ||
|
|
||
| // Execute the strategy | ||
| strategy.Execute(() => { }); | ||
|
|
||
| // ------------------------------------------------------------------------ | ||
| // SIMPLE EXTENSIBILITY MODEL (INLINE STRATEGY) | ||
| // ------------------------------------------------------------------------ | ||
|
|
||
| strategy = new ResilienceStrategyBuilder() | ||
| // Just add the strategy instance directly | ||
| .AddStrategy(new MySimpleStrategy()) | ||
| .Build(); | ||
|
|
||
| // Execute the strategy | ||
| strategy.Execute(() => { }); | ||
|
|
||
| internal class MySimpleStrategy : ResilienceStrategy | ||
| { | ||
| protected override ValueTask<Outcome<TResult>> ExecuteCoreAsync<TResult, TState>(Func<ResilienceContext, TState, ValueTask<Outcome<TResult>>> callback, ResilienceContext context, TState state) | ||
| { | ||
| Console.WriteLine("MySimpleStrategy executing!"); | ||
martincostello marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
|
||
| // The "context" holds information about execution mode | ||
| Console.WriteLine("context.IsSynchronous: {0}", context.IsSynchronous); | ||
| Console.WriteLine("context.ResultType: {0}", context.ResultType); | ||
| Console.WriteLine("context.IsVoid: {0}", context.IsVoid); | ||
|
|
||
| // The "state" is an ambient value passed by the caller that holds the state. | ||
| // Here, we do not do anything with it, just pass it to the callback. | ||
|
|
||
| // Execute the provided callback | ||
| return callback(context, state); | ||
| } | ||
| } | ||
|
|
||
| // ------------------------------------------------------------------------ | ||
| // STANDARD EXTENSIBILITY MODEL | ||
| // ------------------------------------------------------------------------ | ||
|
|
||
| // ------------------------------------------------------------------------ | ||
| // 1. Create options for your custom strategy | ||
| // ------------------------------------------------------------------------ | ||
|
|
||
| // 1.A Define arguments for events that your strategy uses (optional) | ||
| public readonly record struct OnCustomEventArguments(ResilienceContext Context); | ||
|
|
||
| // 1.B Define the options. | ||
| public class MyResilienceStrategyOptions : ResilienceStrategyOptions | ||
| { | ||
| public override string StrategyType => "MyCustomStrategy"; | ||
|
|
||
| // Use the arguments in the delegates. | ||
| // The recommendation is to use asynchronous delegates. | ||
| public Func<OnCustomEventArguments, ValueTask>? OnCustomEvent { get; set; } | ||
| } | ||
|
|
||
| // ------------------------------------------------------------------------ | ||
| // 2. Create a custom resilience strategy that derives from ResilienceStrategy | ||
| // ------------------------------------------------------------------------ | ||
|
|
||
| // The strategy should be internal and not exposed as part of any public API. Instead, expose options and extensions for resilience strategy builder. | ||
| internal class MyResilienceStrategy : ResilienceStrategy | ||
| { | ||
| private readonly ResilienceStrategyTelemetry telemetry; | ||
| private readonly Func<OnCustomEventArguments, ValueTask>? onCustomEvent; | ||
|
|
||
| public MyResilienceStrategy(ResilienceStrategyTelemetry telemetry, MyResilienceStrategyOptions options) | ||
| { | ||
| this.telemetry = telemetry; | ||
| this.onCustomEvent = options.OnCustomEvent; | ||
| } | ||
|
|
||
| protected override async ValueTask<Outcome<TResult>> ExecuteCoreAsync<TResult, TState>(Func<ResilienceContext, TState, ValueTask<Outcome<TResult>>> callback, ResilienceContext context, TState state) | ||
| { | ||
| // Here, do something before callback execution | ||
| // ... | ||
|
|
||
| // Execute the provided callback | ||
| var outcome = await callback(context, state); | ||
|
|
||
| // Here, do something after callback execution | ||
| // ... | ||
|
|
||
| // You can then report important telemetry events | ||
| telemetry.Report("MyCustomEvent", context, new OnCustomEventArguments(context)); | ||
|
|
||
| // Call the delegate if provided by the user | ||
| if (onCustomEvent is not null) | ||
| { | ||
| await onCustomEvent(new OnCustomEventArguments(context)); | ||
| } | ||
|
|
||
| return outcome; | ||
| } | ||
| } | ||
|
|
||
| // ------------------------------------------------------------------------ | ||
| // 3. Expose new extensions for ResilienceStrategyBuilder | ||
| // ------------------------------------------------------------------------ | ||
|
|
||
| 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( | ||
| // 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; | ||
| } | ||
| } | ||
|
|
||
|
|
||
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,14 @@ | ||
| <Project Sdk="Microsoft.NET.Sdk"> | ||
|
|
||
| <PropertyGroup> | ||
| <OutputType>Exe</OutputType> | ||
| <TargetFramework>net7.0</TargetFramework> | ||
| <ImplicitUsings>enable</ImplicitUsings> | ||
| <Nullable>enable</Nullable> | ||
| </PropertyGroup> | ||
|
|
||
| <ItemGroup> | ||
| <PackageReference Include="Polly.Core" /> | ||
| </ItemGroup> | ||
|
|
||
| </Project> |
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,75 @@ | ||
| using Polly; | ||
| using Polly.Fallback; | ||
| using Polly.Retry; | ||
| using Polly.Timeout; | ||
| using System.Net; | ||
|
|
||
| // ---------------------------------------------------------------------------- | ||
| // Create a generic resilience strategy using ResilienceStrategyBuilder<T> | ||
| // ---------------------------------------------------------------------------- | ||
|
|
||
| // The generic ResilienceStrategyBuilder<T> creates a ResilienceStrategy<T> | ||
| // that can execute synchronous and asynchronous callbacks that return T. | ||
|
|
||
| ResilienceStrategy<HttpResponseMessage> strategy = new ResilienceStrategyBuilder<HttpResponseMessage>() | ||
| .AddFallback(new FallbackStrategyOptions<HttpResponseMessage> | ||
| { | ||
| FallbackAction = async _ => | ||
| { | ||
| await Task.Delay(10); | ||
|
|
||
| // Return fallback result | ||
| return new Outcome<HttpResponseMessage>(new HttpResponseMessage(System.Net.HttpStatusCode.OK)); | ||
| }, | ||
| // You can also use switch expressions for succinct syntax | ||
| ShouldHandle = outcome => outcome switch | ||
| { | ||
| // The "PredicateResult.True" is shorthand to "new ValueTask<bool>(true)" | ||
| { Exception: HttpRequestException } => PredicateResult.True, | ||
| { Result: HttpResponseMessage response } when response.StatusCode == HttpStatusCode.InternalServerError => PredicateResult.True, | ||
| _ => PredicateResult.False | ||
| }, | ||
| OnFallback = _ => { Console.WriteLine("Fallback!"); return default; } | ||
| }) | ||
| .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; | ||
| }, | ||
| // Register user callback called whenever retry occurs | ||
| OnRetry = outcome => { Console.WriteLine($"Retrying '{outcome.Result?.StatusCode}'..."); return default; }, | ||
martincostello marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| BaseDelay = TimeSpan.FromMilliseconds(400), | ||
| BackoffType = RetryBackoffType.Constant, | ||
| RetryCount = 3 | ||
| }) | ||
| .AddTimeout(new TimeoutStrategyOptions | ||
| { | ||
| Timeout = TimeSpan.FromMilliseconds(500), | ||
| // Register user callback called whenever timeout occurs | ||
| OnTimeout = _ => { Console.WriteLine("Timeout occurred!"); return default; } | ||
| }) | ||
| .Build(); | ||
|
|
||
| var response = await strategy.ExecuteAsync( | ||
| async token => | ||
| { | ||
| await Task.Delay(10); | ||
| // This causes the action fail, thus using the fallback strategy above | ||
| return new HttpResponseMessage(HttpStatusCode.InternalServerError); | ||
martincostello marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| }, | ||
| CancellationToken.None); | ||
|
|
||
| Console.WriteLine($"Response: {response.StatusCode}"); | ||
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,14 @@ | ||
| <Project Sdk="Microsoft.NET.Sdk"> | ||
|
|
||
| <PropertyGroup> | ||
| <OutputType>Exe</OutputType> | ||
| <TargetFramework>net7.0</TargetFramework> | ||
| <ImplicitUsings>enable</ImplicitUsings> | ||
| <Nullable>enable</Nullable> | ||
| </PropertyGroup> | ||
|
|
||
| <ItemGroup> | ||
| <PackageReference Include="Polly.Core"/> | ||
| </ItemGroup> | ||
|
|
||
| </Project> |
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.