Path: redb-route/redb.Route.Sql/Repositories/SqlIdempotentRepository.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.Sql/Repositories/SqlIdempotentRepository.cs ---- using System.Data.Common; using System.Diagnostics; using System.Globalization; using System.Transactions; using redb.Route.Abstractions; using redb.Route.Sql.Connection; namespace redb.Route.Sql.Repositories; /// /// Idempotent repository backed by a raw ADO.NET table. /// For autonomous use of redb.Route without redb.Core dependency. /// Supports auto-create table and TTL-based cleanup. /// /// Schema bootstrap: when is true (default), /// the table is created on first operation with dialect-aware DDL: SQLite/PostgreSQL/MySQL/MariaDB use /// CREATE TABLE IF NOT EXISTS with VARCHAR key columns (128 for the processor name, 255 for /// the message key — MySQL refuses TEXT in a key); SQL Server (which has no such syntax) is detected /// from the live connection and gets a guarded IF OBJECT_ID(...) IS NULL CREATE TABLE with /// NVARCHAR/INT columns of the same sizes, inside the 900-byte clustered key limit. Set /// = false to manage the schema yourself. /// /// /// Cleanup: when is set, every /// runs a best-effort DELETE WHERE created_at < cutoff. This adds latency to the hot /// path; for high-throughput scenarios prefer running cleanup out-of-band on a schedule. /// /// public sealed class SqlIdempotentRepository : IIdempotentRepository { private readonly ISqlConnectionFactory _connectionFactory; private readonly SqlIdempotentOptions _options; private readonly SemaphoreSlim _ddlLock = new(1, 1); private bool _tableCreated; private bool _claimIdColumnSeen; // What the connections of this repository do in an ambient transaction: 0 until the first one is seen. private const int Joins = 1; private const int StaysOutside = 2; private int _ambientBehaviour; /// Creates an idempotent repository with the given connection factory and options. /// Factory for creating database connections. /// Repository configuration. public SqlIdempotentRepository(ISqlConnectionFactory connectionFactory, SqlIdempotentOptions options) { ArgumentNullException.ThrowIfNull(connectionFactory); ArgumentNullException.ThrowIfNull(options); SqlConnections.RefuseLending(connectionFactory, nameof(SqlIdempotentRepository), nameof(connectionFactory)); _connectionFactory = connectionFactory; _options = options; } /// /// True when the repository's connections enlist in an ambient transaction, so that inside a /// .Transacted() block is rolled back with it: Npgsql (PostgreSQL) and SqlClient (SQL Server), unless the /// connection string sets Enlist=false. False for other providers (Microsoft.Data.Sqlite does not enlist) and /// with Enlist=false; the idempotent consumer then removes the key itself after a rollback. It is learnt from the /// connection opens, and the consumer reads it after ; before the first connection it /// is false. /// public bool JoinsAmbientTransaction => Volatile.Read(ref _ambientBehaviour) == Joins; /// /// /// An insert that loses the key to another one at the same moment (an error on PostgreSQL, and on SQL Server when both /// pass the existence check) answers false: the key is held, the message is a duplicate. /// public Task Add(string key, CancellationToken ct = default) => AddRacingAsync(key, restampAfter: null, claimId: null, ct); /// /// ; with , an insert that took longer than /// that is stamped again, in the same transaction, before it commits: a claim stamped before an insert that then waits on /// a lock would otherwise look abandoned the moment it became visible. Inside an ambient transaction the row stays /// invisible until the caller commits, so it is not stamped again there. A goes into the /// claim_id column; without one the row is written as before 4.8.0, with no claim id. /// private async Task Add(string key, TimeSpan? restampAfter, string? claimId, CancellationToken ct) { await EnsureTableAsync(ct).ConfigureAwait(false); await CleanupIfNeededAsync(ct).ConfigureAwait(false); await using var conn = await _connectionFactory.CreateConnectionAsync(ct: ct).ConfigureAwait(false); var enlists = EnlistsInAmbientTransaction(conn); if (Volatile.Read(ref _ambientBehaviour) == 0) Volatile.Write(ref _ambientBehaviour, enlists ? Joins : StaysOutside); await using var tx = restampAfter is not null && !(enlists && Transaction.Current is not null) ? await conn.BeginTransactionAsync(ct).ConfigureAwait(false) : null; await using var cmd = conn.CreateCommand(); cmd.Transaction = tx; var (claimColumn, claimValue) = claimId is null ? ("", "") : (", claim_id", ", @claim"); cmd.CommandText = $""" INSERT INTO {_options.TableName} (processor_name, message_key, created_at, confirmed{claimColumn}) SELECT @processor, @key, {UtcText(cmd, conn, TimeSpan.Zero)}, 0{claimValue} WHERE NOT EXISTS ( SELECT 1 FROM {_options.TableName} WHERE processor_name = @processor AND message_key = @key ) """; AddParam(cmd, "processor", _options.ProcessorName); AddParam(cmd, "key", key); if (claimId is not null) AddParam(cmd, "claim", claimId); var started = Stopwatch.GetTimestamp(); var rows = await cmd.ExecuteNonQueryAsync(ct).ConfigureAwait(false); if (rows > 0 && tx is not null && Stopwatch.GetElapsedTime(started) > restampAfter) { await using var restamp = conn.CreateCommand(); restamp.Transaction = tx; restamp.CommandText = $""" UPDATE {_options.TableName} SET created_at = {UtcText(restamp, conn, TimeSpan.Zero)} WHERE processor_name = @processor AND message_key = @key """; AddParam(restamp, "processor", _options.ProcessorName); AddParam(restamp, "key", key); await restamp.ExecuteNonQueryAsync(ct).ConfigureAwait(false); } if (tx is not null) await tx.CommitAsync(ct).ConfigureAwait(false); return rows > 0; } /// public async Task Confirm(string key, CancellationToken ct = default) { await EnsureTableAsync(ct).ConfigureAwait(false); await using var conn = await _connectionFactory.CreateConnectionAsync(ct: ct).ConfigureAwait(false); await using var cmd = conn.CreateCommand(); cmd.CommandText = $""" UPDATE {_options.TableName} SET confirmed = 1 WHERE processor_name = @processor AND message_key = @key """; AddParam(cmd, "processor", _options.ProcessorName); AddParam(cmd, "key", key); await cmd.ExecuteNonQueryAsync(ct).ConfigureAwait(false); } /// public async Task Remove(string key, CancellationToken ct = default) { await EnsureTableAsync(ct).ConfigureAwait(false); await using var conn = await _connectionFactory.CreateConnectionAsync(ct: ct).ConfigureAwait(false); await using var cmd = conn.CreateCommand(); cmd.CommandText = $""" DELETE FROM {_options.TableName} WHERE processor_name = @processor AND message_key = @key """; AddParam(cmd, "processor", _options.ProcessorName); AddParam(cmd, "key", key); await cmd.ExecuteNonQueryAsync(ct).ConfigureAwait(false); } /// /// Sets confirmed on the row only while its claim_id is . 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 EnsureTableAsync(ct).ConfigureAwait(false); await EnsureClaimIdColumnAsync(ct).ConfigureAwait(false); await using var conn = await _connectionFactory.CreateConnectionAsync(ct: ct).ConfigureAwait(false); await using var cmd = conn.CreateCommand(); cmd.CommandText = $""" UPDATE {_options.TableName} SET confirmed = 1 WHERE processor_name = @processor AND message_key = @key AND claim_id = @claim """; AddParam(cmd, "processor", _options.ProcessorName); AddParam(cmd, "key", key); AddParam(cmd, "claim", token); return await cmd.ExecuteNonQueryAsync(ct).ConfigureAwait(false) > 0; } /// /// Deletes the row only while its claim_id is . 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 EnsureTableAsync(ct).ConfigureAwait(false); await EnsureClaimIdColumnAsync(ct).ConfigureAwait(false); await using var conn = await _connectionFactory.CreateConnectionAsync(ct: ct).ConfigureAwait(false); await using var cmd = conn.CreateCommand(); cmd.CommandText = $""" DELETE FROM {_options.TableName} WHERE processor_name = @processor AND message_key = @key AND claim_id = @claim """; AddParam(cmd, "processor", _options.ProcessorName); AddParam(cmd, "key", key); AddParam(cmd, "claim", token); return await cmd.ExecuteNonQueryAsync(ct).ConfigureAwait(false) > 0; } /// public async Task Contains(string key, CancellationToken ct = default) { await EnsureTableAsync(ct).ConfigureAwait(false); await using var conn = await _connectionFactory.CreateConnectionAsync(ct: ct).ConfigureAwait(false); await using var cmd = conn.CreateCommand(); cmd.CommandText = $""" SELECT COUNT(1) FROM {_options.TableName} WHERE processor_name = @processor AND message_key = @key """; AddParam(cmd, "processor", _options.ProcessorName); AddParam(cmd, "key", key); var result = await cmd.ExecuteScalarAsync(ct).ConfigureAwait(false); return Convert.ToInt32(result) > 0; } /// public async Task Clear(CancellationToken ct = default) { await EnsureTableAsync(ct).ConfigureAwait(false); await using var conn = await _connectionFactory.CreateConnectionAsync(ct: ct).ConfigureAwait(false); await using var cmd = conn.CreateCommand(); cmd.CommandText = $"DELETE FROM {_options.TableName} WHERE processor_name = @processor"; AddParam(cmd, "processor", _options.ProcessorName); await cmd.ExecuteNonQueryAsync(ct).ConfigureAwait(false); } /// public async Task Claim(string key, TimeSpan? abandonedAfter, CancellationToken ct = default) => (await Lease(key, abandonedAfter, ct).ConfigureAwait(false)).Outcome; /// /// /// Answered from the row's confirmed flag and created_at; the claim's token is a new random id written /// to the row's claim_id. An abandoned claim is taken over by deleting the row only while it is still /// unconfirmed and older than the cutoff, then inserting a new one: of two callers that saw the same stale row, one /// deletes it and the other deletes nothing and finds the new claim in flight. Inside an ambient transaction the /// statements run on the transaction's connection, as does. A row without /// a claim_id (written by or before 4.8.0) is answered and taken /// over the same way. /// /// Both the stamp and the cutoff are the database's clock (created_at keeps its ISO 8601 UTC text, so a row /// written with the application's clock compares as before), and an insert that waits on locks for longer than a tenth /// of is stamped again before it commits. /// /// public async Task Lease(string key, TimeSpan? abandonedAfter, CancellationToken ct = default) { ArgumentNullException.ThrowIfNull(key); await EnsureTableAsync(ct).ConfigureAwait(false); await EnsureClaimIdColumnAsync(ct).ConfigureAwait(false); TimeSpan? restamp = abandonedAfter is { } after ? after / 10 : null; var token = Guid.NewGuid().ToString("N"); var claim = await ClaimAsync(key, abandonedAfter, restamp, 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, TimeSpan? restamp, string token, CancellationToken ct) { if (await AddRacingAsync(key, restamp, token, ct).ConfigureAwait(false)) return IdempotentClaim.Claimed; if (abandonedAfter is { } age) { await using var conn = await _connectionFactory.CreateConnectionAsync(ct: ct).ConfigureAwait(false); await using var takeOver = conn.CreateCommand(); takeOver.CommandText = $""" DELETE FROM {_options.TableName} WHERE processor_name = @processor AND message_key = @key AND confirmed = 0 AND created_at < {UtcText(takeOver, conn, age)} """; AddParam(takeOver, "processor", _options.ProcessorName); AddParam(takeOver, "key", key); if (await takeOver.ExecuteNonQueryAsync(ct).ConfigureAwait(false) > 0) return await AddRacingAsync(key, restamp, token, ct).ConfigureAwait(false) ? IdempotentClaim.TakenOver : IdempotentClaim.InFlight; } return await ReadConfirmedAsync(key, ct).ConfigureAwait(false) switch { true => IdempotentClaim.Confirmed, false => IdempotentClaim.InFlight, // Released between the insert and the read: claim it again. null => await AddRacingAsync(key, restamp, token, ct).ConfigureAwait(false) ? IdempotentClaim.Claimed : IdempotentClaim.InFlight, }; } /// The row's confirmed flag, or null when there is no row. private async Task ReadConfirmedAsync(string key, CancellationToken ct) { await using var conn = await _connectionFactory.CreateConnectionAsync(ct: ct).ConfigureAwait(false); await using var read = conn.CreateCommand(); read.CommandText = $""" SELECT confirmed FROM {_options.TableName} WHERE processor_name = @processor AND message_key = @key """; AddParam(read, "processor", _options.ProcessorName); AddParam(read, "key", key); var confirmed = await read.ExecuteScalarAsync(ct).ConfigureAwait(false); return confirmed is null or DBNull ? null : Convert.ToInt32(confirmed, CultureInfo.InvariantCulture) != 0; } /// /// where another caller may insert the same key at the /// same moment: the primary key lets one row through, and a statement that loses on it (an error on some databases, no /// row on others) means the key is held. /// private async Task AddRacingAsync(string key, TimeSpan? restampAfter, string? claimId, CancellationToken ct) { try { return await Add(key, restampAfter, claimId, ct).ConfigureAwait(false); } catch (DbException) { if (await ReadConfirmedAsync(key, ct).ConfigureAwait(false) is not null) return false; throw; } } private async Task EnsureTableAsync(CancellationToken ct) { if (_tableCreated || !_options.CreateTable) return; await _ddlLock.WaitAsync(ct).ConfigureAwait(false); try { if (_tableCreated) return; // The table is the repository's, not the message's: the first call may run inside the transaction of whatever // message came first, and DDL there would go with its rollback (PostgreSQL, SQL Server) or commit it implicitly // (MySQL, Oracle). As Apache Camel creates the table outside any exchange, it is created outside the transaction. using var outsideTransaction = new TransactionScope(TransactionScopeOption.Suppress, TransactionScopeAsyncFlowOption.Enabled); await using var conn = await _connectionFactory.CreateConnectionAsync(ct: ct).ConfigureAwait(false); await using var cmd = conn.CreateCommand(); // Dialect-aware bootstrap. SQL Server has no CREATE TABLE IF NOT EXISTS, so it gets a // guarded T-SQL statement; SQLite/PostgreSQL/MySQL keep the portable form. Both are // idempotent at the SQL level, so even concurrent first-callers won't error — but we // serialize via _ddlLock to avoid burning round-trips and keep the // "set _tableCreated only after success" logic linear. cmd.CommandText = BuildCreateTableDdl(conn, _options.TableName); await cmd.ExecuteNonQueryAsync(ct).ConfigureAwait(false); // A table created before 4.8.0 has no claim_id column: added here, before any claim needs it. if (!await HasClaimIdColumnAsync(conn, ct).ConfigureAwait(false)) await AddClaimIdColumnAsync(conn, ct).ConfigureAwait(false); outsideTransaction.Complete(); _claimIdColumnSeen = true; _tableCreated = true; } finally { _ddlLock.Release(); } } /// /// Makes sure the table has the claim_id column and the token methods use. With /// it was added with the table; without it a table that lacks the /// column fails here with the statement that adds it. does not need it. /// private async Task EnsureClaimIdColumnAsync(CancellationToken ct) { if (_claimIdColumnSeen) return; await _ddlLock.WaitAsync(ct).ConfigureAwait(false); try { if (_claimIdColumnSeen) return; using var outsideTransaction = new TransactionScope(TransactionScopeOption.Suppress, TransactionScopeAsyncFlowOption.Enabled); await using var conn = await _connectionFactory.CreateConnectionAsync(ct: ct).ConfigureAwait(false); if (!await HasClaimIdColumnAsync(conn, ct).ConfigureAwait(false)) throw new InvalidOperationException( $"The idempotent table {_options.TableName} has no claim_id column, which claims use since redb.Route 4.8.0, " + $"and CreateTable is off, so the repository does not change the schema. Add it, then start the node: " + $"{AddClaimIdColumnDdl(conn, _options.TableName)}"); outsideTransaction.Complete(); _claimIdColumnSeen = true; } finally { _ddlLock.Release(); } } /// Whether the table has a claim_id column: a query that names it, and returns no row, succeeds. private async Task HasClaimIdColumnAsync(DbConnection conn, CancellationToken ct) { await using var probe = conn.CreateCommand(); probe.CommandText = $"SELECT claim_id FROM {_options.TableName} WHERE 1 = 0"; try { await using var reader = await probe.ExecuteReaderAsync(ct).ConfigureAwait(false); return true; } catch (DbException) { return false; } } /// Adds the claim_id column; when another node added it at the same moment, its column is taken. private async Task AddClaimIdColumnAsync(DbConnection conn, CancellationToken ct) { await using var alter = conn.CreateCommand(); alter.CommandText = AddClaimIdColumnDdl(conn, _options.TableName); try { await alter.ExecuteNonQueryAsync(ct).ConfigureAwait(false); } catch (DbException) { if (!await HasClaimIdColumnAsync(conn, ct).ConfigureAwait(false)) throw; } } /// /// The statement that adds the nullable claim_id column to a table created before 4.8.0: rows written before /// keep a null claim id. /// private static string AddClaimIdColumnDdl(DbConnection conn, string table) => IsSqlServer(conn) ? $"ALTER TABLE {table} ADD claim_id NVARCHAR(36) NULL" : $"ALTER TABLE {table} ADD COLUMN claim_id VARCHAR(36) NULL"; /// True when the live connection is a SQL Server connection (exact class-name match, /// so MySqlConnection/NpgsqlConnection/SqliteConnection are not misdetected). private static bool IsSqlServer(DbConnection conn) => string.Equals(conn.GetType().Name, "SqlConnection", StringComparison.Ordinal); /// /// Whether enlists in an ambient transaction. Npgsql and SqlClient do by default (Enlist is /// on) and are the providers this is established for; any other provider, and Enlist=false or no, is taken as /// staying outside, so the consumer removes the key itself rather than leave one whose work never committed. /// private static bool EnlistsInAmbientTransaction(DbConnection conn) { if (conn.GetType().Name is not ("NpgsqlConnection" or "SqlConnection")) return false; var settings = new DbConnectionStringBuilder { ConnectionString = conn.ConnectionString }; return !settings.TryGetValue("Enlist", out var enlist) || Convert.ToString(enlist, CultureInfo.InvariantCulture)?.Trim().ToLowerInvariant() is not ("false" or "no"); } /// /// Returns the CREATE TABLE statement for the connection's dialect. The key columns are sized: MySQL and MariaDB refuse a /// TEXT column in a primary key (error 1170), and on SQL Server a clustered key is limited to 900 bytes — a /// processor name of 128 and a message key of 255 characters (766 bytes as NVARCHAR) stay inside it. /// private static string BuildCreateTableDdl(DbConnection conn, string table) => IsSqlServer(conn) ? $""" IF OBJECT_ID(N'{table}', N'U') IS NULL CREATE TABLE {table} ( processor_name NVARCHAR(128) NOT NULL, message_key NVARCHAR(255) NOT NULL, created_at NVARCHAR(64) NOT NULL, confirmed INT NOT NULL DEFAULT 0, claim_id NVARCHAR(36) NULL, PRIMARY KEY (processor_name, message_key) ) """ : $""" CREATE TABLE IF NOT EXISTS {table} ( processor_name VARCHAR(128) NOT NULL, message_key VARCHAR(255) NOT NULL, created_at VARCHAR(64) NOT NULL, confirmed INTEGER NOT NULL DEFAULT 0, claim_id VARCHAR(36) NULL, PRIMARY KEY (processor_name, message_key) ) """; private async Task CleanupIfNeededAsync(CancellationToken ct) { if (_options.Ttl is not { } ttl) return; await using var conn = await _connectionFactory.CreateConnectionAsync(ct: ct).ConfigureAwait(false); await using var cmd = conn.CreateCommand(); cmd.CommandText = $""" DELETE FROM {_options.TableName} WHERE processor_name = @processor AND created_at < {UtcText(cmd, conn, ttl)} """; AddParam(cmd, "processor", _options.ProcessorName); await cmd.ExecuteNonQueryAsync(ct).ConfigureAwait(false); } /// /// The current UTC time minus , as SQL for (its parameter is added): the /// created_at text, ISO 8601 with seven fraction digits and +00:00, the round-trip form of a /// in UTC, so the text orders as the time does whichever clock wrote it. The database's /// clock on SQL Server, PostgreSQL, SQLite and MySQL/MariaDB, so the nodes' clocks do not enter; on another database /// the application's, as before (the stamp, the re-stamp and the cutoff then all take it). /// private static string UtcText(DbCommand cmd, DbConnection conn, TimeSpan age) { var sql = conn.GetType().Name switch { "SqlConnection" => "FORMAT(DATEADD(SECOND, -CAST(@ageMs / 1000 AS INT), DATEADD(MILLISECOND, -CAST(@ageMs % 1000 AS INT), SYSUTCDATETIME())), " + "'yyyy-MM-dd''T''HH:mm:ss.fffffff', 'en-US') + '+00:00'", "NpgsqlConnection" => "to_char((clock_timestamp() AT TIME ZONE 'UTC') - @ageMs * interval '1 millisecond', 'YYYY-MM-DD\"T\"HH24:MI:SS.US') || '0+00:00'", "SqliteConnection" => "strftime('%Y-%m-%dT%H:%M:%f', 'now', '-' || (@ageMs / 1000.0) || ' seconds') || '0000+00:00'", "MySqlConnection" => "CONCAT(DATE_FORMAT(UTC_TIMESTAMP(6) - INTERVAL (@ageMs * 1000) MICROSECOND, '%Y-%m-%dT%H:%i:%s.%f'), '0+00:00')", _ => null, }; if (sql is null) { AddParam(cmd, "clock", DateTimeOffset.UtcNow.Subtract(age).ToString("O")); return "@clock"; } AddParam(cmd, "ageMs", (long)age.TotalMilliseconds); return sql; } private static void AddParam(DbCommand cmd, string name, object value) { var p = cmd.CreateParameter(); p.ParameterName = name; p.Value = value; cmd.Parameters.Add(p); } }