|
| 1 | +# Ambient Cancellation Support |
| 2 | + |
| 3 | +StackExchange.Redis now supports ambient cancellation using `AsyncLocal<T>` to provide cancellation tokens to Redis operations without expanding the API surface. |
| 4 | + |
| 5 | +## Overview |
| 6 | + |
| 7 | +The ambient cancellation feature allows you to set a cancellation context that applies to all Redis operations within an async scope. This provides a clean way to handle timeouts and cancellation without adding `CancellationToken` parameters to every method. |
| 8 | + |
| 9 | +## Key Features |
| 10 | + |
| 11 | +- **Zero API Surface Impact**: No new parameters added to existing methods |
| 12 | +- **Scoped Cancellation**: Uses `using` statements for proper scope management |
| 13 | +- **Timeout Support**: Can specify timeouts that are converted to cancellation tokens |
| 14 | +- **Composable**: Can combine cancellation tokens with timeouts |
| 15 | +- **Nested Scopes**: Inner scopes override outer scopes |
| 16 | +- **Backward Compatible**: All existing code continues to work unchanged |
| 17 | + |
| 18 | +## Usage |
| 19 | + |
| 20 | +### Basic Cancellation |
| 21 | + |
| 22 | +```csharp |
| 23 | +using var cts = new CancellationTokenSource(); |
| 24 | + |
| 25 | +using (database.WithCancellation(cts.Token)) |
| 26 | +{ |
| 27 | + await database.StringSetAsync("key", "value"); |
| 28 | + var value = await database.StringGetAsync("key"); |
| 29 | + // Both operations use the cancellation token |
| 30 | +} |
| 31 | +``` |
| 32 | + |
| 33 | +### Timeout Support |
| 34 | + |
| 35 | +```csharp |
| 36 | +using (database.WithTimeout(TimeSpan.FromSeconds(5))) |
| 37 | +{ |
| 38 | + await database.StringSetAsync("key", "value"); |
| 39 | + // Operation will be cancelled if it takes longer than 5 seconds |
| 40 | +} |
| 41 | +``` |
| 42 | + |
| 43 | +### Combined Cancellation and Timeout |
| 44 | + |
| 45 | +```csharp |
| 46 | +using var cts = new CancellationTokenSource(); |
| 47 | + |
| 48 | +using (database.WithCancellationAndTimeout(cts.Token, TimeSpan.FromSeconds(10))) |
| 49 | +{ |
| 50 | + await database.StringSetAsync("key", "value"); |
| 51 | + // Operation will be cancelled if either the token is cancelled OR 10 seconds elapse |
| 52 | +} |
| 53 | +``` |
| 54 | + |
| 55 | +### Nested Scopes |
| 56 | + |
| 57 | +```csharp |
| 58 | +using var outerToken = new CancellationTokenSource(); |
| 59 | +using var innerToken = new CancellationTokenSource(); |
| 60 | + |
| 61 | +using (database.WithCancellation(outerToken.Token)) |
| 62 | +{ |
| 63 | + await database.StringSetAsync("key1", "value1"); // Uses outerToken |
| 64 | + |
| 65 | + using (database.WithCancellation(innerToken.Token)) |
| 66 | + { |
| 67 | + await database.StringSetAsync("key2", "value2"); // Uses innerToken |
| 68 | + } |
| 69 | + |
| 70 | + await database.StringSetAsync("key3", "value3"); // Uses outerToken again |
| 71 | +} |
| 72 | +``` |
| 73 | + |
| 74 | +### Pub/Sub Operations |
| 75 | + |
| 76 | +```csharp |
| 77 | +using var cts = new CancellationTokenSource(); |
| 78 | + |
| 79 | +using (subscriber.WithCancellation(cts.Token)) |
| 80 | +{ |
| 81 | + await subscriber.SubscribeAsync("channel", handler); |
| 82 | + await subscriber.PublishAsync("channel", "message"); |
| 83 | + // Both operations use the cancellation token |
| 84 | +} |
| 85 | +``` |
| 86 | + |
| 87 | +## Extension Methods |
| 88 | + |
| 89 | +The functionality is provided through extension methods on `IRedisAsync`: |
| 90 | + |
| 91 | +- `WithCancellation(CancellationToken)` - Sets ambient cancellation token |
| 92 | +- `WithTimeout(TimeSpan)` - Sets ambient timeout (converted to cancellation token) |
| 93 | +- `WithCancellationAndTimeout(CancellationToken, TimeSpan)` - Sets both cancellation and timeout |
| 94 | + |
| 95 | +## Implementation Details |
| 96 | + |
| 97 | +### AsyncLocal Context |
| 98 | + |
| 99 | +The implementation uses `AsyncLocal<T>` to flow the cancellation context through async operations: |
| 100 | + |
| 101 | +```csharp |
| 102 | +private static readonly AsyncLocal<CancellationContext?> _context = new(); |
| 103 | +``` |
| 104 | + |
| 105 | +### Scope Management |
| 106 | + |
| 107 | +Each `WithCancellation` call returns an `IDisposable` that manages the scope: |
| 108 | + |
| 109 | +```csharp |
| 110 | +public static IDisposable WithCancellation(this IRedisAsync redis, CancellationToken cancellationToken) |
| 111 | +{ |
| 112 | + return new CancellationScope(cancellationToken, null); |
| 113 | +} |
| 114 | +``` |
| 115 | + |
| 116 | +### Integration Points |
| 117 | + |
| 118 | +The cancellation token is applied at the core execution level: |
| 119 | + |
| 120 | +1. `RedisBase.ExecuteAsync` retrieves the ambient cancellation token |
| 121 | +2. `ConnectionMultiplexer.ExecuteAsyncImpl` accepts the cancellation token |
| 122 | +3. `TaskResultBox<T>` registers for cancellation and properly handles cancellation |
| 123 | + |
| 124 | +### Timeout Handling |
| 125 | + |
| 126 | +Timeouts are converted to cancellation tokens using `CancellationTokenSource`: |
| 127 | + |
| 128 | +```csharp |
| 129 | +public CancellationToken GetEffectiveToken() |
| 130 | +{ |
| 131 | + if (!Timeout.HasValue) return Token; |
| 132 | + |
| 133 | + var timeoutSource = new CancellationTokenSource(Timeout.Value); |
| 134 | + return Token.CanBeCanceled |
| 135 | + ? CancellationTokenSource.CreateLinkedTokenSource(Token, timeoutSource.Token).Token |
| 136 | + : timeoutSource.Token; |
| 137 | +} |
| 138 | +``` |
| 139 | + |
| 140 | +## Error Handling |
| 141 | + |
| 142 | +When an operation is cancelled, it throws an `OperationCanceledException`: |
| 143 | + |
| 144 | +```csharp |
| 145 | +try |
| 146 | +{ |
| 147 | + using (database.WithCancellation(cancelledToken)) |
| 148 | + { |
| 149 | + await database.StringSetAsync("key", "value"); |
| 150 | + } |
| 151 | +} |
| 152 | +catch (OperationCanceledException) |
| 153 | +{ |
| 154 | + // Handle cancellation |
| 155 | +} |
| 156 | +``` |
| 157 | + |
| 158 | +## Performance Considerations |
| 159 | + |
| 160 | +- **Minimal Overhead**: When no ambient cancellation is set, there's virtually no performance impact |
| 161 | +- **Efficient Scoping**: Uses struct-based scoping to minimize allocations |
| 162 | +- **Proper Cleanup**: Cancellation registrations are properly disposed when operations complete |
| 163 | + |
| 164 | +## Limitations |
| 165 | + |
| 166 | +- **Client-Side Only**: Redis doesn't support server-side cancellation, so cancellation only prevents the client from waiting for a response |
| 167 | +- **In-Flight Operations**: Operations that have already been sent to the server will continue executing on the server even if cancelled on the client |
| 168 | +- **Connection Health**: Cancelled operations don't affect connection health or availability |
| 169 | + |
| 170 | +## Migration |
| 171 | + |
| 172 | +Existing code requires no changes. The ambient cancellation is purely additive: |
| 173 | + |
| 174 | +```csharp |
| 175 | +// This continues to work exactly as before |
| 176 | +await database.StringSetAsync("key", "value"); |
| 177 | + |
| 178 | +// This adds cancellation support |
| 179 | +using (database.WithCancellation(cancellationToken)) |
| 180 | +{ |
| 181 | + await database.StringSetAsync("key", "value"); |
| 182 | +} |
| 183 | +``` |
| 184 | + |
| 185 | +## Best Practices |
| 186 | + |
| 187 | +1. **Use `using` statements** to ensure proper scope cleanup |
| 188 | +2. **Prefer cancellation tokens over timeouts** when possible for better control |
| 189 | +3. **Handle `OperationCanceledException`** appropriately in your application |
| 190 | +4. **Don't rely on cancellation for server-side operation termination** |
| 191 | +5. **Test cancellation scenarios** to ensure your application handles them gracefully |
| 192 | + |
| 193 | +## Examples |
| 194 | + |
| 195 | +See `examples/CancellationExample.cs` for comprehensive usage examples and `tests/StackExchange.Redis.Tests/CancellationTests.cs` for test cases demonstrating the functionality. |
0 commit comments