| | | 1 | | using Microsoft.Extensions.Logging; |
| | | 2 | | using Microsoft.Extensions.Options; |
| | | 3 | | using StackExchange.Redis; |
| | | 4 | | using System.Runtime.CompilerServices; |
| | | 5 | | using System.Text.Json; |
| | | 6 | | |
| | | 7 | | namespace AsyncResponse.Channels.Redis; |
| | | 8 | | |
| | | 9 | | /// <summary> |
| | | 10 | | /// Redis-backed implementation of <see cref="IRecoveryStateStore"/>. |
| | | 11 | | /// </summary> |
| | | 12 | | internal sealed class RedisRecoveryStateStore : IRecoveryStateStore, IRecoveryStateScanner |
| | | 13 | | { |
| | | 14 | | private readonly IConnectionMultiplexer _multiplexer; |
| | | 15 | | private readonly IDatabase _database; |
| | | 16 | | private readonly RedisKeySchema _keys; |
| | | 17 | | private readonly ILogger<RedisRecoveryStateStore> _logger; |
| | | 18 | | |
| | | 19 | | /// <summary>Creates a Redis-backed recovery state store.</summary> |
| | 3 | 20 | | public RedisRecoveryStateStore( |
| | 3 | 21 | | IConnectionMultiplexer multiplexer, |
| | 3 | 22 | | IOptions<RedisAsyncResponseOptions> options, |
| | 3 | 23 | | ILogger<RedisRecoveryStateStore> logger) |
| | | 24 | | { |
| | 3 | 25 | | _multiplexer = multiplexer; |
| | 3 | 26 | | _database = multiplexer.GetDatabase(); |
| | 3 | 27 | | _keys = new RedisKeySchema(options.Value.KeyPrefix); |
| | 3 | 28 | | _logger = logger; |
| | 3 | 29 | | } |
| | | 30 | | |
| | | 31 | | /// <inheritdoc /> |
| | | 32 | | public async Task SaveAsync( |
| | | 33 | | string correlationId, |
| | | 34 | | RecoveryState state, |
| | | 35 | | TimeSpan ttl, |
| | | 36 | | CancellationToken cancellationToken = default) |
| | | 37 | | { |
| | 3 | 38 | | ArgumentException.ThrowIfNullOrWhiteSpace(correlationId); |
| | 3 | 39 | | ArgumentNullException.ThrowIfNull(state); |
| | 3 | 40 | | if (ttl <= TimeSpan.Zero) |
| | 3 | 41 | | throw new ArgumentOutOfRangeException(nameof(ttl), "TTL must be greater than zero."); |
| | 3 | 42 | | if (!string.Equals(state.CorrelationId, correlationId, StringComparison.Ordinal)) |
| | 3 | 43 | | throw new ArgumentException("The recovery-state correlation id must match the store key.", nameof(state)); |
| | 3 | 44 | | if (state.SchemaVersion != RecoveryStateSchema.Current) |
| | 3 | 45 | | throw new ArgumentException("The recovery state must use the current schema version.", nameof(state)); |
| | | 46 | | |
| | 3 | 47 | | cancellationToken.ThrowIfCancellationRequested(); |
| | 3 | 48 | | if (state.RegistrationId == Guid.Empty) |
| | 3 | 49 | | state.RegistrationId = Guid.NewGuid(); |
| | | 50 | | |
| | 3 | 51 | | var recoveryKey = _keys.RecoveryKey(correlationId); |
| | | 52 | | |
| | | 53 | | // Optimistic read-modify-write: two waiters registering the same correlation id |
| | | 54 | | // concurrently must both survive, so each write commits only while the stored value is |
| | | 55 | | // still the one we read (transaction condition), retrying on a conflict. |
| | 3 | 56 | | for (var attempt = 0; attempt < MaxCasAttempts; attempt++) |
| | | 57 | | { |
| | 3 | 58 | | cancellationToken.ThrowIfCancellationRequested(); |
| | | 59 | | |
| | 3 | 60 | | var previous = await _database.StringGetAsync(recoveryKey).ConfigureAwait(false); |
| | 3 | 61 | | var states = previous.IsNullOrEmpty |
| | 3 | 62 | | ? [] |
| | 3 | 63 | | : DeserializeStates(previous, recoveryKey, correlationId, logAsError: true); |
| | 3 | 64 | | states.RemoveAll(existing => existing.RegistrationId == state.RegistrationId); |
| | 3 | 65 | | states.Add(state); |
| | | 66 | | |
| | 3 | 67 | | var transaction = _database.CreateTransaction(); |
| | 3 | 68 | | transaction.AddCondition(previous.IsNull |
| | 3 | 69 | | ? Condition.KeyNotExists(recoveryKey) |
| | 3 | 70 | | : Condition.StringEqual(recoveryKey, previous)); |
| | 3 | 71 | | _ = transaction.StringSetAsync(recoveryKey, AsyncResponseJson.Serialize(states), ttl); |
| | 3 | 72 | | if (await transaction.ExecuteAsync().ConfigureAwait(false)) |
| | 3 | 73 | | return; |
| | | 74 | | } |
| | | 75 | | |
| | 3 | 76 | | throw new InvalidOperationException( |
| | 3 | 77 | | $"Recovery-state save for correlationId '{correlationId}' could not commit after {MaxCasAttempts} optimistic |
| | 3 | 78 | | } |
| | | 79 | | |
| | | 80 | | /// <inheritdoc /> |
| | | 81 | | public async Task<IReadOnlyList<RecoveryState>> GetAllAsync(string correlationId, CancellationToken cancellationToke |
| | | 82 | | { |
| | 3 | 83 | | ArgumentException.ThrowIfNullOrWhiteSpace(correlationId); |
| | 3 | 84 | | cancellationToken.ThrowIfCancellationRequested(); |
| | | 85 | | |
| | 3 | 86 | | var recoveryKey = _keys.RecoveryKey(correlationId); |
| | 3 | 87 | | return await LoadStatesAsync(recoveryKey, correlationId).ConfigureAwait(false); |
| | 3 | 88 | | } |
| | | 89 | | |
| | | 90 | | /// <inheritdoc /> |
| | | 91 | | public async Task<bool> TryDeleteAsync(string correlationId, Guid registrationId, CancellationToken cancellationToke |
| | | 92 | | { |
| | 3 | 93 | | ArgumentException.ThrowIfNullOrWhiteSpace(correlationId); |
| | 3 | 94 | | if (registrationId == Guid.Empty) |
| | 3 | 95 | | throw new ArgumentException("Registration id cannot be empty.", nameof(registrationId)); |
| | 3 | 96 | | cancellationToken.ThrowIfCancellationRequested(); |
| | | 97 | | |
| | 3 | 98 | | var recoveryKey = _keys.RecoveryKey(correlationId); |
| | | 99 | | |
| | | 100 | | // Optimistic removal: deleting one registration must not clobber a registration that a |
| | | 101 | | // concurrent writer appended between our read and our write. |
| | 3 | 102 | | for (var attempt = 0; attempt < MaxCasAttempts; attempt++) |
| | | 103 | | { |
| | 3 | 104 | | cancellationToken.ThrowIfCancellationRequested(); |
| | | 105 | | |
| | 3 | 106 | | var previous = await _database.StringGetAsync(recoveryKey).ConfigureAwait(false); |
| | 3 | 107 | | if (previous.IsNullOrEmpty) |
| | 3 | 108 | | return false; |
| | | 109 | | |
| | 3 | 110 | | var states = DeserializeStates(previous, recoveryKey, correlationId, logAsError: true); |
| | 3 | 111 | | var removed = states.RemoveAll(state => state.RegistrationId == registrationId) > 0; |
| | 3 | 112 | | if (!removed) |
| | 3 | 113 | | return false; |
| | | 114 | | |
| | 3 | 115 | | var transaction = _database.CreateTransaction(); |
| | 3 | 116 | | transaction.AddCondition(Condition.StringEqual(recoveryKey, previous)); |
| | 3 | 117 | | if (states.Count == 0) |
| | 3 | 118 | | _ = transaction.KeyDeleteAsync(recoveryKey); |
| | | 119 | | else |
| | 3 | 120 | | _ = transaction.StringSetAsync(recoveryKey, AsyncResponseJson.Serialize(states), Expiration.KeepTtl, Val |
| | 3 | 121 | | if (await transaction.ExecuteAsync().ConfigureAwait(false)) |
| | 3 | 122 | | return true; |
| | | 123 | | } |
| | | 124 | | |
| | | 125 | | // Leave the registration for expiry rather than risking a lost concurrent registration |
| | | 126 | | // with an unconditional rewrite; the caller treats false as "nothing deleted". |
| | 3 | 127 | | _logger.LogWarning( |
| | 3 | 128 | | "Recovery-state delete for correlationId {CorrelationId} registration {RegistrationId} exhausted {Attempts} |
| | 3 | 129 | | correlationId, registrationId, MaxCasAttempts); |
| | 2 | 130 | | return false; |
| | 3 | 131 | | } |
| | | 132 | | |
| | | 133 | | /// <inheritdoc /> |
| | | 134 | | public async IAsyncEnumerable<RecoveryState> ScanAsync([EnumeratorCancellation] CancellationToken cancellationToken |
| | | 135 | | { |
| | 3 | 136 | | var connectedServers = _multiplexer.GetEndPoints() |
| | 3 | 137 | | .Select(endPoint => _multiplexer.GetServer(endPoint)) |
| | 3 | 138 | | .Where(server => server.IsConnected) |
| | 3 | 139 | | .ToList(); |
| | | 140 | | |
| | 3 | 141 | | var seenKeys = new HashSet<string>(StringComparer.Ordinal); |
| | | 142 | | |
| | 3 | 143 | | foreach (var server in connectedServers) |
| | | 144 | | { |
| | 3 | 145 | | foreach (var key in server.Keys(pattern: _keys.RecoveryKeyPattern, pageSize: 250)) |
| | | 146 | | { |
| | 3 | 147 | | cancellationToken.ThrowIfCancellationRequested(); |
| | | 148 | | |
| | 3 | 149 | | var recoveryKey = key.ToString(); |
| | 3 | 150 | | if (!seenKeys.Add(recoveryKey)) |
| | | 151 | | continue; |
| | | 152 | | |
| | 3 | 153 | | var value = await _database.StringGetAsync(recoveryKey).ConfigureAwait(false); |
| | 3 | 154 | | if (value.IsNullOrEmpty) |
| | | 155 | | continue; |
| | | 156 | | |
| | 3 | 157 | | var correlationId = _keys.CorrelationIdFromRecoveryKey(recoveryKey); |
| | 3 | 158 | | foreach (var state in DeserializeStates(value, recoveryKey, correlationId, logAsError: false)) |
| | 3 | 159 | | yield return state; |
| | 3 | 160 | | } |
| | | 161 | | } |
| | 3 | 162 | | } |
| | | 163 | | |
| | | 164 | | private const int MaxCasAttempts = 4; |
| | | 165 | | |
| | | 166 | | private async Task<List<RecoveryState>> LoadStatesAsync(string recoveryKey, string correlationId) |
| | | 167 | | { |
| | 3 | 168 | | var value = await _database.StringGetAsync(recoveryKey).ConfigureAwait(false); |
| | 3 | 169 | | return value.IsNullOrEmpty |
| | 3 | 170 | | ? [] |
| | 3 | 171 | | : DeserializeStates(value, recoveryKey, correlationId, logAsError: true); |
| | 3 | 172 | | } |
| | | 173 | | |
| | | 174 | | private List<RecoveryState> DeserializeStates(RedisValue value, string recoveryKey, string correlationId, bool logAs |
| | | 175 | | { |
| | | 176 | | try |
| | | 177 | | { |
| | 3 | 178 | | var states = AsyncResponseJson.Deserialize<List<RecoveryState>>(value.ToString()) ?? []; |
| | | 179 | | |
| | 3 | 180 | | for (var i = states.Count - 1; i >= 0; i--) |
| | | 181 | | { |
| | 3 | 182 | | var state = states[i]; |
| | 3 | 183 | | if (state is null || state.RegistrationId == Guid.Empty) |
| | | 184 | | { |
| | 3 | 185 | | _logger.LogWarning( |
| | 3 | 186 | | "Recovery state at {RecoveryKey} has no registration id; rejecting it because it cannot be delet |
| | 3 | 187 | | recoveryKey); |
| | 2 | 188 | | states.RemoveAt(i); |
| | 3 | 189 | | continue; |
| | | 190 | | } |
| | | 191 | | |
| | 3 | 192 | | if (!RecoveryStateSchema.IsReadable(state.SchemaVersion)) |
| | | 193 | | { |
| | 3 | 194 | | _logger.LogWarning( |
| | 3 | 195 | | "Recovery state at {RecoveryKey} has unsupported schema version {SchemaVersion} (current: {Curre |
| | 3 | 196 | | recoveryKey, state.SchemaVersion, RecoveryStateSchema.Current); |
| | 2 | 197 | | states.RemoveAt(i); |
| | 3 | 198 | | continue; |
| | | 199 | | } |
| | | 200 | | |
| | 3 | 201 | | if (!string.Equals(state.CorrelationId, correlationId, StringComparison.Ordinal)) |
| | | 202 | | { |
| | 3 | 203 | | _logger.LogWarning( |
| | 3 | 204 | | "Recovery state at {RecoveryKey} has correlationId {StoredCorrelationId}, expected {CorrelationI |
| | 3 | 205 | | recoveryKey, state.CorrelationId, correlationId); |
| | 3 | 206 | | states.RemoveAt(i); |
| | | 207 | | } |
| | | 208 | | } |
| | | 209 | | |
| | 3 | 210 | | return states; |
| | | 211 | | } |
| | 3 | 212 | | catch (JsonException ex) |
| | | 213 | | { |
| | 3 | 214 | | if (logAsError) |
| | 2 | 215 | | _logger.LogError(ex, "Failed to deserialize recovery state at {RecoveryKey}.", recoveryKey); |
| | | 216 | | else |
| | 2 | 217 | | _logger.LogWarning(ex, "Unreadable recovery state at {RecoveryKey}; skipping.", recoveryKey); |
| | 3 | 218 | | return []; |
| | | 219 | | } |
| | 3 | 220 | | } |
| | | 221 | | |
| | | 222 | | } |