Path: redb-route/tests/redb.Route.Tests.AzureServiceBus/AsbReconnectTests.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.AzureServiceBus/AsbReconnectTests.cs
----
using System.Collections.Concurrent;
using System.Diagnostics;
using System.Globalization;
using System.Text;
using redb.Route.Abstractions;
using redb.Route.AzureServiceBus;
using redb.Route.Configuration;
using redb.Route.Core;
using redb.Route.Tests.Conformance;
namespace redb.Route.Tests.AzureServiceBus;
///
/// A Service Bus consumer through a lost emulator, on , for each of its three kinds: the
/// processor, the session processor and the batch receiver. The client reconnects by itself; what the consumer owes is
/// the truth in health: while the emulator is away the endpoint shows a lost connection (not message errors: the error
/// count stays where it was), it counts one reconnect when the emulator is back, and the route reads on. The stop and
/// start of the emulator are : they run only where REDB_TEST_ASB_CONTAINER names its
/// container, elsewhere they are skipped. Run them with tests/docker/run-fault-suite.sh --broker servicebus.
///
[Trait("Category", "Integration")]
[Collection(AsbEmulatorRestartCollection.Name)]
public sealed class AsbReconnectTests
{
private static readonly AsbFaultStand Stand = AsbFaultStand.Instance;
[BrokerFaultTheory(AsbFaultStand.ContainerVariable)]
[InlineData("queue.fault.single", "")]
[InlineData("queue.fault.session", "enableSessions=true")]
[InlineData("queue.fault.batch", "batching=true&maxBatchMessages=10&pollTimeoutMs=500")]
public async Task A_consumer_shows_the_lost_emulator_in_health_and_reads_again_once_it_is_back(string queue, string query)
{
var fault = Stand.Fault!;
await Stand.DrainAsync(queue, TimeSpan.FromSeconds(1));
var received = new ConcurrentQueue();
await using var context = NewContext();
var uri = Uri(queue, query);
context.AddRoutes(r => r.From(uri).RouteId("restarted").Process(e => Collect(e, received)));
await context.Start();
await Stand.PutAsync(queue, "before");
(await Until(() => received.Contains("before"))).Should().BeTrue("the route reads the queue before the outage");
var statistics = (IEndpointStatistics)context.GetEndpoint(uri);
var errorsBefore = statistics.Errors;
await fault.StopAsync();
try
{
(await Until(() => statistics.HealthStatus != EndpointHealthStatus.Healthy)).Should().BeTrue(
"the endpoint shows that the emulator is gone");
statistics.HealthReason.Should().Contain("connection", $"the reason names the lost connection (last error: {statistics.LastErrorMessage})");
statistics.Errors.Should().Be(errorsBefore, $"a lost connection is not a failed message (last error: {statistics.LastErrorMessage})");
}
finally
{
await fault.StartAsync();
}
(await Until(() => statistics.Reconnects > 0)).Should().BeTrue("the endpoint counts the reconnect");
(await BrokerFault.UntilAsync(async () =>
{
try { await Stand.PutAsync(queue, "after"); return true; }
catch (Exception) { return false; }
}, Stand.Wait, TimeSpan.FromMilliseconds(500))).Should().BeTrue("the emulator takes a message once it is back");
(await Until(() => received.Contains("after"))).Should().BeTrue("the consumer reads what was put after the outage");
statistics.Reconnects.Should().Be(1, "one outage is one reconnect");
statistics.Errors.Should().Be(errorsBefore, $"a lost connection is not a failed message (last error: {statistics.LastErrorMessage})");
statistics.HealthStatus.Should().Be(EndpointHealthStatus.Healthy, $"the emulator is back ({statistics.HealthReason})");
context.GetRoute("restarted")!.Status.Should().Be(RouteStatus.Started, "a lost connection does not stop the route");
}
[BrokerFaultTheory(AsbFaultStand.ContainerVariable)]
[InlineData("queue.fault.single", "")]
[InlineData("queue.fault.session", "enableSessions=true")]
[InlineData("queue.fault.batch", "batching=true&maxBatchMessages=10&pollTimeoutMs=500")]
public async Task A_route_stops_in_time_while_the_emulator_is_away(string queue, string query)
{
var fault = Stand.Fault!;
await Stand.DrainAsync(queue, TimeSpan.FromSeconds(1));
var received = new ConcurrentQueue();
var context = NewContext();
var uri = Uri(queue, query);
context.AddRoutes(r => r.From(uri).RouteId("stopped").Process(e => Collect(e, received)));
await context.Start();
await Stand.PutAsync(queue, "before");
(await Until(() => received.Contains("before"))).Should().BeTrue();
var statistics = (IEndpointStatistics)context.GetEndpoint(uri);
await fault.StopAsync();
try
{
(await Until(() => statistics.HealthStatus != EndpointHealthStatus.Healthy)).Should().BeTrue(
"the consumer knows the emulator is gone");
var watch = Stopwatch.StartNew();
await context.Stop();
await context.DisposeAsync();
watch.Elapsed.Should().BeLessThan(TimeSpan.FromSeconds(30),
"a stop does not wait for the emulator or for a probe of it");
}
finally
{
await fault.StartAsync();
}
}
///
/// The probe of a lost consumer peeks the dead-letter queue through the consumer's own client, so the outage and the
/// recovery never hold a second connection. Counted in the test process, while the stand has no client open: the
/// probe's peeks from the client's own events, the AMQP connections the process opens from the AMQP library's
/// events, and the process's own established sockets to the emulator.
///
[BrokerFaultTheory(AsbFaultStand.ContainerVariable)]
[InlineData("queue.fault.single", "")]
[InlineData("queue.fault.session", "enableSessions=true")]
public async Task The_probe_of_a_lost_consumer_opens_no_second_connection(string queue, string query)
{
var fault = Stand.Fault!;
await Stand.DrainAsync(queue, TimeSpan.FromSeconds(1));
var received = new ConcurrentQueue();
await using var context = NewContext();
var uri = Uri(queue, query);
context.AddRoutes(r => r.From(uri).RouteId("probed").Process(e => Collect(e, received)));
await context.Start();
await Stand.PutAsync(queue, "before");
(await Until(() => received.Contains("before"))).Should().BeTrue("the route reads the queue before the outage");
var statistics = (IEndpointStatistics)context.GetEndpoint(uri);
// The stand's clients are closed by now: what stays established is the consumer's.
(await Until(() => EstablishedToEmulator().Count == 1)).Should().BeTrue(
$"only the consumer's connection is open ({EstablishedToEmulator().Count} established)");
var clock = Stopwatch.StartNew();
using var events = new AsbConnectionEvents(clock);
var most = 0;
var sockets = new ConcurrentDictionary();
using var sampling = new CancellationTokenSource();
var sampler = Task.Run(async () =>
{
while (!sampling.IsCancellationRequested)
{
var now = clock.Elapsed.TotalSeconds;
var open = EstablishedToEmulator();
most = Math.Max(most, open.Count);
foreach (var port in open)
sockets.AddOrUpdate(port, (now, now), (_, seen) => (seen.First, now));
await Task.Delay(20);
}
});
var marks = new List();
await fault.StopAsync();
marks.Add($"stopped {clock.Elapsed.TotalSeconds:0.0}");
try
{
(await Until(() => statistics.HealthStatus != EndpointHealthStatus.Healthy)).Should().BeTrue(
"the endpoint shows that the emulator is gone");
(await Until(() => events.PeeksStarted > 0)).Should().BeTrue("the probe peeks while the emulator is away");
}
finally
{
await fault.StartAsync();
marks.Add($"started {clock.Elapsed.TotalSeconds:0.0}");
}
(await Until(() => statistics.Reconnects > 0)).Should().BeTrue("the endpoint counts the reconnect");
marks.Add($"reconnect counted {clock.Elapsed.TotalSeconds:0.0}");
await Task.Delay(TimeSpan.FromSeconds(5));
await sampling.CancelAsync();
await sampler;
var lifetimes = string.Join(", ", sockets.OrderBy(s => s.Value.First)
.Select(s => $"port {s.Key} {s.Value.First:0.0}-{s.Value.Last:0.0}"));
var seen = $"peeks started {events.PeeksStarted}, completed {events.PeeksCompleted}; AMQP connections opened " +
$"{events.ConnectionsOpened}, closed {events.ConnectionsClosed}; most established sockets {most}; " +
$"{string.Join(", ", marks)}; sockets (s from the listener) {lifetimes}; events {events.Timeline}";
most.Should().Be(1, $"the consumer and its probe share one connection ({seen})");
EstablishedToEmulator().Count.Should().Be(1, $"one connection after the recovery ({seen})");
(events.ConnectionsOpened - events.ConnectionsClosed).Should().BeLessThanOrEqualTo(1,
$"the process holds no more than the consumer's connection ({seen})");
}
///
/// The local ports of the established TCP connections of this process to the emulator's AMQP port (the fault runs are Linux
/// containers): the rows of /proc/net/tcp and /proc/net/tcp6 in state 01 with remote port 5672 whose
/// socket inode is one of this process's descriptors. The tables are the host's (the stand runs with host
/// networking), so the inode keeps out the emulator's own connections to its port.
///
private static HashSet EstablishedToEmulator()
{
var own = new HashSet(StringComparer.Ordinal);
foreach (var descriptor in Directory.EnumerateFiles("/proc/self/fd"))
{
string? target;
try
{
target = new FileInfo(descriptor).LinkTarget;
}
catch (IOException)
{
continue;
}
if (target is not null && target.StartsWith("socket:[", StringComparison.Ordinal))
own.Add(target["socket:[".Length..^1]);
}
// A read of the table is not one snapshot: a row can come twice when the table changes under the read.
var ports = new HashSet(StringComparer.Ordinal);
foreach (var table in new[] { "/proc/net/tcp", "/proc/net/tcp6" })
{
if (!File.Exists(table))
continue;
foreach (var line in File.ReadLines(table).Skip(1))
{
var fields = line.Split(' ', StringSplitOptions.RemoveEmptyEntries);
if (fields.Length > 9 && fields[3] == "01" && fields[2].EndsWith(":1628", StringComparison.Ordinal)
&& own.Contains(fields[9]))
ports.Add(Convert.ToInt32(fields[1][(fields[1].LastIndexOf(':') + 1)..], 16).ToString(CultureInfo.InvariantCulture));
}
}
return ports;
}
private static string Uri(string queue, string query)
=> $"asb://{queue}?connectionString={AsbFaultStand.ConnectionString}" + (query.Length > 0 ? "&" + query : "");
private static RouteContext NewContext()
{
var context = new RouteContext(options: new RouteEngineOptions { ShutdownTimeout = TimeSpan.FromSeconds(5) });
context.AddComponent(new AzureServiceBusComponent());
return context;
}
private static void Collect(IExchange exchange, ConcurrentQueue into)
{
if (exchange.In.Body is List batch)
{
foreach (var message in batch)
into.Enqueue(Text(message.Body));
return;
}
into.Enqueue(Text(exchange.In.Body));
}
private static string Text(object? body) => body switch
{
byte[] bytes => Encoding.UTF8.GetString(bytes),
BinaryData data => data.ToString(),
null => "",
_ => body.ToString() ?? "",
};
private static async Task Until(Func condition)
{
var deadline = DateTime.UtcNow + Stand.Wait;
while (!condition())
{
if (DateTime.UtcNow > deadline)
return false;
await Task.Delay(100);
}
return true;
}
}
/// An emulator stop cuts every connection of the suite, so nothing runs beside the fault tests.
[CollectionDefinition(Name, DisableParallelization = true)]
public sealed class AsbEmulatorRestartCollection
{
/// The collection's name.
public const string Name = "Service Bus emulator restart";
}