diff --git a/docs/strategies/circuit-breaker.md b/docs/strategies/circuit-breaker.md index 1ceeeac383..22ed6d0c38 100644 --- a/docs/strategies/circuit-breaker.md +++ b/docs/strategies/circuit-breaker.md @@ -9,8 +9,8 @@ - `AddCircuitBreaker` - **Strategy Type**: Reactive - **Exception(s)**: - - `BrokenCircuitException`: Thrown when a circuit is broken and the action could not be executed. - - `IsolatedCircuitException`: Thrown when a circuit is isolated (held open) by manual override. + - [`BrokenCircuitException`](xref:Polly.CircuitBreaker.BrokenCircuitException): Thrown when a circuit is broken and the action was not executed. + - [`IsolatedCircuitException`](xref:Polly.CircuitBreaker.IsolatedCircuitException): Thrown when a circuit is isolated (held open) by manual override. --- @@ -92,6 +92,65 @@ new ResiliencePipelineBuilder().AddCircuitBreaker(optionsSt ``` +### Failure handling + +The circuit breaker returns the result / exception during the sampling period. Once the strategy opens the circuit, every subsequent call will be shortcut with a `BrokenCircuitException`. + + +```cs +var pipeline = new ResiliencePipelineBuilder() + .AddCircuitBreaker(new CircuitBreakerStrategyOptions + { + FailureRatio = 0.1, + SamplingDuration = TimeSpan.FromSeconds(1), + MinimumThroughput = 3, + BreakDuration = TimeSpan.FromSeconds(30), + ShouldHandle = new PredicateBuilder().Handle() + }) + .Build(); + +for (int i = 0; i < 10; i++) +{ + try + { + pipeline.Execute(() => throw new SomeExceptionType()); + } + catch (SomeExceptionType) + { + Console.WriteLine("Operation failed please try again."); + } + catch (BrokenCircuitException) + { + Console.WriteLine("Operation failed too many times please try again later."); + } +} +``` + + +The output would look like this: + +```none +Operation failed please try again. +Operation failed please try again. +Operation failed please try again. +Operation failed too many times please try again later. +Operation failed too many times please try again later. +Operation failed too many times please try again later. +Operation failed too many times please try again later. +Operation failed too many times please try again later. +Operation failed too many times please try again later. +Operation failed too many times please try again later. +``` + +The `BrokenCircuitException` and the `IsolatedCircuitException` provide access to the following properties: + +- `RetryAfter`; +- `TelemetrySource`. + +If a `TimeSpan` value is provided to the optional `RetryAfter` property then this indicates that circuit is open for at least this time period and you should retry your operation no sooner than the value given. + +The `TelemetrySource` property is a [`ResilienceTelemetrySource`](xref:Polly.Telemetry.ResilienceTelemetrySource) which allows you retrieve information such as the executed pipeline and strategy. These can be useful if you have multiple circuit breaker strategies in your pipeline and you need to know which strategy caused the `BrokenCircuitException` to be thrown. + ## Defaults | Property | Default Value | Description | diff --git a/docs/strategies/rate-limiter.md b/docs/strategies/rate-limiter.md index 81c4043de5..8781dcf931 100644 --- a/docs/strategies/rate-limiter.md +++ b/docs/strategies/rate-limiter.md @@ -8,7 +8,7 @@ - `AddRateLimiter`, - `AddConcurrencyLimiter` - **Exception(s)**: - - `RateLimiterRejectedException`: Thrown when a rate limiter rejects an execution. + - [`RateLimiterRejectedException`](xref:Polly.RateLimiting.RateLimiterRejectedException): Thrown when a rate limiter rejects an execution. > [!NOTE] > The rate limiter strategy resides inside the [Polly.RateLimiting](https://www.nuget.org/packages/Polly.RateLimiting) package, not in ([Polly.Core](https://www.nuget.org/packages/Polly.Core)) like other strategies. @@ -73,9 +73,9 @@ catch (RateLimiterRejectedException ex) ### Failure handling -It might not be obvious at the first glance what is the difference between these two techniques: +At first glance it might not be obvious what the difference between these two techniques is: - + ```cs var withOnRejected = new ResiliencePipelineBuilder() .AddRateLimiter(new RateLimiterStrategyOptions @@ -90,7 +90,11 @@ var withOnRejected = new ResiliencePipelineBuilder() return default; } }).Build(); +``` + + +```cs var withoutOnRejected = new ResiliencePipelineBuilder() .AddRateLimiter(new RateLimiterStrategyOptions { @@ -111,28 +115,29 @@ catch (RateLimiterRejectedException) ``` -## Defaults - -| Property | Default Value | Description | -|-----------------------------|------------------------------------------------------|-------------------------------------------------------------------------------------------------------------| -| `RateLimiter` | `null` | **Dynamically** creates a `RateLimitLease` for executions. | -| `DefaultRateLimiterOptions` | `PermitLimit` set to 1000 and `QueueLimit` set to 0. | If `RateLimiter` is not provided then this options object will be used for the default concurrency limiter. | -| `OnRejected` | `null` | If provided then it will be invoked after the limiter rejected an execution. | - -### `OnRejected` versus catching `RateLimiterRejectedException` - The `OnRejected` user-provided delegate is called just before the strategy throws the `RateLimiterRejectedException`. This delegate receives a parameter which allows you to access the `Context` object as well as the `Lease`: -- Accessing the `Context` is also possible via a different `Execute{Async}` overload. -- Accessing the rejected `Lease` can be useful in certain scenarios. +- `Context` can be accessed via some `Execute{Async}` overloads. +- `Lease` can be useful in advanced scenarios. So, what is the purpose of the `OnRejected`? The `OnRejected` delegate can be useful when you define a resilience pipeline which consists of multiple strategies. For example, you have a rate limiter as the inner strategy and a retry as the outer strategy. If the retry is defined to handle `RateLimiterRejectedException`, that means the `Execute{Async}` may or may not throw that exception depending on future attempts. So, if you want to get notification about the fact that the rate limit has been exceeded, you have to provide a delegate to the `OnRejected` property. -> [!IMPORTANT] -> The [`RateLimiterRejectedException`](xref:Polly.RateLimiting.RateLimiterRejectedException) has a `RetryAfter` property. If this optional `TimeSpan` is provided then this indicates that your requests are throttled and you should retry them no sooner than the value given. -> Please note that this information is not available inside the `OnRejected` callback. +The `RateLimiterRejectedException` has a `RetryAfter` and a `TelemetrySource` property. If the optional `RetryAfter` value is provided then this indicates that your requests are being throttled and you should retry them no sooner than the property's value. + +> [!NOTE] +> The `RetryAfter` value is not available inside the `OnRejected` callback. + + The `TelemetrySource` property is a [`ResilienceTelemetrySource`](xref:Polly.Telemetry.ResilienceTelemetrySource) which allows you retrieve information such as the executed pipeline and strategy. These can be useful if you have multiple limiter strategies in your pipeline (for example both a rate and concurrency limiter) and you need to know which strategy caused the `RateLimiterRejectedException` to be thrown. + +## Defaults + +| Property | Default Value | Description | +|-----------------------------|------------------------------------------------------|-------------------------------------------------------------------------------------------------------------| +| `RateLimiter` | `null` | **Dynamically** creates a `RateLimitLease` for executions. | +| `DefaultRateLimiterOptions` | `PermitLimit` set to 1000 and `QueueLimit` set to 0. | If `RateLimiter` is not provided then this options object will be used for the default concurrency limiter. | +| `OnRejected` | `null` | If provided then it will be invoked after the limiter rejected an execution. | ## Telemetry @@ -150,7 +155,7 @@ Resilience event occurred. EventName: 'OnRateLimiterRejected', Source: 'MyPipeli ``` > [!NOTE] -> Please note that the `OnRateLimiterRejected` telemetry event will be reported **only if** the rate limiter strategy rejects the provided callback execution. +> The `OnRateLimiterRejected` telemetry event will be reported **only if** the rate limiter strategy rejects the provided callback execution. > > Also remember that the `Result` will be **always empty** for the `OnRateLimiterRejected` telemetry event. diff --git a/docs/strategies/timeout.md b/docs/strategies/timeout.md index 69ca331183..def3ea0c7a 100644 --- a/docs/strategies/timeout.md +++ b/docs/strategies/timeout.md @@ -7,7 +7,7 @@ - **Extension(s)**: - `AddTimeout` - **Exception(s)**: - - `TimeoutRejectedException`: Thrown when a delegate executed through a timeout strategy does not complete before the timeout. + - [`TimeoutRejectedException`](xref:Polly.Timeout.TimeoutRejectedException): Thrown when a delegate executed through a timeout strategy does not complete before the timeout. --- @@ -77,9 +77,9 @@ HttpResponseMessage httpResponse = await pipeline.ExecuteAsync( ### Failure handling -It might not be obvious at the first glance what is the difference between these two techniques: +At first glance it might not be obvious what the difference between these two techniques is: - + ```cs var withOnTimeout = new ResiliencePipelineBuilder() .AddTimeout(new TimeoutStrategyOptions @@ -91,7 +91,11 @@ var withOnTimeout = new ResiliencePipelineBuilder() return default; } }).Build(); +``` + + +```cs var withoutOnTimeout = new ResiliencePipelineBuilder() .AddTimeout(new TimeoutStrategyOptions { @@ -109,6 +113,17 @@ catch (TimeoutRejectedException) ``` +The `OnTimeout` user-provided delegate is called just before the strategy throws the `TimeoutRejectedException`. This delegate receives a parameter which allows you to access the `Context` object as well as the `Timeout`: + +- `Context` can be also accessed via some `Execute{Async}` overloads. +- `Timeout` can be useful if you are using the `TimeoutGenerator` property of the `TimeoutStrategyOptions` rather than its `Timeout` property. + +So, what is the purpose of the `OnTimeout` in case of static timeout settings? + +The `OnTimeout` delegate can be useful when you define a resilience pipeline which consists of multiple strategies. For example you have a timeout as the inner strategy and a retry as the outer strategy. If the retry is defined to handle `TimeoutRejectedException`, that means the `Execute{Async}` may or may not throw that exception depending on future attempts. So, if you need to be notified about a timeout occurring, you must provide a delegate to the `OnTimeout` property. + +The `TimeoutRejectedException` provides access to a `TelemetrySource` property. This property is a [`ResilienceTelemetrySource`](xref:Polly.Telemetry.ResilienceTelemetrySource) which allows you retrieve information such as the executed pipeline and strategy. These can be useful if you have multiple timeout strategies in your pipeline and you need to know which strategy caused the `TimeoutRejectedException` to be thrown. + ## Defaults | Property | Default Value | Description | @@ -123,17 +138,6 @@ catch (TimeoutRejectedException) - If both `Timeout` and `TimeoutGenerator` are specified then `Timeout` will be ignored. - If `TimeoutGenerator` returns a `TimeSpan` that is less than or equal to `TimeSpan.Zero` then the strategy will have no effect. -### `OnTimeout` versus catching `TimeoutRejectedException` - -The `OnTimeout` user-provided delegate is called just before the strategy throws the `TimeoutRejectedException`. This delegate receives a parameter which allows you to access the `Context` object as well as the `Timeout`: - -- Accessing the `Context` is also possible via a different `Execute{Async}` overload. -- Accessing the `Timeout` can be useful if you are using the `TimeoutGenerator` property rather than the `Timeout` property. - -So, what is the purpose of the `OnTimeout` in case of static timeout settings? - -The `OnTimeout` delegate can be useful when you define a resilience pipeline which consists of multiple strategies. For example you have a timeout as the inner strategy and a retry as the outer strategy. If the retry is defined to handle `TimeoutRejectedException`, that means the `Execute{Async}` may or may not throw that exception depending on future attempts. So, if you want to get notification about the fact that a timeout has occurred, you have to provide a delegate to the `OnTimeout` property. - ## Telemetry The timeout strategy reports the following telemetry events: diff --git a/src/Snippets/Docs/CircuitBreaker.cs b/src/Snippets/Docs/CircuitBreaker.cs index 111bad9796..3e0e136a7d 100644 --- a/src/Snippets/Docs/CircuitBreaker.cs +++ b/src/Snippets/Docs/CircuitBreaker.cs @@ -82,6 +82,35 @@ public static async Task Usage() new ResiliencePipelineBuilder().AddCircuitBreaker(optionsStateProvider); #endregion + + #region circuit-breaker-failure-handling + var pipeline = new ResiliencePipelineBuilder() + .AddCircuitBreaker(new CircuitBreakerStrategyOptions + { + FailureRatio = 0.1, + SamplingDuration = TimeSpan.FromSeconds(1), + MinimumThroughput = 3, + BreakDuration = TimeSpan.FromSeconds(30), + ShouldHandle = new PredicateBuilder().Handle() + }) + .Build(); + + for (int i = 0; i < 10; i++) + { + try + { + pipeline.Execute(() => throw new SomeExceptionType()); + } + catch (SomeExceptionType) + { + Console.WriteLine("Operation failed please try again."); + } + catch (BrokenCircuitException) + { + Console.WriteLine("Operation failed too many times please try again later."); + } + } + #endregion } public static void AntiPattern_CircuitAwareRetry() diff --git a/src/Snippets/Docs/RateLimiter.cs b/src/Snippets/Docs/RateLimiter.cs index d16a5e74f8..7a5fe55ccf 100644 --- a/src/Snippets/Docs/RateLimiter.cs +++ b/src/Snippets/Docs/RateLimiter.cs @@ -97,7 +97,7 @@ public static void Usage() public static async Task HandleRejection() { var query = "dummy"; - #region rate-limiter-handling-failure + #region rate-limiter-with-onrejected var withOnRejected = new ResiliencePipelineBuilder() .AddRateLimiter(new RateLimiterStrategyOptions { @@ -111,7 +111,9 @@ public static async Task HandleRejection() return default; } }).Build(); + #endregion + #region rate-limiter-without-onrejected var withoutOnRejected = new ResiliencePipelineBuilder() .AddRateLimiter(new RateLimiterStrategyOptions { diff --git a/src/Snippets/Docs/Timeout.cs b/src/Snippets/Docs/Timeout.cs index a15d3805bc..91f5ca3741 100644 --- a/src/Snippets/Docs/Timeout.cs +++ b/src/Snippets/Docs/Timeout.cs @@ -70,7 +70,7 @@ public static async Task Usage() public static async Task HandleTimeout() { static ValueTask UserDelegate(CancellationToken ct) => ValueTask.CompletedTask; - #region timeout-handling-failure + #region timeout-with-ontimeout var withOnTimeout = new ResiliencePipelineBuilder() .AddTimeout(new TimeoutStrategyOptions { @@ -81,7 +81,9 @@ public static async Task HandleTimeout() return default; } }).Build(); + #endregion + #region timeout-without-ontimeout var withoutOnTimeout = new ResiliencePipelineBuilder() .AddTimeout(new TimeoutStrategyOptions {