Path: redb-route/redb.Route/Processors/InMemoryClaimCheckRepository.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/InMemoryClaimCheckRepository.cs
----
using System;
using System.Collections.Concurrent;
using System.Threading;
using System.Threading.Tasks;
using redb.Route.Abstractions;
namespace redb.Route.Processors;
///
/// In-memory implementation of .
/// Suitable for single-process scenarios, testing, and push/pop stash patterns.
/// Thread-safe via .
///
public sealed class InMemoryClaimCheckRepository : IClaimCheckRepository
{
private readonly ConcurrentDictionary _store = new(StringComparer.Ordinal);
private readonly TimeSpan _defaultTtl;
///
/// Creates a new in-memory claim check repository.
///
/// Default TTL for entries. Zero or null means no expiry.
public InMemoryClaimCheckRepository(TimeSpan? defaultTtl = null)
{
_defaultTtl = defaultTtl ?? TimeSpan.Zero;
}
/// Number of entries currently in the store (including potentially expired).
public int Count => _store.Count;
///
public Task Store(ReadOnlyMemory data, TimeSpan? ttl = null, CancellationToken ct = default)
{
var key = Guid.NewGuid().ToString("N");
StoreInternal(key, data, ttl);
return Task.FromResult(key);
}
///
public Task Store(string key, ReadOnlyMemory data, TimeSpan? ttl = null, CancellationToken ct = default)
{
ArgumentNullException.ThrowIfNull(key);
StoreInternal(key, data, ttl);
return Task.CompletedTask;
}
///
public Task Retrieve(string key, CancellationToken ct = default)
{
ArgumentNullException.ThrowIfNull(key);
if (_store.TryGetValue(key, out var entry))
{
if (entry.IsExpired)
{
_store.TryRemove(key, out _);
return Task.FromResult(null);
}
return Task.FromResult(entry.Data);
}
return Task.FromResult(null);
}
///
public Task RetrieveAndRemove(string key, CancellationToken ct = default)
{
ArgumentNullException.ThrowIfNull(key);
if (_store.TryRemove(key, out var entry) && !entry.IsExpired)
return Task.FromResult(entry.Data);
return Task.FromResult(null);
}
///
public Task Remove(string key, CancellationToken ct = default)
{
ArgumentNullException.ThrowIfNull(key);
_store.TryRemove(key, out _);
return Task.CompletedTask;
}
private void StoreInternal(string key, ReadOnlyMemory data, TimeSpan? ttl)
{
var effectiveTtl = ttl ?? _defaultTtl;
var expiresAt = effectiveTtl > TimeSpan.Zero
? DateTimeOffset.UtcNow + effectiveTtl
: (DateTimeOffset?)null;
_store[key] = new Entry(data.ToArray(), expiresAt);
}
private sealed record Entry(byte[] Data, DateTimeOffset? ExpiresAt)
{
public bool IsExpired => ExpiresAt.HasValue && DateTimeOffset.UtcNow >= ExpiresAt.Value;
}
}