|
| 1 | +using System; |
| 2 | +using System.Buffers; |
| 3 | +using System.Collections.Generic; |
| 4 | +using System.Linq; |
| 5 | +using System.Net; |
| 6 | +using System.Net.Sockets; |
| 7 | +using System.Threading; |
| 8 | +using System.Threading.Tasks; |
| 9 | +using StackExchange.Redis.Server; |
| 10 | +using Xunit; |
| 11 | + |
| 12 | +namespace StackExchange.Redis.Tests; |
| 13 | + |
| 14 | +public class RetryPolicyUnitTests(ITestOutputHelper log) |
| 15 | +{ |
| 16 | + [Theory] |
| 17 | + [InlineData(FailureMode.Success)] |
| 18 | + [InlineData(FailureMode.ConnectionRefused)] |
| 19 | + [InlineData(FailureMode.SlowNonConnect)] |
| 20 | + [InlineData(FailureMode.NoResponses)] |
| 21 | + [InlineData(FailureMode.GarbageResponses)] |
| 22 | + public async Task RetryPolicyFailureCases(FailureMode failureMode) |
| 23 | + { |
| 24 | + using var server = new NonResponsiveServer(log); |
| 25 | + var options = server.GetClientConfig(withPubSub: false); |
| 26 | + var policy = new CountingRetryPolicy(); |
| 27 | + options.ConnectRetry = 5; |
| 28 | + options.SyncTimeout = options.AsyncTimeout = options.ConnectTimeout = 1_000; |
| 29 | + options.ReconnectRetryPolicy = policy; |
| 30 | + |
| 31 | + // connect while the server is stable |
| 32 | + await using var conn = await ConnectionMultiplexer.ConnectAsync(options); |
| 33 | + var db = conn.GetDatabase(); |
| 34 | + db.Ping(); |
| 35 | + Assert.Equal(0, policy.Clear()); |
| 36 | + |
| 37 | + // now tell the server to become non-responsive to the next 2, and kill the current |
| 38 | + server.FailNext(2, failureMode); |
| 39 | + server.ForAllClients(x => x.Kill()); |
| 40 | + |
| 41 | + for (int i = 0; i < 10; i++) |
| 42 | + { |
| 43 | + try |
| 44 | + { |
| 45 | + await db.PingAsync(); |
| 46 | + break; |
| 47 | + } |
| 48 | + catch (Exception ex) |
| 49 | + { |
| 50 | + log.WriteLine($"{nameof(db.PingAsync)} attempt {i}: {ex.GetType().Name}: {ex.Message}"); |
| 51 | + } |
| 52 | + } |
| 53 | + var counts = policy.GetRetryCounts(); |
| 54 | + if (failureMode is FailureMode.Success) |
| 55 | + { |
| 56 | + Assert.Empty(counts); |
| 57 | + } |
| 58 | + else |
| 59 | + { |
| 60 | + Assert.Equal("0,1", string.Join(",", counts)); |
| 61 | + } |
| 62 | + } |
| 63 | + |
| 64 | + private sealed class CountingRetryPolicy : IReconnectRetryPolicy |
| 65 | + { |
| 66 | + private readonly struct RetryRequest(int currentRetryCount, int timeElapsedMillisecondsSinceLastRetry) |
| 67 | + { |
| 68 | + public int CurrentRetryCount { get; } = currentRetryCount; |
| 69 | + public int TimeElapsedMillisecondsSinceLastRetry { get; } = timeElapsedMillisecondsSinceLastRetry; |
| 70 | + } |
| 71 | + private readonly List<RetryRequest> retryCounts = []; |
| 72 | + |
| 73 | + public int Clear() |
| 74 | + { |
| 75 | + lock (retryCounts) |
| 76 | + { |
| 77 | + int count = retryCounts.Count; |
| 78 | + retryCounts.Clear(); |
| 79 | + return count; |
| 80 | + } |
| 81 | + } |
| 82 | + |
| 83 | + public int[] GetRetryCounts() |
| 84 | + { |
| 85 | + lock (retryCounts) |
| 86 | + { |
| 87 | + return retryCounts.Select(x => x.CurrentRetryCount).ToArray(); |
| 88 | + } |
| 89 | + } |
| 90 | + |
| 91 | + public bool ShouldRetry(long currentRetryCount, int timeElapsedMillisecondsSinceLastRetry) |
| 92 | + { |
| 93 | + lock (retryCounts) |
| 94 | + { |
| 95 | + retryCounts.Add(new(checked((int)currentRetryCount), timeElapsedMillisecondsSinceLastRetry)); |
| 96 | + } |
| 97 | + return true; |
| 98 | + } |
| 99 | + } |
| 100 | + |
| 101 | + public enum FailureMode |
| 102 | + { |
| 103 | + Success, |
| 104 | + SlowNonConnect, |
| 105 | + ConnectionRefused, |
| 106 | + NoResponses, |
| 107 | + GarbageResponses, |
| 108 | + } |
| 109 | + private sealed class NonResponsiveServer(ITestOutputHelper log) : InProcessTestServer(log) |
| 110 | + { |
| 111 | + private int _failNext; |
| 112 | + private FailureMode _failureMode; |
| 113 | + |
| 114 | + public void FailNext(int count, FailureMode failureMode) |
| 115 | + { |
| 116 | + _failNext = count; |
| 117 | + _failureMode = failureMode; |
| 118 | + } |
| 119 | + |
| 120 | + protected override ValueTask OnAcceptClientAsync(EndPoint endpoint) |
| 121 | + { |
| 122 | + switch (_failureMode) |
| 123 | + { |
| 124 | + case FailureMode.SlowNonConnect when ShouldIgnoreClient(): |
| 125 | + Log($"(leaving pending connect to {endpoint})"); |
| 126 | + return TimeoutEventually(); |
| 127 | + case FailureMode.ConnectionRefused when ShouldIgnoreClient(): |
| 128 | + Log($"(rejecting connection to {endpoint})"); |
| 129 | + throw new SocketException((int)SocketError.ConnectionRefused); |
| 130 | + default: |
| 131 | + return base.OnAcceptClientAsync(endpoint); |
| 132 | + } |
| 133 | + |
| 134 | + static async ValueTask TimeoutEventually() |
| 135 | + { |
| 136 | + await Task.Delay(TimeSpan.FromMinutes(5)).ConfigureAwait(false); |
| 137 | + throw new TimeoutException(); |
| 138 | + } |
| 139 | + } |
| 140 | + |
| 141 | + private bool ShouldIgnoreClient() |
| 142 | + { |
| 143 | + while (true) |
| 144 | + { |
| 145 | + var oldValue = Volatile.Read(ref _failNext); |
| 146 | + if (oldValue <= 0) return false; |
| 147 | + var newValue = oldValue - 1; |
| 148 | + if (Interlocked.CompareExchange(ref _failNext, newValue, oldValue) == oldValue) return true; |
| 149 | + } |
| 150 | + } |
| 151 | + |
| 152 | + private sealed class GarbageClient(Node node) : RedisClient(node) |
| 153 | + { |
| 154 | + protected override void WriteResponse( |
| 155 | + IBufferWriter<byte> output, |
| 156 | + TypedRedisValue value, |
| 157 | + RedisProtocol protocol) |
| 158 | + { |
| 159 | +#if NET |
| 160 | + var rand = Random.Shared; |
| 161 | +#else |
| 162 | + var rand = new Random(); |
| 163 | +#endif |
| 164 | + var len = rand.Next(1, 1024); |
| 165 | + var buffer = ArrayPool<byte>.Shared.Rent(len); |
| 166 | + var span = buffer.AsSpan(0, len); |
| 167 | + try |
| 168 | + { |
| 169 | +#if NET |
| 170 | + rand.NextBytes(span); |
| 171 | +#else |
| 172 | + rand.NextBytes(buffer); |
| 173 | +#endif |
| 174 | + output.Write(span); |
| 175 | + } |
| 176 | + finally |
| 177 | + { |
| 178 | + ArrayPool<byte>.Shared.Return(buffer); |
| 179 | + } |
| 180 | + } |
| 181 | + } |
| 182 | + |
| 183 | + public override RedisClient CreateClient(Node node) |
| 184 | + { |
| 185 | + RedisClient client; |
| 186 | + if (_failureMode is FailureMode.GarbageResponses && ShouldIgnoreClient()) |
| 187 | + { |
| 188 | + client = new GarbageClient(node); |
| 189 | + Log($"(accepting garbage-responsive connection to {node.Host}:{node.Port})"); |
| 190 | + return client; |
| 191 | + } |
| 192 | + client = base.CreateClient(node); |
| 193 | + if (_failureMode is FailureMode.NoResponses && ShouldIgnoreClient()) |
| 194 | + { |
| 195 | + Log($"(accepting non-responsive connection to {node.Host}:{node.Port})"); |
| 196 | + client.SkipAllReplies(); |
| 197 | + } |
| 198 | + else |
| 199 | + { |
| 200 | + Log($"(accepting responsive connection to {node.Host}:{node.Port})"); |
| 201 | + } |
| 202 | + return client; |
| 203 | + } |
| 204 | + } |
| 205 | +} |
0 commit comments