-
Notifications
You must be signed in to change notification settings - Fork 2
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat(api): Add resilience policies using Polly
This commit adds resilience policies to the API. In `PollyContextExtensions.cs`, a static class `PollyContextExtensions` is added, which defines item names for context items. It also includes a method `TryGetLogger` that retrieves the logger from the resilience context. In `ResiliencePipelineDependencyInjectionExtensions.cs`, two static classes are added: `ResiliencePipelines` and `ResiliencePipelineDependencyInjectionExtensions`. The former defines keys/names of different resilience pipelines, while the latter provides extension methods for adding resilience policies to the dependency injection container using Polly. This file includes an example of adding a specific resilience pipeline called "player-clans-update" with fallback, circuit breaker, and retry policies. Additionally, in the existing file `PlayerService.cs`, changes are made to use the newly added resilience pipeline. The constructor now takes an instance of `ILogger<PlayerService>` and a `ResiliencePipelineProvider<string>`. The logger is used to set the logger property in the resilience context, and then this context is passed to `_resiliencePipeline.ExecuteAsync()` method when updating player clan status. Lastly, in the existing file `Startup.cs`, a call to add resilience policies using the extension method `AddResiliencePolicies()` is added within the ConfigureServices method. These changes enhance the API's ability to handle failures and improve its overall resiliency.
- Loading branch information
1 parent
ed8873d
commit 32c4aac
Showing
5 changed files
with
155 additions
and
9 deletions.
There are no files selected for viewing
25 changes: 25 additions & 0 deletions
25
WowsKarma.Api/Infrastructure/Resilience/PollyContextExtensions.cs
This file contains 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,25 @@ | ||
using System.Diagnostics.CodeAnalysis; | ||
using Polly; | ||
|
||
namespace WowsKarma.Api.Infrastructure.Resilience; | ||
|
||
public static class PollyContextExtensions | ||
{ | ||
/// <summary> | ||
/// Defines the item names for context items. | ||
/// </summary> | ||
/// <seealso cref="ResilienceContext"/> | ||
public static class ContextItems | ||
{ | ||
public static readonly ResiliencePropertyKey<ILogger> Logger = new("logger"); | ||
} | ||
|
||
/// <summary> | ||
/// Gets the logger from the resilience context. | ||
/// </summary> | ||
/// <param name="context">The resilience context.</param> | ||
/// <param name="logger">The logger, if initially provided to the context and found.</param> | ||
/// <returns></returns> | ||
public static bool TryGetLogger(this ResilienceContext context, [NotNullWhen(true)] out ILogger? logger) | ||
=> context.Properties.TryGetValue(ContextItems.Logger, out logger); | ||
} |
91 changes: 91 additions & 0 deletions
91
WowsKarma.Api/Infrastructure/Resilience/ResiliencePipelineDependencyInjectionExtensions.cs
This file contains 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,91 @@ | ||
using System.Text.Json; | ||
using Polly; | ||
using Polly.CircuitBreaker; | ||
using Polly.Retry; | ||
using static WowsKarma.Api.Infrastructure.Resilience.PollyContextExtensions; | ||
|
||
namespace WowsKarma.Api.Infrastructure.Resilience; | ||
|
||
/// <summary> | ||
/// Keys/Names of the different resilience pipelines. | ||
/// </summary> | ||
public static class ResiliencePipelines | ||
{ | ||
public const string PlayerClansUpdatePolicyName = "player-clans-update"; | ||
} | ||
|
||
/// <summary> | ||
/// Extension methods for adding resilience policies to the dependency injection container, using Polly. | ||
/// </summary> | ||
public static class ResiliencePipelineDependencyInjectionExtensions | ||
{ | ||
/// <summary> | ||
/// Adds resilience policies to the dependency injection container, using Polly. | ||
/// </summary> | ||
/// <param name="services">The <see cref="IServiceCollection"/> to add the policies to.</param> | ||
/// <returns>The <see cref="IServiceCollection"/> so that additional calls can be chained.</returns> | ||
public static IServiceCollection AddResiliencePolicies(this IServiceCollection services) | ||
{ | ||
services.AddResiliencePipeline<string, bool>(ResiliencePipelines.PlayerClansUpdatePolicyName, builder => builder | ||
.AddFallback(new() | ||
{ | ||
ShouldHandle = static args => ValueTask.FromResult(args.Outcome.Exception is not null), | ||
FallbackAction = static args => | ||
{ | ||
if (args.Outcome.Exception is not BrokenCircuitException or IsolatedCircuitException) | ||
{ | ||
(args.Context.TryGetLogger(out ILogger? logger) ? logger : null)? | ||
.LogWarning(args.Outcome.Exception, "Fallback triggered for {Policy} policy", ResiliencePipelines.PlayerClansUpdatePolicyName); | ||
} | ||
return Outcome.FromResultAsValueTask(false); | ||
} | ||
}) | ||
.AddCircuitBreaker(new() | ||
{ | ||
ShouldHandle = static args => ValueTask.FromResult(args.Outcome switch | ||
{ | ||
{ Exception: JsonException } => true, | ||
_ => false | ||
}), | ||
OnClosed = static args => | ||
{ | ||
(args.Context.TryGetLogger(out ILogger? logger) ? logger : null)? | ||
.LogInformation("Circuit closed for {Policy} policy", ResiliencePipelines.PlayerClansUpdatePolicyName); | ||
return ValueTask.CompletedTask; | ||
}, | ||
OnHalfOpened = static args => | ||
{ | ||
(args.Context.TryGetLogger(out ILogger? logger) ? logger : null)? | ||
.LogInformation("Circuit half-opened for {Policy} policy", ResiliencePipelines.PlayerClansUpdatePolicyName); | ||
return ValueTask.CompletedTask; | ||
}, | ||
OnOpened = static args => | ||
{ | ||
(args.Context.TryGetLogger(out ILogger? logger) ? logger : null)? | ||
.LogWarning("Circuit opened for {Policy} policy", ResiliencePipelines.PlayerClansUpdatePolicyName); | ||
return ValueTask.CompletedTask; | ||
} | ||
}) | ||
.AddRetry(new() | ||
{ | ||
BackoffType = DelayBackoffType.Exponential, | ||
MaxRetryAttempts = 4, | ||
ShouldHandle = static args => ValueTask.FromResult(args.Outcome switch | ||
{ | ||
{ Exception: HttpRequestException } => true, | ||
_ => false | ||
}) | ||
}) | ||
); | ||
|
||
return services; | ||
} | ||
} |
This file contains 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 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 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