Path: redb-route/tests/redb.Route.Tests.MqttNet/MqttConsumerSettleTests.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/MqttConsumerSettleTests.cs
----
using System.Text;
using MQTTnet;
using MQTTnet.Packets;
using MQTTnet.Protocol;
using redb.Route.Abstractions;
using redb.Route.Core;
using redb.Route.MqttNet;
using redb.Route.MqttNet.Connection;
namespace redb.Route.Tests.MqttNet;
///
/// How the consumer settles a message after the route (Camel paho-mqtt5 as corrected by CAMEL-25793): a success is
/// acknowledged; a failure is acknowledged when the broker would never send it again (QoS 0, or a session not kept after
/// disconnect) and otherwise left unacknowledged while the consumer reconnects after a backoff. Serial and concurrent
/// mode follow the same rule.
///
public sealed class MqttConsumerSettleTests
{
private sealed class Harness
{
public required IMqttClient Client { get; init; }
public required IConsumer Consumer { get; init; }
public int Acks;
public MqttApplicationMessageReceivedEventArgs Args(MqttQualityOfServiceLevel qos, string payload = "m")
{
var message = new MqttApplicationMessageBuilder()
.WithTopic("test/topic")
.WithPayload(Encoding.UTF8.GetBytes(payload))
.WithQualityOfServiceLevel(qos)
.Build();
return new MqttApplicationMessageReceivedEventArgs("c1", message,
new MqttPublishPacket { Topic = "test/topic", QualityOfServiceLevel = qos },
(_, _) => { Interlocked.Increment(ref Acks); return Task.CompletedTask; });
}
public Task Receive(MqttApplicationMessageReceivedEventArgs args)
{
Client.ApplicationMessageReceivedAsync += Raise.Event>(args);
return Task.CompletedTask;
}
public MqttConsumer Mqtt => (MqttConsumer)Consumer;
}
private static async Task StartAsync(IProcessor processor, bool keptSession, int concurrentConsumers = 1)
{
var parameters = new Dictionary
{
["mode"] = "Subscribe",
["broker"] = "main",
["qos"] = "1",
["concurrentConsumers"] = concurrentConsumers.ToString(),
};
var component = new MqttComponent();
var endpoint = (MqttEndpoint)component.CreateEndpoint(
new EndpointUri("mqtt", "test/topic", "mqtt:test/topic", parameters));
var client = Substitute.For();
client.IsConnected.Returns(true);
// The consumer reads "kept" from the client's own options: MQTTnet speaks MQTT 5 by default.
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(Task.FromResult(new MqttClientConnectResult { IsSessionPresent = true }));
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);
await consumer.Start();
return new Harness { Client = client, Consumer = consumer };
}
private static IProcessor Succeeding() => Substitute.For();
private static IProcessor Failing()
{
var processor = Substitute.For();
processor.Process(Arg.Any(), Arg.Any())
.Returns(Task.FromException(new InvalidOperationException("route failed")));
return processor;
}
private static async Task WaitUntil(Func condition, int timeoutMs = 5000)
{
var deadline = DateTime.UtcNow.AddMilliseconds(timeoutMs);
while (!condition() && DateTime.UtcNow < deadline)
await Task.Delay(20);
}
[Theory]
[InlineData(1)]
[InlineData(4)]
public async Task Success_IsAcknowledged_AfterTheRoute(int concurrentConsumers)
{
var h = await StartAsync(Succeeding(), keptSession: true, concurrentConsumers);
var args = h.Args(MqttQualityOfServiceLevel.AtLeastOnce);
await h.Receive(args);
await WaitUntil(() => Volatile.Read(ref h.Acks) == 1);
await h.Consumer.Stop();
args.AutoAcknowledge.Should().BeFalse("the consumer acknowledges after the route, not MQTTnet on receipt");
h.Acks.Should().Be(1);
}
[Theory]
[InlineData(1)]
[InlineData(4)]
public async Task Failure_SessionNotKept_IsAcknowledged_WithoutReconnect(int concurrentConsumers)
{
var h = await StartAsync(Failing(), keptSession: false, concurrentConsumers);
await h.Receive(h.Args(MqttQualityOfServiceLevel.AtLeastOnce));
await WaitUntil(() => Volatile.Read(ref h.Acks) == 1);
await Task.Delay(1500);
await h.Consumer.Stop();
h.Acks.Should().Be(1, "the broker would never send it again: holding the ack only fills the receive window");
await h.Client.DidNotReceive().ConnectAsync(Arg.Any(), Arg.Any());
}
[Fact]
public async Task Failure_QoS0_OnAKeptSession_IsAcknowledged_WithoutReconnect()
{
var h = await StartAsync(Failing(), keptSession: true);
await h.Receive(h.Args(MqttQualityOfServiceLevel.AtMostOnce));
await WaitUntil(() => Volatile.Read(ref h.Acks) == 1);
await Task.Delay(1500);
await h.Consumer.Stop();
h.Acks.Should().Be(1);
await h.Client.DidNotReceive().ConnectAsync(Arg.Any(), Arg.Any());
}
[Theory]
[InlineData(MqttQualityOfServiceLevel.AtLeastOnce, 1)]
[InlineData(MqttQualityOfServiceLevel.ExactlyOnce, 1)]
[InlineData(MqttQualityOfServiceLevel.AtLeastOnce, 4)]
public async Task Failure_KeptSession_IsNotAcknowledged_AndTheConsumerReconnects(
MqttQualityOfServiceLevel qos, int concurrentConsumers)
{
var h = await StartAsync(Failing(), keptSession: true, concurrentConsumers);
await h.Receive(h.Args(qos));
await WaitUntil(() => h.Client.ReceivedCalls().Any(c => c.GetMethodInfo().Name == nameof(IMqttClient.ConnectAsync)));
await h.Consumer.Stop();
h.Acks.Should().Be(0, "the broker sends it again only when the client connects again to the kept session");
await h.Client.Received(1).ConnectAsync(Arg.Any(), Arg.Any());
h.Mqtt.FailedReconnects.Should().Be(1);
}
[Fact]
public async Task RollbackOnly_KeptSession_IsAFailure()
{
var processor = Substitute.For();
processor.Process(Arg.Any(), Arg.Any())
.Returns(Task.CompletedTask)
.AndDoes(call => call.Arg().MarkRollbackOnly());
var h = await StartAsync(processor, keptSession: true);
await h.Receive(h.Args(MqttQualityOfServiceLevel.AtLeastOnce));
await WaitUntil(() => h.Mqtt.FailedReconnects == 1);
await h.Consumer.Stop();
h.Acks.Should().Be(0);
h.Mqtt.FailedReconnects.Should().Be(1);
}
[Fact]
public async Task Failure_DuringStop_StartsNoReconnect()
{
var gate = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
var processor = Substitute.For();
processor.Process(Arg.Any(), Arg.Any())
.Returns(async _ =>
{
await gate.Task;
throw new InvalidOperationException("route failed while the consumer stops");
});
var h = await StartAsync(processor, keptSession: true);
var receiving = Task.Run(() => h.Receive(h.Args(MqttQualityOfServiceLevel.AtLeastOnce)));
await Task.Delay(100);
var stopping = h.Consumer.Stop();
await Task.Delay(100);
gate.SetResult();
await stopping;
await receiving;
await Task.Delay(1500);
h.Acks.Should().Be(0, "a failure while stopping is left unacknowledged");
h.Mqtt.FailedReconnects.Should().Be(0, "a failure while stopping starts no reconnect");
await h.Client.DidNotReceive().ConnectAsync(Arg.Any(), Arg.Any());
}
[Fact]
public async Task Success_AfterAReconnect_ResetsTheBackoff()
{
var calls = 0;
var processor = Substitute.For();
processor.Process(Arg.Any(), Arg.Any())
.Returns(_ => Interlocked.Increment(ref calls) == 1
? Task.FromException(new InvalidOperationException("first delivery fails"))
: Task.CompletedTask);
var h = await StartAsync(processor, keptSession: true);
await h.Receive(h.Args(MqttQualityOfServiceLevel.AtLeastOnce));
await WaitUntil(() => h.Client.ReceivedCalls().Any(c => c.GetMethodInfo().Name == nameof(IMqttClient.ConnectAsync)));
h.Mqtt.FailedReconnects.Should().Be(1);
// The broker sends it again on the new connection.
await h.Receive(h.Args(MqttQualityOfServiceLevel.AtLeastOnce));
await WaitUntil(() => Volatile.Read(ref h.Acks) == 1);
await h.Consumer.Stop();
h.Acks.Should().Be(1);
h.Mqtt.FailedReconnects.Should().Be(0, "a success resets the backoff");
}
[Theory]
[InlineData(1, 128_000, 1_000)]
[InlineData(2, 128_000, 2_000)]
[InlineData(8, 128_000, 128_000)]
[InlineData(9, 128_000, 128_000)]
[InlineData(40, 128_000, 128_000)]
[InlineData(10, 5_000, 5_000)]
[InlineData(3, 0, 1_000)]
public void ReconnectDelay_DoublesFromOneSecond_UpToTheMaximum(int attempt, int max, int expectedMs)
=> MqttConsumer.ReconnectDelay(attempt, max).TotalMilliseconds.Should().Be(expectedMs);
}