|
| 1 | +using System; |
| 2 | +using System.Diagnostics; |
| 3 | +using System.Threading; |
| 4 | +using System.Threading.Tasks; |
| 5 | +using Xunit; |
| 6 | +using Xunit.Abstractions; |
| 7 | + |
| 8 | +namespace StackExchange.Redis.Tests; |
| 9 | + |
| 10 | +#if !NET6_0_OR_GREATER |
| 11 | +internal static class TaskExtensions |
| 12 | +{ |
| 13 | + // suboptimal polyfill version of the .NET 6+ API; I'm not recommending this for production use, |
| 14 | + // but it's good enough for tests |
| 15 | + public static Task<T> WaitAsync<T>(this Task<T> task, CancellationToken cancellationToken) |
| 16 | + { |
| 17 | + if (task.IsCompleted || !cancellationToken.CanBeCanceled) return task; |
| 18 | + return Wrap(task, cancellationToken); |
| 19 | + |
| 20 | + static async Task<T> Wrap(Task<T> task, CancellationToken cancellationToken) |
| 21 | + { |
| 22 | + var tcs = new TaskCompletionSource<T>(); |
| 23 | + using var reg = cancellationToken.Register(() => tcs.TrySetCanceled(cancellationToken)); |
| 24 | + _ = task.ContinueWith(t => |
| 25 | + { |
| 26 | + if (t.IsCanceled) tcs.TrySetCanceled(); |
| 27 | + else if (t.IsFaulted) tcs.TrySetException(t.Exception!); |
| 28 | + else tcs.TrySetResult(t.Result); |
| 29 | + }); |
| 30 | + return await tcs.Task; |
| 31 | + } |
| 32 | + } |
| 33 | + |
| 34 | + public static Task<T> WaitAsync<T>(this Task<T> task, TimeSpan timeout) |
| 35 | + { |
| 36 | + if (task.IsCompleted) return task; |
| 37 | + return Wrap(task, timeout); |
| 38 | + |
| 39 | + static async Task<T> Wrap(Task<T> task, TimeSpan timeout) |
| 40 | + { |
| 41 | + Task other = Task.Delay(timeout); |
| 42 | + var first = await Task.WhenAny(task, other); |
| 43 | + if (ReferenceEquals(first, other)) |
| 44 | + { |
| 45 | + throw new TimeoutException(); |
| 46 | + } |
| 47 | + return await task; |
| 48 | + } |
| 49 | + } |
| 50 | +} |
| 51 | +#endif |
| 52 | + |
| 53 | +[Collection(SharedConnectionFixture.Key)] |
| 54 | +public class CancellationTests : TestBase |
| 55 | +{ |
| 56 | + public CancellationTests(ITestOutputHelper output, SharedConnectionFixture fixture) : base(output, fixture) { } |
| 57 | + |
| 58 | + [Fact] |
| 59 | + public async Task WithCancellation_CancelledToken_ThrowsOperationCanceledException() |
| 60 | + { |
| 61 | + using var conn = Create(); |
| 62 | + var db = conn.GetDatabase(); |
| 63 | + |
| 64 | + using var cts = new CancellationTokenSource(); |
| 65 | + cts.Cancel(); // Cancel immediately |
| 66 | + |
| 67 | + await Assert.ThrowsAnyAsync<OperationCanceledException>(async () => |
| 68 | + { |
| 69 | + await db.StringSetAsync(Me(), "value").WaitAsync(cts.Token); |
| 70 | + }); |
| 71 | + } |
| 72 | + |
| 73 | + private IInternalConnectionMultiplexer Create() => Create(syncTimeout: 10_000); |
| 74 | + |
| 75 | + [Fact] |
| 76 | + public async Task WithCancellation_ValidToken_OperationSucceeds() |
| 77 | + { |
| 78 | + using var conn = Create(); |
| 79 | + var db = conn.GetDatabase(); |
| 80 | + |
| 81 | + using var cts = new CancellationTokenSource(); |
| 82 | + |
| 83 | + RedisKey key = Me(); |
| 84 | + // This should succeed |
| 85 | + await db.StringSetAsync(key, "value"); |
| 86 | + var result = await db.StringGetAsync(key).WaitAsync(cts.Token); |
| 87 | + Assert.Equal("value", result); |
| 88 | + } |
| 89 | + |
| 90 | + private void Pause(IDatabase db) |
| 91 | + { |
| 92 | + db.Execute("client", new object[] { "pause", ConnectionPauseMilliseconds }, CommandFlags.FireAndForget); |
| 93 | + } |
| 94 | + |
| 95 | + [Fact] |
| 96 | + public async Task WithTimeout_ShortTimeout_Async_ThrowsOperationCanceledException() |
| 97 | + { |
| 98 | + using var conn = Create(); |
| 99 | + var db = conn.GetDatabase(); |
| 100 | + |
| 101 | + var watch = Stopwatch.StartNew(); |
| 102 | + Pause(db); |
| 103 | + |
| 104 | + var timeout = TimeSpan.FromMilliseconds(ShortDelayMilliseconds); |
| 105 | + // This might throw due to timeout, but let's test the mechanism |
| 106 | + var pending = db.StringSetAsync(Me(), "value").WaitAsync(timeout); // check we get past this |
| 107 | + try |
| 108 | + { |
| 109 | + await pending; |
| 110 | + // If it succeeds, that's fine too - Redis is fast |
| 111 | + Assert.Fail(ExpectedCancel + ": " + watch.ElapsedMilliseconds + "ms"); |
| 112 | + } |
| 113 | + catch (TimeoutException) |
| 114 | + { |
| 115 | + // Expected for very short timeouts |
| 116 | + Log($"Timeout after {watch.ElapsedMilliseconds}ms"); |
| 117 | + } |
| 118 | + } |
| 119 | + |
| 120 | + private const string ExpectedCancel = "This operation should have been cancelled"; |
| 121 | + |
| 122 | + [Fact] |
| 123 | + public async Task WithoutCancellation_OperationsWorkNormally() |
| 124 | + { |
| 125 | + using var conn = Create(); |
| 126 | + var db = conn.GetDatabase(); |
| 127 | + |
| 128 | + // No cancellation - should work normally |
| 129 | + RedisKey key = Me(); |
| 130 | + await db.StringSetAsync(key, "value"); |
| 131 | + var result = await db.StringGetAsync(key); |
| 132 | + Assert.Equal("value", result); |
| 133 | + } |
| 134 | + |
| 135 | + public enum CancelStrategy |
| 136 | + { |
| 137 | + Constructor, |
| 138 | + Method, |
| 139 | + Manual, |
| 140 | + } |
| 141 | + |
| 142 | + private const int ConnectionPauseMilliseconds = 50, ShortDelayMilliseconds = 5; |
| 143 | + |
| 144 | + private static CancellationTokenSource CreateCts(CancelStrategy strategy) |
| 145 | + { |
| 146 | + switch (strategy) |
| 147 | + { |
| 148 | + case CancelStrategy.Constructor: |
| 149 | + return new CancellationTokenSource(TimeSpan.FromMilliseconds(ShortDelayMilliseconds)); |
| 150 | + case CancelStrategy.Method: |
| 151 | + var cts = new CancellationTokenSource(); |
| 152 | + cts.CancelAfter(TimeSpan.FromMilliseconds(ShortDelayMilliseconds)); |
| 153 | + return cts; |
| 154 | + case CancelStrategy.Manual: |
| 155 | + cts = new(); |
| 156 | + _ = Task.Run(async () => |
| 157 | + { |
| 158 | + await Task.Delay(ShortDelayMilliseconds); |
| 159 | + // ReSharper disable once MethodHasAsyncOverload - TFM-dependent |
| 160 | + cts.Cancel(); |
| 161 | + }); |
| 162 | + return cts; |
| 163 | + default: |
| 164 | + throw new ArgumentOutOfRangeException(nameof(strategy)); |
| 165 | + } |
| 166 | + } |
| 167 | + |
| 168 | + [Theory] |
| 169 | + [InlineData(CancelStrategy.Constructor)] |
| 170 | + [InlineData(CancelStrategy.Method)] |
| 171 | + [InlineData(CancelStrategy.Manual)] |
| 172 | + public async Task CancellationDuringOperation_Async_CancelsGracefully(CancelStrategy strategy) |
| 173 | + { |
| 174 | + using var conn = Create(); |
| 175 | + var db = conn.GetDatabase(); |
| 176 | + |
| 177 | + var watch = Stopwatch.StartNew(); |
| 178 | + Pause(db); |
| 179 | + |
| 180 | + // Cancel after a short delay |
| 181 | + using var cts = CreateCts(strategy); |
| 182 | + |
| 183 | + // Start an operation and cancel it mid-flight |
| 184 | + var pending = db.StringSetAsync($"{Me()}:{strategy}", "value").WaitAsync(cts.Token); |
| 185 | + |
| 186 | + try |
| 187 | + { |
| 188 | + await pending; |
| 189 | + Assert.Fail(ExpectedCancel + ": " + watch.ElapsedMilliseconds + "ms"); |
| 190 | + } |
| 191 | + catch (OperationCanceledException oce) |
| 192 | + { |
| 193 | + // Expected if cancellation happens during operation |
| 194 | + Log($"Cancelled after {watch.ElapsedMilliseconds}ms"); |
| 195 | + Assert.Equal(cts.Token, oce.CancellationToken); |
| 196 | + } |
| 197 | + } |
| 198 | +} |
0 commit comments