Path: redb-route/tests/redb.Route.Tests.Sql/E2E/Base/SqlIdempotentLeaseTestsBase.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/tests/redb.Route.Tests.Sql/E2E/Base/SqlIdempotentLeaseTestsBase.cs
----
using System.Data.Common;
using redb.Route.Abstractions;
using redb.Route.Sql.Connection;
using redb.Route.Sql.Repositories;
using redb.Route.Tests.Sql.E2E.Infrastructure;
namespace redb.Route.Tests.Sql.E2E.Base;
///
/// The claim id of : a holder that outlived the timeout and was taken over settles
/// nothing of the new holder's claim, rows without a claim id (written by Add or by a 4.7 node) are claimed as
/// before, a 4.7 node's unconditional Confirm and Remove still work on the table, and a table created before 4.8.0 gets
/// its claim_id column from the repository, or names the statement that adds it when the repository may not.
/// Takeovers are made deterministic by ageing the held row in the database, not by waiting.
///
public abstract class SqlIdempotentLeaseTestsBase : IAsyncLifetime
{
private static readonly TimeSpan Timeout = TimeSpan.FromMinutes(1);
private readonly string _table = "rsql_lease_" + Guid.NewGuid().ToString("N")[..12];
/// The provider under test.
protected abstract SqlE2EProvider Provider { get; }
public Task InitializeAsync() => Task.CompletedTask;
public async Task DisposeAsync()
{
try
{
await using var connection = await Factory().CreateConnectionAsync();
try { await SqlE2EDatabase.ExecuteAsync(connection, null, $"DROP TABLE {_table}"); }
catch (DbException) { /* the test failed before the table existed */ }
}
finally
{
(Provider as IDisposable)?.Dispose();
}
}
[Fact]
public async Task StaleHolder_AfterATakeover_ConfirmsNothing_TheNewHolderConfirms()
{
var nodeA = Repository();
var nodeB = Repository();
var first = await nodeA.Lease("m1", Timeout);
first.Outcome.Should().Be(IdempotentClaim.Claimed);
first.Token.Should().NotBeNullOrEmpty();
await AgeAsync("m1");
var second = await nodeB.Lease("m1", Timeout);
second.Outcome.Should().Be(IdempotentClaim.TakenOver);
second.Token.Should().NotBe(first.Token);
(await nodeA.Confirm("m1", first.Token, default)).Should().BeFalse("node A's claim was taken over");
(await nodeA.Lease("m1", null)).Outcome.Should().Be(IdempotentClaim.InFlight, "node B's claim is still unconfirmed");
(await nodeB.Confirm("m1", second.Token, default)).Should().BeTrue();
(await nodeA.Lease("m1", null)).Outcome.Should().Be(IdempotentClaim.Confirmed);
}
[Fact]
public async Task StaleHolder_AfterATakeover_ReleasesNothing_TheNewHolderReleases()
{
var nodeA = Repository();
var nodeB = Repository();
var first = await nodeA.Lease("m2", Timeout);
await AgeAsync("m2");
var second = await nodeB.Lease("m2", Timeout);
second.Outcome.Should().Be(IdempotentClaim.TakenOver);
(await nodeA.Release("m2", first.Token, default)).Should().BeFalse("node A's claim was taken over");
(await ClaimIdAsync("m2")).Should().Be(second.Token, "node B's claim stays");
(await nodeB.Release("m2", second.Token, default)).Should().BeTrue();
(await nodeA.Contains("m2")).Should().BeFalse();
(await nodeA.Lease("m2", Timeout)).Outcome.Should().Be(IdempotentClaim.Claimed);
}
[Fact]
public async Task OwnClaim_ConfirmsAndReleases_ByItsToken()
{
var repository = Repository();
var lease = await repository.Lease("own", Timeout);
(await ClaimIdAsync("own")).Should().Be(lease.Token);
(await repository.Confirm("own", lease.Token, default)).Should().BeTrue();
(await repository.Confirm("own", lease.Token, default)).Should().BeTrue("confirming again finds the same claim");
(await repository.Lease("own", Timeout)).Should().Be(new IdempotentLease(IdempotentClaim.Confirmed, null));
var other = await repository.Lease("own-2", Timeout);
(await repository.Release("own-2", other.Token, default)).Should().BeTrue();
(await repository.Contains("own-2")).Should().BeFalse();
}
[Fact]
public async Task RowWithoutClaimId_IsClaimedAsBefore_AndNoTokenSettlesIt()
{
// A row as a 4.7 node, or Add, writes it: no claim id.
var repository = Repository();
(await repository.Add("legacy")).Should().BeTrue();
(await ClaimIdAsync("legacy")).Should().BeNull();
(await repository.Lease("legacy", Timeout)).Should().Be(new IdempotentLease(IdempotentClaim.InFlight, null));
(await repository.Confirm("legacy", Guid.NewGuid().ToString("N"), default)).Should().BeFalse("no token holds a row without a claim id");
(await repository.Release("legacy", Guid.NewGuid().ToString("N"), default)).Should().BeFalse();
(await repository.Contains("legacy")).Should().BeTrue();
await AgeAsync("legacy");
var takeover = await repository.Lease("legacy", Timeout);
takeover.Outcome.Should().Be(IdempotentClaim.TakenOver, "an abandoned row without a claim id is taken over as before");
(await ClaimIdAsync("legacy")).Should().Be(takeover.Token);
await repository.Add("legacy-done");
await repository.Confirm("legacy-done");
await AgeAsync("legacy-done");
(await repository.Lease("legacy-done", Timeout)).Outcome.Should().Be(IdempotentClaim.Confirmed, "a confirmed row is never taken over");
}
[Fact]
public async Task OldNode_UnconditionalConfirmAndRemove_StillWorkOnAClaimWithAnId()
{
// The rolling upgrade: a 4.8 node holds a claim with an id; a 4.7 node settles the key with the calls it has.
var newNode = Repository();
var oldNode = Repository();
var held = await newNode.Lease("rolling", Timeout);
await oldNode.Confirm("rolling");
(await newNode.Lease("rolling", Timeout)).Outcome.Should().Be(IdempotentClaim.Confirmed);
(await newNode.Confirm("rolling", held.Token, default)).Should().BeTrue("the claim is still the one node A holds");
var again = await newNode.Lease("rolling-2", Timeout);
await oldNode.Remove("rolling-2");
(await newNode.Release("rolling-2", again.Token, default)).Should().BeFalse("the old node removed it already");
(await oldNode.Add("rolling-2")).Should().BeTrue("the old node's insert names its columns and leaves claim_id empty");
(await newNode.Lease("rolling-2", Timeout)).Outcome.Should().Be(IdempotentClaim.InFlight);
}
[Fact]
public async Task TableFromBefore48_GetsItsClaimIdColumn_WhenTheRepositoryCreatesTables()
{
await CreateTableWithoutClaimIdAsync();
await SeedAsync("before", confirmed: false, createdAt: "2000-01-01T00:00:00.0000000+00:00");
var repository = Repository();
var lease = await repository.Lease("after", Timeout);
lease.Outcome.Should().Be(IdempotentClaim.Claimed);
(await ClaimIdAsync("after")).Should().Be(lease.Token);
(await ClaimIdAsync("before")).Should().BeNull("rows written before keep an empty claim id");
(await repository.Lease("before", Timeout)).Outcome.Should().Be(IdempotentClaim.TakenOver);
}
[Fact]
public async Task TableFromBefore48_WithoutCreateTable_FailsTheFirstClaim_NamingTheAlter_AddStillWorks()
{
await CreateTableWithoutClaimIdAsync();
var repository = Repository(createTable: false);
(await repository.Add("plain")).Should().BeTrue("Add writes no claim id and needs no new column");
var act = () => repository.Lease("claimed", Timeout);
(await act.Should().ThrowAsync())
.WithMessage($"*{_table}*claim_id*ALTER TABLE {_table} ADD*claim_id*");
await using (var connection = await Factory().CreateConnectionAsync())
await SqlE2EDatabase.ExecuteAsync(connection, null, AlterSql());
(await repository.Lease("claimed", Timeout)).Outcome.Should().Be(IdempotentClaim.Claimed, "after the ALTER the node claims");
}
/// Makes the row of look abandoned: its stamp moves to the year 2000.
private async Task AgeAsync(string key)
{
await using var connection = await Factory().CreateConnectionAsync();
await SqlE2EDatabase.ExecuteAsync(connection, null,
$"UPDATE {_table} SET created_at = '2000-01-01T00:00:00.0000000+00:00' WHERE processor_name = 'route-1' AND message_key = '{key}'");
}
private async Task ClaimIdAsync(string key)
{
await using var connection = await Factory().CreateConnectionAsync();
await using var cmd = connection.CreateCommand();
cmd.CommandText = $"SELECT claim_id FROM {_table} WHERE processor_name = 'route-1' AND message_key = '{key}'";
return await cmd.ExecuteScalarAsync() is string id ? id : null;
}
/// The table as redb.Route 4.7 created it: no claim_id column.
private async Task CreateTableWithoutClaimIdAsync()
{
await using var connection = await Factory().CreateConnectionAsync();
await SqlE2EDatabase.ExecuteAsync(connection, null, $"""
CREATE TABLE {_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,
PRIMARY KEY (processor_name, message_key)
)
""");
}
private async Task SeedAsync(string key, bool confirmed, string createdAt)
{
await using var connection = await Factory().CreateConnectionAsync();
await SqlE2EDatabase.ExecuteAsync(connection, null,
$"INSERT INTO {_table} (processor_name, message_key, created_at, confirmed) VALUES ('route-1', '{key}', '{createdAt}', {(confirmed ? 1 : 0)})");
}
private string AlterSql() => Provider.Factory.GetType().Name == "SqlClientFactory"
? $"ALTER TABLE {_table} ADD claim_id NVARCHAR(36) NULL"
: $"ALTER TABLE {_table} ADD COLUMN claim_id VARCHAR(36) NULL";
private SqlIdempotentRepository Repository(bool createTable = true) =>
new(Factory(), new SqlIdempotentOptions { ProcessorName = "route-1", TableName = _table, CreateTable = createTable });
private ISqlConnectionFactory Factory() =>
new SqlConnectionFactory(new SqlConnectionOptions { ConnectionString = Provider.ConnectionString, ProviderFactory = Provider.Factory });
}