Path: redb-route/tests/redb.Route.Tests.AzureServiceBus/AzureServiceBusConnectionWatchTests.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/AzureServiceBusConnectionWatchTests.cs
----
using System.Net.Sockets;
using Azure.Messaging.ServiceBus;
using redb.Route.Abstractions;
using redb.Route.AzureServiceBus;
using redb.Route.Core;
namespace redb.Route.Tests.AzureServiceBus;
///
/// What a Service Bus consumer hands its connection supervisor: only errors of the connection (a lost connection shows in
/// health and is not counted as a failed message); a receive brings the connection back; a probe, the dead-letter peek,
/// brings it back on an idle entity and ends with the consumer's stop. Driven by a fake .
///
public sealed class AzureServiceBusConnectionWatchTests
{
private static (AzureServiceBusEndpoint Endpoint, ServiceBusClient Client, ServiceBusReceiver Receiver) Endpoint()
{
var client = Substitute.For();
var receiver = Substitute.For();
client.CreateReceiver(Arg.Any(), Arg.Any()).Returns(receiver);
var endpoint = (AzureServiceBusEndpoint)new AzureServiceBusComponent().CreateEndpoint(
EndpointUriParser.Parse("asb://orders?connectionString=Endpoint=sb://test"));
endpoint.ClientSource = () => client;
return (endpoint, client, receiver);
}
private static ServiceBusException Lost() =>
new("the connection was closed", ServiceBusFailureReason.ServiceCommunicationProblem);
public static TheoryData Errors() => new()
{
{ Lost(), true },
{ new InvalidOperationException("receive failed", new IOException("reset", new SocketException(10054))), true },
{ new ServiceBusException("no such queue", ServiceBusFailureReason.MessagingEntityNotFound), false },
{ new ServiceBusException("timed out", ServiceBusFailureReason.ServiceTimeout), false },
{ new UnauthorizedAccessException("claim Listen is missing"), false },
{ new InvalidOperationException("the route failed"), false },
};
[Theory]
[MemberData(nameof(Errors))]
public void Only_an_error_of_the_connection_is_the_supervisors(Exception error, bool connection)
=> AzureServiceBusConnectionWatch.IsConnectionError(error).Should().Be(connection);
[Fact]
public void A_lost_connection_shows_in_health_without_an_error_and_a_receive_brings_it_back()
{
var (endpoint, client, _) = Endpoint();
var watch = new AzureServiceBusConnectionWatch(endpoint, client, null, null, probe: false);
var statistics = (IEndpointStatistics)endpoint;
watch.Report(Lost()).Should().BeTrue();
statistics.HealthStatus.Should().NotBe(EndpointHealthStatus.Healthy);
statistics.HealthReason.Should().Contain("connection lost");
statistics.Errors.Should().Be(0, "a lost connection is not a failed message");
watch.Report(Lost()).Should().BeTrue();
watch.Supervisor.State.Should().Be(ConnectionState.Disconnected,
"without a probe the client's own failed receive is the failed attempt");
statistics.HealthStatus.Should().Be(EndpointHealthStatus.Critical);
watch.Traffic();
watch.Supervisor.State.Should().Be(ConnectionState.Connected);
statistics.Reconnects.Should().Be(1);
statistics.HealthStatus.Should().Be(EndpointHealthStatus.Healthy);
watch.Stop();
}
[Fact]
public void An_error_that_is_not_the_connections_is_left_to_the_consumer()
{
var (endpoint, client, _) = Endpoint();
var watch = new AzureServiceBusConnectionWatch(endpoint, client, null, null, probe: true);
watch.Report(new ServiceBusException("no such queue", ServiceBusFailureReason.MessagingEntityNotFound))
.Should().BeFalse("the consumer records it on the endpoint: it is not a connection being retried");
watch.Supervisor.State.Should().Be(ConnectionState.Connected);
watch.Stop();
}
[Fact]
public void A_lost_session_lock_is_neither_a_failed_message_nor_a_lost_connection()
{
var (endpoint, client, _) = Endpoint();
var watch = new AzureServiceBusConnectionWatch(endpoint, client, null, null, probe: true);
watch.Report(new ServiceBusException("session lock lost", ServiceBusFailureReason.SessionLockLost)).Should().BeTrue(
"the session processor accepts a session again by itself");
watch.Supervisor.State.Should().Be(ConnectionState.Connected);
((IEndpointStatistics)endpoint).Errors.Should().Be(0);
watch.Stop();
}
[Fact]
public void While_the_connection_is_lost_any_error_of_a_receive_is_the_losss_reason()
{
var (endpoint, client, _) = Endpoint();
var watch = new AzureServiceBusConnectionWatch(endpoint, client, null, null, probe: false);
var statistics = (IEndpointStatistics)endpoint;
watch.Report(Lost());
watch.Report(new ServiceBusException("session lock lost", ServiceBusFailureReason.SessionLockLost)).Should().BeTrue();
watch.Report(new ServiceBusException("no such queue", ServiceBusFailureReason.MessagingEntityNotFound)).Should().BeTrue(
"a namespace coming back may refuse the entity for a moment");
statistics.Errors.Should().Be(0);
statistics.HealthReason.Should().Contain("no such queue", "the last failure is the reason health shows");
watch.Traffic();
watch.Report(new ServiceBusException("no such queue", ServiceBusFailureReason.MessagingEntityNotFound)).Should().BeFalse(
"connected again: a missing entity is the consumer's error to record");
watch.Stop();
}
[Fact]
public async Task On_an_idle_entity_the_dead_letter_peek_brings_the_connection_back()
{
var (endpoint, client, receiver) = Endpoint();
var watch = new AzureServiceBusConnectionWatch(endpoint, client, null, null, probe: true);
watch.Report(Lost());
var deadline = DateTime.UtcNow + TimeSpan.FromSeconds(10);
while (watch.Supervisor.State != ConnectionState.Connected && DateTime.UtcNow < deadline)
await Task.Delay(50);
watch.Supervisor.State.Should().Be(ConnectionState.Connected, "the peek answered");
((IEndpointStatistics)endpoint).Reconnects.Should().Be(1);
client.Received().CreateReceiver("orders",
Arg.Is(o => o.SubQueue == SubQueue.DeadLetter && o.ReceiveMode == ServiceBusReceiveMode.PeekLock));
await receiver.Received().PeekMessageAsync(Arg.Any(), Arg.Any());
watch.Stop();
}
[Fact]
public async Task A_stop_ends_a_probe_that_hangs()
{
var (endpoint, client, receiver) = Endpoint();
var peeking = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
receiver.PeekMessageAsync(Arg.Any(), Arg.Any()).Returns(async call =>
{
peeking.TrySetResult();
await Task.Delay(Timeout.Infinite, call.ArgAt(1));
return (ServiceBusReceivedMessage?)null;
});
var watch = new AzureServiceBusConnectionWatch(endpoint, client, null, null, probe: true);
watch.Report(Lost());
await peeking.Task.WaitAsync(TimeSpan.FromSeconds(10));
watch.Stop();
var deadline = DateTime.UtcNow + TimeSpan.FromSeconds(5);
while (receiver.ReceivedCalls().All(c => c.GetMethodInfo().Name != nameof(ServiceBusReceiver.DisposeAsync))
&& DateTime.UtcNow < deadline)
await Task.Delay(50);
await receiver.Received().DisposeAsync();
watch.Supervisor.State.Should().NotBe(ConnectionState.Connected, "nothing answered; the stop ended the probe");
}
}