Path: redb-route/redb.Route/Processors/InMemoryIdempotentRepository.cs Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route/Processors/InMemoryIdempotentRepository.cs ---- using System.Collections.Concurrent; using redb.Route.Abstractions; namespace redb.Route.Processors; /// /// In-memory implementation of . /// Uses a for thread-safe deduplication. /// Supports optional TTL-based eviction to prevent unbounded memory growth. /// Suitable for single-process scenarios and testing. /// public sealed class InMemoryIdempotentRepository : IIdempotentRepository { // One immutable entry per key: replaced whole (compare-and-swap) on Confirm and on a takeover. // Token: the claim id Lease hands out, a GUID per claim; null for a key taken by Add. private sealed record Entry(DateTimeOffset ClaimedAt, bool Confirmed, string? Token = null); private readonly ConcurrentDictionary _store = new(StringComparer.Ordinal); private readonly TimeSpan? _ttl; /// Creates a repository with optional TTL for automatic key expiration. /// /// Time-to-live for keys. Keys older than this are evicted on next call. /// Null means keys are kept indefinitely (default). /// public InMemoryIdempotentRepository(TimeSpan? ttl = null) { _ttl = ttl; } /// Gets the current number of tracked keys (including potentially expired ones). public int Count => _store.Count; /// public Task Add(string key, CancellationToken ct = default) { ArgumentNullException.ThrowIfNull(key); // Lazy eviction: remove expired entries on each Add if (_ttl.HasValue) EvictExpired(); var added = _store.TryAdd(key, new Entry(DateTimeOffset.UtcNow, Confirmed: false)); return Task.FromResult(added); } /// public Task Confirm(string key, CancellationToken ct = default) { ArgumentNullException.ThrowIfNull(key); while (_store.TryGetValue(key, out var entry) && !entry.Confirmed) { if (_store.TryUpdate(key, entry with { Confirmed = true }, entry)) break; } return Task.CompletedTask; } /// public Task Remove(string key, CancellationToken ct = default) { ArgumentNullException.ThrowIfNull(key); _store.TryRemove(key, out _); return Task.CompletedTask; } /// public Task Contains(string key, CancellationToken ct = default) { ArgumentNullException.ThrowIfNull(key); if (_ttl.HasValue && _store.TryGetValue(key, out var entry)) { if (DateTimeOffset.UtcNow - entry.ClaimedAt > _ttl.Value) { _store.TryRemove(key, out _); return Task.FromResult(false); } } return Task.FromResult(_store.ContainsKey(key)); } /// public Task Clear(CancellationToken ct = default) { _store.Clear(); return Task.CompletedTask; } /// public async Task Claim(string key, TimeSpan? abandonedAfter, CancellationToken ct = default) => (await Lease(key, abandonedAfter, ct).ConfigureAwait(false)).Outcome; /// /// /// The confirmed state, the time of the claim and its id are kept with the key; an abandoned claim is replaced by a /// compare-and-swap of exactly the entry that was read, so of two callers taking it over at once one wins. /// public Task Lease(string key, TimeSpan? abandonedAfter, CancellationToken ct = default) { ArgumentNullException.ThrowIfNull(key); if (_ttl.HasValue) EvictExpired(); while (true) { var now = DateTimeOffset.UtcNow; var claim = new Entry(now, Confirmed: false, Guid.NewGuid().ToString("N")); if (_store.TryAdd(key, claim)) return Task.FromResult(new IdempotentLease(IdempotentClaim.Claimed, claim.Token)); if (!_store.TryGetValue(key, out var held)) continue; // released between the two calls: claim it again if (held.Confirmed) return Task.FromResult(new IdempotentLease(IdempotentClaim.Confirmed, null)); if (abandonedAfter is { } age && now - held.ClaimedAt > age) return Task.FromResult(_store.TryUpdate(key, claim, held) ? new IdempotentLease(IdempotentClaim.TakenOver, claim.Token) : new IdempotentLease(IdempotentClaim.InFlight, null)); return Task.FromResult(new IdempotentLease(IdempotentClaim.InFlight, null)); } } /// public async Task Confirm(string key, string? token, CancellationToken ct = default) { ArgumentNullException.ThrowIfNull(key); if (token is null) { await Confirm(key, ct).ConfigureAwait(false); return true; } while (_store.TryGetValue(key, out var entry) && entry.Token == token) { if (entry.Confirmed || _store.TryUpdate(key, entry with { Confirmed = true }, entry)) return true; } return false; } /// public async Task Release(string key, string? token, CancellationToken ct = default) { ArgumentNullException.ThrowIfNull(key); if (token is null) { await Remove(key, ct).ConfigureAwait(false); return true; } while (_store.TryGetValue(key, out var entry) && entry.Token == token) { if (_store.TryRemove(new KeyValuePair(key, entry))) return true; } return false; } private void EvictExpired() { var cutoff = DateTimeOffset.UtcNow - _ttl!.Value; foreach (var kvp in _store) { if (kvp.Value.ClaimedAt < cutoff) _store.TryRemove(kvp.Key, out _); } } }