Path: redb-route/tests/redb.Route.Tests.As2/As2DuplicateTests.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.As2/As2DuplicateTests.cs ---- using System.Net; using AwesomeAssertions; using redb.Route.As2; using redb.Route.As2.Crypto; using redb.Route.As2.Mdn; using redb.Route.Components; using redb.Route.Core; using redb.Route.Processors; using As2Dsl = redb.Route.As2.Fluent.As2; using static redb.Route.Tests.As2.As2TestKit; namespace redb.Route.Tests.As2; /// /// A partner that did not get our answer sends the document again with the same Message-ID. /// With an idempotent repository named, the resend is answered and not delivered twice, as the AS4 receiver does. /// public class As2DuplicateTests { private static async Task<(RouteContext Context, List Routed, int Port)> StartReceiver( string? repository, Func? failOnAttempt = null) { var port = FreePort(); var context = new RouteContext(); context.AddComponent(new As2Component()); context.AddToRegistry("recv", Receiver()); context.AddIdempotentRepository("dedup", new InMemoryIdempotentRepository()); var routed = new List(); var attempts = 0; var receive = As2Dsl.Receive("/in").Host("127.0.0.1").Port(port).ConnectionFactory("recv"); if (repository is not null) receive = receive.IdempotentRepository(repository); context.AddRoutes(r => r.From(receive).Process(e => { var attempt = Interlocked.Increment(ref attempts); if (failOnAttempt?.Invoke(attempt) == true) throw new InvalidOperationException("the route is down"); lock (routed) routed.Add(e.In.GetHeader(As2Headers.MessageId)!); })); await context.Start(); return (context, routed, port); } private static MdnParser.MdnResult Mdn(HttpResponseMessage response) => MdnParser.Parse( response.Content.Headers.ContentType?.ToString(), response.Content.Headers.TryGetValues("Content-Transfer-Encoding", out var v) ? string.Join(",", v) : null, response.Content.ReadAsByteArrayAsync().GetAwaiter().GetResult(), new As2CryptoEngine(), Cert); [Fact] public async Task Resend_OfADeliveredMessage_IsAnswered_AndNotDeliveredAgain() { var (context, routed, port) = await StartReceiver("dedup"); await using var _ = context; var message = BuildMessage("PO*ONCE~", Cert, Cert); var id = new Dictionary { ["Message-ID"] = "" }; var first = Mdn(await PostAsync(port, "/in", message, id)); var again = Mdn(await PostAsync(port, "/in", message, id)); routed.Should().ContainSingle().Which.Should().Be(""); first.Disposition.Should().EndWith("; processed"); again.IsPositive.Should().BeTrue("the document was processed, once"); again.Disposition.Should().EndWith("processed/warning: duplicate-document"); again.ReceivedMic.Should().Be(first.ReceivedMic); } [Fact] public async Task Resend_AfterTheRouteFailed_IsDelivered() { var (context, routed, port) = await StartReceiver("dedup", attempt => attempt == 1); await using var _ = context; var message = BuildMessage("PO*RETRY~", Cert, Cert); var id = new Dictionary { ["Message-ID"] = "" }; Mdn(await PostAsync(port, "/in", message, id)).IsPositive.Should().BeFalse(); Mdn(await PostAsync(port, "/in", message, id)).IsPositive.Should().BeTrue(); routed.Should().ContainSingle("the first attempt did not process the document, so its resend is not a duplicate"); } [Fact] public async Task ForgedCopy_DoesNotBurnTheMessageId() { var (context, routed, port) = await StartReceiver("dedup"); await using var _ = context; var id = new Dictionary { ["Message-ID"] = "" }; // Claimed only after authentication: a stranger's copy with the id must not make the real message a "duplicate". await PostAsync(port, "/in", BuildMessage("PO*FORGED~", Stranger, Cert), id); await PostAsync(port, "/in", BuildMessage("PO*REAL~", Cert, Cert), id); routed.Should().ContainSingle(); } [Fact] public async Task WithoutARepository_EveryCopyIsDelivered() { var (context, routed, port) = await StartReceiver(null); await using var _ = context; var message = BuildMessage("PO*TWICE~", Cert, Cert); var id = new Dictionary { ["Message-ID"] = "" }; await PostAsync(port, "/in", message, id); await PostAsync(port, "/in", message, id); routed.Should().HaveCount(2); } [Fact] public async Task UnknownRepository_StopsTheReceiverFromStarting() { await using var context = new RouteContext(); context.AddComponent(new As2Component()); context.AddToRegistry("recv", Receiver()); var consumer = context.GetEndpoint(As2Dsl.Receive("/in").Host("127.0.0.1").Port(FreePort()).ConnectionFactory("recv").IdempotentRepository("nope")) .CreateConsumer(new DelegateProcessor(_ => { })); var act = () => consumer.Start(); (await act.Should().ThrowAsync()).Which.Message.Should().Contain("nope"); } [Fact] public async Task Resend_WhileTheFirstCopyIsStillInTheRoute_IsRefusedAsBusy_AndDeliveredAfterTheFirstFails() { // The first copy fails after the resend arrived: answering the resend "duplicate-document" would have told the // partner the document was received, and the release of the first claim would have lost it. var port = FreePort(); var entered = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); var release = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); var attempts = 0; var routed = new List(); await using var context = new RouteContext(); context.AddComponent(new As2Component()); context.AddToRegistry("recv", Receiver()); context.AddIdempotentRepository("dedup", new InMemoryIdempotentRepository()); context.AddRoutes(r => r.From(As2Dsl.Receive("/in").Host("127.0.0.1").Port(port).ConnectionFactory("recv").IdempotentRepository("dedup")) .Process(async (e, _) => { if (Interlocked.Increment(ref attempts) == 1) { entered.TrySetResult(); await release.Task; throw new InvalidOperationException("the route is down"); } lock (routed) routed.Add(e.In.GetHeader(As2Headers.MessageId)!); })); await context.Start(); var message = BuildMessage("PO*INFLIGHT~", Cert, Cert); var id = new Dictionary { ["Message-ID"] = "" }; var first = PostAsync(port, "/in", message, id); await entered.Task.WaitAsync(TimeSpan.FromSeconds(10)); var resend = await PostAsync(port, "/in", message, id); resend.StatusCode.Should().Be(HttpStatusCode.ServiceUnavailable); resend.Headers.RetryAfter!.Delta.Should().Be(TimeSpan.FromSeconds(30)); resend.Content.Headers.ContentLength.Should().Be(0, "no MDN: nothing was decided about the document"); release.SetResult(); Mdn(await first).Disposition.Should().EndWith("processed/error: unexpected-processing-error"); var later = Mdn(await PostAsync(port, "/in", message, id)); later.Disposition.Should().EndWith("; processed", "the failed copy released its claim, so the resend is delivered"); routed.Should().ContainSingle().Which.Should().Be(""); } [Fact] public async Task AClaimTakenOverWhileTheRouteRuns_IsNotConfirmedByTheFirstHolder() { // The route outlives the timeout and another node takes the claim over meanwhile: the first holder's confirmation // must leave that node's claim alone, unconfirmed, for its holder to settle. var repository = new InMemoryIdempotentRepository(); var port = FreePort(); string? otherToken = null; await using var context = new RouteContext(); context.AddComponent(new As2Component()); context.AddToRegistry("recv", Receiver()); context.AddIdempotentRepository("dedup", repository); context.AddRoutes(r => r.From(As2Dsl.Receive("/in").Host("127.0.0.1").Port(port).ConnectionFactory("recv") .IdempotentRepository("dedup")) .Process(_ => { Thread.Sleep(50); var other = repository.Lease("", TimeSpan.FromMilliseconds(10)).GetAwaiter().GetResult(); other.Outcome.Should().Be(redb.Route.Abstractions.IdempotentClaim.TakenOver); otherToken = other.Token; })); await context.Start(); var mdn = Mdn(await PostAsync(port, "/in", BuildMessage("PO*SLOW~", Cert, Cert), new Dictionary { ["Message-ID"] = "" })); mdn.Disposition.Should().EndWith("; processed"); (await repository.Claim("", null)).Should().Be(redb.Route.Abstractions.IdempotentClaim.InFlight, "the other node's claim is still its own, unconfirmed"); (await repository.Confirm("", otherToken)).Should().BeTrue(); } [Fact] public async Task AClaimNeverConfirmed_OlderThanInFlightClaimTimeout_IsTakenOver_AndTheMessageDelivered() { // A node stopped between the claim and its confirmation: the claim stays, unconfirmed. var repository = new InMemoryIdempotentRepository(); (await repository.Add("")).Should().BeTrue(); var port = FreePort(); var routed = 0; await using var context = new RouteContext(); context.AddComponent(new As2Component()); context.AddToRegistry("recv", Receiver()); context.AddIdempotentRepository("dedup", repository); context.AddRoutes(r => r.From(As2Dsl.Receive("/in").Host("127.0.0.1").Port(port).ConnectionFactory("recv") .IdempotentRepository("dedup").InFlightClaimTimeout(50)) .Process(_ => Interlocked.Increment(ref routed))); await context.Start(); await Task.Delay(200); var mdn = Mdn(await PostAsync(port, "/in", BuildMessage("PO*ORPHAN~", Cert, Cert), new Dictionary { ["Message-ID"] = "" })); mdn.Disposition.Should().EndWith("; processed"); routed.Should().Be(1); (await repository.Claim("", null)).Should().Be(redb.Route.Abstractions.IdempotentClaim.Confirmed); } [Fact] public async Task AClaimNeverConfirmed_YoungerThanInFlightClaimTimeout_IsRefusedAsBusy() { var repository = new InMemoryIdempotentRepository(); (await repository.Add("")).Should().BeTrue(); var port = FreePort(); await using var context = new RouteContext(); context.AddComponent(new As2Component()); context.AddToRegistry("recv", Receiver()); context.AddIdempotentRepository("dedup", repository); context.AddRoutes(r => r.From(As2Dsl.Receive("/in").Host("127.0.0.1").Port(port).ConnectionFactory("recv").IdempotentRepository("dedup")) .Process(_ => { })); await context.Start(); var response = await PostAsync(port, "/in", BuildMessage("PO*YOUNG~", Cert, Cert), new Dictionary { ["Message-ID"] = "" }); response.StatusCode.Should().Be(HttpStatusCode.ServiceUnavailable); } }