Path: redb-route/redb.Route.Core/Repositories/RedbIdempotentRepository.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.Core/Repositories/RedbIdempotentRepository.cs
----
using Microsoft.Extensions.DependencyInjection;
using redb.Core;
using redb.Core.Data;
using redb.Core.Exceptions;
using redb.Core.Models.Contracts;
using redb.Core.Models.Entities;
using redb.Route.Abstractions;
using redb.Route.RedbCore.Models;
namespace redb.Route.RedbCore.Repositories;
///
/// Idempotent repository backed by redb.Core props storage.
/// Works on any redb-supported database (PostgreSQL, SQL Server, SQLite) via
/// without raw DDL — the scheme is managed automatically
/// through .
///
/// Opens a fresh scope per operation, so it is safe for concurrent use from multiple route
/// threads: from an , or from any source of , such as a named
/// redb instance of the route context (context.CreateRedbScope(name)).
///
///
/// Identity strategy: each entry stores its composite identity
/// "{ProcessorName}:{MessageKey}" twice: in the indexed
/// column (readable, O(log n) lookups via IX__objects__name) and in
/// , which the core guards with the per-scheme UNIQUE
/// index UIX__objects__scheme_unique on every provider. A composite longer than
/// 440 characters (client keys can be arbitrary) is normalized to a readable prefix plus a
/// SHA-256 tail so it fits both columns on every provider.
///
///
/// Cluster safety: concurrent calls for one key race to insert the
/// same ValueUnique; the database lets exactly one row through and the loser's typed
/// is treated as «already processed» — first wins,
/// nobody crashes, at-most-once holds across threads and cluster nodes. Entries created by
/// older versions carry no ValueUnique; the Name lookups still find them, so no
/// backfill is required.
///
///
public sealed class RedbIdempotentRepository : IIdempotentRepository
{
private readonly Func _openScope;
private readonly RedbIdempotentOptions _options;
private bool _schemeEnsured;
// Higher retry budget: multi-process TFM runs cause heavy cross-table contention on MsSql
private const int MaxRetries = 5;
private const int BaseDelayMs = 200;
/// Creates a repository over the of the scopes opens.
public RedbIdempotentRepository(IServiceScopeFactory scopeFactory, RedbIdempotentOptions options)
: this(OpenFrom(scopeFactory ?? throw new ArgumentNullException(nameof(scopeFactory))), options)
{
}
///
/// Creates a repository over the redb scopes opens, one per operation; the repository
/// disposes each. A named instance of a route context: () => context.CreateRedbScope("orders").
///
public RedbIdempotentRepository(Func openScope, RedbIdempotentOptions options)
{
ArgumentNullException.ThrowIfNull(openScope);
ArgumentNullException.ThrowIfNull(options);
_openScope = openScope;
_options = options;
}
private static Func OpenFrom(IServiceScopeFactory scopeFactory) => () =>
{
var scope = scopeFactory.CreateScope();
try
{
return new RedbScope(scope.ServiceProvider.GetRequiredService(), scope);
}
catch
{
scope.Dispose();
throw;
}
};
///
/// True: inside an ambient transaction redb writes on the transaction's connection (core AmbientConnectionRegistry,
/// on every provider — SQLite through a transaction of its own enlisted with the scope), so the key commits and rolls
/// back with the work of the .Transacted() block.
///
public bool JoinsAmbientTransaction => true;
///
/// Composite identity name for a (processor, key) pair. Stored in the indexed
/// _objects._name column for fast lookup and in _objects._value_unique
/// for the database-enforced uniqueness guarantee.
///
private string ComposeName(string key) => ComposeEntryName(_options.ProcessorName, key);
///
/// "{processorName}:{key}", normalized by the shared
/// helper (440-char cap, SHA-256 tail for over-long composites). Internal so tests can
/// compute the stored identity without copying the format.
///
internal static string ComposeEntryName(string processorName, string key)
=> RedbUniqueKey.Normalize($"{processorName}:{key}");
///
public Task Add(string key, CancellationToken ct = default) => Add(key, restampAfter: null, claimId: null, ct);
///
/// ; with , an insert that took longer than
/// that is stamped again in its own transaction before it commits, so the entry never becomes visible already aged
/// by a lock wait (a claim stamped before an insert that then waits would look abandoned the moment it appears).
/// is the entry's .
///
private async Task Add(string key, TimeSpan? restampAfter, string? claimId, CancellationToken ct)
{
ArgumentNullException.ThrowIfNull(key);
await EnsureSchemeAsync().ConfigureAwait(false);
if (_options.Ttl.HasValue)
await CleanupExpiredAsync(ct).ConfigureAwait(false);
var entryName = ComposeName(key);
return await DeadlockRetryHelper.ExecuteWithRetryAsync(async () =>
{
using var scope = _openScope();
var redb = scope.Service;
// Indexed lookup by composite name (IX__objects__name).
// Defensive Props filter guards against any name collision from foreign schemes
// that happen to share the same name format.
var existing = await redb.Query()
.WhereRedb(x => x.Name == entryName)
.ToListAsync()
.ConfigureAwait(false);
if (existing.Any(e => IsEntryOf(e, key)))
return false;
var entry = new RedbObject
{
name = entryName,
ValueUnique = entryName,
Props = new IdempotentEntryProps
{
ProcessorName = _options.ProcessorName,
MessageKey = key,
CreatedAt = DateTimeOffset.UtcNow,
Confirmed = false,
ClaimId = claimId
}
};
try
{
if (restampAfter is not { } threshold)
await redb.SaveAsync(entry).ConfigureAwait(false);
else
await redb.Context.ExecuteAtomicAsync(async () =>
{
await redb.SaveAsync(entry).ConfigureAwait(false);
var now = DateTimeOffset.UtcNow;
if (now - entry.Props.CreatedAt <= threshold) return;
entry.Props.CreatedAt = now;
await redb.SaveAsync(entry).ConfigureAwait(false);
}, ct).ConfigureAwait(false);
}
catch (RedbUniqueViolationException)
{
// Lost the creation race: a concurrent Add committed this key between our
// lookup and insert. First wins — the message is already claimed.
return false;
}
return true;
}, MaxRetries, BaseDelayMs);
}
///
public async Task Confirm(string key, CancellationToken ct = default)
{
ArgumentNullException.ThrowIfNull(key);
await EnsureSchemeAsync().ConfigureAwait(false);
var entryName = ComposeName(key);
await DeadlockRetryHelper.ExecuteWithRetryAsync(async () =>
{
using var scope = _openScope();
var redb = scope.Service;
var items = await redb.Query()
.WhereRedb(x => x.Name == entryName)
.ToListAsync()
.ConfigureAwait(false);
foreach (var item in items)
{
if (!IsEntryOf(item, key)) continue;
item.Props.Confirmed = true;
await redb.SaveAsync(item).ConfigureAwait(false);
}
}, MaxRetries, BaseDelayMs);
}
///
public async Task Remove(string key, CancellationToken ct = default)
{
ArgumentNullException.ThrowIfNull(key);
await EnsureSchemeAsync().ConfigureAwait(false);
var entryName = ComposeName(key);
await DeadlockRetryHelper.ExecuteWithRetryAsync(async () =>
{
using var scope = _openScope();
var redb = scope.Service;
var items = await redb.Query()
.WhereRedb(x => x.Name == entryName)
.ToListAsync()
.ConfigureAwait(false);
foreach (var item in items)
{
if (!IsEntryOf(item, key)) continue;
await redb.DeleteAsync(item).ConfigureAwait(false);
}
}, MaxRetries, BaseDelayMs);
}
///
///
/// Confirms the entry only while its is . The entry is
/// read and then saved; a takeover between the two replaces the entry under a new object, and the save of the old one
/// then loses on ValueUnique and answers false. When the save lands between the takeover's delete and its insert,
/// the old entry comes back confirmed (the default missing-object strategy inserts it again), the takeover's insert
/// loses and answers in flight, and the next claim finds the message processed, which it was.
///
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;
}
await EnsureSchemeAsync().ConfigureAwait(false);
var entryName = ComposeName(key);
return await DeadlockRetryHelper.ExecuteWithRetryAsync(async () =>
{
using var scope = _openScope();
var redb = scope.Service;
var held = (await redb.Query()
.WhereRedb(x => x.Name == entryName)
.ToListAsync()
.ConfigureAwait(false))
.FirstOrDefault(e => IsEntryOf(e, key) && e.Props.ClaimId == token);
if (held is null)
return false;
if (held.Props.Confirmed)
return true;
held.Props.Confirmed = true;
try
{
await redb.SaveAsync(held).ConfigureAwait(false);
}
catch (RedbUniqueViolationException)
{
return false;
}
return true;
}, MaxRetries, BaseDelayMs).ConfigureAwait(false);
}
///
///
/// Deletes the entry only while its is , by its object
/// id: an entry a takeover put in its place is another object and stays.
///
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;
}
await EnsureSchemeAsync().ConfigureAwait(false);
var entryName = ComposeName(key);
return await DeadlockRetryHelper.ExecuteWithRetryAsync(async () =>
{
using var scope = _openScope();
var redb = scope.Service;
var held = (await redb.Query()
.WhereRedb(x => x.Name == entryName)
.ToListAsync()
.ConfigureAwait(false))
.FirstOrDefault(e => IsEntryOf(e, key) && e.Props.ClaimId == token);
return held is not null && await redb.DeleteAsync(held.Id).ConfigureAwait(false);
}, MaxRetries, BaseDelayMs).ConfigureAwait(false);
}
///
public async Task Contains(string key, CancellationToken ct = default)
{
ArgumentNullException.ThrowIfNull(key);
await EnsureSchemeAsync().ConfigureAwait(false);
var entryName = ComposeName(key);
return await DeadlockRetryHelper.ExecuteWithRetryAsync(async () =>
{
using var scope = _openScope();
var redb = scope.Service;
var items = await redb.Query()
.WhereRedb(x => x.Name == entryName)
.ToListAsync()
.ConfigureAwait(false);
return items.Any(e => IsEntryOf(e, key));
}, MaxRetries, BaseDelayMs);
}
///
public async Task Clear(CancellationToken ct = default)
{
await EnsureSchemeAsync().ConfigureAwait(false);
await DeadlockRetryHelper.ExecuteWithRetryAsync(async () =>
{
using var scope = _openScope();
var redb = scope.Service;
// Bulk clear is scope-wide; name-prefix filter not used (would require LIKE),
// so we fall back to the Props-level scan here.
var items = await redb.Query()
.Where(e => e.ProcessorName == _options.ProcessorName)
.ToListAsync()
.ConfigureAwait(false);
if (items.Count > 0)
await redb.DeleteAsync((IEnumerable)items).ConfigureAwait(false);
}, MaxRetries, BaseDelayMs);
}
///
public async Task Claim(string key, TimeSpan? abandonedAfter, CancellationToken ct = default) =>
(await Lease(key, abandonedAfter, ct).ConfigureAwait(false)).Outcome;
///
///
/// The token is a new random id kept in the entry's .
/// Answered from the entry's and .
/// An abandoned claim is taken over by deleting the entry that was read, by its object id, and inserting a new one: a
/// caller that read the same stale entry deletes nothing that is new (its delete finds no object, or its insert loses
/// on ValueUnique) and answers . Inside an ambient transaction both run
/// on the transaction's connection, as does.
///
/// The age is against this node's clock, so
/// must stay far above the clock skew between nodes. An insert that waits on locks
/// for longer than a tenth of is stamped again before it commits: a claim stamped
/// before such a wait would look abandoned the moment it became visible, and another node would take it over.
///
///
public async Task Lease(string key, TimeSpan? abandonedAfter, CancellationToken ct = default)
{
ArgumentNullException.ThrowIfNull(key);
var token = Guid.NewGuid().ToString("N");
var claim = await ClaimAsync(key, abandonedAfter, token, ct).ConfigureAwait(false);
return new IdempotentLease(claim, claim is IdempotentClaim.Claimed or IdempotentClaim.TakenOver ? token : null);
}
private async Task ClaimAsync(string key, TimeSpan? abandonedAfter, string token, CancellationToken ct)
{
TimeSpan? restamp = abandonedAfter is { } after ? after / 10 : null;
if (await Add(key, restamp, token, ct).ConfigureAwait(false))
return IdempotentClaim.Claimed;
var entryName = ComposeName(key);
var held = await DeadlockRetryHelper.ExecuteWithRetryAsync(async () =>
{
using var scope = _openScope();
var items = await scope.Service.Query()
.WhereRedb(x => x.Name == entryName)
.ToListAsync()
.ConfigureAwait(false);
return items.FirstOrDefault(e => IsEntryOf(e, key));
}, MaxRetries, BaseDelayMs).ConfigureAwait(false);
if (held is null)
// Released between the insert and the read: claim it again.
return await Add(key, restamp, token, ct).ConfigureAwait(false) ? IdempotentClaim.Claimed : IdempotentClaim.InFlight;
if (held.Props.Confirmed)
return IdempotentClaim.Confirmed;
if (abandonedAfter is not { } age || DateTimeOffset.UtcNow - held.Props.CreatedAt <= age)
return IdempotentClaim.InFlight;
// Read again right before the delete: a holder that confirmed meanwhile, or another caller that already took the
// claim over, keeps its entry. The delete by id cannot itself test the flag, so a confirmation landing between
// this read and the delete is still lost; that window is the at-least-once of a takeover.
var heldId = held.Id;
var outcome = await DeadlockRetryHelper.ExecuteWithRetryAsync(async () =>
{
using var scope = _openScope();
var current = await scope.Service.Query()
.WhereRedb(x => x.Id == heldId)
.ToListAsync()
.ConfigureAwait(false);
if (current.Count != 1 || current[0].Props is not { } now || now.CreatedAt != held.Props.CreatedAt)
return IdempotentClaim.InFlight;
if (now.Confirmed)
return IdempotentClaim.Confirmed;
return await scope.Service.DeleteAsync(heldId).ConfigureAwait(false) ? IdempotentClaim.TakenOver : IdempotentClaim.InFlight;
}, MaxRetries, BaseDelayMs).ConfigureAwait(false);
if (outcome != IdempotentClaim.TakenOver)
return outcome;
// A new entry: ValueUnique lets one caller through.
return await Add(key, restamp, token, ct).ConfigureAwait(false) ? IdempotentClaim.TakenOver : IdempotentClaim.InFlight;
}
///
/// Whether is the entry of for this processor. An entry another caller is
/// deleting at that moment can come back without its props: it is passed over, as one already gone.
///
private bool IsEntryOf(RedbObject entry, string key) =>
entry.Props is { } props && props.ProcessorName == _options.ProcessorName && props.MessageKey == key;
private async Task EnsureSchemeAsync()
{
if (_schemeEnsured) return;
using var scope = _openScope();
var redb = scope.Service;
await redb.SyncSchemeAsync().ConfigureAwait(false);
_schemeEnsured = true;
}
private async Task CleanupExpiredAsync(CancellationToken ct)
{
if (_options.Ttl is not { } ttl) return;
var cutoff = DateTimeOffset.UtcNow.Subtract(ttl);
await DeadlockRetryHelper.ExecuteWithRetryAsync(async () =>
{
using var scope = _openScope();
var redb = scope.Service;
var expired = await redb.Query()
.Where(e => e.ProcessorName == _options.ProcessorName && e.CreatedAt < cutoff)
.ToListAsync()
.ConfigureAwait(false);
if (expired.Count > 0)
await redb.DeleteAsync((IEnumerable)expired).ConfigureAwait(false);
}, MaxRetries, BaseDelayMs);
}
}