-
-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
index.md
380 lines (307 loc) · 12.3 KB
/
index.md
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
# Resilience pipelines
The `ResiliencePipeline` allows executing arbitrary user-provided callbacks. It is a combination of one or more resilience strategies.
## Usage
The `ResiliencePipeline` allow executing various synchronous and asynchronous user-provided callbacks as seen in the examples below:
<!-- snippet: resilience-pipeline-usage -->
```cs
// Creating a new resilience pipeline
ResiliencePipeline pipeline = new ResiliencePipelineBuilder()
.AddConcurrencyLimiter(100)
.Build();
// Executing an asynchronous void callback
await pipeline.ExecuteAsync(
async token => await MyMethodAsync(token),
cancellationToken);
// Executing a synchronous void callback
pipeline.Execute(() => MyMethod());
// Executing an asynchronous callback that returns a value
await pipeline.ExecuteAsync(
async token => await httpClient.GetAsync(endpoint, token),
cancellationToken);
// Executing an asynchronous callback without allocating a lambda
await pipeline.ExecuteAsync(
static async (state, token) => await state.httpClient.GetAsync(state.endpoint, token),
(httpClient, endpoint), // State provided here
cancellationToken);
// Executing an asynchronous callback and passing custom data
// 1. Retrieve a context from the shared pool
ResilienceContext context = ResilienceContextPool.Shared.Get(cancellationToken);
// 2. Add custom data to the context
context.Properties.Set(new ResiliencePropertyKey<string>("my-custom-data"), "my-custom-data");
// 3. Execute the callback
await pipeline.ExecuteAsync(static async context =>
{
// Retrieve custom data from the context
var customData = context.Properties.GetValue(
new ResiliencePropertyKey<string>("my-custom-data"),
"default-value");
Console.WriteLine("Custom Data: {0}", customData);
await MyMethodAsync(context.CancellationToken);
},
context);
// 4. Optionally, return the context to the shared pool
ResilienceContextPool.Shared.Return(context);
```
<!-- endSnippet -->
The above samples demonstrate how to use the resilience pipeline within the same scope. Additionally, consider the following:
- Separate the resilience pipeline's definition from its usage. Inject pipelines into the code that will consume them. This [facilitates various unit-testing scenarios](https://github.com/App-vNext/Polly/wiki/Unit-testing-with-Polly---with-examples).
- If your application uses Polly in multiple locations, define all pipelines at startup using [`ResiliencePipelineRegistry`](/docs/resilience-pipeline-registry.md) or using the `AddResiliencePipeline` extension. This is a common approach in .NET Core applications. For example, you could create your own extension method on `IServiceCollection` to configure pipelines consumed elsewhere in your application.
<!-- snippet: resilience-pipeline-di-usage -->
```cs
public static void ConfigureMyPipelines(IServiceCollection services)
{
services.AddResiliencePipeline("pipeline-A", builder => builder.AddConcurrencyLimiter(100));
services.AddResiliencePipeline("pipeline-B", builder => builder.AddRetry(new()));
// Later, resolve the pipeline by name using ResiliencePipelineProvider<string> or ResiliencePipelineRegistry<string>
var pipelineProvider = services.BuildServiceProvider().GetRequiredService<ResiliencePipelineProvider<string>>();
pipelineProvider.GetPipeline("pipeline-A").Execute(() => { });
}
```
<!-- endSnippet -->
## Empty resilience pipeline
The empty resilience pipeline is a special construct that lacks any resilience strategies. You can access it through the following ways:
- `ResiliencePipeline.Empty`
- `ResiliencePipeline<T>.Empty`
This is particularly useful in test scenarios where implementing resilience strategies could slow down the test execution or over-complicate test setup.
## Retrieving execution results with `Outcome<T>`
The `ResiliencePipeline` class provides the `ExecuteOutcomeAsync(...)` method, which is designed to never throw exceptions. Instead, it stores either the result or the exception within an `Outcome<T>` struct.
<!-- snippet: resilience-pipeline-outcome -->
```cs
// Acquire a ResilienceContext from the pool
ResilienceContext context = ResilienceContextPool.Shared.Get();
// Execute the pipeline and store the result in an Outcome<bool>
Outcome<bool> outcome = await pipeline.ExecuteOutcomeAsync(
static async (context, state) =>
{
Console.WriteLine("State: {0}", state);
try
{
await MyMethodAsync(context.CancellationToken);
// Use static utility methods from Outcome to easily create an Outcome<T> instance
return Outcome.FromResult(true);
}
catch (Exception e)
{
// Create an Outcome<T> instance that holds the exception
return Outcome.FromException<bool>(e);
}
},
context,
"my-state");
// Return the acquired ResilienceContext to the pool
ResilienceContextPool.Shared.Return(context);
// Evaluate the outcome
if (outcome.Exception is not null)
{
Console.WriteLine("Execution Failed: {0}", outcome.Exception.Message);
}
else
{
Console.WriteLine("Execution Result: {0}", outcome.Result);
}
```
<!-- endSnippet -->
Use `ExecuteOutcomeAsync(...)` in high-performance scenarios where you wish to avoid re-throwing exceptions. Keep in mind that Polly's resilience strategies also make use of the `Outcome` struct to prevent unnecessary exception throwing.
### Context vs State
In the previous example the `ExecuteOutcomeAsync` was called with `"my-state"` state object. You might wonder what's the point of the `state`, or can't we just use the `context`?
The `state` object was introduced to be able to pass a parameter to the user callback without using a [closure](https://stackoverflow.com/a/428624/1064169).
- It allows you to access any object of the `ExecuteOutcomeAsync`'s caller method without any extra memory allocation
- It also enables you to use static anonymous methods
So, it is a performance optimization tool. Of course you can pass more complex object than just a simple string like `(instance: this, request)`.
While the `state` object is accessible only inside the user callback, you can use the `context` in many places.
For example in case of Retry the `context` is accessible:
- inside the `ShouldHandle` delegate;
- inside the `OnRetry` delegate;
- inside the `DelayGenerator` delegate;
- through the `Outcome` property.
As a rule of thumb:
- Use the `state` object to pass a parameter to your decorated method;
- Use the `context` object to exchange information between delegates of an instance of `XYZOptions` or between invocation attempts (in the case of retry or hedging strategies).
## Diagrams
### Sequence diagram for a pipeline with retry and timeout
Let's create the following pipeline:
- the inner strategy is a timeout,
- the outer is a retry which is timeout-aware.
<!-- snippet: resilience-pipeline-diagram-retry-timeout -->
```cs
ResiliencePipeline pipeline = new ResiliencePipelineBuilder()
.AddRetry(new() { ShouldHandle = new PredicateBuilder().Handle<TimeoutRejectedException>() }) // outer
.AddTimeout(TimeSpan.FromSeconds(1)) // inner
.Build();
```
<!-- endSnippet -->
Let's suppose that the first request takes too long but the second is fast enough.
```mermaid
sequenceDiagram
autonumber
actor C as Caller
participant P as Pipeline
participant R as Retry
participant T as Timeout
participant D as DecoratedUserCallback
C->>P: Calls ExecuteAsync
P->>R: Calls ExecuteCore
R->>T: Calls ExecuteCore
Note over R, D: Initial attempt
Note over T: Wait start
activate T
T->>D: Invokes
activate D
D-->>D: Performs <br/>long-running <br/>operation
Note over T: Wait end
deactivate T
T-->>T: Times out
T->>D: Propagates cancellation
D-->>D: Cancellation of callback
D->>T: Cancellation finished
deactivate D
T->>R: Throws <br/>TimeoutRejectedException
R-->>R: Sleeps
Note over R, D: First retry attempt
R->>T: Calls ExecuteCore
Note over T: Wait start
activate T
T->>D: Invokes
activate D
D-->>D: Performs <br/>long-running <br/>operation
D->>T: Returns result
deactivate D
deactivate T
Note over T: Wait end
T->>R: Returns result
R->>P: Returns result
P->>C: Returns result
```
### Sequence diagram for a pipeline with timeout and retry
Let's create the following pipeline:
- the inner strategy is a retry,
- the outer is a timeout which is overarching all retry attempts.
<!-- snippet: resilience-pipeline-diagram-timeout-retry -->
```cs
ResiliencePipeline pipeline = new ResiliencePipelineBuilder()
.AddTimeout(TimeSpan.FromSeconds(10)) // outer
.AddRetry(new()) // inner
.Build();
```
<!-- endSnippet -->
Let's suppose that the first and the second requests are failing. The third request is not awaited since the overarching timeout elapsed.
```mermaid
sequenceDiagram
autonumber
actor C as Caller
participant P as Pipeline
participant T as Timeout
participant R as Retry
participant D as DecoratedUserCallback
C->>P: Calls ExecuteAsync
P->>T: Calls ExecuteCore
Note over T: Wait start
activate T
T->>R: Calls ExecuteCore
Note over R, D: Initial attempt
R->>D: Invokes
activate D
D-->>D: Performs <br/>operation
D->>R: Fails
deactivate D
R-->>R: Sleeps
Note over R, D: First retry attempt
R->>D: Invokes
activate D
D-->>D: Performs <br/>operation
D->>R: Fails
deactivate D
R-->>R: Sleeps
Note over R, D: Second retry attempt
R->>D: Invokes
activate D
D-->>D: Performs <br/>operation
deactivate T
Note over T: Wait end
T-->>T: Times out
T->>R: Propagates cancellation
R->>D: Propagates cancellation
D-->>D: Cancellation of callback
D->>T: Cancellation finished
deactivate D
T->>P: Throws <br/>TimeoutRejectedException
P->>C: Propagates exception
```
### Sequence diagram for a pipeline with timeout, retry and timeout
Let's create the following pipeline:
- the inner most strategy is a timeout (per attempt),
- the middle one is a retry which is timeout-aware,
- the outer most is a timeout which is overarching all retry attempts.
<!-- snippet: resilience-pipeline-diagram-timeout-retry-timeout -->
```cs
ResiliencePipeline pipeline = new ResiliencePipelineBuilder()
.AddTimeout(TimeSpan.FromSeconds(10)) // outer most
.AddRetry(new() { ShouldHandle = new PredicateBuilder().Handle<TimeoutRejectedException>() })
.AddTimeout(TimeSpan.FromSeconds(1)) // inner most
.Build();
```
<!-- endSnippet -->
Let's suppose that the first request fails and the second takes too long. The third request is not awaited since the overarching timeout elapsed.
```mermaid
sequenceDiagram
autonumber
actor C as Caller
participant P as Pipeline
participant TO as TimeoutOuter
participant R as Retry
participant TI as TimeoutInner
participant D as DecoratedUserCallback
C->>P: Calls ExecuteAsync
P->>TO: Calls ExecuteCore
Note over TO: Wait start
activate TO
TO->>R: Calls ExecuteCore
Note over R, D: Initial attempt
R->>TI: Calls ExecuteCore
Note over TI: Wait start
activate TI
TI->>D: Invokes
activate D
D-->>D: Performs <br/>operation
D->>TI: Fails
deactivate D
deactivate TI
Note over TI: Wait end
TI->>R: Propagate failure
R-->>R: Sleeps
Note over R, D: First retry attempt
R->>TI: Calls ExecuteCore
Note over TI: Wait start
activate TI
TI->>D: Invokes
activate D
D-->>D: Performs <br/>operation
TI-->>TI: Times-out
deactivate TI
Note over TI: Wait end
TI->>D: Propagates cancellation
D-->>D: Cancellation of callback
D->>TI: Cancellation finished
deactivate D
TI->>R: Throws <br/>TimeoutRejectedException
R->>R: Sleeps
Note over R, D: Second retry attempt
R->>TI: Calls ExecuteCore
Note over TI: Wait start
activate TI
TI->>D: Invokes
activate D
D-->>D: Performs <br/>operation
TO-->>TO: Times-out
deactivate TO
Note over TO: Wait end
TO->>R: Propagates cancellation
R->>TI: Propagates cancellation
TI->>D: Propagates cancellation
D-->>D: Cancellation of callback
D->>TO: Cancellation finished
deactivate TI
deactivate D
TO->>P: Throws <br/>TimeoutRejectedException
P->>C: Propagates exception
```