Path: redb-route/tests/redb.Route.Tests.Amqp/AmqpConsumerReattachTests.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.Amqp/AmqpConsumerReattachTests.cs
----
using System.Collections.Concurrent;
using System.Net;
using System.Net.Sockets;
using Amqp;
using Amqp.Framing;
using Amqp.Listener;
using redb.Route.Abstractions;
using redb.Route.Amqp;
using redb.Route.Configuration;
using redb.Route.Core;
using AmqpMessage = global::Amqp.Message;
namespace redb.Route.Tests.Amqp;
///
/// The AMQP consumer attaches its receiver link again when the broker takes it away, on the connection supervisor of
/// its worker (F-6). The broker is AMQPNetLite's own in the test process: it can detach a
/// link while the connection stays, and drop every connection by closing. Single and batch, and a stop while the
/// consumer waits for a broker that does not come back.
///
public sealed class AmqpConsumerReattachTests : IAsyncDisposable
{
private static readonly TimeSpan Wait = TimeSpan.FromSeconds(20);
private readonly int _port = FreePort();
private readonly Source _source = new();
private ContainerHost? _host;
public AmqpConsumerReattachTests() => OpenHost();
public ValueTask DisposeAsync()
{
_host?.Close();
return ValueTask.CompletedTask;
}
[Theory]
[InlineData("")]
[InlineData("&batching=true&maxBatchMessages=10&pollTimeoutMs=100")]
public async Task A_link_the_broker_detaches_is_attached_again_and_the_route_reads_on(string extra)
{
var (context, received, uri) = await StartAsync(extra);
await using (context)
{
_source.Enqueue("before");
(await Until(() => received.Contains("before"))).Should().BeTrue();
_source.DetachAll(new Error(new global::Amqp.Types.Symbol("amqp:link:detach-forced")) { Description = "test" });
_source.Enqueue("after");
(await Until(() => received.Contains("after"))).Should().BeTrue("the worker attaches its link again and reads on");
var statistics = (IEndpointStatistics)context.GetEndpoint(uri);
statistics.Reconnects.Should().Be(1, "the reattach is counted once");
statistics.HealthStatus.Should().Be(EndpointHealthStatus.Healthy);
context.GetRoute("reader")!.Status.Should().Be(RouteStatus.Started);
}
}
[Theory]
[InlineData("")]
[InlineData("&batching=true&maxBatchMessages=10&pollTimeoutMs=100")]
public async Task A_lost_connection_is_opened_again_and_the_link_attached_on_it(string extra)
{
var (context, received, uri) = await StartAsync(extra);
await using (context)
{
_source.Enqueue("before");
(await Until(() => received.Contains("before"))).Should().BeTrue();
_host!.Close();
var statistics = (IEndpointStatistics)context.GetEndpoint(uri);
(await Until(() => statistics.HealthStatus != EndpointHealthStatus.Healthy)).Should().BeTrue(
"health shows the lost link while it is away");
OpenHost();
(await Until(() => statistics.Reconnects == 1)).Should().BeTrue("the worker attaches its link on a new connection");
_source.Enqueue("after");
(await Until(() => received.Contains("after"))).Should().BeTrue();
statistics.HealthStatus.Should().Be(EndpointHealthStatus.Healthy);
}
}
[Fact]
public async Task A_stop_while_the_broker_is_away_ends_the_reattach_and_opens_nothing()
{
var (context, received, uri) = await StartAsync("");
_source.Enqueue("before");
(await Until(() => received.Contains("before"))).Should().BeTrue();
_host!.Close();
_host = null;
var statistics = (IEndpointStatistics)context.GetEndpoint(uri);
(await Until(() => statistics.HealthStatus != EndpointHealthStatus.Healthy)).Should().BeTrue();
var stop = context.Stop();
(await Task.WhenAny(stop, Task.Delay(Wait))).Should().BeSameAs(stop, "the stop ends the reattach loop");
await context.DisposeAsync();
statistics.Reconnects.Should().Be(0);
}
private async Task<(RouteContext Context, ConcurrentQueue Received, string Uri)> StartAsync(string extra)
{
var context = new RouteContext(options: new RouteEngineOptions
{
ShutdownTimeout = TimeSpan.FromSeconds(5),
Reconnect = new ReconnectOptions
{
Delay = TimeSpan.FromMilliseconds(100), MaxDelay = TimeSpan.FromMilliseconds(200),
AttemptTimeout = TimeSpan.FromSeconds(5),
},
});
context.AddComponent(new AmqpComponent());
var received = new ConcurrentQueue();
var uri = $"amqp://{Source.Address}?host=localhost&port={_port}&timeout=5&receiveTimeout=1{extra}";
context.AddRoutes(r => r.From(uri).RouteId("reader").Process(e =>
{
if (e.In.Body is IEnumerable batch)
foreach (var message in batch)
received.Enqueue(Text(message.Body));
else
received.Enqueue(Text(e.In.Body));
}));
await context.Start();
return (context, received, uri);
}
private void OpenHost()
{
var host = new ContainerHost(new Address($"amqp://localhost:{_port}"));
// The connector always opens a SASL layer (ANONYMOUS without a user).
host.Listeners[0].SASL.EnableAnonymousMechanism = true;
host.RegisterMessageSource(Source.Address, _source);
host.Open();
_host = host;
}
// The consumer hands the route the body as UTF-8 bytes.
private static string Text(object? body) => body is byte[] bytes ? System.Text.Encoding.UTF8.GetString(bytes) : body?.ToString() ?? "";
private static int FreePort()
{
var listener = new TcpListener(IPAddress.Loopback, 0);
listener.Start();
var port = ((IPEndPoint)listener.LocalEndpoint).Port;
listener.Stop();
return port;
}
private static async Task Until(Func condition)
{
var deadline = DateTime.UtcNow + Wait;
while (!condition())
{
if (DateTime.UtcNow > deadline)
return false;
await Task.Delay(50);
}
return true;
}
///
/// The address the consumer reads: hands out what the test enqueues, one message per credit, and keeps the links it
/// serves so the test can detach them as a broker does.
///
private sealed class Source : IMessageSource
{
public const string Address = "orders";
private readonly ConcurrentQueue _bodies = new();
private readonly SemaphoreSlim _available = new(0);
private readonly ConcurrentDictionary _links = new();
public void Enqueue(string body)
{
_bodies.Enqueue(body);
_available.Release();
}
public void DetachAll(Error error)
{
foreach (var link in _links.Keys)
{
_links.TryRemove(link, out _);
link.Close(TimeSpan.Zero, error);
}
}
public async Task GetMessageAsync(ListenerLink link)
{
_links.TryAdd(link, true);
while (true)
{
await _available.WaitAsync();
if (link.IsClosed)
{
_available.Release();
return null!;
}
if (_bodies.TryDequeue(out var body))
return new ReceiveContext(link, new AmqpMessage(body));
}
}
public void DisposeMessage(ReceiveContext receiveContext, DispositionContext dispositionContext)
=> dispositionContext.Complete();
}
}