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

Introduce samples folder #1295

Merged
merged 8 commits into from
Jun 16, 2023
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
7 changes: 6 additions & 1 deletion CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,11 @@
## 8.0.0-alpha.1

- The first public preview of [Polly v8](https://github.com/App-vNext/Polly/issues/1048) with our [new high-performance core API](https://github.com/App-vNext/Polly/blob/main/src/Polly.Core/README.md) and extensions - Thanks to:
- The first public preview of [Polly v8](https://github.com/App-vNext/Polly/issues/1048) with our [new high-performance core API](https://github.com/App-vNext/Polly/blob/main/src/Polly.Core/README.md) and extensions. Visit the [samples](samples/) to see Polly V8 in action.
- Releasing [`Polly.Core`](https://nuget.org/packages/Polly.Core) NuGet package.
martincostello marked this conversation as resolved.
Show resolved Hide resolved
- Releasing [`Polly.Extensions`](https://nuget.org/packages/Polly.Extensions) NuGet package.
- Releasing [`Polly.RateLimiting`](https://nuget.org/packages/Polly.RateLimiting) NuGet package.

Thanks to:
- [@adamnova](https://github.com/adamnova)
- [@andrey-noskov](https://github.com/andrey-noskov)
- [@joelhulen](https://github.com/joelhulen)
Expand Down
2 changes: 2 additions & 0 deletions Directory.Packages.props
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
<PackageVersion Include="FluentAssertions" Version="6.11.0" />
<PackageVersion Include="GitHubActionsTestLogger" Version="2.3.2" />
<PackageVersion Include="Microsoft.Bcl.AsyncInterfaces" Version="1.0.0" />
<PackageVersion Include="Microsoft.Extensions.Logging.Console" Version="7.0.0" />
<PackageVersion Include="Microsoft.Extensions.Caching.Memory" Version="7.0.0" />
<PackageVersion Include="Microsoft.Extensions.Configuration" Version="7.0.0" />
<PackageVersion Include="Microsoft.Extensions.DependencyInjection" Version="7.0.0" />
Expand All @@ -17,6 +18,7 @@
<PackageVersion Include="Microsoft.SourceLink.GitHub" Version="1.1.1" />
<PackageVersion Include="MinVer" Version="4.3.0" />
<PackageVersion Include="Moq" Version="4.18.4" />
<PackageVersion Include="Polly" Version="7.2.4" />
<PackageVersion Include="Polly.Contrib.WaitAndRetry" Version="1.1.1" />
<PackageVersion Include="ReportGenerator" Version="5.1.22" />
<PackageVersion Include="SonarAnalyzer.CSharp" Version="9.3.0.71466" />
Expand Down
3 changes: 3 additions & 0 deletions samples/.vscode/settings.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
{
"dotnet.defaultSolution": "Samples.sln"
}
20 changes: 20 additions & 0 deletions samples/DependencyInjection/DependencyInjection.csproj
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
<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" />
</ItemGroup>

<ItemGroup>
<ProjectReference Include="..\..\src\Polly.Core\Polly.Core.csproj" />
<ProjectReference Include="..\..\src\Polly.Extensions\Polly.Extensions.csproj" />
</ItemGroup>

</Project>
51 changes: 51 additions & 0 deletions samples/DependencyInjection/Program.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
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)
{
martincostello marked this conversation as resolved.
Show resolved Hide resolved
}
8 changes: 8 additions & 0 deletions samples/Directory.Build.props
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>
3 changes: 3 additions & 0 deletions samples/Directory.Build.targets
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>
18 changes: 18 additions & 0 deletions samples/Extensibility/Extensibility.csproj
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net7.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Polly" />
</ItemGroup>

<ItemGroup>
<ProjectReference Include="..\..\src\Polly.Core\Polly.Core.csproj" />
</ItemGroup>

</Project>
123 changes: 123 additions & 0 deletions samples/Extensibility/Program.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,123 @@
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()
.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

// 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
martincostello marked this conversation as resolved.
Show resolved Hide resolved
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 should report important telemetry events
martincostello marked this conversation as resolved.
Show resolved Hide resolved
telemetry.Report("MyCustomEvent", context, new OnCustomEventArguments(context));

// Call the delegate
onCustomEvent?.Invoke(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 instance is automatically validated by the builder
options);

return builder;
}
}


14 changes: 14 additions & 0 deletions samples/GenericStrategies/GenericStrategies.csproj
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>
<ProjectReference Include="..\..\src\Polly.Core\Polly.Core.csproj" />
</ItemGroup>

</Project>
74 changes: 74 additions & 0 deletions samples/GenericStrategies/Program.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
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.Yield();
martincostello marked this conversation as resolved.
Show resolved Hide resolved

// return fallback result
martincostello marked this conversation as resolved.
Show resolved Hide resolved
return new Outcome<HttpResponseMessage>(new HttpResponseMessage(System.Net.HttpStatusCode.OK));
},
// You can also use switch expressions for succinct syntax
ShouldHandle = outcome => outcome switch
{
{ 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 == System.Net.HttpStatusCode.InternalServerError)
{
// The "PredicateResult.True" is shorthand to "new ValueTask<bool>(true)"
martincostello marked this conversation as resolved.
Show resolved Hide resolved
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.Yield();
return new HttpResponseMessage(HttpStatusCode.InternalServerError);
martincostello marked this conversation as resolved.
Show resolved Hide resolved
},
CancellationToken.None);

Console.WriteLine($"Response: {response.StatusCode}");
14 changes: 14 additions & 0 deletions samples/Intro/Intro.csproj
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>
<ProjectReference Include="..\..\src\Polly.Core\Polly.Core.csproj" />
martincostello marked this conversation as resolved.
Show resolved Hide resolved
</ItemGroup>

</Project>
Loading