| | | 1 | | using System.Collections.Concurrent; |
| | | 2 | | using System.Runtime.CompilerServices; |
| | | 3 | | |
| | | 4 | | namespace AsyncResponse; |
| | | 5 | | |
| | | 6 | | /// <summary> |
| | | 7 | | /// Process-local recovery state store. Useful for the default no-infrastructure setup, tests, |
| | | 8 | | /// and single-process apps. It is intentionally not durable: entries disappear when the process |
| | | 9 | | /// exits. |
| | | 10 | | /// </summary> |
| | | 11 | | internal sealed class InMemoryRecoveryStateStore : IRecoveryStateStore, IRecoveryStateScanner |
| | | 12 | | { |
| | 2 | 13 | | private sealed record Entry(RecoveryState State, DateTime ExpiresAtUtc); |
| | | 14 | | |
| | | 15 | | private readonly ConcurrentDictionary<string, EntryBucket> _entries = new(StringComparer.Ordinal); |
| | | 16 | | |
| | | 17 | | /// <inheritdoc /> |
| | | 18 | | public Task SaveAsync( |
| | | 19 | | string correlationId, |
| | | 20 | | RecoveryState state, |
| | | 21 | | TimeSpan ttl, |
| | | 22 | | CancellationToken cancellationToken = default) |
| | | 23 | | { |
| | | 24 | | ArgumentException.ThrowIfNullOrWhiteSpace(correlationId); |
| | | 25 | | ArgumentNullException.ThrowIfNull(state); |
| | | 26 | | if (ttl <= TimeSpan.Zero) |
| | | 27 | | throw new ArgumentOutOfRangeException(nameof(ttl), "TTL must be greater than zero."); |
| | | 28 | | if (!string.Equals(state.CorrelationId, correlationId, StringComparison.Ordinal)) |
| | | 29 | | throw new ArgumentException("The recovery-state correlation id must match the store key.", nameof(state)); |
| | | 30 | | if (state.SchemaVersion != RecoveryStateSchema.Current) |
| | | 31 | | throw new ArgumentException("The recovery state must use the current schema version.", nameof(state)); |
| | | 32 | | |
| | | 33 | | cancellationToken.ThrowIfCancellationRequested(); |
| | | 34 | | if (state.RegistrationId == Guid.Empty) |
| | | 35 | | state.RegistrationId = Guid.NewGuid(); |
| | | 36 | | |
| | | 37 | | var nowUtc = DateTime.UtcNow; |
| | | 38 | | var entry = new Entry(state, nowUtc.Add(ttl)); |
| | | 39 | | while (true) |
| | | 40 | | { |
| | | 41 | | if (!_entries.TryGetValue(correlationId, out var bucket)) |
| | | 42 | | { |
| | | 43 | | if (_entries.TryAdd(correlationId, EntryBucket.Single(entry))) |
| | | 44 | | return Task.CompletedTask; |
| | | 45 | | |
| | | 46 | | continue; |
| | | 47 | | } |
| | | 48 | | |
| | | 49 | | var next = bucket.PruneExpired(nowUtc).Upsert(entry); |
| | | 50 | | if (_entries.TryUpdate(correlationId, next, bucket)) |
| | | 51 | | return Task.CompletedTask; |
| | | 52 | | } |
| | | 53 | | } |
| | | 54 | | |
| | | 55 | | /// <inheritdoc /> |
| | | 56 | | public Task<IReadOnlyList<RecoveryState>> GetAllAsync(string correlationId, CancellationToken cancellationToken = de |
| | | 57 | | { |
| | | 58 | | ArgumentException.ThrowIfNullOrWhiteSpace(correlationId); |
| | | 59 | | cancellationToken.ThrowIfCancellationRequested(); |
| | | 60 | | |
| | | 61 | | while (_entries.TryGetValue(correlationId, out var bucket)) |
| | | 62 | | { |
| | | 63 | | var pruned = bucket.PruneExpired(DateTime.UtcNow); |
| | | 64 | | if (pruned.IsEmpty) |
| | | 65 | | { |
| | | 66 | | TryRemove(correlationId, bucket); |
| | | 67 | | return Task.FromResult<IReadOnlyList<RecoveryState>>([]); |
| | | 68 | | } |
| | | 69 | | |
| | | 70 | | if (!pruned.Equals(bucket) && !_entries.TryUpdate(correlationId, pruned, bucket)) |
| | | 71 | | continue; |
| | | 72 | | |
| | | 73 | | return Task.FromResult(pruned.ReadableStates()); |
| | | 74 | | } |
| | | 75 | | |
| | | 76 | | return Task.FromResult<IReadOnlyList<RecoveryState>>([]); |
| | | 77 | | } |
| | | 78 | | |
| | | 79 | | /// <inheritdoc /> |
| | | 80 | | public Task<bool> TryDeleteAsync(string correlationId, Guid registrationId, CancellationToken cancellationToken = de |
| | | 81 | | { |
| | | 82 | | ArgumentException.ThrowIfNullOrWhiteSpace(correlationId); |
| | | 83 | | if (registrationId == Guid.Empty) |
| | | 84 | | throw new ArgumentException("Registration id cannot be empty.", nameof(registrationId)); |
| | | 85 | | cancellationToken.ThrowIfCancellationRequested(); |
| | | 86 | | |
| | | 87 | | while (_entries.TryGetValue(correlationId, out var bucket)) |
| | | 88 | | { |
| | | 89 | | var pruned = bucket.PruneExpired(DateTime.UtcNow); |
| | | 90 | | if (pruned.IsEmpty) |
| | | 91 | | { |
| | | 92 | | TryRemove(correlationId, bucket); |
| | | 93 | | return Task.FromResult(false); |
| | | 94 | | } |
| | | 95 | | |
| | | 96 | | var next = pruned.Remove(registrationId, out var removed); |
| | | 97 | | if (!removed) |
| | | 98 | | { |
| | | 99 | | if (!pruned.Equals(bucket) && !_entries.TryUpdate(correlationId, pruned, bucket)) |
| | | 100 | | continue; |
| | | 101 | | |
| | | 102 | | return Task.FromResult(false); |
| | | 103 | | } |
| | | 104 | | |
| | | 105 | | if (next.IsEmpty) |
| | | 106 | | { |
| | | 107 | | if (TryRemove(correlationId, bucket)) |
| | | 108 | | return Task.FromResult(true); |
| | | 109 | | } |
| | | 110 | | else if (_entries.TryUpdate(correlationId, next, bucket)) |
| | | 111 | | { |
| | | 112 | | return Task.FromResult(true); |
| | | 113 | | } |
| | | 114 | | } |
| | | 115 | | |
| | | 116 | | return Task.FromResult(false); |
| | | 117 | | } |
| | | 118 | | |
| | | 119 | | private bool TryRemove(string correlationId, EntryBucket bucket) |
| | | 120 | | => ((ICollection<KeyValuePair<string, EntryBucket>>)_entries) |
| | | 121 | | .Remove(new KeyValuePair<string, EntryBucket>(correlationId, bucket)); |
| | | 122 | | |
| | | 123 | | // Deliberately not a flat ConcurrentDictionary<(correlationId, registrationId), Entry>: the |
| | | 124 | | // hot-path lookup is GetAllAsync(correlationId) — every lost-subscriber dispatch — which needs |
| | | 125 | | // all of one correlation id's registrations in O(1)+small-array, and TTL pruning is per-bucket. |
| | | 126 | | // A flat tuple key would make both O(total entries). The reference-identity Equals below is |
| | | 127 | | // what lets a prune+mutate publish atomically via TryUpdate's compare operand. |
| | | 128 | | private readonly struct EntryBucket : IEquatable<EntryBucket> |
| | | 129 | | { |
| | | 130 | | private readonly Entry? _single; |
| | | 131 | | private readonly Entry[]? _many; |
| | | 132 | | |
| | | 133 | | private EntryBucket(Entry? single, Entry[]? many) |
| | | 134 | | { |
| | | 135 | | _single = single; |
| | | 136 | | _many = many; |
| | | 137 | | } |
| | | 138 | | |
| | | 139 | | public bool IsEmpty => _single is null && _many is null; |
| | | 140 | | public Entry? SingleEntry => _single; |
| | | 141 | | public Entry[]? ManyEntries => _many; |
| | | 142 | | |
| | | 143 | | public static EntryBucket Single(Entry entry) => new(entry, null); |
| | | 144 | | |
| | | 145 | | public EntryBucket Upsert(Entry entry) |
| | | 146 | | { |
| | | 147 | | if (_single is null) |
| | | 148 | | { |
| | | 149 | | if (_many is null) |
| | | 150 | | return Single(entry); |
| | | 151 | | |
| | | 152 | | for (var i = 0; i < _many.Length; i++) |
| | | 153 | | { |
| | | 154 | | if (_many[i].State.RegistrationId != entry.State.RegistrationId) |
| | | 155 | | continue; |
| | | 156 | | |
| | | 157 | | var replaced = (Entry[])_many.Clone(); |
| | | 158 | | replaced[i] = entry; |
| | | 159 | | return new EntryBucket(null, replaced); |
| | | 160 | | } |
| | | 161 | | |
| | | 162 | | var appended = new Entry[_many.Length + 1]; |
| | | 163 | | Array.Copy(_many, appended, _many.Length); |
| | | 164 | | appended[^1] = entry; |
| | | 165 | | return new EntryBucket(null, appended); |
| | | 166 | | } |
| | | 167 | | |
| | | 168 | | if (_single.State.RegistrationId == entry.State.RegistrationId) |
| | | 169 | | return Single(entry); |
| | | 170 | | |
| | | 171 | | return new EntryBucket(null, [_single, entry]); |
| | | 172 | | } |
| | | 173 | | |
| | | 174 | | public EntryBucket PruneExpired(DateTime nowUtc) |
| | | 175 | | { |
| | | 176 | | if (_single is not null) |
| | | 177 | | return _single.ExpiresAtUtc <= nowUtc ? default : this; |
| | | 178 | | |
| | | 179 | | if (_many is null) |
| | | 180 | | return this; |
| | | 181 | | |
| | | 182 | | var liveCount = 0; |
| | | 183 | | Entry? lastLive = null; |
| | | 184 | | foreach (var entry in _many) |
| | | 185 | | { |
| | | 186 | | if (entry.ExpiresAtUtc <= nowUtc) |
| | | 187 | | continue; |
| | | 188 | | |
| | | 189 | | liveCount++; |
| | | 190 | | lastLive = entry; |
| | | 191 | | } |
| | | 192 | | |
| | | 193 | | if (liveCount == _many.Length) |
| | | 194 | | return this; |
| | | 195 | | if (liveCount == 0) |
| | | 196 | | return default; |
| | | 197 | | if (liveCount == 1) |
| | | 198 | | return Single(lastLive!); |
| | | 199 | | |
| | | 200 | | var live = new Entry[liveCount]; |
| | | 201 | | var index = 0; |
| | | 202 | | foreach (var entry in _many) |
| | | 203 | | { |
| | | 204 | | if (entry.ExpiresAtUtc > nowUtc) |
| | | 205 | | live[index++] = entry; |
| | | 206 | | } |
| | | 207 | | |
| | | 208 | | return new EntryBucket(null, live); |
| | | 209 | | } |
| | | 210 | | |
| | | 211 | | public EntryBucket Remove(Guid registrationId, out bool removed) |
| | | 212 | | { |
| | | 213 | | if (_single is not null) |
| | | 214 | | { |
| | | 215 | | removed = _single.State.RegistrationId == registrationId; |
| | | 216 | | return removed ? default : this; |
| | | 217 | | } |
| | | 218 | | |
| | | 219 | | if (_many is null) |
| | | 220 | | { |
| | | 221 | | removed = false; |
| | | 222 | | return this; |
| | | 223 | | } |
| | | 224 | | |
| | | 225 | | var removeIndex = -1; |
| | | 226 | | for (var i = 0; i < _many.Length; i++) |
| | | 227 | | { |
| | | 228 | | if (_many[i].State.RegistrationId == registrationId) |
| | | 229 | | { |
| | | 230 | | removeIndex = i; |
| | | 231 | | break; |
| | | 232 | | } |
| | | 233 | | } |
| | | 234 | | |
| | | 235 | | if (removeIndex < 0) |
| | | 236 | | { |
| | | 237 | | removed = false; |
| | | 238 | | return this; |
| | | 239 | | } |
| | | 240 | | |
| | | 241 | | removed = true; |
| | | 242 | | if (_many.Length == 2) |
| | | 243 | | return Single(_many[removeIndex == 0 ? 1 : 0]); |
| | | 244 | | |
| | | 245 | | var remaining = new Entry[_many.Length - 1]; |
| | | 246 | | if (removeIndex > 0) |
| | | 247 | | Array.Copy(_many, 0, remaining, 0, removeIndex); |
| | | 248 | | if (removeIndex < _many.Length - 1) |
| | | 249 | | Array.Copy(_many, removeIndex + 1, remaining, removeIndex, _many.Length - removeIndex - 1); |
| | | 250 | | |
| | | 251 | | return new EntryBucket(null, remaining); |
| | | 252 | | } |
| | | 253 | | |
| | | 254 | | public IReadOnlyList<RecoveryState> ReadableStates() |
| | | 255 | | { |
| | | 256 | | if (_single is not null) |
| | | 257 | | return RecoveryStateSchema.IsReadable(_single.State.SchemaVersion) ? [_single.State] : []; |
| | | 258 | | |
| | | 259 | | if (_many is null) |
| | | 260 | | return []; |
| | | 261 | | |
| | | 262 | | var readableCount = 0; |
| | | 263 | | foreach (var entry in _many) |
| | | 264 | | { |
| | | 265 | | if (RecoveryStateSchema.IsReadable(entry.State.SchemaVersion)) |
| | | 266 | | readableCount++; |
| | | 267 | | } |
| | | 268 | | |
| | | 269 | | if (readableCount == 0) |
| | | 270 | | return []; |
| | | 271 | | |
| | | 272 | | var states = new RecoveryState[readableCount]; |
| | | 273 | | var index = 0; |
| | | 274 | | foreach (var entry in _many) |
| | | 275 | | { |
| | | 276 | | if (RecoveryStateSchema.IsReadable(entry.State.SchemaVersion)) |
| | | 277 | | states[index++] = entry.State; |
| | | 278 | | } |
| | | 279 | | |
| | | 280 | | return states; |
| | | 281 | | } |
| | | 282 | | |
| | | 283 | | public bool Equals(EntryBucket other) |
| | | 284 | | => ReferenceEquals(_single, other._single) && ReferenceEquals(_many, other._many); |
| | | 285 | | |
| | | 286 | | [System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage] |
| | | 287 | | public override bool Equals(object? obj) |
| | | 288 | | => obj is EntryBucket other && Equals(other); |
| | | 289 | | |
| | | 290 | | [System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage] |
| | | 291 | | public override int GetHashCode() |
| | | 292 | | => HashCode.Combine( |
| | | 293 | | _single is null ? 0 : RuntimeHelpers.GetHashCode(_single), |
| | | 294 | | _many is null ? 0 : RuntimeHelpers.GetHashCode(_many)); |
| | | 295 | | } |
| | | 296 | | |
| | | 297 | | /// <inheritdoc /> |
| | | 298 | | public async IAsyncEnumerable<RecoveryState> ScanAsync([EnumeratorCancellation] CancellationToken cancellationToken |
| | | 299 | | { |
| | | 300 | | await Task.CompletedTask.ConfigureAwait(false); // process-local store: no async I/O to await |
| | | 301 | | |
| | | 302 | | var nowUtc = DateTime.UtcNow; |
| | | 303 | | foreach (var (correlationId, bucket) in _entries) |
| | | 304 | | { |
| | | 305 | | cancellationToken.ThrowIfCancellationRequested(); |
| | | 306 | | |
| | | 307 | | var pruned = bucket.PruneExpired(nowUtc); |
| | | 308 | | if (pruned.IsEmpty) |
| | | 309 | | { |
| | | 310 | | TryRemove(correlationId, bucket); |
| | | 311 | | continue; |
| | | 312 | | } |
| | | 313 | | |
| | | 314 | | if (!pruned.Equals(bucket)) |
| | | 315 | | _entries.TryUpdate(correlationId, pruned, bucket); |
| | | 316 | | |
| | | 317 | | if (pruned.SingleEntry is { } single) |
| | | 318 | | { |
| | | 319 | | if (RecoveryStateSchema.IsReadable(single.State.SchemaVersion)) |
| | | 320 | | yield return single.State; |
| | | 321 | | continue; |
| | | 322 | | } |
| | | 323 | | |
| | | 324 | | if (pruned.ManyEntries is null) |
| | | 325 | | continue; |
| | | 326 | | |
| | | 327 | | foreach (var entry in pruned.ManyEntries) |
| | | 328 | | { |
| | | 329 | | if (RecoveryStateSchema.IsReadable(entry.State.SchemaVersion)) |
| | | 330 | | yield return entry.State; |
| | | 331 | | } |
| | | 332 | | } |
| | | 333 | | } |
| | | 334 | | } |