Path: redb-route/tests/redb.Route.Tests.Core/RedbIdempotentRepositoryTests.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.Core/RedbIdempotentRepositoryTests.cs
----
using Microsoft.Extensions.DependencyInjection;
using redb.Core;
using redb.Core.Models.Contracts;
using redb.Core.Models.Entities;
using redb.Core.Query;
using redb.Route.Abstractions;
using redb.Route.RedbCore.Models;
using redb.Route.RedbCore.Repositories;
using System.Linq.Expressions;
namespace redb.Route.Tests.Core;
///
/// Unit tests for .
/// Uses NSubstitute to mock behind .
///
public sealed class RedbIdempotentRepositoryTests
{
private readonly IRedbService _redb = Substitute.For();
private readonly IServiceScopeFactory _scopeFactory;
private readonly RedbIdempotentOptions _defaultOptions = new()
{
ProcessorName = "test-route"
};
public RedbIdempotentRepositoryTests()
{
var scope = Substitute.For();
var sp = Substitute.For();
sp.GetService(typeof(IRedbService)).Returns(_redb);
scope.ServiceProvider.Returns(sp);
_scopeFactory = Substitute.For();
_scopeFactory.CreateScope().Returns(scope);
}
private IServiceScopeFactory CreateScopeFactory(IRedbService redb)
{
var scope = Substitute.For();
var sp = Substitute.For();
sp.GetService(typeof(IRedbService)).Returns(redb);
scope.ServiceProvider.Returns(sp);
var factory = Substitute.For();
factory.CreateScope().Returns(scope);
return factory;
}
private RedbIdempotentRepository CreateSut(RedbIdempotentOptions? options = null)
=> new(_scopeFactory, options ?? _defaultOptions);
private void SetupQuery(List> results)
{
var queryable = Substitute.For>();
queryable.Where(Arg.Any>>()).Returns(queryable);
queryable.WhereRedb(Arg.Any>>()).Returns(queryable);
queryable.ToListAsync().Returns(Task.FromResult(results));
_redb.Query().Returns(queryable);
}
// ── Constructor ─────────────────────────────────────────────────
[Fact]
public void Ctor_NullScopeFactory_Throws()
{
var act = () => new RedbIdempotentRepository((IServiceScopeFactory)null!, _defaultOptions);
act.Should().Throw().WithParameterName("scopeFactory");
}
[Fact]
public void Ctor_NullOpenScope_Throws()
{
var act = () => new RedbIdempotentRepository((Func)null!, _defaultOptions);
act.Should().Throw().WithParameterName("openScope");
}
[Fact]
public void Ctor_NullOptions_Throws()
{
var act = () => new RedbIdempotentRepository(_scopeFactory, null!);
act.Should().Throw().WithParameterName("options");
}
// ── Add ─────────────────────────────────────────────────────────
[Fact]
public async Task Add_NullKey_Throws()
{
var sut = CreateSut();
var act = () => sut.Add(null!);
await act.Should().ThrowAsync().WithParameterName("key");
}
[Fact]
public async Task Add_NewKey_SyncsScheme_SavesEntry_ReturnsTrue()
{
SetupQuery([]);
_redb.SaveAsync(Arg.Any>()).Returns(1L);
var sut = CreateSut();
var result = await sut.Add("msg-001");
result.Should().BeTrue();
await _redb.Received(1).SyncSchemeAsync();
await _redb.Received(1).SaveAsync(Arg.Is>(o =>
o.Props.ProcessorName == "test-route" &&
o.Props.MessageKey == "msg-001" &&
o.Props.Confirmed == false));
}
[Fact]
public async Task Add_DuplicateKey_ReturnsFalse()
{
var existing = new RedbObject
{
id = 42,
Props = new IdempotentEntryProps
{
ProcessorName = "test-route",
MessageKey = "msg-001",
CreatedAt = DateTimeOffset.UtcNow,
Confirmed = false
}
};
SetupQuery([existing]);
var sut = CreateSut();
var result = await sut.Add("msg-001");
result.Should().BeFalse();
await _redb.DidNotReceive().SaveAsync(Arg.Any>());
}
[Fact]
public async Task Add_SyncSchemeCalledOnlyOnce()
{
SetupQuery([]);
_redb.SaveAsync(Arg.Any>()).Returns(1L);
var sut = CreateSut();
await sut.Add("msg-001");
await sut.Add("msg-002");
await _redb.Received(1).SyncSchemeAsync();
}
// ── Add: unique-key race barrier ────────────────────────────────
[Fact]
public async Task Add_SaveHitsUniqueViolation_ReturnsFalseInsteadOfThrowing()
{
// The lookup saw nothing, but a concurrent Add committed the key before our insert:
// the per-scheme unique index rejects the row and the loser must report "duplicate".
SetupQuery([]);
_redb.SaveAsync(Arg.Any>())
.Returns(Task.FromException(new redb.Core.Exceptions.RedbUniqueViolationException(
null, null, null, null, "UIX__objects__scheme_unique", null, new InvalidOperationException("23505"))));
var sut = CreateSut();
var result = await sut.Add("msg-race");
result.Should().BeFalse();
}
[Fact]
public async Task Add_StampsValueUnique_WithCompositeName()
{
SetupQuery([]);
RedbObject? saved = null;
_redb.SaveAsync(Arg.Do>(o => saved = (RedbObject)o))
.Returns(1L);
var sut = CreateSut();
await sut.Add("msg-001");
saved.Should().NotBeNull();
saved!.ValueUnique.Should().Be("test-route:msg-001");
saved.name.Should().Be(saved.ValueUnique);
}
// ── ComposeEntryName normalization ──────────────────────────────
[Fact]
public void ComposeEntryName_ShortComposite_IsRawAndReadable()
{
RedbIdempotentRepository.ComposeEntryName("proc", "key-1")
.Should().Be("proc:key-1");
}
[Fact]
public void ComposeEntryName_LongComposite_FitsLimitAndStaysDistinct()
{
var prefix = new string('a', 500);
var name1 = RedbIdempotentRepository.ComposeEntryName("proc", prefix + "-tail-1");
var name2 = RedbIdempotentRepository.ComposeEntryName("proc", prefix + "-tail-2");
// Fits _objects._value_unique (varchar(440)) and MSSQL _objects._name (nvarchar(450)).
name1.Length.Should().Be(440);
name1.Should().StartWith("proc:aaaa");
// Keys differing only past the readable prefix still map to distinct identities.
name1.Should().NotBe(name2);
name1[..375].Should().Be(name2[..375]);
// Deterministic: the same composite always maps to the same identity.
RedbIdempotentRepository.ComposeEntryName("proc", prefix + "-tail-1").Should().Be(name1);
}
// ── Add with TTL cleanup ────────────────────────────────────────
[Fact]
public async Task Add_WithTtl_CleansExpired()
{
var options = new RedbIdempotentOptions
{
ProcessorName = "test-route",
Ttl = TimeSpan.FromMinutes(30)
};
// Setup two separate query chains: one for cleanup, one for add-check
var cleanupQuery = Substitute.For>();
cleanupQuery.Where(Arg.Any>>()).Returns(cleanupQuery);
cleanupQuery.WhereRedb(Arg.Any>>()).Returns(cleanupQuery);
cleanupQuery.ToListAsync().Returns(Task.FromResult(new List>()));
_redb.Query().Returns(cleanupQuery);
_redb.SaveAsync(Arg.Any>()).Returns(1L);
var sut = CreateSut(options);
await sut.Add("msg-001");
// Query called at least twice: once for cleanup, once for duplicate check
_redb.Received(2).Query();
}
// ── Confirm ─────────────────────────────────────────────────────
[Fact]
public async Task Confirm_NullKey_Throws()
{
var sut = CreateSut();
var act = () => sut.Confirm(null!);
await act.Should().ThrowAsync().WithParameterName("key");
}
[Fact]
public async Task Confirm_ExistingEntry_SetsConfirmedTrue()
{
var entry = new RedbObject
{
id = 42,
Props = new IdempotentEntryProps
{
ProcessorName = "test-route",
MessageKey = "msg-001",
CreatedAt = DateTimeOffset.UtcNow,
Confirmed = false
}
};
SetupQuery([entry]);
_redb.SaveAsync(Arg.Any()).Returns(42L);
var sut = CreateSut();
await sut.Confirm("msg-001");
entry.Props.Confirmed.Should().BeTrue();
await _redb.Received(1).SaveAsync(Arg.Is>(o =>
o.Props.Confirmed == true));
}
[Fact]
public async Task Confirm_NoEntry_DoesNothing()
{
SetupQuery([]);
var sut = CreateSut();
await sut.Confirm("msg-missing");
await _redb.DidNotReceive().SaveAsync(Arg.Any());
}
// ── Remove ──────────────────────────────────────────────────────
[Fact]
public async Task Remove_NullKey_Throws()
{
var sut = CreateSut();
var act = () => sut.Remove(null!);
await act.Should().ThrowAsync().WithParameterName("key");
}
[Fact]
public async Task Remove_ExistingEntry_DeletesIt()
{
var entry = new RedbObject
{
id = 42,
Props = new IdempotentEntryProps
{
ProcessorName = "test-route",
MessageKey = "msg-001",
CreatedAt = DateTimeOffset.UtcNow
}
};
SetupQuery([entry]);
_redb.DeleteAsync(Arg.Any()).Returns(true);
var sut = CreateSut();
await sut.Remove("msg-001");
await _redb.Received(1).DeleteAsync(Arg.Is>(o => o.id == 42));
}
[Fact]
public async Task Remove_NoEntry_DoesNothing()
{
SetupQuery([]);
var sut = CreateSut();
await sut.Remove("msg-missing");
await _redb.DidNotReceive().DeleteAsync(Arg.Any());
}
// ── Contains ────────────────────────────────────────────────────
[Fact]
public async Task Contains_NullKey_Throws()
{
var sut = CreateSut();
var act = () => sut.Contains(null!);
await act.Should().ThrowAsync().WithParameterName("key");
}
[Fact]
public async Task Contains_ExistingEntry_ReturnsTrue()
{
var entry = new RedbObject
{
id = 42,
Props = new IdempotentEntryProps
{
ProcessorName = "test-route",
MessageKey = "msg-001",
CreatedAt = DateTimeOffset.UtcNow
}
};
SetupQuery([entry]);
var sut = CreateSut();
var result = await sut.Contains("msg-001");
result.Should().BeTrue();
}
[Fact]
public async Task Contains_MissingEntry_ReturnsFalse()
{
SetupQuery([]);
var sut = CreateSut();
var result = await sut.Contains("msg-missing");
result.Should().BeFalse();
}
// ── Clear ───────────────────────────────────────────────────────
[Fact]
public async Task Clear_EntriesExist_DeletesAll()
{
var entries = new List>
{
new() { id = 1, Props = new() { ProcessorName = "test-route", MessageKey = "a" } },
new() { id = 2, Props = new() { ProcessorName = "test-route", MessageKey = "b" } },
new() { id = 3, Props = new() { ProcessorName = "test-route", MessageKey = "c" } }
};
SetupQuery(entries);
_redb.DeleteAsync(Arg.Any>()).Returns(3);
var sut = CreateSut();
await sut.Clear();
await _redb.Received(1).DeleteAsync(Arg.Any>());
}
[Fact]
public async Task Clear_NoEntries_SkipsDelete()
{
SetupQuery([]);
var sut = CreateSut();
await sut.Clear();
await _redb.DidNotReceive().DeleteAsync(Arg.Any>());
}
// ── Processor isolation ─────────────────────────────────────────
[Fact]
public async Task Add_DifferentProcessors_AreIsolated()
{
// Processor A has "msg-001"
var aQuery = Substitute.For>();
aQuery.Where(Arg.Any>>()).Returns(aQuery);
aQuery.WhereRedb(Arg.Any>>()).Returns(aQuery);
aQuery.ToListAsync().Returns(Task.FromResult(new List>
{
new()
{
id = 1,
Props = new() { ProcessorName = "route-A", MessageKey = "msg-001" }
}
}));
// Processor B does not have "msg-001"
var bRedb = Substitute.For();
var bQuery = Substitute.For>();
bQuery.Where(Arg.Any>>()).Returns(bQuery);
bQuery.WhereRedb(Arg.Any>>()).Returns(bQuery);
bQuery.ToListAsync().Returns(Task.FromResult(new List>()));
bRedb.Query().Returns(bQuery);
bRedb.SaveAsync(Arg.Any>()).Returns(2L);
_redb.Query().Returns(aQuery);
var sutA = new RedbIdempotentRepository(_scopeFactory, new RedbIdempotentOptions { ProcessorName = "route-A" });
var sutB = new RedbIdempotentRepository(CreateScopeFactory(bRedb), new RedbIdempotentOptions { ProcessorName = "route-B" });
var resultA = await sutA.Add("msg-001"); // already exists
var resultB = await sutB.Add("msg-001"); // new for route-B
resultA.Should().BeFalse();
resultB.Should().BeTrue();
}
// ── IdempotentEntryProps model ──────────────────────────────────
[Fact]
public void IdempotentEntryProps_Defaults()
{
var props = new IdempotentEntryProps();
props.ProcessorName.Should().BeEmpty();
props.MessageKey.Should().BeEmpty();
props.CreatedAt.Should().Be(default);
props.Confirmed.Should().BeFalse();
}
// ── Interface compliance ────────────────────────────────────────
[Fact]
public void Implements_IIdempotentRepository()
{
var sut = CreateSut();
sut.Should().BeAssignableTo();
}
// ── An entry read while another caller deletes it ───────────────
///
/// The entry of a key that another node is deleting at that moment: the lookup by name still finds its object, and
/// its props are gone (PostgreSQL, two nodes on one key). Each operation passes it over instead of failing.
///
private static RedbObject EntryBeingDeleted() => new() { id = 42, Props = null! };
[Fact]
public async Task Add_WhileTheEntryIsBeingDeleted_ClaimsTheKey_InsteadOfThrowing()
{
SetupQuery([EntryBeingDeleted()]);
_redb.SaveAsync(Arg.Any>()).Returns(1L);
var result = await CreateSut().Add("msg-001");
result.Should().BeTrue("the entry found is on its way out; uniqueness decides if it is not gone yet");
}
[Fact]
public async Task Contains_WhileTheEntryIsBeingDeleted_IsFalse_InsteadOfThrowing()
{
SetupQuery([EntryBeingDeleted()]);
(await CreateSut().Contains("msg-001")).Should().BeFalse();
}
[Fact]
public async Task Confirm_WhileTheEntryIsBeingDeleted_SavesNothing_InsteadOfThrowing()
{
SetupQuery([EntryBeingDeleted()]);
await CreateSut().Confirm("msg-001");
await _redb.DidNotReceive().SaveAsync(Arg.Any>());
}
[Fact]
public async Task Remove_WhileTheEntryIsBeingDeleted_DeletesNothing_InsteadOfThrowing()
{
SetupQuery([EntryBeingDeleted()]);
await CreateSut().Remove("msg-001");
await _redb.DidNotReceive().DeleteAsync(Arg.Any());
}
[Fact]
public async Task Claim_WhileTheEntryIsBeingDeleted_DoesNotThrow()
{
SetupQuery([EntryBeingDeleted()]);
_redb.SaveAsync(Arg.Any>()).Returns(1L);
(await CreateSut().Claim("msg-001", TimeSpan.FromMinutes(10))).Should().Be(IdempotentClaim.Claimed);
}
}