Path: redb-route/tests/redb.Route.Tests.As2/As2AsyncMdnPoolTests.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/As2AsyncMdnPoolTests.cs
----
using System.Diagnostics.Metrics;
using System.Net;
using AwesomeAssertions;
using redb.Route.As2;
using redb.Route.Core;
using As2Dsl = redb.Route.As2.Fluent.As2;
using static redb.Route.Tests.As2.As2TestKit;
namespace redb.Route.Tests.As2;
///
/// Asynchronous MDNs go through a bounded pool: a message that asks for one takes a slot when it is admitted, before
/// any work, and keeps it until its receipt is posted (with bounded retries); with every slot taken it is refused with
/// the endpoint's reject status and Retry-After, as the admission limit refuses (RFC 4130 ยง7: the response comes before
/// the MDN, so the receiver cannot post it in the caller's place).
///
[Collection(nameof(AsyncMdnMetricsCollection))]
public class As2AsyncMdnPoolTests
{
private static As2ConnectionFactory AsyncReceiver() => Receiver(f =>
{
f.MdnMode = As2MdnMode.Async;
f.AsyncMdnAllowedHosts = ["127.0.0.1"];
});
private static Dictionary ReceiptTo(As2Trap trap) => new() { ["Receipt-Delivery-Option"] = trap.Url() };
[Fact]
public void Defaults_Are503_RetryAfter30_Pool20_ThreeAttempts()
{
var options = new As2EndpointOptions();
options.RejectStatusCode.Should().Be(503);
options.RetryAfterSeconds.Should().Be(30);
options.AsyncMdnPoolSize.Should().Be(20);
options.AsyncMdnAttempts.Should().Be(3);
options.AsyncMdnRetryDelay.Should().Be(5000);
}
[Theory]
[InlineData(0, 3, 5000, "asyncMdnPoolSize")]
[InlineData(20, 0, 5000, "asyncMdnAttempts")]
[InlineData(20, 3, -1, "asyncMdnRetryDelay")]
public void InvalidPoolOptions_AreRefused(int pool, int attempts, int delay, string named)
{
var act = () => new As2EndpointOptions { AsyncMdnPoolSize = pool, AsyncMdnAttempts = attempts, AsyncMdnRetryDelay = delay }.Validate();
act.Should().Throw().WithMessage($"*{named}*");
}
[Fact]
public void UriAndDsl_CarryThePoolOptions()
{
var built = As2Dsl.Receive("/in").Port(4080).AsyncMdnPoolSize(4).AsyncMdnRetry(attempts: 5, delayMs: 250).Build();
var options = ((As2Endpoint)new As2Component().CreateEndpoint(EndpointUriParser.Parse(built))).EndpointOptions;
options.AsyncMdnPoolSize.Should().Be(4);
options.AsyncMdnAttempts.Should().Be(5);
options.AsyncMdnRetryDelay.Should().Be(250);
}
[Fact]
public async Task WithEverySlotTaken_AMessageAskingForAnAsyncMdn_IsRefused503_WithRetryAfter_BeforeAnyWork()
{
using var trap = new As2Trap(FreePort());
var port = FreePort();
var entered = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
var release = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
var routed = 0;
await using var context = new RouteContext();
context.AddComponent(new As2Component());
context.AddToRegistry("recv", AsyncReceiver());
context.AddRoutes(r => r.From(As2Dsl.Receive("/in").Host("127.0.0.1").Port(port).ConnectionFactory("recv").AsyncMdnPoolSize(1))
.Process(async (_, _) =>
{
// Only the first message waits: it holds the one slot while it is in the route.
if (Interlocked.Increment(ref routed) != 1) return;
entered.TrySetResult();
await release.Task;
}));
await context.Start();
var first = PostAsync(port, "/in", BuildMessage("PO*1~", Cert, Cert), ReceiptTo(trap));
await entered.Task.WaitAsync(TimeSpan.FromSeconds(10));
var refused = await PostAsync(port, "/in", BuildMessage("PO*2~", Cert, Cert), ReceiptTo(trap));
refused.StatusCode.Should().Be(HttpStatusCode.ServiceUnavailable);
refused.Headers.RetryAfter!.Delta.Should().Be(TimeSpan.FromSeconds(30));
routed.Should().Be(1, "the refused message was not processed");
// A synchronous receipt does not need a slot.
var sync = await PostAsync(port, "/in", BuildMessage("PO*SYNC~", Cert, Cert));
sync.StatusCode.Should().Be(HttpStatusCode.OK);
routed.Should().Be(2);
release.SetResult();
(await first).StatusCode.Should().Be(HttpStatusCode.OK);
(await trap.HitAsync(TimeSpan.FromSeconds(10))).Should().BeTrue();
// The slot comes back once the receipt is posted.
var deadline = DateTime.UtcNow.AddSeconds(10);
HttpResponseMessage again;
do again = await PostAsync(port, "/in", BuildMessage("PO*3~", Cert, Cert), ReceiptTo(trap));
while (again.StatusCode == HttpStatusCode.ServiceUnavailable && DateTime.UtcNow < deadline && await Delay());
again.StatusCode.Should().Be(HttpStatusCode.OK);
}
private static async Task Delay()
{
await Task.Delay(50);
return true;
}
[Fact]
public async Task AnAsyncMdnAnsweredWithAServerError_IsPostedAgain_UntilItIsTaken()
{
using var trap = new As2Trap(FreePort(), hit => hit == 1 ? 503 : 200);
var port = FreePort();
await using var context = new RouteContext();
context.AddComponent(new As2Component());
context.AddToRegistry("recv", AsyncReceiver());
context.AddRoutes(r => r.From(As2Dsl.Receive("/in").Host("127.0.0.1").Port(port).ConnectionFactory("recv").AsyncMdnRetry(3, 50))
.Process(_ => { }));
await context.Start();
(await PostAsync(port, "/in", BuildMessage("PO*RETRY~", Cert, Cert), ReceiptTo(trap))).StatusCode.Should().Be(HttpStatusCode.OK);
var deadline = DateTime.UtcNow.AddSeconds(10);
while (trap.Requests.Count < 2 && DateTime.UtcNow < deadline) await Task.Delay(20);
await Task.Delay(300);
trap.Requests.Should().HaveCount(2, "one failed post, one taken; nothing after it is taken");
}
[Fact]
public async Task AnAsyncMdnThatIsNeverTaken_GivesUpAfterTheAttempts_AndIsCounted()
{
using var trap = new As2Trap(FreePort(), _ => 500);
var port = FreePort();
long failed = 0;
using var listener = new MeterListener();
listener.InstrumentPublished = (instrument, l) =>
{
if (instrument.Name == "redb.route.as2.mdn.async_failed") l.EnableMeasurementEvents(instrument);
};
listener.SetMeasurementEventCallback((_, value, _, _) => Interlocked.Add(ref failed, value));
listener.Start();
await using var context = new RouteContext();
context.AddComponent(new As2Component());
context.AddToRegistry("recv", AsyncReceiver());
context.AddRoutes(r => r.From(As2Dsl.Receive("/in").Host("127.0.0.1").Port(port).ConnectionFactory("recv").AsyncMdnRetry(3, 50))
.Process(_ => { }));
await context.Start();
(await PostAsync(port, "/in", BuildMessage("PO*NEVER~", Cert, Cert), ReceiptTo(trap))).StatusCode.Should().Be(HttpStatusCode.OK);
var deadline = DateTime.UtcNow.AddSeconds(10);
while (Interlocked.Read(ref failed) == 0 && DateTime.UtcNow < deadline) await Task.Delay(20);
Interlocked.Read(ref failed).Should().Be(1);
trap.Requests.Should().HaveCount(3);
}
[Fact]
public async Task AnAsyncMdnRefusedWithAClientError_IsNotPostedAgain()
{
using var trap = new As2Trap(FreePort(), _ => 400);
var port = FreePort();
await using var context = new RouteContext();
context.AddComponent(new As2Component());
context.AddToRegistry("recv", AsyncReceiver());
context.AddRoutes(r => r.From(As2Dsl.Receive("/in").Host("127.0.0.1").Port(port).ConnectionFactory("recv").AsyncMdnRetry(3, 50))
.Process(_ => { }));
await context.Start();
(await PostAsync(port, "/in", BuildMessage("PO*BAD~", Cert, Cert), ReceiptTo(trap))).StatusCode.Should().Be(HttpStatusCode.OK);
(await trap.HitAsync(TimeSpan.FromSeconds(10))).Should().BeTrue();
await Task.Delay(500);
trap.Requests.Should().HaveCount(1, "the partner refused the receipt itself; sending it again changes nothing");
}
}
/// The give-up counter is process-wide: its test does not share the meter with a parallel one.
[CollectionDefinition(nameof(AsyncMdnMetricsCollection), DisableParallelization = true)]
public sealed class AsyncMdnMetricsCollection;