Bundle: redb-route / tests/redb.Route.Tests.MqttNet (tests.redb.Route.Tests.MqttNet.txt), 23 files Snapshot: 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 Index: https://redbase.app/src/dev-2026-12-06/redb-route/_index.txt ==== Path: redb-route/tests/redb.Route.Tests.MqttNet/MqttBrokerRegistryTests.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/MqttBrokerRegistryTests.cs ---- using redb.Route.MqttNet.Connection; namespace redb.Route.Tests.MqttNet; public class MqttBrokerRegistryTests { [Fact] public void Register_AndGetOptions_ReturnsSameOptions() { var registry = new MqttBrokerRegistry(); var options = new MqttBrokerOptions { Server = "broker1.local", Port = 1883 }; registry.Register("prod", options); var result = registry.GetOptions("prod"); result.Should().BeSameAs(options); } [Fact] public void Contains_RegisteredBroker_ReturnsTrue() { var registry = new MqttBrokerRegistry(); registry.Register("main", new MqttBrokerOptions()); registry.Contains("main").Should().BeTrue(); } [Fact] public void Contains_UnregisteredBroker_ReturnsFalse() { var registry = new MqttBrokerRegistry(); registry.Contains("unknown").Should().BeFalse(); } [Fact] public void GetOptions_UnregisteredBroker_Throws() { var registry = new MqttBrokerRegistry(); var act = () => registry.GetOptions("missing"); act.Should().Throw().WithMessage("*'missing'*not registered*"); } [Fact] public void Register_CaseInsensitive() { var registry = new MqttBrokerRegistry(); registry.Register("Main", new MqttBrokerOptions { Server = "a" }); registry.Contains("main").Should().BeTrue(); registry.Contains("MAIN").Should().BeTrue(); registry.GetOptions("main").Server.Should().Be("a"); } [Fact] public void Register_OverwritesExisting() { var registry = new MqttBrokerRegistry(); registry.Register("main", new MqttBrokerOptions { Server = "old" }); registry.Register("main", new MqttBrokerOptions { Server = "new" }); registry.GetOptions("main").Server.Should().Be("new"); } [Fact] public void Register_NullName_Throws() { var registry = new MqttBrokerRegistry(); var act = () => registry.Register(null!, new MqttBrokerOptions()); act.Should().Throw(); } [Fact] public void Register_EmptyName_Throws() { var registry = new MqttBrokerRegistry(); var act = () => registry.Register("", new MqttBrokerOptions()); act.Should().Throw(); } [Fact] public void Register_NullOptions_Throws() { var registry = new MqttBrokerRegistry(); var act = () => registry.Register("main", null!); act.Should().Throw(); } [Fact] public void MultipleBrokers_IndependentLookup() { var registry = new MqttBrokerRegistry(); registry.Register("prod", new MqttBrokerOptions { Server = "prod.broker" }); registry.Register("dev", new MqttBrokerOptions { Server = "dev.broker" }); registry.GetOptions("prod").Server.Should().Be("prod.broker"); registry.GetOptions("dev").Server.Should().Be("dev.broker"); } } public class MqttBrokerOptionsTests { [Fact] public void DefaultServer_IsLocalhost() { new MqttBrokerOptions().Server.Should().Be("localhost"); } [Fact] public void DefaultPort_Is1883() { new MqttBrokerOptions().Port.Should().Be(1883); } [Fact] public void DefaultKeepAlive_Is60() { new MqttBrokerOptions().KeepAlive.Should().Be(60); } [Fact] public void DefaultCleanSession_IsTrue() { new MqttBrokerOptions().CleanSession.Should().BeTrue(); } [Fact] public void DefaultUseTls_IsFalse() { new MqttBrokerOptions().UseTls.Should().BeFalse(); } } Path: redb-route/tests/redb.Route.Tests.MqttNet/MqttBuilderTests.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/MqttBuilderTests.cs ---- using redb.Route.MqttNet; using redb.Route.Expressions; namespace redb.Route.Tests.MqttNet; public class MqttBuilderTests { private static ConstantExpression C(string s) => new(s); // ── Factory methods ───────────────────────────────────────────── [Fact] public void Subscribe_SetsSubscribeMode() { var uri = Mqtt.Subscribe("sensors/temp").Broker(C("main")).Build(); uri.Should().Contain("mode=Subscribe"); } [Fact] public void Publish_SetsPublishMode() { var uri = Mqtt.Publish("sensors/temp").Broker(C("main")).Build(); uri.Should().Contain("mode=Publish"); } [Fact] public void NullTopic_Throws() { var act = () => Mqtt.Subscribe(null!); act.Should().Throw(); } [Fact] public void EmptyTopic_Throws() { var act = () => Mqtt.Subscribe(""); act.Should().Throw(); } [Fact] public void WhitespaceTopic_Throws() { var act = () => Mqtt.Publish(" "); act.Should().Throw(); } // ── URI structure ─────────────────────────────────────────────── [Fact] public void Build_StartsWithMqttScheme() { var uri = Mqtt.Subscribe("test").Broker(C("main")).Build(); uri.Should().StartWith("mqtt:"); } [Fact] public void Build_ContainsTopicInPath() { var uri = Mqtt.Subscribe("sensors/temperature").Broker(C("main")).Build(); uri.Should().StartWith("mqtt:sensors/temperature"); } [Fact] public void Build_FirstParamAfterQuestionMark() { var uri = Mqtt.Subscribe("topic").Broker(C("main")).Build(); uri.Should().Contain("?mode="); } // ── Connection parameters ─────────────────────────────────────── [Fact] public void Broker_SetsParam() { var uri = Mqtt.Subscribe("t").Broker(C("prod")).Build(); uri.Should().Contain("broker=prod"); } [Fact] public void Server_SetsParam() { var uri = Mqtt.Subscribe("t").Server(C("mqtt.example.com")).Build(); uri.Should().Contain("server=mqtt.example.com"); } [Fact] public void Port_SetsParam() { var uri = Mqtt.Subscribe("t").Server(C("localhost")).Port(8883).Build(); uri.Should().Contain("port=8883"); } [Fact] public void Username_SetsParam() { var uri = Mqtt.Subscribe("t").Server(C("localhost")).Username(C("admin")).Build(); uri.Should().Contain("username=admin"); } [Fact] public void Password_SetsParam() { var uri = Mqtt.Subscribe("t").Server(C("localhost")).Password(C("secret")).Build(); uri.Should().Contain("password=secret"); } [Fact] public void ClientId_SetsParam() { var uri = Mqtt.Subscribe("t").Broker(C("main")).ClientId(C("myClient")).Build(); uri.Should().Contain("clientId=myClient"); } [Fact] public void UseTls_SetsParam() { var uri = Mqtt.Subscribe("t").Broker(C("main")).UseTls().Build(); uri.Should().Contain("useTls=true"); } [Fact] public void KeepAlive_SetsParam() { var uri = Mqtt.Subscribe("t").Broker(C("main")).KeepAlive(30).Build(); uri.Should().Contain("keepAlive=30"); } [Fact] public void CleanSession_True_SetsParam() { var uri = Mqtt.Subscribe("t").Broker(C("main")).CleanSession(true).Build(); uri.Should().Contain("cleanSession=true"); } [Fact] public void CleanSession_False_SetsParam() { var uri = Mqtt.Subscribe("t").Broker(C("main")).CleanSession(false).Build(); uri.Should().Contain("cleanSession=false"); } // ── QoS ───────────────────────────────────────────────────────── [Theory] [InlineData(0)] [InlineData(1)] [InlineData(2)] public void Qos_SetsParam(int qos) { var uri = Mqtt.Subscribe("t").Broker(C("main")).Qos(qos).Build(); uri.Should().Contain($"qos={qos}"); } // ── Subscribe parameters ──────────────────────────────────────── [Fact] public void SharedSubscription_SetsParam() { var uri = Mqtt.Subscribe("t").Broker(C("main")).SharedSubscription(C("group1")).Build(); uri.Should().Contain("sharedSubscription=group1"); } // ── Publish parameters ────────────────────────────────────────── [Fact] public void Retain_SetsParam() { var uri = Mqtt.Publish("t").Broker(C("main")).Retain().Build(); uri.Should().Contain("retain=true"); } [Fact] public void MessageExpiryInterval_SetsParam() { var uri = Mqtt.Publish("t").Broker(C("main")).MessageExpiryInterval(3600).Build(); uri.Should().Contain("messageExpiryInterval=3600"); } [Fact] public void ContentType_SetsParam() { var uri = Mqtt.Publish("t").Broker(C("main")).ContentType("application/json").Build(); uri.Should().Contain("contentType=application%2Fjson"); } [Fact] public void ResponseTopic_SetsParam() { var uri = Mqtt.Publish("t").Broker(C("main")).ResponseTopic(C("response/topic")).Build(); uri.Should().Contain("responseTopic=response%2Ftopic"); } // ── Implicit string conversion ────────────────────────────────── [Fact] public void ImplicitConversion_ReturnsUri() { string uri = Mqtt.Subscribe("test").Broker(C("main")).Qos(1); uri.Should().StartWith("mqtt:test?"); uri.Should().Contain("mode=Subscribe"); uri.Should().Contain("broker=main"); uri.Should().Contain("qos=1"); } [Fact] public void ToString_ReturnsSameAsBuild() { var builder = Mqtt.Publish("events").Broker(C("main")).Qos(2).Retain(); builder.ToString().Should().Be(builder.Build()); } // ── Full fluent chain ─────────────────────────────────────────── [Fact] public void FullSubscribeChain_BuildsCorrectUri() { var uri = Mqtt.Subscribe("sensors/+/data") .Broker(C("main")) .Qos(1) .SharedSubscription(C("workers")) .ClientId(C("sub-1")) .Build(); uri.Should().StartWith("mqtt:sensors/+/data?"); uri.Should().Contain("mode=Subscribe"); uri.Should().Contain("broker=main"); uri.Should().Contain("qos=1"); uri.Should().Contain("sharedSubscription=workers"); uri.Should().Contain("clientId=sub-1"); } [Fact] public void FullPublishChain_BuildsCorrectUri() { var uri = Mqtt.Publish("commands/device1") .Server(C("mqtt.example.com")) .Port(8883) .UseTls() .Username(C("admin")) .Password(C("pass")) .Qos(2) .Retain() .MessageExpiryInterval(600) .ContentType("application/json") .ResponseTopic(C("responses/device1")) .Build(); uri.Should().StartWith("mqtt:commands/device1?"); uri.Should().Contain("mode=Publish"); uri.Should().Contain("server=mqtt.example.com"); uri.Should().Contain("port=8883"); uri.Should().Contain("useTls=true"); uri.Should().Contain("username=admin"); uri.Should().Contain("password=pass"); uri.Should().Contain("qos=2"); uri.Should().Contain("retain=true"); uri.Should().Contain("messageExpiryInterval=600"); uri.Should().Contain("contentType=application%2Fjson"); uri.Should().Contain("responseTopic=responses%2Fdevice1"); } // ── Defaults: optional params not included in URI ─────────────── [Fact] public void Build_NoPort_OmitsPort() { var uri = Mqtt.Subscribe("t").Broker(C("main")).Build(); uri.Should().NotContain("port="); } [Fact] public void Build_NoRetain_OmitsRetain() { var uri = Mqtt.Publish("t").Broker(C("main")).Build(); uri.Should().NotContain("retain="); } [Fact] public void Build_NoTls_OmitsTls() { var uri = Mqtt.Subscribe("t").Broker(C("main")).Build(); uri.Should().NotContain("useTls="); } [Fact] public void Build_NoCleanSession_OmitsCleanSession() { var uri = Mqtt.Subscribe("t").Broker(C("main")).Build(); uri.Should().NotContain("cleanSession="); } } Path: redb-route/tests/redb.Route.Tests.MqttNet/MqttComponentTests.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/MqttComponentTests.cs ---- using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.MqttNet; namespace redb.Route.Tests.MqttNet; public class MqttComponentTests { [Fact] public void Scheme_ReturnsMqtt() { var component = new MqttComponent(); component.Scheme.Should().Be("mqtt"); } [Fact] public void CreateEndpoint_ValidUri_ReturnsMqttEndpoint() { var component = new MqttComponent(); var uri = new EndpointUri("mqtt", "sensors/temp", "mqtt:sensors/temp?mode=Subscribe&broker=main", new Dictionary { ["mode"] = "Subscribe", ["broker"] = "main" }); var endpoint = component.CreateEndpoint(uri); endpoint.Should().BeOfType(); endpoint.Uri.Should().BeSameAs(uri); endpoint.Component.Should().BeSameAs(component); } [Fact] public void CreateEndpoint_NullUri_Throws() { var component = new MqttComponent(); var act = () => component.CreateEndpoint(null!); act.Should().Throw(); } [Fact] public void CreateEndpoint_BindsOptionsCorrectly() { var component = new MqttComponent(); var parameters = new Dictionary { ["mode"] = "Subscribe", ["broker"] = "main", ["qos"] = "1", ["sharedSubscription"] = "group1", ["cleanSession"] = "true", ["keepAlive"] = "30" }; var uri = new EndpointUri("mqtt", "sensors/+", "mqtt:sensors/+?...", parameters); var endpoint = (MqttEndpoint)component.CreateEndpoint(uri); endpoint.EndpointOptions.Mode.Should().Be(MqttMode.Subscribe); endpoint.EndpointOptions.Broker.Should().Be("main"); endpoint.EndpointOptions.Qos.Should().Be(1); endpoint.EndpointOptions.SharedSubscription.Should().Be("group1"); endpoint.EndpointOptions.CleanSession.Should().BeTrue(); endpoint.EndpointOptions.KeepAlive.Should().Be(30); } [Fact] public void CreateEndpoint_NoBrokerNorServer_Throws() { var component = new MqttComponent(); var uri = new EndpointUri("mqtt", "topic", "mqtt:topic", new Dictionary { ["mode"] = "Subscribe" }); var act = () => component.CreateEndpoint(uri); act.Should().Throw().WithMessage("*Broker*Server*"); } [Fact] public void CreateEndpoint_InvalidQos_Throws() { var component = new MqttComponent(); var uri = new EndpointUri("mqtt", "topic", "mqtt:topic", new Dictionary { ["broker"] = "main", ["qos"] = "5" }); var act = () => component.CreateEndpoint(uri); act.Should().Throw().WithMessage("*QoS*"); } } public class MqttEndpointTests { private static MqttEndpoint CreateEndpoint( MqttMode mode = MqttMode.Subscribe, string topic = "test/topic", string? broker = "main", string? server = null) { var component = new MqttComponent(); var parameters = new Dictionary { ["mode"] = mode.ToString() }; if (broker != null) parameters["broker"] = broker; if (server != null) parameters["server"] = server; var uri = new EndpointUri("mqtt", topic, $"mqtt:{topic}", parameters); return (MqttEndpoint)component.CreateEndpoint(uri); } [Fact] public void Topic_ReturnsUriPath() { var endpoint = CreateEndpoint(topic: "sensors/temperature"); endpoint.Topic.Should().Be("sensors/temperature"); } [Fact] public void CreateProducer_ReturnsProducer() { var endpoint = CreateEndpoint(MqttMode.Publish); var producer = endpoint.CreateProducer(); producer.Should().NotBeNull(); } [Fact] public void CreateConsumer_SubscribeMode_ReturnsConsumer() { var endpoint = CreateEndpoint(MqttMode.Subscribe); var processor = Substitute.For(); var consumer = endpoint.CreateConsumer(processor); consumer.Should().NotBeNull(); } [Fact] public void CreateConsumer_PublishMode_Throws() { var endpoint = CreateEndpoint(MqttMode.Publish); var processor = Substitute.For(); var act = () => endpoint.CreateConsumer(processor); act.Should().Throw().WithMessage("*Mode=Publish*"); } [Fact] public void CreateConsumer_NullProcessor_Throws() { var endpoint = CreateEndpoint(MqttMode.Subscribe); var act = () => endpoint.CreateConsumer(null!); act.Should().Throw(); } [Fact] public void MqttComponent_ReturnsCastComponent() { var endpoint = CreateEndpoint(); endpoint.MqttComponent.Should().BeOfType(); } [Fact] public void EndpointOptions_ReturnsOptions() { var endpoint = CreateEndpoint(); endpoint.EndpointOptions.Should().NotBeNull(); endpoint.EndpointOptions.Broker.Should().Be("main"); } } Path: redb-route/tests/redb.Route.Tests.MqttNet/MqttConcurrentConsumersTests.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/MqttConcurrentConsumersTests.cs ---- 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; using Xunit.Abstractions; namespace redb.Route.Tests.MqttNet; /// /// Integration tests for MQTT concurrentConsumers (Threads/B) against a real Mosquitto broker. /// Proves: N>1 processes up to N messages in parallel; default (1) stays strictly serial; and no /// message is lost (each is acknowledged only after its worker finishes — manual ack-after-process). /// Broker: localhost:11883 (anonymous). /// [Trait("Category", "Integration")] public sealed class MqttConcurrentConsumersTests { private const string Server = "localhost"; private const int Port = 11883; private readonly ITestOutputHelper _output; public MqttConcurrentConsumersTests(ITestOutputHelper output) => _output = output; private static string UniqueTopic() => $"test/{Guid.NewGuid():N}"; private static MqttEndpoint CreateEndpoint(string topic, string extraParams) { var uri = EndpointUriParser.Parse($"mqtt:{topic}?mode=Subscribe&server={Server}&port={Port}&{extraParams}"); var component = new MqttComponent { ClientFactory = new DefaultMqttClientFactory() }; return (MqttEndpoint)component.CreateEndpoint(uri); } private static async Task CreateRawClientAsync() { var factory = new MqttClientFactory(); var client = factory.CreateMqttClient(); var options = new MqttClientOptionsBuilder() .WithTcpServer(Server, Port) .WithClientId($"test-raw-{Guid.NewGuid():N}") .WithCleanSession() .Build(); await client.ConnectAsync(options); return client; } private static async Task PublishManyAsync(string topic, int count) { using var raw = await CreateRawClientAsync(); for (var i = 0; i < count; i++) { var msg = new MqttApplicationMessageBuilder() .WithTopic(topic) .WithPayload(Encoding.UTF8.GetBytes($"msg-{i}")) .WithQualityOfServiceLevel(MqttQualityOfServiceLevel.AtLeastOnce) .Build(); await raw.PublishAsync(msg); } await raw.DisconnectAsync(); } [Fact] public async Task ConcurrentConsumers_ProcessesUpToNInParallel() { const int pool = 5, total = 20; var topic = UniqueTopic(); var current = 0; var max = 0; var maxLock = new object(); var received = 0; var done = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); var processor = Substitute.For(); processor.Process(Arg.Any(), Arg.Any()) .Returns(async _ => { var c = Interlocked.Increment(ref current); lock (maxLock) { if (c > max) max = c; } // Service time must exceed pool/delivery-rate so the workers stay saturated rather than // starve on the broker's QoS-1 delivery pacing (Little's law) — then the pool reaches N. await Task.Delay(200); Interlocked.Decrement(ref current); if (Interlocked.Increment(ref received) >= total) done.TrySetResult(); }); var consumer = CreateEndpoint(topic, $"qos=1&concurrentConsumers={pool}").CreateConsumer(processor); await consumer.Start(); try { await PublishManyAsync(topic, total); await Task.WhenAny(done.Task, Task.Delay(30_000)); Volatile.Read(ref received).Should().Be(total, "no message may be lost under concurrent dispatch"); max.Should().Be(pool, "the pool must saturate to exactly N workers processing at once"); _output.WriteLine("concurrentConsumers={0}: max observed concurrency = {1}, received = {2}", pool, max, received); } finally { await consumer.Stop(); } } [Fact] public async Task Default_IsStrictlySerial() { const int total = 8; var topic = UniqueTopic(); var current = 0; var max = 0; var maxLock = new object(); var received = 0; var done = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); var processor = Substitute.For(); processor.Process(Arg.Any(), Arg.Any()) .Returns(async _ => { var c = Interlocked.Increment(ref current); lock (maxLock) { if (c > max) max = c; } await Task.Delay(20); Interlocked.Decrement(ref current); if (Interlocked.Increment(ref received) >= total) done.TrySetResult(); }); // No concurrentConsumers → default 1 → strictly serial (backward-compatible). var consumer = CreateEndpoint(topic, "qos=1").CreateConsumer(processor); await consumer.Start(); try { await PublishManyAsync(topic, total); await Task.WhenAny(done.Task, Task.Delay(30_000)); Volatile.Read(ref received).Should().Be(total); max.Should().Be(1, "the default consumer must never run two bodies at once"); } finally { await consumer.Stop(); } } } Path: redb-route/tests/redb.Route.Tests.MqttNet/MqttConnectionFactoryTests.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/MqttConnectionFactoryTests.cs ---- using redb.Route.Core; using redb.Route.MqttNet; namespace redb.Route.Tests.MqttNet; /// /// Broker credentials must be able to live in the registry instead of the endpoint URI, /// so they never reach logs, telemetry, or the dashboard. /// public sealed class MqttConnectionFactoryTests { private const string Secret = "brokerP4ssw0rd"; private static MqttComponent Wire(string name, MqttConnectionFactory factory) { var context = new RouteContext(); var component = new MqttComponent(); context.AddComponent(component); context.AddToRegistry(name, factory); return component; } [Fact] public void Factory_SuppliesBrokerAndCredentials_WhenUriCarriesNone() { var component = Wire("iot-broker", new MqttConnectionFactory { Server = "mqtt.corp.local", Port = 8883, UseTls = true, Username = "svc-ingest", Password = Secret, ClientId = "ingest-1" }); // Validate() requires a broker — this throws if the factory is not applied first. var uri = EndpointUriParser.Parse("mqtt://sensors/temp?connectionFactory=iot-broker"); var endpoint = component.CreateEndpoint(uri); endpoint.Should().NotBeNull(); uri.ToUriString().Should().NotContain(Secret); uri.ToString().Should().NotContain(Secret); } [Fact] public void ExplicitUriValue_WinsOverFactory() { var component = Wire("f", new MqttConnectionFactory { Server = "from-factory", Port = 8883, Username = "factory-user" }); var uri = EndpointUriParser.Parse( "mqtt://sensors/temp?connectionFactory=f&server=from-uri&username=uri-user"); component.CreateEndpoint(uri).Should().NotBeNull(); uri.RawParameters["server"].Should().Be("from-uri"); uri.RawParameters["username"].Should().Be("uri-user"); } [Fact] public void MissingFactory_FailsLoud() { var context = new RouteContext(); var component = new MqttComponent(); context.AddComponent(component); var uri = EndpointUriParser.Parse("mqtt://sensors/temp?connectionFactory=absent&server=direct"); var act = () => component.CreateEndpoint(uri); // A typo in connectionFactory must fail loud, not fall back silently act.Should().Throw() .Which.Message.Should().Contain("absent"); } [Fact] public void Dsl_EmitsConnectionFactory() { var uri = Mqtt.Subscribe("sensors/temp").ConnectionFactory("iot-broker").Build(); uri.Should().Contain("connectionFactory=iot-broker"); uri.Should().NotContain("password="); } } 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); } } 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); } Path: redb-route/tests/redb.Route.Tests.MqttNet/MqttConsumerTests.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/MqttConsumerTests.cs ---- using System.Buffers; 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; public class MqttConsumerTests { private static MqttEndpoint CreateEndpoint( MqttMode mode = MqttMode.Subscribe, string topic = "test/topic", string? broker = "main", string? server = null, int qos = 0, string? sharedSubscription = null, string? clientId = null) { var component = new MqttComponent(); var parameters = new Dictionary { ["mode"] = mode.ToString() }; if (broker != null) parameters["broker"] = broker; if (server != null) parameters["server"] = server; if (qos > 0) parameters["qos"] = qos.ToString(); if (sharedSubscription != null) parameters["sharedSubscription"] = sharedSubscription; if (clientId != null) parameters["clientId"] = clientId; var uri = new EndpointUri("mqtt", topic, $"mqtt:{topic}", parameters); return (MqttEndpoint)component.CreateEndpoint(uri); } private static MqttEndpoint CreateEndpointWithMocks( out IMqttClient mockClient, out IMqttClientFactory mockFactory, out IMqttBrokerRegistry mockRegistry, string topic = "test/topic", int qos = 0, string? sharedSubscription = null, string? clientId = null) { var endpoint = CreateEndpoint( MqttMode.Subscribe, topic, "main", qos: qos, sharedSubscription: sharedSubscription, clientId: clientId); mockClient = Substitute.For(); mockClient.IsConnected.Returns(true); mockFactory = Substitute.For(); mockFactory.CreateConnectedClientAsync( Arg.Any(), Arg.Any(), Arg.Any()) .Returns(Task.FromResult(mockClient)); mockRegistry = Substitute.For(); mockRegistry.GetOptions("main").Returns(new MqttBrokerOptions { Server = "localhost" }); mockRegistry.Contains("main").Returns(true); endpoint.MqttComponent.ClientFactory = mockFactory; endpoint.MqttComponent.BrokerRegistry = mockRegistry; return endpoint; } private static MqttApplicationMessageReceivedEventArgs CreateReceivedArgs( MqttApplicationMessage message, string clientId = "c1") { var packet = new MqttPublishPacket { Topic = message.Topic }; return new MqttApplicationMessageReceivedEventArgs(clientId, message, packet, null); } // ── Start / Stop lifecycle ────────────────────────────────────── [Fact] public async Task Start_ConnectsAndSubscribes() { var endpoint = CreateEndpointWithMocks( out var mockClient, out var mockFactory, out _); var processor = Substitute.For(); var consumer = endpoint.CreateConsumer(processor); await consumer.Start(); await mockFactory.Received(1).CreateConnectedClientAsync( Arg.Any(), Arg.Any(), Arg.Any()); await mockClient.Received(1).SubscribeAsync( Arg.Any(), Arg.Any()); } [Fact] public async Task Stop_UnsubscribesAndDisconnects() { var endpoint = CreateEndpointWithMocks( out var mockClient, out _, out _); var processor = Substitute.For(); var consumer = endpoint.CreateConsumer(processor); await consumer.Start(); await consumer.Stop(); await mockClient.Received(1).UnsubscribeAsync( Arg.Any(), Arg.Any()); await mockClient.Received(1).DisconnectAsync( Arg.Any(), Arg.Any()); } // ── Broker resolution ─────────────────────────────────────────── [Fact] public async Task Start_NamedBroker_ResolvesFromRegistry() { var endpoint = CreateEndpointWithMocks( out _, out _, out var mockRegistry); var processor = Substitute.For(); var consumer = endpoint.CreateConsumer(processor); await consumer.Start(); mockRegistry.Received(1).GetOptions("main"); } [Fact] public async Task Start_InlineServer_DoesNotUseRegistry() { var endpoint = CreateEndpoint( MqttMode.Subscribe, "test", broker: null, server: "mqtt.local"); var mockClient = Substitute.For(); mockClient.IsConnected.Returns(true); var mockFactory = Substitute.For(); mockFactory.CreateConnectedClientAsync( Arg.Any(), Arg.Any(), Arg.Any()) .Returns(Task.FromResult(mockClient)); endpoint.MqttComponent.ClientFactory = mockFactory; var processor = Substitute.For(); var consumer = endpoint.CreateConsumer(processor); await consumer.Start(); await mockFactory.Received(1).CreateConnectedClientAsync( Arg.Is(o => o.Server == "mqtt.local"), Arg.Any(), Arg.Any()); } [Fact] public void Start_NoBrokerNoRegistryNoServer_Throws() { // Broker is set but no registry var endpoint = CreateEndpoint(MqttMode.Subscribe, "t", broker: "main"); // Don't set BrokerRegistry — it's null var processor = Substitute.For(); var consumer = endpoint.CreateConsumer(processor); var act = async () => await consumer.Start(); act.Should().ThrowAsync().WithMessage("*IMqttBrokerRegistry*"); } // ── SharedSubscription topic format ───────────────────────────── [Fact] public async Task Start_SharedSubscription_SubscribesWithSharedTopic() { var endpoint = CreateEndpointWithMocks( out var mockClient, out _, out _, topic: "sensors/temp", sharedSubscription: "workers"); var processor = Substitute.For(); var consumer = endpoint.CreateConsumer(processor); await consumer.Start(); await mockClient.Received(1).SubscribeAsync( Arg.Is(opts => opts.TopicFilters.Count == 1 && opts.TopicFilters[0].Topic == "$share/workers/sensors/temp"), Arg.Any()); } // ── QoS subscription level ────────────────────────────────────── [Theory] [InlineData(0, MqttQualityOfServiceLevel.AtMostOnce)] [InlineData(1, MqttQualityOfServiceLevel.AtLeastOnce)] [InlineData(2, MqttQualityOfServiceLevel.ExactlyOnce)] public async Task Start_QosLevel_SetCorrectly(int qos, MqttQualityOfServiceLevel expected) { var endpoint = CreateEndpointWithMocks( out var mockClient, out _, out _, qos: qos); var processor = Substitute.For(); var consumer = endpoint.CreateConsumer(processor); await consumer.Start(); await mockClient.Received(1).SubscribeAsync( Arg.Is(opts => opts.TopicFilters[0].QualityOfServiceLevel == expected), Arg.Any()); } // ── CreateExchange tests (via message receive simulation) ─────── [Fact] public async Task OnMessage_CreatesExchangeWithBody() { var endpoint = CreateEndpointWithMocks( out var mockClient, out _, out _); IExchange? capturedExchange = null; var processor = Substitute.For(); processor.Process(Arg.Any(), Arg.Any()) .Returns(Task.CompletedTask) .AndDoes(x => capturedExchange = x.Arg()); var consumer = endpoint.CreateConsumer(processor); await consumer.Start(); // Simulate message received var payload = Encoding.UTF8.GetBytes("Hello MQTT"); var message = new MqttApplicationMessageBuilder() .WithTopic("test/topic") .WithPayload(payload) .WithQualityOfServiceLevel(MqttQualityOfServiceLevel.AtLeastOnce) .Build(); // Trigger the event mockClient.ApplicationMessageReceivedAsync += Raise.Event>( CreateReceivedArgs(message, "client1")); // Wait briefly for async processing await Task.Delay(100); capturedExchange.Should().NotBeNull(); Encoding.UTF8.GetString((byte[])capturedExchange!.In.Body!).Should().Be("Hello MQTT"); } [Fact] public async Task OnMessage_SetsTopicHeader() { var endpoint = CreateEndpointWithMocks( out var mockClient, out _, out _); IExchange? capturedExchange = null; var processor = Substitute.For(); processor.Process(Arg.Any(), Arg.Any()) .Returns(Task.CompletedTask) .AndDoes(x => capturedExchange = x.Arg()); var consumer = endpoint.CreateConsumer(processor); await consumer.Start(); var message = new MqttApplicationMessageBuilder() .WithTopic("sensors/temperature") .WithPayload(Encoding.UTF8.GetBytes("data")) .Build(); mockClient.ApplicationMessageReceivedAsync += Raise.Event>( CreateReceivedArgs(message)); await Task.Delay(100); capturedExchange.Should().NotBeNull(); capturedExchange!.In.Headers[MqttHeaders.Topic].Should().Be("sensors/temperature"); } [Fact] public async Task OnMessage_SetsQosHeader() { var endpoint = CreateEndpointWithMocks( out var mockClient, out _, out _); IExchange? capturedExchange = null; var processor = Substitute.For(); processor.Process(Arg.Any(), Arg.Any()) .Returns(Task.CompletedTask) .AndDoes(x => capturedExchange = x.Arg()); var consumer = endpoint.CreateConsumer(processor); await consumer.Start(); var message = new MqttApplicationMessageBuilder() .WithTopic("t") .WithPayload(Encoding.UTF8.GetBytes("data")) .WithQualityOfServiceLevel(MqttQualityOfServiceLevel.ExactlyOnce) .Build(); mockClient.ApplicationMessageReceivedAsync += Raise.Event>( CreateReceivedArgs(message)); await Task.Delay(100); capturedExchange.Should().NotBeNull(); capturedExchange!.In.Headers[MqttHeaders.Qos].Should().Be(2); } [Fact] public async Task OnMessage_EmptyPayload_BodyIsNull() { var endpoint = CreateEndpointWithMocks( out var mockClient, out _, out _); IExchange? capturedExchange = null; var processor = Substitute.For(); processor.Process(Arg.Any(), Arg.Any()) .Returns(Task.CompletedTask) .AndDoes(x => capturedExchange = x.Arg()); var consumer = endpoint.CreateConsumer(processor); await consumer.Start(); var message = new MqttApplicationMessageBuilder() .WithTopic("t") .Build(); mockClient.ApplicationMessageReceivedAsync += Raise.Event>( CreateReceivedArgs(message)); await Task.Delay(100); capturedExchange.Should().NotBeNull(); capturedExchange!.In.Body.Should().BeNull(); } [Fact] public async Task OnMessage_BrokerHeader_Set() { var endpoint = CreateEndpointWithMocks( out var mockClient, out _, out _); IExchange? capturedExchange = null; var processor = Substitute.For(); processor.Process(Arg.Any(), Arg.Any()) .Returns(Task.CompletedTask) .AndDoes(x => capturedExchange = x.Arg()); var consumer = endpoint.CreateConsumer(processor); await consumer.Start(); var message = new MqttApplicationMessageBuilder() .WithTopic("t") .WithPayload(Encoding.UTF8.GetBytes("x")) .Build(); mockClient.ApplicationMessageReceivedAsync += Raise.Event>( CreateReceivedArgs(message)); await Task.Delay(100); capturedExchange.Should().NotBeNull(); capturedExchange!.In.Headers[MqttHeaders.Broker].Should().Be("main"); } [Fact] public async Task OnMessage_ClientIdHeader_Set() { var endpoint = CreateEndpointWithMocks( out var mockClient, out _, out _, clientId: "my-consumer"); IExchange? capturedExchange = null; var processor = Substitute.For(); processor.Process(Arg.Any(), Arg.Any()) .Returns(Task.CompletedTask) .AndDoes(x => capturedExchange = x.Arg()); var consumer = endpoint.CreateConsumer(processor); await consumer.Start(); var message = new MqttApplicationMessageBuilder() .WithTopic("t") .WithPayload(Encoding.UTF8.GetBytes("data")) .Build(); mockClient.ApplicationMessageReceivedAsync += Raise.Event>( CreateReceivedArgs(message)); await Task.Delay(100); capturedExchange.Should().NotBeNull(); capturedExchange!.In.Headers[MqttHeaders.ClientId].Should().Be("my-consumer"); } [Fact] public async Task OnMessage_ContentType_SetInHeaders() { var endpoint = CreateEndpointWithMocks( out var mockClient, out _, out _); IExchange? capturedExchange = null; var processor = Substitute.For(); processor.Process(Arg.Any(), Arg.Any()) .Returns(Task.CompletedTask) .AndDoes(x => capturedExchange = x.Arg()); var consumer = endpoint.CreateConsumer(processor); await consumer.Start(); var message = new MqttApplicationMessageBuilder() .WithTopic("t") .WithPayload(Encoding.UTF8.GetBytes("{}")) .WithContentType("application/json") .Build(); mockClient.ApplicationMessageReceivedAsync += Raise.Event>( CreateReceivedArgs(message)); await Task.Delay(100); capturedExchange.Should().NotBeNull(); capturedExchange!.In.Headers[MqttHeaders.ContentType].Should().Be("application/json"); } [Fact] public async Task OnMessage_RetainHeader_Set() { var endpoint = CreateEndpointWithMocks( out var mockClient, out _, out _); IExchange? capturedExchange = null; var processor = Substitute.For(); processor.Process(Arg.Any(), Arg.Any()) .Returns(Task.CompletedTask) .AndDoes(x => capturedExchange = x.Arg()); var consumer = endpoint.CreateConsumer(processor); await consumer.Start(); var message = new MqttApplicationMessageBuilder() .WithTopic("t") .WithPayload(Encoding.UTF8.GetBytes("data")) .WithRetainFlag(true) .Build(); mockClient.ApplicationMessageReceivedAsync += Raise.Event>( CreateReceivedArgs(message)); await Task.Delay(100); capturedExchange.Should().NotBeNull(); capturedExchange!.In.Headers[MqttHeaders.Retain].Should().Be(true); } } Path: redb-route/tests/redb.Route.Tests.MqttNet/MqttEndpointOptionsTests.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/MqttEndpointOptionsTests.cs ---- using redb.Route.Core; using redb.Route.MqttNet; namespace redb.Route.Tests.MqttNet; public class MqttEndpointOptionsTests { // ── BindFromUri ───────────────────────────────────────────────── [Fact] public void BindFromUri_Mode_Parsed() { var options = new MqttEndpointOptions(); options.BindFromUri(new Dictionary { ["mode"] = "Publish", ["broker"] = "main" }); options.Mode.Should().Be(MqttMode.Publish); } [Fact] public void BindFromUri_Subscribe_IsDefault() { var options = new MqttEndpointOptions(); options.BindFromUri(new Dictionary { ["broker"] = "main" }); options.Mode.Should().Be(MqttMode.Subscribe); } [Fact] public void BindFromUri_Broker_Parsed() { var options = new MqttEndpointOptions(); options.BindFromUri(new Dictionary { ["broker"] = "production" }); options.Broker.Should().Be("production"); } [Fact] public void BindFromUri_Server_Parsed() { var options = new MqttEndpointOptions(); options.BindFromUri(new Dictionary { ["server"] = "mqtt.local" }); options.Server.Should().Be("mqtt.local"); } [Fact] public void BindFromUri_Port_Parsed() { var options = new MqttEndpointOptions(); options.BindFromUri(new Dictionary { ["server"] = "x", ["port"] = "8883" }); options.Port.Should().Be(8883); } [Fact] public void BindFromUri_Qos_Parsed() { var options = new MqttEndpointOptions(); options.BindFromUri(new Dictionary { ["broker"] = "m", ["qos"] = "2" }); options.Qos.Should().Be(2); } [Fact] public void BindFromUri_UseTls_Parsed() { var options = new MqttEndpointOptions(); options.BindFromUri(new Dictionary { ["broker"] = "m", ["useTls"] = "true" }); options.UseTls.Should().BeTrue(); } [Fact] public void BindFromUri_CleanSession_Parsed() { var options = new MqttEndpointOptions(); options.BindFromUri(new Dictionary { ["broker"] = "m", ["cleanSession"] = "false" }); options.CleanSession.Should().BeFalse(); } [Fact] public void BindFromUri_KeepAlive_Parsed() { var options = new MqttEndpointOptions(); options.BindFromUri(new Dictionary { ["broker"] = "m", ["keepAlive"] = "30" }); options.KeepAlive.Should().Be(30); } [Fact] public void BindFromUri_Retain_Parsed() { var options = new MqttEndpointOptions(); options.BindFromUri(new Dictionary { ["broker"] = "m", ["retain"] = "true" }); options.Retain.Should().BeTrue(); } [Fact] public void BindFromUri_SharedSubscription_Parsed() { var options = new MqttEndpointOptions(); options.BindFromUri(new Dictionary { ["broker"] = "m", ["sharedSubscription"] = "grp" }); options.SharedSubscription.Should().Be("grp"); } [Fact] public void BindFromUri_MessageExpiryInterval_Parsed() { var options = new MqttEndpointOptions(); options.BindFromUri(new Dictionary { ["broker"] = "m", ["messageExpiryInterval"] = "600" }); options.MessageExpiryInterval.Should().Be(600); } [Fact] public void BindFromUri_ContentType_Parsed() { var options = new MqttEndpointOptions(); options.BindFromUri(new Dictionary { ["broker"] = "m", ["contentType"] = "application/json" }); options.ContentType.Should().Be("application/json"); } [Fact] public void BindFromUri_ResponseTopic_Parsed() { var options = new MqttEndpointOptions(); options.BindFromUri(new Dictionary { ["broker"] = "m", ["responseTopic"] = "resp/t" }); options.ResponseTopic.Should().Be("resp/t"); } [Fact] public void BindFromUri_Username_Parsed() { var options = new MqttEndpointOptions(); options.BindFromUri(new Dictionary { ["server"] = "x", ["username"] = "admin" }); options.Username.Should().Be("admin"); } [Fact] public void BindFromUri_Password_Parsed() { var options = new MqttEndpointOptions(); options.BindFromUri(new Dictionary { ["server"] = "x", ["password"] = "secret" }); options.Password.Should().Be("secret"); } [Fact] public void BindFromUri_ClientId_Parsed() { var options = new MqttEndpointOptions(); options.BindFromUri(new Dictionary { ["broker"] = "m", ["clientId"] = "myClient" }); options.ClientId.Should().Be("myClient"); } // ── Validate ──────────────────────────────────────────────────── [Fact] public void Validate_NoBrokerNoServer_Throws() { var options = new MqttEndpointOptions(); var act = () => options.Validate(); act.Should().Throw().WithMessage("*Broker*Server*"); } [Fact] public void Validate_WithBroker_DoesNotThrow() { var options = new MqttEndpointOptions { Broker = "main" }; var act = () => options.Validate(); act.Should().NotThrow(); } [Fact] public void Validate_WithServer_DoesNotThrow() { var options = new MqttEndpointOptions { Server = "localhost" }; var act = () => options.Validate(); act.Should().NotThrow(); } [Theory] [InlineData(-1)] [InlineData(3)] [InlineData(99)] public void Validate_InvalidQos_Throws(int qos) { var options = new MqttEndpointOptions { Broker = "main", Qos = qos }; var act = () => options.Validate(); act.Should().Throw().WithMessage("*QoS*"); } [Theory] [InlineData(0)] [InlineData(1)] [InlineData(2)] public void Validate_ValidQos_DoesNotThrow(int qos) { var options = new MqttEndpointOptions { Broker = "main", Qos = qos }; var act = () => options.Validate(); act.Should().NotThrow(); } // ── Defaults ──────────────────────────────────────────────────── [Fact] public void DefaultMode_IsSubscribe() { new MqttEndpointOptions().Mode.Should().Be(MqttMode.Subscribe); } [Fact] public void DefaultQos_IsZero() { new MqttEndpointOptions().Qos.Should().Be(0); } [Fact] public void DefaultKeepAlive_Is60() { new MqttEndpointOptions().KeepAlive.Should().Be(60); } [Fact] public void DefaultCleanSession_IsTrue() { new MqttEndpointOptions().CleanSession.Should().BeTrue(); } [Fact] public void DefaultRetain_IsFalse() { new MqttEndpointOptions().Retain.Should().BeFalse(); } [Fact] public void DefaultMessageExpiryInterval_IsZero() { new MqttEndpointOptions().MessageExpiryInterval.Should().Be(0); } [Fact] public void DefaultPort_IsZero() { new MqttEndpointOptions().Port.Should().Be(0); } [Fact] public void DefaultUseTls_IsFalse() { new MqttEndpointOptions().UseTls.Should().BeFalse(); } } 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(); } } } Path: redb-route/tests/redb.Route.Tests.MqttNet/MqttHeaderMappingCharacterizationTests.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/MqttHeaderMappingCharacterizationTests.cs ---- using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.MqttNet; using redb.Route.MqttNet.Connection; namespace redb.Route.Tests.MqttNet; /// /// What crosses an MQTT message today, producer to consumer: pinned before the header filter strategy. /// MQTT does not carry exchange headers: only the user properties the /// route put into the one redbMqtt.userProperties dictionary are sent, so it is a transport of explicit consent /// and gets no strategy. /// [Trait("Category", "Integration")] public sealed class MqttHeaderMappingCharacterizationTests { private const string Broker = "server=localhost&port=11883"; [Fact] public async Task ProducerToConsumer_OnlyTheUserPropertiesDictionaryCrosses() { var topic = $"test/hdr-char-{Guid.NewGuid():N}"; var received = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); await using var ctx = new RouteContext(); ctx.AddComponent(new MqttComponent { ClientFactory = new DefaultMqttClientFactory() }); ctx.AddRoutes(r => r.From($"mqtt:{topic}?mode=Subscribe&{Broker}").Process(e => received.TrySetResult(e))); await ctx.Start(); var exchange = new Exchange(new Message("body")); exchange.In.Headers["X-Corr"] = "c1"; exchange.In.Headers["Authorization"] = "Bearer secret"; exchange.In.Headers["redbHttp.Method"] = "DELETE"; exchange.In.Headers[MqttHeaders.UserProperties] = new Dictionary { ["X-Explicit"] = "e1" }; var producer = ctx.GetEndpoint($"mqtt:{topic}?mode=Publish&{Broker}").CreateProducer(); await producer.Start(); await producer.Process(exchange); await producer.Stop(); var headers = (await received.Task.WaitAsync(TimeSpan.FromSeconds(15))).In.Headers; headers.Should().NotContainKey("X-Corr", "an exchange header is not sent"); headers.Should().NotContainKey("Authorization"); headers.Should().NotContainKey("redbHttp.Method"); // The client speaks MQTT 5: user properties exist, and only the dictionary's entries (and the trace context) // come back, in the same one header. var userProperties = headers[MqttHeaders.UserProperties].Should().BeOfType>().Subject; userProperties["X-Explicit"].Should().Be("e1"); userProperties.Should().NotContainKey("X-Corr"); userProperties.Should().NotContainKey("Authorization"); } } Path: redb-route/tests/redb.Route.Tests.MqttNet/MqttHeadersTests.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/MqttHeadersTests.cs ---- using redb.Route.MqttNet; namespace redb.Route.Tests.MqttNet; public class MqttHeadersTests { [Fact] public void Prefix_IsRedbMqttDot() { MqttHeaders.Prefix.Should().Be("redbMqtt."); } [Theory] [InlineData(nameof(MqttHeaders.Topic), "redbMqtt.topic")] [InlineData(nameof(MqttHeaders.OverrideTopic), "redbMqtt.overrideTopic")] [InlineData(nameof(MqttHeaders.Qos), "redbMqtt.qos")] [InlineData(nameof(MqttHeaders.OverrideQos), "redbMqtt.overrideQos")] [InlineData(nameof(MqttHeaders.Retain), "redbMqtt.retain")] [InlineData(nameof(MqttHeaders.OverrideRetain), "redbMqtt.overrideRetain")] [InlineData(nameof(MqttHeaders.ContentType), "redbMqtt.contentType")] [InlineData(nameof(MqttHeaders.ResponseTopic), "redbMqtt.responseTopic")] [InlineData(nameof(MqttHeaders.CorrelationData), "redbMqtt.correlationData")] [InlineData(nameof(MqttHeaders.MessageExpiryInterval), "redbMqtt.messageExpiryInterval")] [InlineData(nameof(MqttHeaders.Broker), "redbMqtt.broker")] [InlineData(nameof(MqttHeaders.ClientId), "redbMqtt.clientId")] [InlineData(nameof(MqttHeaders.UserProperties), "redbMqtt.userProperties")] public void HeaderConstants_HaveCorrectValues(string fieldName, string expected) { var field = typeof(MqttHeaders).GetField(fieldName); field.Should().NotBeNull(); field!.GetValue(null).Should().Be(expected); } [Fact] public void AllHeaders_StartWithPrefix() { var fields = typeof(MqttHeaders).GetFields( System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Static); foreach (var field in fields) { if (field.Name == nameof(MqttHeaders.Prefix)) continue; var value = (string)field.GetValue(null)!; value.Should().StartWith(MqttHeaders.Prefix, $"header {field.Name} should start with prefix '{MqttHeaders.Prefix}'"); } } } Path: redb-route/tests/redb.Route.Tests.MqttNet/MqttIntegrationTests.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/MqttIntegrationTests.cs ---- using System.Collections.Concurrent; using System.Text; using Microsoft.Extensions.DependencyInjection; using MQTTnet; using MQTTnet.Protocol; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.MqttNet; using redb.Route.Expressions; using redb.Route.MqttNet.Connection; using Xunit.Abstractions; namespace redb.Route.Tests.MqttNet; /// /// Integration tests for the MQTT connector against a real Mosquitto broker. /// Requires: docker compose -f docker-compose.tests.yml up -d mosquitto /// Broker: localhost:11883 (anonymous, no auth). /// [Trait("Category", "Integration")] public sealed class MqttIntegrationTests { private const string Server = "localhost"; private const int Port = 11883; private readonly ITestOutputHelper _output; public MqttIntegrationTests(ITestOutputHelper output) => _output = output; // ── Helpers ───────────────────────────────────────────────────── private static string UniqueTopic() => $"test/{Guid.NewGuid():N}"; /// /// Creates a connected MqttEndpoint from a URI with inline server (no named broker). /// The component gets a real DefaultMqttClientFactory. /// private static MqttEndpoint CreateEndpoint(string topic, MqttMode mode, string? extraParams = null) { var qs = $"mode={mode}&server={Server}&port={Port}"; if (extraParams is not null) qs += $"&{extraParams}"; var uri = EndpointUriParser.Parse($"mqtt:{topic}?{qs}"); var component = new MqttComponent { ClientFactory = new DefaultMqttClientFactory() }; return (MqttEndpoint)component.CreateEndpoint(uri); } /// Creates a standalone MQTTnet client for test-side pub/sub. private static async Task CreateRawClientAsync(string? clientId = null) { var factory = new MqttClientFactory(); var client = factory.CreateMqttClient(); var options = new MqttClientOptionsBuilder() .WithTcpServer(Server, Port) .WithClientId(clientId ?? $"test-raw-{Guid.NewGuid():N}") .WithCleanSession() .Build(); await client.ConnectAsync(options); return client; } // ── Basic Publish → Subscribe roundtrip ───────────────────────── [Fact] public async Task PublishAndSubscribe_Roundtrip() { var topic = UniqueTopic(); var received = new ConcurrentBag(); var tcs = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); // Consumer var subEndpoint = CreateEndpoint(topic, MqttMode.Subscribe, "qos=1"); var processor = Substitute.For(); processor.Process(Arg.Any(), Arg.Any()) .Returns(Task.CompletedTask) .AndDoes(x => { received.Add(x.Arg()); tcs.TrySetResult(); }); var consumer = subEndpoint.CreateConsumer(processor); await consumer.Start(); try { // Producer var pubEndpoint = CreateEndpoint(topic, MqttMode.Publish, "qos=1"); var producer = pubEndpoint.CreateProducer(); await producer.Start(); try { var exchange = new Exchange(new Message("Hello from integration test")); await ((IProducer)producer).Process(exchange); _output.WriteLine("Published message to {0}", topic); await Task.WhenAny(tcs.Task, Task.Delay(15_000)); received.Should().NotBeEmpty(); Encoding.UTF8.GetString((byte[])received.First().In.Body!).Should().Be("Hello from integration test"); _output.WriteLine("Received {0} message(s)", received.Count); } finally { await producer.Stop(); } } finally { await consumer.Stop(); } } // ── Multiple messages ─────────────────────────────────────────── [Fact] public async Task PublishMultiple_AllReceived() { var topic = UniqueTopic(); const int messageCount = 10; var received = new ConcurrentBag(); var tcs = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); var subEndpoint = CreateEndpoint(topic, MqttMode.Subscribe, "qos=1"); var processor = Substitute.For(); processor.Process(Arg.Any(), Arg.Any()) .Returns(Task.CompletedTask) .AndDoes(x => { received.Add(x.Arg()); if (received.Count >= messageCount) tcs.TrySetResult(); }); var consumer = subEndpoint.CreateConsumer(processor); await consumer.Start(); try { var pubEndpoint = CreateEndpoint(topic, MqttMode.Publish, "qos=1"); var producer = pubEndpoint.CreateProducer(); await producer.Start(); try { for (var i = 0; i < messageCount; i++) { var exchange = new Exchange(new Message($"msg-{i}")); await ((IProducer)producer).Process(exchange); } await Task.WhenAny(tcs.Task, Task.Delay(15_000)); received.Should().HaveCount(messageCount); _output.WriteLine("All {0} messages received", received.Count); } finally { await producer.Stop(); } } finally { await consumer.Stop(); } } // ── QoS levels ────────────────────────────────────────────────── [Theory] [InlineData(0)] [InlineData(1)] [InlineData(2)] public async Task QosLevels_WorkCorrectly(int qos) { var topic = UniqueTopic(); var received = new ConcurrentBag(); var tcs = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); var subEndpoint = CreateEndpoint(topic, MqttMode.Subscribe, $"qos={qos}"); var processor = Substitute.For(); processor.Process(Arg.Any(), Arg.Any()) .Returns(Task.CompletedTask) .AndDoes(x => { received.Add(x.Arg()); tcs.TrySetResult(); }); var consumer = subEndpoint.CreateConsumer(processor); await consumer.Start(); try { var pubEndpoint = CreateEndpoint(topic, MqttMode.Publish, $"qos={qos}"); var producer = pubEndpoint.CreateProducer(); await producer.Start(); try { await ((IProducer)producer).Process(new Exchange(new Message($"qos-{qos}-test"))); await Task.WhenAny(tcs.Task, Task.Delay(15_000)); received.Should().NotBeEmpty(); received.First().In.Headers[MqttHeaders.Qos].Should().Be(qos); _output.WriteLine("QoS {0} roundtrip OK", qos); } finally { await producer.Stop(); } } finally { await consumer.Stop(); } } // ── Wildcard subscription (+) ─────────────────────────────────── [Fact] public async Task WildcardSubscription_SingleLevel() { var baseTopic = $"test/{Guid.NewGuid():N}"; var subTopic = $"{baseTopic}/+/data"; var pubTopic = $"{baseTopic}/sensor1/data"; var received = new ConcurrentBag(); var tcs = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); var subEndpoint = CreateEndpoint(subTopic, MqttMode.Subscribe, "qos=1"); var processor = Substitute.For(); processor.Process(Arg.Any(), Arg.Any()) .Returns(Task.CompletedTask) .AndDoes(x => { received.Add(x.Arg()); tcs.TrySetResult(); }); var consumer = subEndpoint.CreateConsumer(processor); await consumer.Start(); try { // Publish via raw client to a specific sub-topic using var rawClient = await CreateRawClientAsync(); var message = new MqttApplicationMessageBuilder() .WithTopic(pubTopic) .WithPayload(Encoding.UTF8.GetBytes("wildcard-test")) .WithQualityOfServiceLevel(MqttQualityOfServiceLevel.AtLeastOnce) .Build(); await rawClient.PublishAsync(message); await rawClient.DisconnectAsync(); await Task.WhenAny(tcs.Task, Task.Delay(15_000)); received.Should().NotBeEmpty(); Encoding.UTF8.GetString((byte[])received.First().In.Body!).Should().Be("wildcard-test"); received.First().In.Headers[MqttHeaders.Topic].Should().Be(pubTopic); _output.WriteLine("Wildcard subscription matched: {0} → {1}", subTopic, pubTopic); } finally { await consumer.Stop(); } } // ── Wildcard subscription (#) ─────────────────────────────────── [Fact] public async Task WildcardSubscription_MultiLevel() { var baseTopic = $"test/{Guid.NewGuid():N}"; var subTopic = $"{baseTopic}/#"; var pubTopic = $"{baseTopic}/a/b/c"; var received = new ConcurrentBag(); var tcs = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); var subEndpoint = CreateEndpoint(subTopic, MqttMode.Subscribe, "qos=1"); var processor = Substitute.For(); processor.Process(Arg.Any(), Arg.Any()) .Returns(Task.CompletedTask) .AndDoes(x => { received.Add(x.Arg()); tcs.TrySetResult(); }); var consumer = subEndpoint.CreateConsumer(processor); await consumer.Start(); try { using var rawClient = await CreateRawClientAsync(); var message = new MqttApplicationMessageBuilder() .WithTopic(pubTopic) .WithPayload(Encoding.UTF8.GetBytes("multi-level")) .WithQualityOfServiceLevel(MqttQualityOfServiceLevel.AtLeastOnce) .Build(); await rawClient.PublishAsync(message); await rawClient.DisconnectAsync(); await Task.WhenAny(tcs.Task, Task.Delay(15_000)); received.Should().NotBeEmpty(); received.First().In.Headers[MqttHeaders.Topic].Should().Be(pubTopic); _output.WriteLine("Multi-level wildcard matched: {0} → {1}", subTopic, pubTopic); } finally { await consumer.Stop(); } } // ── Retain flag ───────────────────────────────────────────────── [Fact] public async Task RetainedMessage_ReceivedOnSubscribe() { var topic = UniqueTopic(); // First: publish a retained message var pubEndpoint = CreateEndpoint(topic, MqttMode.Publish, "qos=1&retain=true"); var producer = pubEndpoint.CreateProducer(); await producer.Start(); try { await ((IProducer)producer).Process(new Exchange(new Message("retained-payload"))); } finally { await producer.Stop(); } // Brief delay for broker to store the retained message await Task.Delay(500); // Now subscribe — should receive the retained message immediately var received = new ConcurrentBag(); var tcs = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); var subEndpoint = CreateEndpoint(topic, MqttMode.Subscribe, "qos=1"); var processor = Substitute.For(); processor.Process(Arg.Any(), Arg.Any()) .Returns(Task.CompletedTask) .AndDoes(x => { received.Add(x.Arg()); tcs.TrySetResult(); }); var consumer = subEndpoint.CreateConsumer(processor); await consumer.Start(); try { await Task.WhenAny(tcs.Task, Task.Delay(15_000)); received.Should().NotBeEmpty(); Encoding.UTF8.GetString((byte[])received.First().In.Body!).Should().Be("retained-payload"); ((bool)received.First().In.Headers[MqttHeaders.Retain]!).Should().BeTrue(); _output.WriteLine("Retained message received"); } finally { await consumer.Stop(); // Cleanup: clear retained message by publishing empty payload with retain using var rawClient = await CreateRawClientAsync(); var clearMsg = new MqttApplicationMessageBuilder() .WithTopic(topic) .WithPayload(Array.Empty()) .WithRetainFlag(true) .Build(); await rawClient.PublishAsync(clearMsg); await rawClient.DisconnectAsync(); } } // ── MQTT 5.0 properties roundtrip ─────────────────────────────── [Fact] public async Task Mqtt5Properties_ContentType_Roundtrip() { var topic = UniqueTopic(); var received = new ConcurrentBag(); var tcs = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); var subEndpoint = CreateEndpoint(topic, MqttMode.Subscribe, "qos=1"); var processor = Substitute.For(); processor.Process(Arg.Any(), Arg.Any()) .Returns(Task.CompletedTask) .AndDoes(x => { received.Add(x.Arg()); tcs.TrySetResult(); }); var consumer = subEndpoint.CreateConsumer(processor); await consumer.Start(); try { var pubEndpoint = CreateEndpoint(topic, MqttMode.Publish, "qos=1&contentType=application/json"); var producer = pubEndpoint.CreateProducer(); await producer.Start(); try { await ((IProducer)producer).Process( new Exchange(new Message("{\"temp\":22.5}"))); await Task.WhenAny(tcs.Task, Task.Delay(15_000)); received.Should().NotBeEmpty(); var ex = received.First(); Encoding.UTF8.GetString((byte[])ex.In.Body!).Should().Be("{\"temp\":22.5}"); ex.In.Headers[MqttHeaders.ContentType].Should().Be("application/json"); _output.WriteLine("MQTT 5.0 ContentType roundtrip OK"); } finally { await producer.Stop(); } } finally { await consumer.Stop(); } } // ── Response topic roundtrip ──────────────────────────────────── [Fact] public async Task Mqtt5Properties_ResponseTopic_Roundtrip() { var topic = UniqueTopic(); var responseTopic = UniqueTopic(); var received = new ConcurrentBag(); var tcs = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); var subEndpoint = CreateEndpoint(topic, MqttMode.Subscribe, "qos=1"); var processor = Substitute.For(); processor.Process(Arg.Any(), Arg.Any()) .Returns(Task.CompletedTask) .AndDoes(x => { received.Add(x.Arg()); tcs.TrySetResult(); }); var consumer = subEndpoint.CreateConsumer(processor); await consumer.Start(); try { // Publish with response topic via raw client (to set MQTT 5 props directly) using var rawClient = await CreateRawClientAsync(); var message = new MqttApplicationMessageBuilder() .WithTopic(topic) .WithPayload(Encoding.UTF8.GetBytes("request")) .WithQualityOfServiceLevel(MqttQualityOfServiceLevel.AtLeastOnce) .WithResponseTopic(responseTopic) .WithCorrelationData(Encoding.UTF8.GetBytes("corr-123")) .Build(); await rawClient.PublishAsync(message); await rawClient.DisconnectAsync(); await Task.WhenAny(tcs.Task, Task.Delay(15_000)); received.Should().NotBeEmpty(); var ex = received.First(); ex.In.Headers[MqttHeaders.ResponseTopic].Should().Be(responseTopic); ex.In.Headers[MqttHeaders.CorrelationData].Should().Be("corr-123"); _output.WriteLine("MQTT 5.0 ResponseTopic + CorrelationData roundtrip OK"); } finally { await consumer.Stop(); } } // ── Topic override from header ────────────────────────────────── [Fact] public async Task Producer_TopicOverrideFromHeader() { var defaultTopic = UniqueTopic(); var actualTopic = UniqueTopic(); var received = new ConcurrentBag(); var tcs = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); // Subscribe to the actual (overridden) topic var subEndpoint = CreateEndpoint(actualTopic, MqttMode.Subscribe, "qos=1"); var processor = Substitute.For(); processor.Process(Arg.Any(), Arg.Any()) .Returns(Task.CompletedTask) .AndDoes(x => { received.Add(x.Arg()); tcs.TrySetResult(); }); var consumer = subEndpoint.CreateConsumer(processor); await consumer.Start(); try { // Producer configured for default topic, but header overrides var pubEndpoint = CreateEndpoint(defaultTopic, MqttMode.Publish, "qos=1"); var producer = pubEndpoint.CreateProducer(); await producer.Start(); try { var exchange = new Exchange(new Message("overridden")); exchange.In.Headers[MqttHeaders.OverrideTopic] = actualTopic; await ((IProducer)producer).Process(exchange); await Task.WhenAny(tcs.Task, Task.Delay(15_000)); received.Should().NotBeEmpty(); Encoding.UTF8.GetString((byte[])received.First().In.Body!).Should().Be("overridden"); _output.WriteLine("Topic override: {0} → {1}", defaultTopic, actualTopic); } finally { await producer.Stop(); } } finally { await consumer.Stop(); } } // ── Binary payload roundtrip ──────────────────────────────────── [Fact] public async Task BinaryPayload_Roundtrip() { var topic = UniqueTopic(); var received = new ConcurrentBag(); var tcs = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); var subEndpoint = CreateEndpoint(topic, MqttMode.Subscribe, "qos=1"); var processor = Substitute.For(); processor.Process(Arg.Any(), Arg.Any()) .Returns(Task.CompletedTask) .AndDoes(x => { received.Add(x.Arg()); tcs.TrySetResult(); }); var consumer = subEndpoint.CreateConsumer(processor); await consumer.Start(); try { var pubEndpoint = CreateEndpoint(topic, MqttMode.Publish, "qos=1"); var producer = pubEndpoint.CreateProducer(); await producer.Start(); try { // Send raw bytes var data = new byte[] { 0x00, 0x01, 0x02, 0xFF, 0xFE }; await ((IProducer)producer).Process(new Exchange(new Message(data))); await Task.WhenAny(tcs.Task, Task.Delay(15_000)); received.Should().NotBeEmpty(); // Consumer decodes as UTF8 string; binary data survives as string received.First().In.Body.Should().NotBeNull(); _output.WriteLine("Binary payload roundtrip OK"); } finally { await producer.Stop(); } } finally { await consumer.Stop(); } } // ── Fluent builder URI integration ────────────────────────────── [Fact] public async Task FluentBuilder_EndToEnd() { var topic = UniqueTopic(); var received = new ConcurrentBag(); var tcs = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); // Use the fluent builder to generate URIs (like a real route definition) string subUri = Mqtt.Subscribe(topic).Server(new ConstantExpression(Server)).Port(Port).Qos(1); string pubUri = Mqtt.Publish(topic).Server(new ConstantExpression(Server)).Port(Port).Qos(1); _output.WriteLine("Sub URI: {0}", subUri); _output.WriteLine("Pub URI: {0}", pubUri); var component = new MqttComponent { ClientFactory = new DefaultMqttClientFactory() }; var subEndpoint = (MqttEndpoint)component.CreateEndpoint(EndpointUriParser.Parse(subUri)); var processor = Substitute.For(); processor.Process(Arg.Any(), Arg.Any()) .Returns(Task.CompletedTask) .AndDoes(x => { received.Add(x.Arg()); tcs.TrySetResult(); }); var consumer = subEndpoint.CreateConsumer(processor); await consumer.Start(); try { var pubEndpoint = (MqttEndpoint)component.CreateEndpoint(EndpointUriParser.Parse(pubUri)); var producer = pubEndpoint.CreateProducer(); await producer.Start(); try { await ((IProducer)producer).Process(new Exchange(new Message("fluent-builder-test"))); await Task.WhenAny(tcs.Task, Task.Delay(15_000)); received.Should().NotBeEmpty(); Encoding.UTF8.GetString((byte[])received.First().In.Body!).Should().Be("fluent-builder-test"); _output.WriteLine("Fluent builder end-to-end OK"); } finally { await producer.Stop(); } } finally { await consumer.Stop(); } } // ── DI registration integration ───────────────────────────────── [Fact] public async Task DiRegistration_NamedBroker_EndToEnd() { var topic = UniqueTopic(); var received = new ConcurrentBag(); var tcs = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); // Build DI container var services = new Microsoft.Extensions.DependencyInjection.ServiceCollection(); services.AddSingleton(Substitute.For()); services.AddRedbRouteMqtt(mqtt => { mqtt.AddBroker("test", o => { o.Server = Server; o.Port = Port; }); }); var sp = services.BuildServiceProvider(); var component = sp.GetRequiredService(); component.BrokerRegistry = sp.GetRequiredService(); component.ClientFactory = sp.GetRequiredService(); // Create endpoints using named broker string subUri = Mqtt.Subscribe(topic).Broker(new ConstantExpression("test")).Qos(1); string pubUri = Mqtt.Publish(topic).Broker(new ConstantExpression("test")).Qos(1); var subEndpoint = (MqttEndpoint)component.CreateEndpoint(EndpointUriParser.Parse(subUri)); var processor = Substitute.For(); processor.Process(Arg.Any(), Arg.Any()) .Returns(Task.CompletedTask) .AndDoes(x => { received.Add(x.Arg()); tcs.TrySetResult(); }); var consumer = subEndpoint.CreateConsumer(processor); await consumer.Start(); try { var pubEndpoint = (MqttEndpoint)component.CreateEndpoint(EndpointUriParser.Parse(pubUri)); var producer = pubEndpoint.CreateProducer(); await producer.Start(); try { await ((IProducer)producer).Process(new Exchange(new Message("di-test"))); await Task.WhenAny(tcs.Task, Task.Delay(15_000)); received.Should().NotBeEmpty(); Encoding.UTF8.GetString((byte[])received.First().In.Body!).Should().Be("di-test"); received.First().In.Headers[MqttHeaders.Broker].Should().Be("test"); _output.WriteLine("DI named broker end-to-end OK"); } finally { await producer.Stop(); } } finally { await consumer.Stop(); } } // ── Consumer Stop/Start lifecycle ─────────────────────────────── [Fact] public async Task Consumer_StopAndRestart() { var topic = UniqueTopic(); var received = new ConcurrentBag(); var subEndpoint = CreateEndpoint(topic, MqttMode.Subscribe, "qos=1"); var processor = Substitute.For(); processor.Process(Arg.Any(), Arg.Any()) .Returns(Task.CompletedTask) .AndDoes(x => received.Add(x.Arg())); var consumer = subEndpoint.CreateConsumer(processor); await consumer.Start(); await consumer.Stop(); // Publish while consumer is stopped — should NOT receive using (var rawClient = await CreateRawClientAsync()) { var msg = new MqttApplicationMessageBuilder() .WithTopic(topic) .WithPayload(Encoding.UTF8.GetBytes("missed")) .WithQualityOfServiceLevel(MqttQualityOfServiceLevel.AtMostOnce) .Build(); await rawClient.PublishAsync(msg); await rawClient.DisconnectAsync(); } await Task.Delay(1000); received.Should().BeEmpty("consumer was stopped, should not receive"); // Restart with new consumer var tcs = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); var received2 = new ConcurrentBag(); var processor2 = Substitute.For(); processor2.Process(Arg.Any(), Arg.Any()) .Returns(Task.CompletedTask) .AndDoes(x => { received2.Add(x.Arg()); tcs.TrySetResult(); }); var subEndpoint2 = CreateEndpoint(topic, MqttMode.Subscribe, "qos=1"); var consumer2 = subEndpoint2.CreateConsumer(processor2); await consumer2.Start(); try { using var rawClient2 = await CreateRawClientAsync(); var msg2 = new MqttApplicationMessageBuilder() .WithTopic(topic) .WithPayload(Encoding.UTF8.GetBytes("after-restart")) .WithQualityOfServiceLevel(MqttQualityOfServiceLevel.AtLeastOnce) .Build(); await rawClient2.PublishAsync(msg2); await rawClient2.DisconnectAsync(); await Task.WhenAny(tcs.Task, Task.Delay(15_000)); received2.Should().NotBeEmpty(); Encoding.UTF8.GetString((byte[])received2.First().In.Body!).Should().Be("after-restart"); _output.WriteLine("Consumer stop/restart lifecycle OK"); } finally { await consumer2.Stop(); } } // ── Expression resolution roundtrip ───────────────────────────── [Fact] public async Task Producer_ExpressionTopic_ResolvesAtRuntime() { var baseTopic = UniqueTopic(); // Producer topic uses an expression: the actual topic is resolved from header // Topic is the URI path, so we put the template there directly var pubEndpoint = CreateEndpoint("${header.actualTopic}", MqttMode.Publish, "qos=1"); var producer = (MqttProducer)pubEndpoint.CreateProducer(); await producer.Start(); var received = new ConcurrentBag(); var tcs = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); // Consumer subscribes to the real topic var subEndpoint = CreateEndpoint(baseTopic, MqttMode.Subscribe, "qos=1"); var processor = Substitute.For(); processor.Process(Arg.Any(), Arg.Any()) .Returns(Task.CompletedTask) .AndDoes(x => { received.Add(x.Arg()); tcs.TrySetResult(); }); var consumer = (MqttConsumer)subEndpoint.CreateConsumer(processor); await consumer.Start(); // Publish with expression-resolved topic var msg = new Message("expr-topic-test"); msg.Headers["actualTopic"] = baseTopic; var exchange = new Exchange(msg); await producer.Process(exchange); await Task.WhenAny(tcs.Task, Task.Delay(15_000)); await producer.Stop(); await consumer.Stop(); await pubEndpoint.Stop(); await subEndpoint.Stop(); received.Should().NotBeEmpty("topic expression should resolve to the subscribed topic"); Encoding.UTF8.GetString((byte[])received.First().In.Body!) .Should().Be("expr-topic-test"); } } Path: redb-route/tests/redb.Route.Tests.MqttNet/MqttModeTests.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/MqttModeTests.cs ---- using redb.Route.MqttNet; namespace redb.Route.Tests.MqttNet; public class MqttModeTests { [Fact] public void Subscribe_HasValue0() { ((int)MqttMode.Subscribe).Should().Be(0); } [Fact] public void Publish_HasValue1() { ((int)MqttMode.Publish).Should().Be(1); } [Fact] public void Enum_HasTwoValues() { Enum.GetValues().Should().HaveCount(2); } } Path: redb-route/tests/redb.Route.Tests.MqttNet/MqttProducerExpressionTests.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/MqttProducerExpressionTests.cs ---- using MQTTnet; using MQTTnet.Protocol; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Expressions; using redb.Route.MqttNet; using redb.Route.MqttNet.Connection; namespace redb.Route.Tests.MqttNet; /// /// Tests for expression resolution in MQTT producer (Phase 1 bugfix). /// Verifies header > expression > static priority for all properties. /// public class MqttProducerExpressionTests { // ── Helpers ────────────────────────────────────────────────────── private static MqttEndpoint CreateEndpoint( Dictionary parameters, string topic = "test/topic") { var component = new MqttComponent(); parameters["mode"] = "Publish"; if (!parameters.ContainsKey("broker")) parameters["broker"] = "main"; var uri = new EndpointUri("mqtt", topic, $"mqtt:{topic}", parameters); return (MqttEndpoint)component.CreateEndpoint(uri); } private static (MqttEndpoint endpoint, IMqttClient mockClient) CreateMocked( Dictionary parameters, string topic = "test/topic") { var endpoint = CreateEndpoint(parameters, topic); var mockClient = Substitute.For(); mockClient.IsConnected.Returns(true); mockClient.PublishAsync(Arg.Any(), Arg.Any()) .Returns(Task.FromResult(new MqttClientPublishResult(0, MqttClientPublishReasonCode.Success, "", null))); var mockFactory = Substitute.For(); mockFactory.CreateConnectedClientAsync( Arg.Any(), Arg.Any(), Arg.Any()) .Returns(Task.FromResult(mockClient)); var mockRegistry = Substitute.For(); mockRegistry.GetOptions("main").Returns(new MqttBrokerOptions { Server = "localhost" }); endpoint.MqttComponent.ClientFactory = mockFactory; endpoint.MqttComponent.BrokerRegistry = mockRegistry; return (endpoint, mockClient); } private static async Task SendAndCapture( MqttEndpoint endpoint, IMqttClient mockClient, IExchange exchange) { MqttApplicationMessage? captured = null; mockClient.PublishAsync(Arg.Any(), Arg.Any()) .Returns(Task.FromResult(new MqttClientPublishResult(0, MqttClientPublishReasonCode.Success, "", null))) .AndDoes(x => captured = x.Arg()); var producer = endpoint.CreateProducer(); await producer.Start(); await ((IProducer)producer).Process(exchange); return captured!; } // ── Topic expression ───────────────────────────────────────────── [Fact] public async Task Topic_Expression_ResolvesFromHeader() { var (endpoint, client) = CreateMocked(new(), topic: "prefix/${header.device}"); var msg = new Message("payload"); msg.Headers["device"] = "sensor42"; var exchange = new Exchange(msg); var published = await SendAndCapture(endpoint, client, exchange); published.Topic.Should().Be("prefix/sensor42"); } [Fact] public async Task Topic_HeaderOverride_WinsOverExpression() { var (endpoint, client) = CreateMocked(new(), topic: "prefix/${header.device}"); var msg = new Message("payload"); msg.Headers["device"] = "sensor42"; msg.Headers[MqttHeaders.OverrideTopic] = "override/topic"; var exchange = new Exchange(msg); var published = await SendAndCapture(endpoint, client, exchange); published.Topic.Should().Be("override/topic"); } // ── QoS expression ─────────────────────────────────────────────── [Fact] public async Task Qos_Expression_ResolvesFromHeader() { var (endpoint, client) = CreateMocked(new() { ["qosExpression"] = "${header.qosLevel}" }); var msg = new Message("payload"); msg.Headers["qosLevel"] = "2"; var exchange = new Exchange(msg); var published = await SendAndCapture(endpoint, client, exchange); published.QualityOfServiceLevel.Should().Be(MqttQualityOfServiceLevel.ExactlyOnce); } [Fact] public async Task Qos_HeaderOverride_WinsOverExpression() { var (endpoint, client) = CreateMocked(new() { ["qosExpression"] = "${header.qosLevel}" }); var msg = new Message("payload"); msg.Headers["qosLevel"] = "2"; msg.Headers[MqttHeaders.OverrideQos] = 1; // int header var exchange = new Exchange(msg); var published = await SendAndCapture(endpoint, client, exchange); published.QualityOfServiceLevel.Should().Be(MqttQualityOfServiceLevel.AtLeastOnce); } [Fact] public async Task Qos_StaticFallback_WhenNoExpressionOrHeader() { var (endpoint, client) = CreateMocked(new() { ["qos"] = "1" }); var msg = new Message("payload"); var exchange = new Exchange(msg); var published = await SendAndCapture(endpoint, client, exchange); published.QualityOfServiceLevel.Should().Be(MqttQualityOfServiceLevel.AtLeastOnce); } // ── MessageExpiryInterval expression ───────────────────────────── [Fact] public async Task MessageExpiryInterval_Expression_ResolvesFromHeader() { var (endpoint, client) = CreateMocked(new() { ["messageExpiryIntervalExpression"] = "${header.ttl}" }); var msg = new Message("payload"); msg.Headers["ttl"] = "300"; var exchange = new Exchange(msg); var published = await SendAndCapture(endpoint, client, exchange); published.MessageExpiryInterval.Should().Be(300); } [Fact] public async Task MessageExpiryInterval_HeaderOverride_WinsOverExpression() { var (endpoint, client) = CreateMocked(new() { ["messageExpiryIntervalExpression"] = "${header.ttl}" }); var msg = new Message("payload"); msg.Headers["ttl"] = "300"; msg.Headers[MqttHeaders.MessageExpiryInterval] = 60; var exchange = new Exchange(msg); var published = await SendAndCapture(endpoint, client, exchange); published.MessageExpiryInterval.Should().Be(60); } // ── ContentType expression ─────────────────────────────────────── [Fact] public async Task ContentType_Expression_ResolvesFromHeader() { var (endpoint, client) = CreateMocked(new() { ["contentType"] = "${header.ct}" }); var msg = new Message("payload"); msg.Headers["ct"] = "application/json"; var exchange = new Exchange(msg); var published = await SendAndCapture(endpoint, client, exchange); published.ContentType.Should().Be("application/json"); } [Fact] public async Task ContentType_HeaderOverride_WinsOverExpression() { var (endpoint, client) = CreateMocked(new() { ["contentType"] = "${header.ct}" }); var msg = new Message("payload"); msg.Headers["ct"] = "application/json"; msg.Headers[MqttHeaders.ContentType] = "text/xml"; var exchange = new Exchange(msg); var published = await SendAndCapture(endpoint, client, exchange); published.ContentType.Should().Be("text/xml"); } // ── ResponseTopic expression ───────────────────────────────────── [Fact] public async Task ResponseTopic_Expression_ResolvesFromHeader() { var (endpoint, client) = CreateMocked(new() { ["responseTopic"] = "reply/${header.device}" }); var msg = new Message("payload"); msg.Headers["device"] = "sensor42"; var exchange = new Exchange(msg); var published = await SendAndCapture(endpoint, client, exchange); published.ResponseTopic.Should().Be("reply/sensor42"); } [Fact] public async Task ResponseTopic_HeaderOverride_WinsOverExpression() { var (endpoint, client) = CreateMocked(new() { ["responseTopic"] = "reply/${header.device}" }); var msg = new Message("payload"); msg.Headers["device"] = "sensor42"; msg.Headers[MqttHeaders.ResponseTopic] = "override/reply"; var exchange = new Exchange(msg); var published = await SendAndCapture(endpoint, client, exchange); published.ResponseTopic.Should().Be("override/reply"); } // ── DSL Build expression routing ───────────────────────────────── [Fact] public void DslBuild_QosExpression_RoutesToExpressionParam() { var uri = Mqtt.Publish("test/topic").Qos(new HeaderExpression("qosLevel")).Build(); uri.Should().Contain("qosExpression="); uri.Should().NotContain("&qos="); } [Fact] public void DslBuild_QosStatic_RoutesToNormalParam() { var uri = Mqtt.Publish("test/topic").Qos(1).Build(); uri.Should().Contain("qos=1"); uri.Should().NotContain("qosExpression"); } [Fact] public void DslBuild_MessageExpiryExpression_RoutesToExpressionParam() { var uri = Mqtt.Publish("test/topic").MessageExpiryInterval(new HeaderExpression("ttl")).Build(); uri.Should().Contain("messageExpiryIntervalExpression="); uri.Should().NotContain("&messageExpiryInterval="); } } Path: redb-route/tests/redb.Route.Tests.MqttNet/MqttProducerTests.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/MqttProducerTests.cs ---- 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; public class MqttProducerTests { private static MqttEndpoint CreateEndpoint( string topic = "out/topic", string? broker = "main", string? server = null, int qos = 0, bool retain = false, int messageExpiryInterval = 0, string? contentType = null, string? responseTopic = null) { var component = new MqttComponent(); var parameters = new Dictionary { ["mode"] = "Publish" }; if (broker != null) parameters["broker"] = broker; if (server != null) parameters["server"] = server; if (qos > 0) parameters["qos"] = qos.ToString(); if (retain) parameters["retain"] = "true"; if (messageExpiryInterval > 0) parameters["messageExpiryInterval"] = messageExpiryInterval.ToString(); if (contentType != null) parameters["contentType"] = contentType; if (responseTopic != null) parameters["responseTopic"] = responseTopic; var uri = new EndpointUri("mqtt", topic, $"mqtt:{topic}", parameters); return (MqttEndpoint)component.CreateEndpoint(uri); } private static MqttEndpoint CreateEndpointWithMocks( out IMqttClient mockClient, out IMqttClientFactory mockFactory, out IMqttBrokerRegistry mockRegistry, string topic = "out/topic", int qos = 0, bool retain = false, int messageExpiryInterval = 0, string? contentType = null, string? responseTopic = null) { var endpoint = CreateEndpoint(topic, "main", qos: qos, retain: retain, messageExpiryInterval: messageExpiryInterval, contentType: contentType, responseTopic: responseTopic); mockClient = Substitute.For(); mockClient.IsConnected.Returns(true); mockClient.PublishAsync(Arg.Any(), Arg.Any()) .Returns(Task.FromResult(new MqttClientPublishResult(0, MqttClientPublishReasonCode.Success, "", null))); mockFactory = Substitute.For(); mockFactory.CreateConnectedClientAsync( Arg.Any(), Arg.Any(), Arg.Any()) .Returns(Task.FromResult(mockClient)); mockRegistry = Substitute.For(); mockRegistry.GetOptions("main").Returns(new MqttBrokerOptions { Server = "localhost" }); endpoint.MqttComponent.ClientFactory = mockFactory; endpoint.MqttComponent.BrokerRegistry = mockRegistry; return endpoint; } // ── Start / Stop lifecycle ────────────────────────────────────── [Fact] public async Task Start_ConnectsClient() { var endpoint = CreateEndpointWithMocks( out _, out var mockFactory, out _); var producer = endpoint.CreateProducer(); await producer.Start(); await mockFactory.Received(1).CreateConnectedClientAsync( Arg.Any(), Arg.Any(), Arg.Any()); } [Fact] public async Task Stop_DisconnectsClient() { var endpoint = CreateEndpointWithMocks( out var mockClient, out _, out _); var producer = endpoint.CreateProducer(); await producer.Start(); await producer.Stop(); await mockClient.Received(1).DisconnectAsync( Arg.Any(), Arg.Any()); } // ── Process / Publish ─────────────────────────────────────────── [Fact] public async Task Process_NotStarted_Throws() { var endpoint = CreateEndpointWithMocks( out _, out _, out _); var producer = endpoint.CreateProducer(); var exchange = new Exchange(new Message("data")); var act = async () => await ((IProducer)producer).Process(exchange); await act.Should().ThrowAsync().WithMessage("*not connected*"); } [Fact] public async Task Process_PublishesMessage() { var endpoint = CreateEndpointWithMocks( out var mockClient, out _, out _); var producer = endpoint.CreateProducer(); await producer.Start(); var exchange = new Exchange(new Message("Hello")); await ((IProducer)producer).Process(exchange); await mockClient.Received(1).PublishAsync( Arg.Any(), Arg.Any()); } [Fact] public async Task Process_TopicFromEndpoint() { MqttApplicationMessage? capturedMessage = null; var endpoint = CreateEndpointWithMocks( out var mockClient, out _, out _, topic: "commands/device1"); mockClient.PublishAsync(Arg.Any(), Arg.Any()) .Returns(Task.FromResult(new MqttClientPublishResult(0, MqttClientPublishReasonCode.Success, "", null))) .AndDoes(x => capturedMessage = x.Arg()); var producer = endpoint.CreateProducer(); await producer.Start(); var exchange = new Exchange(new Message("payload")); await ((IProducer)producer).Process(exchange); capturedMessage.Should().NotBeNull(); capturedMessage!.Topic.Should().Be("commands/device1"); } [Fact] public async Task Process_RecordsPayloadBytesOut_OnlyForPublishedMessages() { var endpoint = CreateEndpointWithMocks(out var mockClient, out _, out _); var producer = endpoint.CreateProducer(); await producer.Start(); await producer.Process(new Exchange(new Message("héllo"))); // 6 bytes in UTF-8 ((IEndpointStatistics)endpoint).BytesOut.Should().Be(6, "the published payload is counted in wire bytes"); mockClient.PublishAsync(Arg.Any(), Arg.Any()) .Returns>(_ => throw new InvalidOperationException("broker refused")); var failed = () => producer.Process(new Exchange(new Message("not sent"))); await failed.Should().ThrowAsync(); ((IEndpointStatistics)endpoint).BytesOut.Should().Be(6, "a publish that failed sent nothing"); } [Fact] public async Task Process_TopicOverrideFromHeader() { MqttApplicationMessage? capturedMessage = null; var endpoint = CreateEndpointWithMocks( out var mockClient, out _, out _, topic: "default/topic"); mockClient.PublishAsync(Arg.Any(), Arg.Any()) .Returns(Task.FromResult(new MqttClientPublishResult(0, MqttClientPublishReasonCode.Success, "", null))) .AndDoes(x => capturedMessage = x.Arg()); var producer = endpoint.CreateProducer(); await producer.Start(); var exchange = new Exchange(new Message("data")); exchange.In.Headers[MqttHeaders.OverrideTopic] = "override/topic"; await ((IProducer)producer).Process(exchange); capturedMessage.Should().NotBeNull(); capturedMessage!.Topic.Should().Be("override/topic"); } private static async Task PublishedTopic(string endpointTopic, IExchange exchange) { MqttApplicationMessage? captured = null; var endpoint = CreateEndpointWithMocks(out var client, out _, out _, topic: endpointTopic); client.PublishAsync(Arg.Any(), Arg.Any()) .Returns(Task.FromResult(new MqttClientPublishResult(0, MqttClientPublishReasonCode.Success, "", null))) .AndDoes(x => captured = x.Arg()); var producer = endpoint.CreateProducer(); await producer.Start(); await ((IProducer)producer).Process(exchange); return captured!.Topic; } /// /// Two publishes of one exchange to different endpoints: each goes to its own topic. The first publish writes /// redbMqtt.topic, which the second used to read as its target. /// [Fact] public async Task Two_publishes_in_one_route_each_go_to_their_endpoint_topic() { var exchange = new Exchange(new Message("21.5")); var first = await PublishedTopic("sensors/room-1/temperature", exchange); var second = await PublishedTopic("sensors/room-2/temperature", exchange); first.Should().Be("sensors/room-1/temperature"); second.Should().Be("sensors/room-2/temperature"); exchange.In.Headers[MqttHeaders.Topic].Should().Be("sensors/room-2/temperature", "the header tells where it went"); } /// A received message republished to a fixed topic goes there, not back to the topic it came from. [Fact] public async Task A_received_message_republished_goes_to_the_endpoint_topic() { var exchange = new Exchange(new Message("42")); exchange.In.Headers[MqttHeaders.Topic] = "sensors/room-1/temperature"; // as the consumer writes it var topic = await PublishedTopic("alerts/temperature", exchange); topic.Should().Be("alerts/temperature"); } private static async Task Published(IExchange exchange, int qos, bool retain) { MqttApplicationMessage? captured = null; var endpoint = CreateEndpointWithMocks(out var client, out _, out _, qos: qos, retain: retain); client.PublishAsync(Arg.Any(), Arg.Any()) .Returns(Task.FromResult(new MqttClientPublishResult(0, MqttClientPublishReasonCode.Success, "", null))) .AndDoes(x => captured = x.Arg()); var producer = endpoint.CreateProducer(); await producer.Start(); await ((IProducer)producer).Process(exchange); return captured!; } /// /// A retained QoS 2 message received and republished goes out with the endpoint's QoS and retain flag. The /// consumer's redbMqtt.qos and redbMqtt.retain used to carry over, so the republish was retained again. /// [Fact] public async Task A_received_retained_message_republished_takes_the_endpoint_qos_and_retain() { var exchange = new Exchange(new Message("42")); exchange.In.Headers[MqttHeaders.Qos] = 2; // as the consumer writes them exchange.In.Headers[MqttHeaders.Retain] = true; var published = await Published(exchange, qos: 1, retain: false); published.QualityOfServiceLevel.Should().Be(MqttQualityOfServiceLevel.AtLeastOnce); published.Retain.Should().BeFalse(); } [Fact] public async Task The_override_headers_win_over_the_endpoint_and_the_incoming_flags() { var exchange = new Exchange(new Message("42")); exchange.In.Headers[MqttHeaders.Qos] = 2; exchange.In.Headers[MqttHeaders.Retain] = true; exchange.In.Headers[MqttHeaders.OverrideQos] = 0; exchange.In.Headers[MqttHeaders.OverrideRetain] = false; var published = await Published(exchange, qos: 1, retain: true); published.QualityOfServiceLevel.Should().Be(MqttQualityOfServiceLevel.AtMostOnce); published.Retain.Should().BeFalse(); } /// Markup sets a header as text (<setHeader value="2"/>); the override takes it. [Fact] public async Task The_override_headers_given_as_text_apply() { var exchange = new Exchange(new Message("42")); exchange.In.Headers[MqttHeaders.OverrideQos] = "2"; exchange.In.Headers[MqttHeaders.OverrideRetain] = "true"; var published = await Published(exchange, qos: 0, retain: false); published.QualityOfServiceLevel.Should().Be(MqttQualityOfServiceLevel.ExactlyOnce); published.Retain.Should().BeTrue(); } [Theory] [InlineData(3)] [InlineData(-1)] [InlineData("high")] [InlineData(1L)] public async Task A_qos_override_out_of_range_fails_the_publish(object value) { var exchange = new Exchange(new Message("42")); exchange.In.Headers[MqttHeaders.OverrideQos] = value; var publish = () => Published(exchange, qos: 0, retain: false); await publish.Should().ThrowAsync().WithMessage("*redbMqtt.overrideQos*"); } [Theory] [InlineData("yes")] [InlineData(1)] public async Task A_retain_override_that_is_not_a_bool_fails_the_publish(object value) { var exchange = new Exchange(new Message("42")); exchange.In.Headers[MqttHeaders.OverrideRetain] = value; var publish = () => Published(exchange, qos: 0, retain: false); await publish.Should().ThrowAsync().WithMessage("*redbMqtt.overrideRetain*"); } [Fact] public async Task Process_QosFromOptions() { MqttApplicationMessage? capturedMessage = null; var endpoint = CreateEndpointWithMocks( out var mockClient, out _, out _, qos: 2); mockClient.PublishAsync(Arg.Any(), Arg.Any()) .Returns(Task.FromResult(new MqttClientPublishResult(0, MqttClientPublishReasonCode.Success, "", null))) .AndDoes(x => capturedMessage = x.Arg()); var producer = endpoint.CreateProducer(); await producer.Start(); var exchange = new Exchange(new Message("data")); await ((IProducer)producer).Process(exchange); capturedMessage.Should().NotBeNull(); capturedMessage!.QualityOfServiceLevel.Should().Be(MqttQualityOfServiceLevel.ExactlyOnce); } [Fact] public async Task Process_QosOverrideFromHeader() { MqttApplicationMessage? capturedMessage = null; var endpoint = CreateEndpointWithMocks( out var mockClient, out _, out _, qos: 0); mockClient.PublishAsync(Arg.Any(), Arg.Any()) .Returns(Task.FromResult(new MqttClientPublishResult(0, MqttClientPublishReasonCode.Success, "", null))) .AndDoes(x => capturedMessage = x.Arg()); var producer = endpoint.CreateProducer(); await producer.Start(); var exchange = new Exchange(new Message("data")); exchange.In.Headers[MqttHeaders.OverrideQos] = 2; await ((IProducer)producer).Process(exchange); capturedMessage.Should().NotBeNull(); capturedMessage!.QualityOfServiceLevel.Should().Be(MqttQualityOfServiceLevel.ExactlyOnce); } [Fact] public async Task Process_RetainFromOptions() { MqttApplicationMessage? capturedMessage = null; var endpoint = CreateEndpointWithMocks( out var mockClient, out _, out _, retain: true); mockClient.PublishAsync(Arg.Any(), Arg.Any()) .Returns(Task.FromResult(new MqttClientPublishResult(0, MqttClientPublishReasonCode.Success, "", null))) .AndDoes(x => capturedMessage = x.Arg()); var producer = endpoint.CreateProducer(); await producer.Start(); var exchange = new Exchange(new Message("data")); await ((IProducer)producer).Process(exchange); capturedMessage.Should().NotBeNull(); capturedMessage!.Retain.Should().BeTrue(); } [Fact] public async Task Process_RetainOverrideFromHeader() { MqttApplicationMessage? capturedMessage = null; var endpoint = CreateEndpointWithMocks( out var mockClient, out _, out _, retain: false); mockClient.PublishAsync(Arg.Any(), Arg.Any()) .Returns(Task.FromResult(new MqttClientPublishResult(0, MqttClientPublishReasonCode.Success, "", null))) .AndDoes(x => capturedMessage = x.Arg()); var producer = endpoint.CreateProducer(); await producer.Start(); var exchange = new Exchange(new Message("data")); exchange.In.Headers[MqttHeaders.OverrideRetain] = true; await ((IProducer)producer).Process(exchange); capturedMessage.Should().NotBeNull(); capturedMessage!.Retain.Should().BeTrue(); } // ── SerializeBody ─────────────────────────────────────────────── [Fact] public async Task Process_StringBody_SerializedToUtf8() { MqttApplicationMessage? capturedMessage = null; var endpoint = CreateEndpointWithMocks( out var mockClient, out _, out _); mockClient.PublishAsync(Arg.Any(), Arg.Any()) .Returns(Task.FromResult(new MqttClientPublishResult(0, MqttClientPublishReasonCode.Success, "", null))) .AndDoes(x => capturedMessage = x.Arg()); var producer = endpoint.CreateProducer(); await producer.Start(); var exchange = new Exchange(new Message("Hello World")); await ((IProducer)producer).Process(exchange); capturedMessage.Should().NotBeNull(); Encoding.UTF8.GetString(capturedMessage!.Payload).Should().Be("Hello World"); } [Fact] public async Task Process_ByteArrayBody_SentDirectly() { MqttApplicationMessage? capturedMessage = null; var endpoint = CreateEndpointWithMocks( out var mockClient, out _, out _); mockClient.PublishAsync(Arg.Any(), Arg.Any()) .Returns(Task.FromResult(new MqttClientPublishResult(0, MqttClientPublishReasonCode.Success, "", null))) .AndDoes(x => capturedMessage = x.Arg()); var producer = endpoint.CreateProducer(); await producer.Start(); var data = new byte[] { 0x01, 0x02, 0x03 }; var exchange = new Exchange(new Message(data)); await ((IProducer)producer).Process(exchange); capturedMessage.Should().NotBeNull(); Encoding.UTF8.GetString(capturedMessage!.Payload).Should().Be(Encoding.UTF8.GetString(data)); } [Fact] public async Task Process_NullBody_EmptyPayload() { MqttApplicationMessage? capturedMessage = null; var endpoint = CreateEndpointWithMocks( out var mockClient, out _, out _); mockClient.PublishAsync(Arg.Any(), Arg.Any()) .Returns(Task.FromResult(new MqttClientPublishResult(0, MqttClientPublishReasonCode.Success, "", null))) .AndDoes(x => capturedMessage = x.Arg()); var producer = endpoint.CreateProducer(); await producer.Start(); var exchange = new Exchange(new Message(null)); await ((IProducer)producer).Process(exchange); capturedMessage.Should().NotBeNull(); capturedMessage!.Payload.Length.Should().Be(0); } [Fact] public async Task Process_ObjectBody_UseToString() { MqttApplicationMessage? capturedMessage = null; var endpoint = CreateEndpointWithMocks( out var mockClient, out _, out _); mockClient.PublishAsync(Arg.Any(), Arg.Any()) .Returns(Task.FromResult(new MqttClientPublishResult(0, MqttClientPublishReasonCode.Success, "", null))) .AndDoes(x => capturedMessage = x.Arg()); var producer = endpoint.CreateProducer(); await producer.Start(); var exchange = new Exchange(new Message(42)); await ((IProducer)producer).Process(exchange); capturedMessage.Should().NotBeNull(); Encoding.UTF8.GetString(capturedMessage!.Payload).Should().Be("42"); } // ── MQTT 5.0 properties ──────────────────────────────────────── [Fact] public async Task Process_ContentType_SetOnMessage() { MqttApplicationMessage? capturedMessage = null; var endpoint = CreateEndpointWithMocks( out var mockClient, out _, out _, contentType: "application/json"); mockClient.PublishAsync(Arg.Any(), Arg.Any()) .Returns(Task.FromResult(new MqttClientPublishResult(0, MqttClientPublishReasonCode.Success, "", null))) .AndDoes(x => capturedMessage = x.Arg()); var producer = endpoint.CreateProducer(); await producer.Start(); var exchange = new Exchange(new Message("{}")); await ((IProducer)producer).Process(exchange); capturedMessage.Should().NotBeNull(); capturedMessage!.ContentType.Should().Be("application/json"); } [Fact] public async Task Process_ResponseTopic_SetOnMessage() { MqttApplicationMessage? capturedMessage = null; var endpoint = CreateEndpointWithMocks( out var mockClient, out _, out _, responseTopic: "responses/dev1"); mockClient.PublishAsync(Arg.Any(), Arg.Any()) .Returns(Task.FromResult(new MqttClientPublishResult(0, MqttClientPublishReasonCode.Success, "", null))) .AndDoes(x => capturedMessage = x.Arg()); var producer = endpoint.CreateProducer(); await producer.Start(); var exchange = new Exchange(new Message("data")); await ((IProducer)producer).Process(exchange); capturedMessage.Should().NotBeNull(); capturedMessage!.ResponseTopic.Should().Be("responses/dev1"); } [Fact] public async Task Process_MessageExpiryInterval_SetOnMessage() { MqttApplicationMessage? capturedMessage = null; var endpoint = CreateEndpointWithMocks( out var mockClient, out _, out _, messageExpiryInterval: 600); mockClient.PublishAsync(Arg.Any(), Arg.Any()) .Returns(Task.FromResult(new MqttClientPublishResult(0, MqttClientPublishReasonCode.Success, "", null))) .AndDoes(x => capturedMessage = x.Arg()); var producer = endpoint.CreateProducer(); await producer.Start(); var exchange = new Exchange(new Message("data")); await ((IProducer)producer).Process(exchange); capturedMessage.Should().NotBeNull(); capturedMessage!.MessageExpiryInterval.Should().Be(600); } // ── Result headers ────────────────────────────────────────────── [Fact] public async Task Process_SetsResultHeaders() { var endpoint = CreateEndpointWithMocks( out var mockClient, out _, out _, topic: "result/topic"); mockClient.PublishAsync(Arg.Any(), Arg.Any()) .Returns(Task.FromResult(new MqttClientPublishResult(0, MqttClientPublishReasonCode.Success, "", null))); var producer = endpoint.CreateProducer(); await producer.Start(); var exchange = new Exchange(new Message("data")); await ((IProducer)producer).Process(exchange); exchange.In.Headers[MqttHeaders.Topic].Should().Be("result/topic"); exchange.In.Headers[MqttHeaders.Qos].Should().Be(0); exchange.In.Headers[MqttHeaders.Broker].Should().Be("main"); } // ── Broker resolution ─────────────────────────────────────────── [Fact] public async Task Start_NamedBroker_ResolvesFromRegistry() { var endpoint = CreateEndpointWithMocks( out _, out _, out var mockRegistry); var producer = endpoint.CreateProducer(); await producer.Start(); mockRegistry.Received(1).GetOptions("main"); } [Fact] public async Task Start_InlineServer_BuildsBrokerOptions() { var endpoint = CreateEndpoint( topic: "t", broker: null, server: "mqtt.example.com"); var mockClient = Substitute.For(); mockClient.IsConnected.Returns(true); var mockFactory = Substitute.For(); mockFactory.CreateConnectedClientAsync( Arg.Any(), Arg.Any(), Arg.Any()) .Returns(Task.FromResult(mockClient)); endpoint.MqttComponent.ClientFactory = mockFactory; var producer = endpoint.CreateProducer(); await producer.Start(); await mockFactory.Received(1).CreateConnectedClientAsync( Arg.Is(o => o.Server == "mqtt.example.com"), Arg.Any(), Arg.Any()); } [Fact] public void Start_NoBrokerNoServer_Throws() { var component = new MqttComponent(); var parameters = new Dictionary { ["mode"] = "Publish", ["broker"] = "main" }; var uri = new EndpointUri("mqtt", "t", "mqtt:t", parameters); var endpoint = (MqttEndpoint)component.CreateEndpoint(uri); // No registry set var producer = endpoint.CreateProducer(); var act = async () => await producer.Start(); act.Should().ThrowAsync().WithMessage("*IMqttBrokerRegistry*"); } // ── UserProperties ────────────────────────────────────────────── [Fact] public async Task Process_UserProperties_ForwardedToMessage() { MqttApplicationMessage? capturedMessage = null; var endpoint = CreateEndpointWithMocks( out var mockClient, out _, out _); mockClient.PublishAsync(Arg.Any(), Arg.Any()) .Returns(Task.FromResult(new MqttClientPublishResult(0, MqttClientPublishReasonCode.Success, "", null))) .AndDoes(x => capturedMessage = x.Arg()); var producer = endpoint.CreateProducer(); await producer.Start(); var exchange = new Exchange(new Message("data")); exchange.In.Headers[MqttHeaders.UserProperties] = new Dictionary { ["key1"] = "value1", ["key2"] = "value2" }; await ((IProducer)producer).Process(exchange); capturedMessage.Should().NotBeNull(); capturedMessage!.UserProperties.Should().HaveCount(2); } } Path: redb-route/tests/redb.Route.Tests.MqttNet/MqttReconnectTests.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/MqttReconnectTests.cs ---- using System.Collections.Concurrent; using System.Text; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.MqttNet; using redb.Route.MqttNet.Connection; using redb.Route.Tests.Conformance; namespace redb.Route.Tests.MqttNet; /// /// A consumer outlives a broker restart: the restart drops its connection without a failed message to trigger the /// reconnect, and once the broker is back the consumer connects and subscribes again (the broker keeps nothing over the /// restart, its persistence is off), the same route reads the topic again, serial and concurrent, and the endpoint /// counts one reconnect. The restart is on : it runs only /// where REDB_TEST_MQTT_CONTAINER names the broker's container, elsewhere it is skipped. Run it with /// tests/docker/run-fault-suite.sh --broker mosquitto. /// [Trait("Category", "Integration")] [Collection(MqttBrokerRestartCollection.Name)] public sealed class MqttReconnectTests { private const string Broker = "server=localhost&port=11883"; private static readonly MqttStand Stand = MqttStand.Instance; [BrokerFaultTheory(MqttStand.ContainerVariable)] [InlineData(1)] [InlineData(4)] public async Task A_consumer_reads_the_topic_again_after_the_broker_restarts(int concurrentConsumers) { var topic = $"test/restart-{Guid.NewGuid():N}"; var received = new ConcurrentQueue(); await using var context = new RouteContext(); context.AddComponent(new MqttComponent { ClientFactory = new DefaultMqttClientFactory() }); var uri = $"mqtt:{topic}?mode=Subscribe&{Broker}&qos=1&clientId=test-restart-{Guid.NewGuid():N}" + $"&concurrentConsumers={concurrentConsumers}"; context.AddRoutes(r => r.From(uri).RouteId("restarted").Process(e => received.Enqueue(e.In.Body is byte[] bytes ? Encoding.UTF8.GetString(bytes) : e.In.Body?.ToString() ?? ""))); await context.Start(); await Stand.PutAsync(topic, "before"); (await Until(() => received.Contains("before"))).Should().BeTrue("the route reads the topic before the restart"); await Stand.Fault!.RestartAsync(); // A message published while nobody is subscribed is gone: publish only once the subscription is back. var statistics = (IEndpointStatistics)context.GetEndpoint(uri); (await Until(() => statistics.Reconnects > 0)).Should().BeTrue( "the consumer connects and subscribes again after the broker restarts"); await Stand.PutAsync(topic, "after"); (await Until(() => received.Contains("after"))).Should().BeTrue("the consumer reads what was published after the restart"); statistics.Reconnects.Should().Be(1, "one restart is one reconnect"); statistics.HealthStatus.Should().Be(EndpointHealthStatus.Healthy, "the subscription is back"); context.GetRoute("restarted")!.Status.Should().Be(RouteStatus.Started, "a lost connection does not stop the route"); } 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; } } /// A broker restart cuts every connection of the suite, so nothing runs beside the restart tests. [CollectionDefinition(Name, DisableParallelization = true)] public sealed class MqttBrokerRestartCollection { /// The collection's name. public const string Name = "MQTT broker restart"; } Path: redb-route/tests/redb.Route.Tests.MqttNet/MqttRedeliveryCharacterizationTests.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/MqttRedeliveryCharacterizationTests.cs ---- using System.Text; using MQTTnet; using MQTTnet.Formatter; using MQTTnet.Protocol; namespace redb.Route.Tests.MqttNet; /// /// What MQTTnet and the broker do with a message the client does not acknowledge, pinned against Mosquitto /// (localhost:11883): the consumer's failure rule relies on it. MQTT has no negative acknowledgement; the broker sends /// an unacknowledged QoS 1 or QoS 2 message again only when the client connects again to a session the broker kept. /// Unlike Paho, MQTTnet holds back the PUBREC of a QoS 2 message too while AutoAcknowledge is off, so a /// QoS 2 message comes again as well. /// [Trait("Category", "Integration")] public sealed class MqttRedeliveryCharacterizationTests { private const string Server = "localhost"; private const int Port = 11883; [Theory] [InlineData(MqttQualityOfServiceLevel.AtLeastOnce, MqttProtocolVersion.V311)] [InlineData(MqttQualityOfServiceLevel.ExactlyOnce, MqttProtocolVersion.V311)] [InlineData(MqttQualityOfServiceLevel.AtLeastOnce, MqttProtocolVersion.V500)] [InlineData(MqttQualityOfServiceLevel.ExactlyOnce, MqttProtocolVersion.V500)] public async Task UnacknowledgedMessage_KeptSession_IsSentAgainAfterReconnect( MqttQualityOfServiceLevel qos, MqttProtocolVersion version) { var topic = $"test/redeliver-{Guid.NewGuid():N}"; var clientId = $"test-redeliver-{Guid.NewGuid():N}"; var factory = new MqttClientFactory(); var builder = new MqttClientOptionsBuilder() .WithTcpServer(Server, Port) .WithClientId(clientId) .WithProtocolVersion(version) .WithCleanSession(false); if (version == MqttProtocolVersion.V500) builder.WithSessionExpiryInterval(300); // MQTT 5: an absent interval ends the session with the connection var options = builder.Build(); var deliveries = 0; var first = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); var again = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); using var subscriber = factory.CreateMqttClient(); subscriber.ApplicationMessageReceivedAsync += args => { var payload = Encoding.UTF8.GetString(args.ApplicationMessage.Payload); if (Interlocked.Increment(ref deliveries) == 1) { args.AutoAcknowledge = false; // the route failed: no PUBACK / PUBREC first.TrySetResult(payload); } else { again.TrySetResult(payload); } return Task.CompletedTask; }; await subscriber.ConnectAsync(options); await subscriber.SubscribeAsync(new MqttClientSubscribeOptionsBuilder() .WithTopicFilter(topic, qos).Build()); using var publisher = factory.CreateMqttClient(); await publisher.ConnectAsync(new MqttClientOptionsBuilder().WithTcpServer(Server, Port) .WithClientId($"test-pub-{Guid.NewGuid():N}").Build()); await publisher.PublishAsync(new MqttApplicationMessageBuilder() .WithTopic(topic).WithPayload("payload-1").WithQualityOfServiceLevel(qos).Build()); (await first.Task.WaitAsync(TimeSpan.FromSeconds(10))).Should().Be("payload-1"); // Within the same connection the broker does not send it again. await Task.Delay(1500); again.Task.IsCompleted.Should().BeFalse("MQTT forbids resending on the same connection"); await subscriber.DisconnectAsync(); var result = await subscriber.ConnectAsync(options); result.IsSessionPresent.Should().BeTrue("the broker kept the session"); (await again.Task.WaitAsync(TimeSpan.FromSeconds(10))).Should().Be("payload-1", $"an unacknowledged QoS {(int)qos} message is sent again after the reconnect"); await subscriber.DisconnectAsync(); await publisher.DisconnectAsync(); } } Path: redb-route/tests/redb.Route.Tests.MqttNet/MqttStand.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/MqttStand.cs ---- using System.Buffers; using System.Collections.Concurrent; using System.Text; using MQTTnet; using MQTTnet.Protocol; using redb.Route.Tests.Conformance; namespace redb.Route.Tests.MqttNet; /// /// The MQTT stand: Mosquitto at localhost:11883 (anonymous, no persistence), reached through MQTTnet directly, not /// through the connector. MQTT has no queue: publishes at QoS 1 to a topic, and /// returns what arrives on the topic while it listens. Its container, when /// names it, is broken with ; the broker is ready when it /// answers a subscription to its uptime topic. /// public sealed class MqttStand : IConnectorStand { /// The variable that names the Mosquitto container a test may restart. public const string ContainerVariable = "REDB_TEST_MQTT_CONTAINER"; private const string Host = "localhost"; private const int Port = 11883; /// The stand of this process. public static MqttStand Instance { get; } = new(); private MqttStand() { } /// public BrokerFault? Fault { get; } = BrokerFault.FromEnvironment(ContainerVariable, "mosquitto_sub", "-h", Host, "-p", "11883", "-t", "$SYS/broker/uptime", "-C", "1", "-W", "3"); /// public TimeSpan Wait { get; } = BrokerFault.DefaultWait; /// public async Task PutAsync(string destination, string body, CancellationToken ct = default) { using var client = new MqttClientFactory().CreateMqttClient(); await client.ConnectAsync(Options(), ct); await client.PublishAsync(new MqttApplicationMessageBuilder().WithTopic(destination).WithPayload(body) .WithQualityOfServiceLevel(MqttQualityOfServiceLevel.AtLeastOnce).Build(), ct); await client.DisconnectAsync(cancellationToken: ct); } /// public async Task> DrainAsync(string destination, TimeSpan wait, CancellationToken ct = default) { var bodies = new ConcurrentQueue(); using var client = new MqttClientFactory().CreateMqttClient(); client.ApplicationMessageReceivedAsync += args => { bodies.Enqueue(Encoding.UTF8.GetString(args.ApplicationMessage.Payload.ToArray())); return Task.CompletedTask; }; await client.ConnectAsync(Options(), ct); await client.SubscribeAsync(new MqttClientSubscribeOptionsBuilder() .WithTopicFilter(destination, MqttQualityOfServiceLevel.AtLeastOnce).Build(), ct); await Task.Delay(wait, ct); await client.DisconnectAsync(cancellationToken: ct); return bodies.ToArray(); } private static MqttClientOptions Options() => new MqttClientOptionsBuilder().WithTcpServer(Host, Port) .WithClientId($"stand-{Guid.NewGuid():N}").Build(); } Path: redb-route/tests/redb.Route.Tests.MqttNet/MqttTelemetrySmokeTests.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/MqttTelemetrySmokeTests.cs ---- using System.Diagnostics; using MQTTnet; using MQTTnet.Protocol; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.MqttNet; using redb.Route.MqttNet.Connection; using redb.Route.Telemetry; using redb.Route.Tests.Shared; namespace redb.Route.Tests.MqttNet; /// Smoke test for the P1 transport span opened by . public sealed class MqttTelemetrySmokeTests { [Fact] public async Task MqttProducer_EmitsTransportSpanWithMessagingMqttTags() { var component = new MqttComponent(); var pars = new Dictionary { ["mode"] = "Publish", ["broker"] = "main" }; var uri = new EndpointUri("mqtt", "out/topic", "mqtt:out/topic", pars); var endpoint = (MqttEndpoint)component.CreateEndpoint(uri); var mockClient = Substitute.For(); mockClient.IsConnected.Returns(true); mockClient.PublishAsync(Arg.Any(), Arg.Any()) .Returns(Task.FromResult(new MqttClientPublishResult(0, MqttClientPublishReasonCode.Success, "", null))); var mockFactory = Substitute.For(); mockFactory.CreateConnectedClientAsync( Arg.Any(), Arg.Any(), Arg.Any()) .Returns(Task.FromResult(mockClient)); var mockRegistry = Substitute.For(); mockRegistry.GetOptions("main").Returns(new MqttBrokerOptions { Server = "localhost" }); endpoint.MqttComponent.ClientFactory = mockFactory; endpoint.MqttComponent.BrokerRegistry = mockRegistry; var producer = (MqttProducer)endpoint.CreateProducer(); await producer.Start(); using var capture = new SpanCapture(); // this test's spans only await producer.Process(new Exchange(new Message("hello"))); await producer.Stop(); var activities = capture.Spans; activities.Should().NotBeEmpty(); var activity = activities.First(); activity.Source.Name.Should().Be(RouteActivitySource.SourceName); activity.Kind.Should().Be(ActivityKind.Producer); activity.GetTagItem("messaging.system").Should().Be("mqtt"); activity.GetTagItem("messaging.operation").Should().Be("publish"); activity.GetTagItem("messaging.destination.name").Should().Be("out/topic"); activity.GetTagItem("redb.route.endpoint").Should().NotBeNull(); } } Path: redb-route/tests/redb.Route.Tests.MqttNet/MqttTraceTests.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/MqttTraceTests.cs ---- using System.Diagnostics; using System.Threading.Channels; using MQTTnet; using MQTTnet.Formatter; using redb.Route.Abstractions; using redb.Route.Configuration; using redb.Route.Core; using redb.Route.MqttNet; using redb.Route.MqttNet.Connection; using redb.Route.Tests.Telemetry; namespace redb.Route.Tests.MqttNet; /// /// The trace context travels in MQTT 5 user properties, and only on a connection that speaks v5: the producer writes it /// (replacing a traceparent copied from an earlier hop), the consumer reads it and parents its span on it. Under /// 3.1.1 nothing is written — MQTTnet refuses user properties there — and the receive span is a root. Without a context /// the span is a root, never a child of the activity the consumer inherited. A failed route marks it red; our own stop /// does not. EnableTelemetry=false opens no span on either side. Broker: route-mosquitto on localhost:11883. /// [Trait("Category", "Integration")] public sealed class MqttTraceTests { private const string Server = "localhost"; private const int Port = 11883; private static readonly TimeSpan Wait = TimeSpan.FromSeconds(10); private readonly string _topic = $"test/trace/{Guid.NewGuid():N}"; private string SubscribeUri => $"mqtt:{_topic}?mode=Subscribe&server={Server}&port={Port}&qos=1"; private string PublishUri => $"mqtt:{_topic}?mode=Publish&server={Server}&port={Port}&qos=1"; private RouteTelemetryProbe Spans(ActivityKind? kind = null) => new(a => (kind is null || a.Kind == kind) && RouteTelemetryProbe.Tag(a, "messaging.destination.name") == _topic); private static async Task Start(Action routes, bool telemetry = true, MqttProtocolVersion version = MqttProtocolVersion.V500) { var ctx = new RouteContext(options: new RouteEngineOptions { EnableTelemetry = telemetry }); ctx.AddComponent(new MqttComponent { ClientFactory = new VersionedClientFactory(version) }); ctx.AddRoutes(routes); using (new Activity("host startup").SetIdFormat(ActivityIdFormat.W3C).Start()) await ctx.Start(); return ctx; } private static async Task RawClient() { var client = new MqttClientFactory().CreateMqttClient(); await client.ConnectAsync(new MqttClientOptionsBuilder() .WithTcpServer(Server, Port) .WithClientId($"test-raw-{Guid.NewGuid():N}") .WithCleanSession() .Build()); return client; } private async Task Publish(string payload, string? traceparent = null) { using var client = await RawClient(); var builder = new MqttApplicationMessageBuilder().WithTopic(_topic).WithPayload(payload) .WithQualityOfServiceLevel(MQTTnet.Protocol.MqttQualityOfServiceLevel.AtLeastOnce); if (traceparent is not null) builder.WithUserProperty("traceparent", traceparent); await client.PublishAsync(builder.Build()); await client.DisconnectAsync(); } private async Task<(IMqttClient Client, ChannelReader Messages)> RawSubscriber() { var client = await RawClient(); var messages = Channel.CreateUnbounded(); client.ApplicationMessageReceivedAsync += e => { messages.Writer.TryWrite(e.ApplicationMessage); return Task.CompletedTask; }; await client.SubscribeAsync(_topic, MQTTnet.Protocol.MqttQualityOfServiceLevel.AtLeastOnce); return (client, messages.Reader); } private static async Task Until(Func done) { var deadline = DateTime.UtcNow + Wait; while (!done() && DateTime.UtcNow < deadline) await Task.Delay(50); } #pragma warning disable CS0618 // MQTTnet marks Value as obsolete in favor of ValueBuffer private static string[] UserProperty(MqttApplicationMessage message, string name) => message.UserProperties?.Where(p => p.Name == name).Select(p => p.Value).ToArray() ?? []; #pragma warning restore CS0618 [Fact] public async Task Under_v5_the_context_travels_from_the_send_to_the_receive() { using var probe = Spans(); await using (var ctx = await Start(r => { r.From("direct:send").To(PublishUri); r.From(SubscribeUri).Process(_ => { }); })) { await Task.Delay(300); using var template = new ProducerTemplate(ctx); template.Start(); using (new Activity("caller").SetIdFormat(ActivityIdFormat.W3C).Start()) await template.SendAsync("direct:send", "hello"); await Until(() => probe.Activities.Any(a => a.Kind == ActivityKind.Consumer)); } var send = probe.Activities.Should().ContainSingle(a => a.Kind == ActivityKind.Producer).Subject; var receive = probe.Activities.Should().ContainSingle(a => a.Kind == ActivityKind.Consumer).Subject; receive.TraceId.Should().Be(send.TraceId); receive.ParentSpanId.Should().Be(send.SpanId, "the receive span is a child of the send span that carried the context"); } [Fact] public async Task The_send_replaces_a_traceparent_copied_from_an_earlier_hop() { using var probe = Spans(ActivityKind.Producer); var (subscriber, messages) = await RawSubscriber(); using var _ = subscriber; var stale = $"00-{ActivityTraceId.CreateRandom()}-{ActivitySpanId.CreateRandom()}-01"; await using (var ctx = await Start(r => r.From("direct:send").To(PublishUri))) { using var template = new ProducerTemplate(ctx); template.Start(); var message = new Message("hello"); message.Headers[MqttHeaders.UserProperties] = new Dictionary { ["traceparent"] = stale, ["k"] = "v" }; await template.SendAsync("direct:send", message); } using var cts = new CancellationTokenSource(Wait); var received = await messages.ReadAsync(cts.Token); var send = probe.Activities.Should().ContainSingle().Subject; UserProperty(received, "traceparent").Should().Equal($"00-{send.TraceId}-{send.SpanId}-{(int)send.ActivityTraceFlags:x2}"); UserProperty(received, "k").Should().Equal("v"); } [Fact] public async Task Each_message_without_a_context_opens_a_root_span_even_under_an_ambient_activity() { using var probe = Spans(ActivityKind.Consumer); await using (await Start(r => r.From(SubscribeUri).Process(_ => { }))) { await Publish("a"); await Publish("b"); await Until(() => probe.Activities.Count >= 2); } probe.Activities.Should().HaveCount(2, "one span per routed message"); probe.Activities.Should().OnlyContain(a => a.ParentSpanId == default(ActivitySpanId), "a message without a context starts a trace rather than joining the host's"); } [Fact] public async Task Nothing_arriving_opens_no_span() { using var probe = Spans(); await using (await Start(r => r.From(SubscribeUri).Process(_ => { }))) await Task.Delay(800); probe.Activities.Should().BeEmpty(); } [Fact] public async Task A_failed_route_marks_the_span_red() { using var probe = Spans(ActivityKind.Consumer); await using (await Start(r => r.From(SubscribeUri).Process(_ => throw new InvalidOperationException("route failed")))) { await Publish("fail"); await Until(() => probe.Activities.Count >= 1); } probe.Activities.Should().NotBeEmpty(); probe.Activities.Should().OnlyContain(a => a.Status == ActivityStatusCode.Error); } [Fact] public async Task Our_stop_cancelling_the_route_does_not_mark_the_span() { using var probe = Spans(ActivityKind.Consumer); var entered = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); var processor = Substitute.For(); processor.Process(Arg.Any(), Arg.Any()) .Returns(async ci => { entered.TrySetResult(); await Task.Delay(Timeout.Infinite, ci.Arg()); }); var component = new MqttComponent { ClientFactory = new DefaultMqttClientFactory() }; var endpoint = (MqttEndpoint)component.CreateEndpoint(EndpointUriParser.Parse(SubscribeUri)); var consumer = endpoint.CreateConsumer(processor); using var stop = new CancellationTokenSource(); await consumer.Start(stop.Token); try { await Publish("wait"); (await Task.WhenAny(entered.Task, Task.Delay(Wait))).Should().Be(entered.Task); // Our stop from above: the token the consumer was started with. await stop.CancelAsync(); await Until(() => probe.Activities.Count >= 1); } finally { await consumer.Stop(); } probe.Activities.Should().ContainSingle().Which.Status.Should().NotBe(ActivityStatusCode.Error, "our own stop cancelling the route is not a failure"); } [Fact] public async Task Under_3_1_1_the_receive_span_is_a_root() { using var probe = Spans(ActivityKind.Consumer); await using (await Start(r => r.From(SubscribeUri).Process(_ => { }), version: MqttProtocolVersion.V311)) { await Publish("old", $"00-{ActivityTraceId.CreateRandom()}-{ActivitySpanId.CreateRandom()}-01"); await Until(() => probe.Activities.Count >= 1); } probe.Activities.Should().ContainSingle().Which.ParentSpanId.Should().Be(default(ActivitySpanId)); } [Fact] public async Task Under_3_1_1_the_send_writes_no_context_and_does_not_fail() { // MQTTnet throws NotSupportedException for user properties on a 3.1.1 connection. var (subscriber, messages) = await RawSubscriber(); using var _ = subscriber; await using (var ctx = await Start(r => r.From("direct:send").To(PublishUri), version: MqttProtocolVersion.V311)) { using var template = new ProducerTemplate(ctx); template.Start(); using (new Activity("caller").SetIdFormat(ActivityIdFormat.W3C).Start()) await template.SendAsync("direct:send", "old"); } using var cts = new CancellationTokenSource(Wait); var received = await messages.ReadAsync(cts.Token); UserProperty(received, "traceparent").Should().BeEmpty(); } [Fact] public async Task Tracing_off_opens_no_span_on_either_side() { using var probe = Spans(); var routed = new TaskCompletionSource(); await using (var ctx = await Start(r => { r.From("direct:send").To(PublishUri); r.From(SubscribeUri).Process(_ => routed.TrySetResult()); }, telemetry: false)) { await Task.Delay(300); using var template = new ProducerTemplate(ctx); template.Start(); await template.SendAsync("direct:send", "off"); (await Task.WhenAny(routed.Task, Task.Delay(Wait))).Should().Be(routed.Task); } probe.Activities.Should().BeEmpty(); } /// The default client factory, on the protocol version the test asks for. private sealed class VersionedClientFactory(MqttProtocolVersion version) : IMqttClientFactory { public async Task CreateConnectedClientAsync( MqttBrokerOptions options, string? clientIdOverride = null, CancellationToken ct = default) { var client = new MqttClientFactory().CreateMqttClient(); await client.ConnectAsync(new MqttClientOptionsBuilder() .WithTcpServer(options.Server, options.Port) .WithClientId(clientIdOverride ?? options.ClientId ?? $"redb-route-{Guid.NewGuid():N}") .WithCleanSession(options.CleanSession) .WithProtocolVersion(version) .Build(), ct).ConfigureAwait(false); return client; } } } Path: redb-route/tests/redb.Route.Tests.MqttNet/ServiceCollectionExtensionsTests.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/ServiceCollectionExtensionsTests.cs ---- using Microsoft.Extensions.DependencyInjection; using redb.Route.Abstractions; using redb.Route.MqttNet; using redb.Route.MqttNet.Connection; namespace redb.Route.Tests.MqttNet; public class ServiceCollectionExtensionsTests { [Fact] public void AddRedbRouteMqtt_RegistersMqttComponent() { var services = new ServiceCollection(); services.AddSingleton(Substitute.For()); services.AddRedbRouteMqtt(); var sp = services.BuildServiceProvider(); sp.GetService().Should().NotBeNull(); } [Fact] public void AddRedbRouteMqtt_RegistersBrokerRegistry() { var services = new ServiceCollection(); services.AddSingleton(Substitute.For()); services.AddRedbRouteMqtt(); var sp = services.BuildServiceProvider(); sp.GetService().Should().NotBeNull(); } [Fact] public void AddRedbRouteMqtt_RegistersClientFactory() { var services = new ServiceCollection(); services.AddSingleton(Substitute.For()); services.AddRedbRouteMqtt(); var sp = services.BuildServiceProvider(); sp.GetService().Should().NotBeNull(); } [Fact] public void AddBroker_RegistersBrokerInRegistry() { var services = new ServiceCollection(); services.AddSingleton(Substitute.For()); services.AddRedbRouteMqtt(mqtt => { mqtt.AddBroker("test", o => { o.Server = "mqtt.test.com"; o.Port = 8883; }); }); var sp = services.BuildServiceProvider(); var registry = sp.GetRequiredService(); registry.Contains("test").Should().BeTrue(); registry.GetOptions("test").Server.Should().Be("mqtt.test.com"); registry.GetOptions("test").Port.Should().Be(8883); } [Fact] public void AddBroker_WithPrebuiltOptions_RegistersBrokerInRegistry() { var services = new ServiceCollection(); services.AddSingleton(Substitute.For()); var options = new MqttBrokerOptions { Server = "broker.local", Port = 1884 }; services.AddRedbRouteMqtt(mqtt => { mqtt.AddBroker("direct", options); }); var sp = services.BuildServiceProvider(); var registry = sp.GetRequiredService(); registry.GetOptions("direct").Should().BeSameAs(options); } [Fact] public void AddMultipleBrokers_AllRegistered() { var services = new ServiceCollection(); services.AddSingleton(Substitute.For()); services.AddRedbRouteMqtt(mqtt => { mqtt.AddBroker("prod", o => o.Server = "prod.mqtt.com"); mqtt.AddBroker("dev", o => o.Server = "dev.mqtt.com"); mqtt.AddBroker("staging", o => o.Server = "staging.mqtt.com"); }); var sp = services.BuildServiceProvider(); var registry = sp.GetRequiredService(); registry.Contains("prod").Should().BeTrue(); registry.Contains("dev").Should().BeTrue(); registry.Contains("staging").Should().BeTrue(); } [Fact] public void UseClientFactory_ReplacesDefault() { var customFactory = Substitute.For(); var services = new ServiceCollection(); services.AddSingleton(Substitute.For()); services.AddRedbRouteMqtt(mqtt => { mqtt.UseClientFactory(customFactory); }); var sp = services.BuildServiceProvider(); sp.GetRequiredService().Should().BeSameAs(customFactory); } [Fact] public void ConfigurationBuilder_Services_ExposesServiceCollection() { var services = new ServiceCollection(); services.AddSingleton(Substitute.For()); IServiceCollection? capturedServices = null; services.AddRedbRouteMqtt(mqtt => { capturedServices = mqtt.Services; }); capturedServices.Should().BeSameAs(services); } } Path: redb-route/tests/redb.Route.Tests.MqttNet/redb.Route.Tests.MqttNet.csproj 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/redb.Route.Tests.MqttNet.csproj ----