Path: redb-route/tests/redb.Route.Tests.MqttNet/MqttFailedMessageTests.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/MqttFailedMessageTests.cs
----
using System.Collections.Concurrent;
using System.Text;
using MQTTnet;
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;
///
/// A message the route fails on, against Mosquitto (localhost:11883), with the rule of Camel paho-mqtt5 as corrected by
/// CAMEL-25793: on a kept session (cleanSession=false, sessionExpiryInterval > 0) the consumer reconnects and the
/// broker sends the message again; on a session that ends with the connection the message is acknowledged and the
/// consumer goes on, it never stalls on failed messages.
///
[Trait("Category", "Integration")]
public sealed class MqttFailedMessageTests
{
private const string Broker = "server=localhost&port=11883";
private static MqttEndpoint CreateEndpoint(string topic, string extraParams)
{
var uri = EndpointUriParser.Parse($"mqtt:{topic}?mode=Subscribe&{Broker}&{extraParams}");
var component = new MqttComponent { ClientFactory = new DefaultMqttClientFactory() };
return (MqttEndpoint)component.CreateEndpoint(uri);
}
private static async Task PublishAsync(string topic, MqttQualityOfServiceLevel qos, params string[] payloads)
{
using var client = new MqttClientFactory().CreateMqttClient();
await client.ConnectAsync(new MqttClientOptionsBuilder().WithTcpServer("localhost", 11883)
.WithClientId($"test-pub-{Guid.NewGuid():N}").Build());
foreach (var payload in payloads)
await client.PublishAsync(new MqttApplicationMessageBuilder().WithTopic(topic)
.WithPayload(payload).WithQualityOfServiceLevel(qos).Build());
await client.DisconnectAsync();
}
/// Fails the first delivery of each payload in , every delivery of .
private sealed class Route(ISet? failFirst = null, ISet? failAlways = null) : IProcessor
{
public readonly ConcurrentQueue Deliveries = new();
public readonly ConcurrentDictionary Succeeded = new();
public Task Process(IExchange exchange, CancellationToken ct = default)
{
var payload = Encoding.UTF8.GetString((byte[])exchange.In.Body!);
var seen = Deliveries.Count(p => p == payload);
Deliveries.Enqueue(payload);
if (failAlways?.Contains(payload) == true || (failFirst?.Contains(payload) == true && seen == 0))
throw new InvalidOperationException($"route failed on {payload}");
Succeeded.AddOrUpdate(payload, 1, (_, n) => n + 1);
return Task.CompletedTask;
}
public int DeliveriesOf(string payload) => Deliveries.Count(p => p == payload);
}
private static async Task WaitUntil(Func condition, int timeoutMs)
{
var deadline = DateTime.UtcNow.AddMilliseconds(timeoutMs);
while (!condition() && DateTime.UtcNow < deadline)
await Task.Delay(50);
return condition();
}
[Theory]
[InlineData(1, 1)]
[InlineData(2, 1)]
[InlineData(1, 4)]
[InlineData(2, 4)]
public async Task KeptSession_FailedMessage_IsSentAgainAfterTheReconnect_AndProcessed(int qos, int concurrentConsumers)
{
var topic = $"test/fail-kept-{Guid.NewGuid():N}";
var route = new Route(failFirst: new HashSet { "m1" });
var endpoint = CreateEndpoint(topic,
$"qos={qos}&clientId=test-kept-{Guid.NewGuid():N}&cleanSession=false&sessionExpiryInterval=300" +
$"&concurrentConsumers={concurrentConsumers}");
var consumer = endpoint.CreateConsumer(route);
await consumer.Start();
try
{
await PublishAsync(topic, (MqttQualityOfServiceLevel)qos, "m1", "m2");
(await WaitUntil(() => route.Succeeded.ContainsKey("m1") && route.Succeeded.ContainsKey("m2"), 15_000))
.Should().BeTrue("the broker sends the failed m1 again after the reconnect, and m2 goes through");
route.DeliveriesOf("m1").Should().BeGreaterThanOrEqualTo(2, "m1 failed once and came again");
// m1 was acknowledged on the new connection: it does not come a third time.
await Task.Delay(2500);
route.Succeeded["m1"].Should().Be(1);
}
finally
{
await consumer.Stop();
await endpoint.Stop();
}
}
[Theory]
[InlineData(1)]
[InlineData(4)]
public async Task SessionNotKept_FailedMessage_IsAcknowledged_NotSentAgain(int concurrentConsumers)
{
var topic = $"test/fail-clean-{Guid.NewGuid():N}";
var route = new Route(failFirst: new HashSet { "m1" });
var endpoint = CreateEndpoint(topic, $"qos=1&concurrentConsumers={concurrentConsumers}");
var consumer = endpoint.CreateConsumer(route);
await consumer.Start();
try
{
await PublishAsync(topic, MqttQualityOfServiceLevel.AtLeastOnce, "m1", "m2");
(await WaitUntil(() => route.Succeeded.ContainsKey("m2"), 10_000)).Should().BeTrue();
await Task.Delay(2000);
route.DeliveriesOf("m1").Should().Be(1,
"with cleanSession=true the broker never sends it again; the route's error handling is where it is kept");
}
finally
{
await consumer.Stop();
await endpoint.Stop();
}
}
///
/// Before the rule a failed message in concurrent mode stayed unacknowledged for good: Mosquitto sends no more than
/// 20 unacknowledged messages to a client (max_inflight_messages), so 30 failures stopped the consumer. Now each is
/// acknowledged and the message after them goes through.
///
[Fact]
public async Task SessionNotKept_ManyFailures_DoNotStallTheConsumer()
{
var topic = $"test/fail-window-{Guid.NewGuid():N}";
var failing = Enumerable.Range(0, 30).Select(i => $"bad-{i}").ToArray();
var route = new Route(failAlways: failing.ToHashSet());
var endpoint = CreateEndpoint(topic, "qos=1&concurrentConsumers=4");
var consumer = endpoint.CreateConsumer(route);
await consumer.Start();
try
{
await PublishAsync(topic, MqttQualityOfServiceLevel.AtLeastOnce, [.. failing, "good"]);
(await WaitUntil(() => route.Succeeded.ContainsKey("good"), 15_000))
.Should().BeTrue("failed messages no longer fill the receive window");
}
finally
{
await consumer.Stop();
await endpoint.Stop();
}
}
}