Path: redb-route/tests/redb.Route.Tests.MqttNet/MqttConsumerConnectionLossTests.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.MqttNet/MqttConsumerConnectionLossTests.cs
----
using MQTTnet;
using redb.Route.Abstractions;
using redb.Route.Core;
using redb.Route.MqttNet;
using redb.Route.MqttNet.Connection;
namespace redb.Route.Tests.MqttNet;
///
/// A connection the broker or the network drops: the consumer reports it to its supervisor, connects again on the
/// RedbRoute:Reconnect schedule (defaults here: first attempt after 1 s) and subscribes again when the broker did
/// not keep the session; the endpoint counts one reconnect and is healthy again. A disconnect the consumer makes itself
/// is not a loss, and a stop ends the reconnecting. No broker: the client is a substitute.
///
public sealed class MqttConsumerConnectionLossTests
{
private sealed class Harness
{
public required IMqttClient Client { get; init; }
public required IConsumer Consumer { get; init; }
public required IEndpointStatistics Statistics { get; init; }
/// Whether the substitute client is connected; the consumer reads it through IsConnected.
public volatile bool Connected = true;
/// Connect attempts that fail before one succeeds.
public int FailingConnects;
/// Whether a successful connect finds the session kept by the broker.
public bool SessionPresent;
public int Connects;
public int Subscribes;
/// The broker or the network drops the connection.
public void Drop(bool clientWasConnected = true)
{
Connected = false;
Client.DisconnectedAsync += Raise.Event>(
new MqttClientDisconnectedEventArgs(clientWasConnected, null, MqttClientDisconnectReason.ServerShuttingDown,
"broker restart", null, new IOException("connection reset")));
}
}
private static async Task StartAsync(IProcessor? processor = null, bool keptSession = false)
{
var parameters = new Dictionary
{
["mode"] = "Subscribe",
["broker"] = "main",
["qos"] = "1",
};
var component = new MqttComponent();
var endpoint = (MqttEndpoint)component.CreateEndpoint(
new EndpointUri("mqtt", "test/topic", "mqtt:test/topic", parameters));
var client = Substitute.For();
Harness? h = null;
client.IsConnected.Returns(_ => h!.Connected);
client.Options.Returns(keptSession
? new MqttClientOptionsBuilder().WithTcpServer("localhost").WithCleanSession(false)
.WithSessionExpiryInterval(300).Build()
: new MqttClientOptionsBuilder().WithTcpServer("localhost").WithCleanSession(true).Build());
client.ConnectAsync(Arg.Any(), Arg.Any())
.Returns(_ =>
{
Interlocked.Increment(ref h!.Connects);
if (Interlocked.Decrement(ref h.FailingConnects) >= 0)
return Task.FromException(new IOException("connection refused"));
h.Connected = true;
return Task.FromResult(new MqttClientConnectResult { IsSessionPresent = h.SessionPresent });
});
client.SubscribeAsync(Arg.Any(), Arg.Any())
.Returns(_ =>
{
Interlocked.Increment(ref h!.Subscribes);
return Task.FromResult(null!);
});
client.DisconnectAsync(Arg.Any(), Arg.Any())
.Returns(_ =>
{
// MQTTnet raises Disconnected for a disconnect the client was asked for, too.
h!.Drop();
return Task.CompletedTask;
});
var factory = Substitute.For();
factory.CreateConnectedClientAsync(Arg.Any(), Arg.Any(), Arg.Any())
.Returns(Task.FromResult(client));
var registry = Substitute.For();
registry.GetOptions("main").Returns(new MqttBrokerOptions { Server = "localhost" });
registry.Contains("main").Returns(true);
endpoint.MqttComponent.ClientFactory = factory;
endpoint.MqttComponent.BrokerRegistry = registry;
var consumer = endpoint.CreateConsumer(processor ?? Substitute.For());
h = new Harness { Client = client, Consumer = consumer, Statistics = endpoint };
await consumer.Start();
return h;
}
private static async Task WaitUntil(Func condition, int timeoutMs = 10_000)
{
var deadline = DateTime.UtcNow.AddMilliseconds(timeoutMs);
while (!condition())
{
if (DateTime.UtcNow > deadline)
return false;
await Task.Delay(20);
}
return true;
}
[Fact]
public async Task A_dropped_connection_is_connected_and_subscribed_again()
{
var h = await StartAsync();
h.Subscribes.Should().Be(1);
h.Drop();
h.Statistics.HealthStatus.Should().NotBe(EndpointHealthStatus.Healthy, "the connection is away");
(await WaitUntil(() => h.Statistics.Reconnects == 1)).Should().BeTrue("the consumer connects again");
await h.Consumer.Stop();
h.Connects.Should().Be(1);
h.Subscribes.Should().Be(2, "the broker did not keep the session, so the subscription is made again");
}
[Fact]
public async Task A_kept_session_is_not_subscribed_again()
{
var h = await StartAsync(keptSession: true);
h.SessionPresent = true;
h.Drop();
(await WaitUntil(() => h.Statistics.Reconnects == 1)).Should().BeTrue();
var health = h.Statistics.HealthStatus;
await h.Consumer.Stop();
health.Should().Be(EndpointHealthStatus.Healthy, "the connection is back");
h.Subscribes.Should().Be(1, "a kept session keeps the subscription; subscribing again resends the retained message");
}
[Fact]
public async Task Failed_attempts_go_on_until_the_broker_is_back()
{
var h = await StartAsync();
h.FailingConnects = 1;
h.Drop();
(await WaitUntil(() => h.Connects == 1)).Should().BeTrue();
await WaitUntil(() => h.Statistics.HealthStatus == EndpointHealthStatus.Critical, 2_000);
h.Statistics.HealthStatus.Should().Be(EndpointHealthStatus.Critical, "an attempt to connect failed");
(await WaitUntil(() => h.Statistics.Reconnects == 1)).Should().BeTrue("the second attempt connects");
var health = h.Statistics.HealthStatus;
await h.Consumer.Stop();
h.Connects.Should().Be(2);
health.Should().Be(EndpointHealthStatus.Healthy);
h.Statistics.Errors.Should().Be(0, "a lost connection is not an error of a message");
}
[Fact]
public async Task A_failed_connect_attempt_is_not_a_loss()
{
var h = await StartAsync();
h.Drop(clientWasConnected: false);
await Task.Delay(1_500);
await h.Consumer.Stop();
h.Connects.Should().Be(0);
h.Statistics.Reconnects.Should().Be(0);
}
[Fact]
public async Task The_stop_disconnect_is_not_a_loss()
{
var h = await StartAsync();
await h.Consumer.Stop();
await Task.Delay(1_500);
h.Connects.Should().Be(0, "the consumer disconnected itself");
h.Statistics.Reconnects.Should().Be(0);
}
[Fact]
public async Task A_stop_while_the_broker_is_away_ends_the_reconnecting()
{
var h = await StartAsync();
h.FailingConnects = int.MaxValue;
h.Drop();
(await WaitUntil(() => h.Connects >= 1)).Should().BeTrue();
var stop = h.Consumer.Stop();
(await Task.WhenAny(stop, Task.Delay(10_000))).Should().BeSameAs(stop, "the stop does not wait for the broker");
await stop;
var connects = h.Connects;
await Task.Delay(2_500);
h.Connects.Should().Be(connects, "no attempt after the stop");
h.Statistics.Reconnects.Should().Be(0);
}
[Fact]
public async Task A_reconnect_after_a_failed_message_that_cannot_connect_is_handed_to_the_supervisor()
{
var processor = Substitute.For();
processor.Process(Arg.Any(), Arg.Any())
.Returns(Task.FromException(new InvalidOperationException("route failed")));
var h = await StartAsync(processor, keptSession: true);
h.SessionPresent = true;
h.FailingConnects = 1;
var message = new MqttApplicationMessageBuilder().WithTopic("test/topic").WithPayload("m")
.WithQualityOfServiceLevel(MQTTnet.Protocol.MqttQualityOfServiceLevel.AtLeastOnce).Build();
h.Client.ApplicationMessageReceivedAsync += Raise.Event>(
new MqttApplicationMessageReceivedEventArgs("c1", message,
new MQTTnet.Packets.MqttPublishPacket { Topic = "test/topic" }, (_, _) => Task.CompletedTask));
// The failed message reconnects after 1 s; that connect fails and the supervisor connects on its schedule.
(await WaitUntil(() => h.Statistics.Reconnects == 1, 15_000)).Should().BeTrue(
"the supervisor takes over the connection the reconnect could not bring back");
await h.Consumer.Stop();
h.Connects.Should().Be(2);
}
}