Bundle: redb-route / redb.Route.MqttNet (redb.Route.MqttNet.txt), 14 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/redb.Route.MqttNet/Connection/MqttBrokerOptions.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/redb.Route.MqttNet/Connection/MqttBrokerOptions.cs
----
namespace redb.Route.MqttNet.Connection;
///
/// Options for connecting to an MQTT broker.
///
public sealed class MqttBrokerOptions
{
/// Broker server hostname or IP.
public string Server { get; set; } = "localhost";
/// Broker port. Default 1883.
public int Port { get; set; } = 1883;
/// Username for authentication.
public string? Username { get; set; }
/// Password for authentication.
public string? Password { get; set; }
/// Client ID prefix. Final ID may include a unique suffix.
public string? ClientId { get; set; }
/// Enable TLS.
public bool UseTls { get; set; }
/// Keep-alive interval in seconds.
public int KeepAlive { get; set; } = 60;
/// Clean session / clean start.
public bool CleanSession { get; set; } = true;
///
/// MQTT 5 Session Expiry Interval in seconds: how long the broker keeps the session after the connection closes.
/// 0 (the default) ends the session with the connection.
///
public int SessionExpiryInterval { get; set; }
}
Path: redb-route/redb.Route.MqttNet/Connection/MqttBrokerRegistry.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/redb.Route.MqttNet/Connection/MqttBrokerRegistry.cs
----
namespace redb.Route.MqttNet.Connection;
///
/// Registry for named MQTT broker connections.
///
public interface IMqttBrokerRegistry
{
/// Gets broker options by name.
MqttBrokerOptions GetOptions(string name);
/// Checks if a named broker is registered.
bool Contains(string name);
}
///
/// In-memory broker registry. Populated at startup via .
///
internal sealed class MqttBrokerRegistry : IMqttBrokerRegistry
{
private readonly Dictionary _brokers = new(StringComparer.OrdinalIgnoreCase);
/// Registers a broker with the given name.
internal void Register(string name, MqttBrokerOptions options)
{
ArgumentException.ThrowIfNullOrWhiteSpace(name);
ArgumentNullException.ThrowIfNull(options);
_brokers[name] = options;
}
///
public MqttBrokerOptions GetOptions(string name)
{
if (_brokers.TryGetValue(name, out var options))
return options;
throw new InvalidOperationException(
$"MQTT broker '{name}' is not registered. Call AddBroker(\"{name}\", ...) in AddRedbRouteMqtt().");
}
///
public bool Contains(string name) => _brokers.ContainsKey(name);
}
Path: redb-route/redb.Route.MqttNet/Connection/MqttClientFactory.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/redb.Route.MqttNet/Connection/MqttClientFactory.cs
----
using MQTTnet;
namespace redb.Route.MqttNet.Connection;
///
/// Creates and manages instances.
///
public interface IMqttClientFactory
{
/// Creates a connected MQTT client from broker options.
Task CreateConnectedClientAsync(
MqttBrokerOptions options,
string? clientIdOverride = null,
CancellationToken ct = default);
}
///
/// Default factory using MQTTnet's .
///
internal sealed class DefaultMqttClientFactory : IMqttClientFactory
{
///
public async Task CreateConnectedClientAsync(
MqttBrokerOptions options,
string? clientIdOverride = null,
CancellationToken ct = default)
{
var factory = new MqttClientFactory();
var client = factory.CreateMqttClient();
var clientId = clientIdOverride
?? options.ClientId
?? $"redb-route-{Guid.NewGuid():N}";
var builder = new MqttClientOptionsBuilder()
.WithTcpServer(options.Server, options.Port)
.WithClientId(clientId)
.WithKeepAlivePeriod(TimeSpan.FromSeconds(options.KeepAlive))
.WithCleanSession(options.CleanSession);
// MQTT 5 (MQTTnet's default protocol): without the interval the session ends with the connection.
if (options.SessionExpiryInterval > 0)
builder.WithSessionExpiryInterval((uint)options.SessionExpiryInterval);
if (options.Username != null)
builder.WithCredentials(options.Username, options.Password);
if (options.UseTls)
builder.WithTlsOptions(o => { });
var mqttOptions = builder.Build();
await client.ConnectAsync(mqttOptions, ct).ConfigureAwait(false);
return client;
}
}
Path: redb-route/redb.Route.MqttNet/Extensions/ServiceCollectionExtensions.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/redb.Route.MqttNet/Extensions/ServiceCollectionExtensions.cs
----
using Microsoft.Extensions.DependencyInjection;
using redb.Route.Extensions;
using redb.Route.MqttNet.Connection;
namespace redb.Route.MqttNet;
///
/// DI registration for the MQTT connector.
///
public static class ServiceCollectionExtensions
{
///
/// Registers the MQTT component with the route framework.
///
///
/// services.AddRedbRoute();
/// services.AddRedbRouteMqtt(mqtt =>
/// {
/// mqtt.AddBroker("main", o =>
/// {
/// o.Server = "localhost";
/// o.Port = 1883;
/// });
/// });
///
///
///
public static IServiceCollection AddRedbRouteMqtt(
this IServiceCollection services,
Action? configure = null)
{
var builder = new MqttConfigurationBuilder(services);
configure?.Invoke(builder);
services.AddSingleton(builder.BuildRegistry());
services.AddSingleton(builder.BuildClientFactory());
services.AddSingleton();
// IRouteContextConfigurator is applied by RouteHostedService at startup --
// the correct registration hook (a lazy marker singleton never fires).
services.AddRouteContextConfigurator((sp, context) =>
{
var component = sp.GetRequiredService();
component.BrokerRegistry = sp.GetRequiredService();
component.ClientFactory = sp.GetRequiredService();
context.AddComponent(component);
});
return services;
}
}
///
/// Fluent builder for MQTT DI configuration.
///
public sealed class MqttConfigurationBuilder
{
private readonly IServiceCollection _services;
private readonly MqttBrokerRegistry _brokerRegistry = new();
private IMqttClientFactory? _clientFactory;
internal MqttConfigurationBuilder(IServiceCollection services) => _services = services;
/// The service collection.
public IServiceCollection Services => _services;
///
/// Registers a named broker for use with Mqtt.Subscribe("topic").Broker("name").
///
public MqttConfigurationBuilder AddBroker(string name, Action configure)
{
var options = new MqttBrokerOptions();
configure(options);
_brokerRegistry.Register(name, options);
return this;
}
///
/// Registers a named broker with pre-built options.
///
public MqttConfigurationBuilder AddBroker(string name, MqttBrokerOptions options)
{
_brokerRegistry.Register(name, options);
return this;
}
///
/// Replaces the default client factory (for testing or custom client management).
///
public MqttConfigurationBuilder UseClientFactory(IMqttClientFactory factory)
{
_clientFactory = factory;
return this;
}
internal IMqttBrokerRegistry BuildRegistry() => _brokerRegistry;
internal IMqttClientFactory BuildClientFactory() => _clientFactory ?? new DefaultMqttClientFactory();
}
Path: redb-route/redb.Route.MqttNet/Fluent/MqttDsl.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/redb.Route.MqttNet/Fluent/MqttDsl.cs
----
using System.Text;
using redb.Route.Abstractions;
using redb.Route.Expressions;
namespace redb.Route.MqttNet;
///
/// Entry point for the MQTT Fluent API. Two methods: Subscribe and Publish.
/// Each returns an for fluent configuration.
///
/// The builder generates a URI string equivalent to writing the URI manually.
/// Both paths converge in via URI binding.
///
///
///
/// // Subscribe (consumer):
/// .From(Mqtt.Subscribe("sensors/temperature")
/// .Broker("main").Qos(1).SharedSubscription("group1"))
///
/// // Publish (producer):
/// .To(Mqtt.Publish("sensors/commands")
/// .Broker("main").Qos(1).Retain())
///
/// // URI equivalent:
/// .From("mqtt:sensors/temperature?mode=Subscribe&broker=main&qos=1&sharedSubscription=group1")
///
///
///
public static class Mqtt
{
/// Creates a subscription consumer for the given topic or topic filter (wildcards supported).
/// MQTT topic or topic filter (e.g. sensors/+/temperature, home/#).
public static MqttBuilder Subscribe(string topic) => new(MqttMode.Subscribe, topic);
/// Creates a publisher producer for the given topic.
/// MQTT topic to publish to.
public static MqttBuilder Publish(string topic) => new(MqttMode.Publish, topic);
}
///
/// Fluent builder for MQTT endpoint URIs. Thin sugar over .
/// Call or use implicit conversion to
/// to get the URI for From() / To().
///
public sealed class MqttBuilder
{
private readonly MqttMode _mode;
private readonly string _topic;
// Connection
private string? _broker;
private string? _server;
private string? _port;
private string? _username;
private string? _password;
private string? _connectionFactory;
private string? _clientId;
private bool _useTls;
private string? _keepAlive;
private bool? _cleanSession;
private int? _sessionExpiryInterval;
private int? _maxReconnectDelay;
// Subscribe
private string? _qos;
private string? _sharedSubscription;
private string? _concurrentConsumers;
// Publish
private bool _retain;
private string? _messageExpiryInterval;
private string? _contentType;
private string? _responseTopic;
/// Creates a builder for the given mode and topic.
internal MqttBuilder(MqttMode mode, string topic)
{
ArgumentException.ThrowIfNullOrWhiteSpace(topic);
_mode = mode;
_topic = topic;
}
// ── Connection ────────────────────────────────────────────────────
/// Use a named broker registered via AddBroker().
public MqttBuilder Broker(IExpression name) { _broker = name.ToTemplateString(); return this; }
/// Use a named broker registered via AddBroker() (template string, supports ${...}).
public MqttBuilder Broker(string name) { _broker = name; return this; }
/// Connect directly to this server (hostname or IP).
public MqttBuilder Server(IExpression server) { _server = server.ToTemplateString(); return this; }
/// Connect directly to this server, hostname or IP (template string, supports ${...}).
public MqttBuilder Server(string server) { _server = server; return this; }
/// Server port. Default 1883.
public MqttBuilder Port(int port) { _port = port.ToString(); return this; }
/// Server port from an expression.
public MqttBuilder Port(IExpression port) { _port = port.ToTemplateString(); return this; }
/// Username for broker authentication.
public MqttBuilder Username(IExpression username) { _username = username.ToTemplateString(); return this; }
/// Username for broker authentication (template string, supports ${...}).
public MqttBuilder Username(string username) { _username = username; return this; }
/// Password for broker authentication.
public MqttBuilder Password(IExpression password) { _password = password.ToTemplateString(); return this; }
/// Password for broker authentication (template string, supports ${...}).
public MqttBuilder Password(string password) { _password = password; return this; }
///
/// References a named from the route registry instead of
/// putting broker credentials in the URI.
///
public MqttBuilder ConnectionFactory(string name) { _connectionFactory = name; return this; }
/// Client ID for the MQTT connection.
public MqttBuilder ClientId(IExpression clientId) { _clientId = clientId.ToTemplateString(); return this; }
/// Client ID for the MQTT connection (template string, supports ${...}).
public MqttBuilder ClientId(string clientId) { _clientId = clientId; return this; }
/// Enable TLS/SSL.
public MqttBuilder UseTls() { _useTls = true; return this; }
/// Keep-alive interval in seconds.
public MqttBuilder KeepAlive(int seconds) { _keepAlive = seconds.ToString(); return this; }
/// Keep-alive interval from an expression.
public MqttBuilder KeepAlive(IExpression seconds) { _keepAlive = seconds.ToTemplateString(); return this; }
/// Set clean session flag.
public MqttBuilder CleanSession(bool clean = true) { _cleanSession = clean; return this; }
///
/// MQTT 5 Session Expiry Interval in seconds: how long the broker keeps the session after the connection closes.
/// With CleanSession(false) and a value above 0 a failed message is sent again after a reconnect.
///
public MqttBuilder SessionExpiryInterval(int seconds) { _sessionExpiryInterval = seconds; return this; }
/// Longest pause in milliseconds before the consumer reconnects after a failed message. Default 128000.
public MqttBuilder MaxReconnectDelay(int milliseconds) { _maxReconnectDelay = milliseconds; return this; }
// ── QoS ──────────────────────────────────────────────────────────
/// Quality of Service level: 0 (at most once), 1 (at least once), 2 (exactly once).
public MqttBuilder Qos(int level) { _qos = level.ToString(); return this; }
/// QoS from an expression.
public MqttBuilder Qos(IExpression level) { _qos = level.ToTemplateString(); return this; }
// ── Subscribe ────────────────────────────────────────────────────
/// MQTT 5.0 shared subscription group for load-balanced consuming.
public MqttBuilder SharedSubscription(IExpression group) { _sharedSubscription = group.ToTemplateString(); return this; }
/// MQTT 5.0 shared subscription group for load-balanced consuming (template string, supports ${...}).
public MqttBuilder SharedSubscription(string group) { _sharedSubscription = group; return this; }
///
/// Number of concurrent processing workers for received messages (default 1 = serial).
/// When > 1, messages are processed by a pool of N workers and acknowledged only after each
/// worker finishes (manual ack) — parallelism with at-least-once preserved for QoS 1/2.
/// Ordering is not preserved when > 1.
///
public MqttBuilder ConcurrentConsumers(int count) { _concurrentConsumers = count.ToString(); return this; }
/// Consumer parallelism as a string: a number or "auto" (= max(CPU, 2)).
public MqttBuilder ConcurrentConsumers(string count) { _concurrentConsumers = count; return this; }
// ── Publish ──────────────────────────────────────────────────────
/// Set retain flag on published messages.
public MqttBuilder Retain() { _retain = true; return this; }
/// Message expiry interval in seconds (MQTT 5.0).
public MqttBuilder MessageExpiryInterval(int seconds) { _messageExpiryInterval = seconds.ToString(); return this; }
/// Message expiry from an expression.
public MqttBuilder MessageExpiryInterval(IExpression seconds) { _messageExpiryInterval = seconds.ToTemplateString(); return this; }
/// Content type for published messages (MQTT 5.0).
public MqttBuilder ContentType(string contentType) { _contentType = contentType; return this; }
/// Content type from an expression.
public MqttBuilder ContentType(IExpression contentType) { _contentType = contentType.ToTemplateString(); return this; }
/// Response topic for request/response pattern (MQTT 5.0).
public MqttBuilder ResponseTopic(IExpression topic) { _responseTopic = topic.ToTemplateString(); return this; }
/// Response topic for request/response pattern, MQTT 5.0 (template string, supports ${...}).
public MqttBuilder ResponseTopic(string topic) { _responseTopic = topic; return this; }
// ── Build ─────────────────────────────────────────────────────────
/// Builds the MQTT URI string.
public string Build()
{
var sb = new StringBuilder();
sb.Append("mqtt:");
sb.Append(_topic);
var separator = '?';
void Append(string key, string value)
{
sb.Append(separator);
sb.Append(key);
sb.Append('=');
sb.Append(Uri.EscapeDataString(value));
separator = '&';
}
void AppendIf(string key, string? value) { if (value != null) Append(key, value); }
void AppendBool(string key, bool value) { if (value) Append(key, "true"); }
// Route int-or-expression params to the correct property
void AppendIntOrExpression(string key, string? value)
{
if (value == null) return;
if (value.Contains("${"))
Append(key + "Expression", value);
else
Append(key, value);
}
Append("mode", _mode.ToString());
// Connection
AppendIf("broker", _broker);
AppendIf("server", _server);
AppendIf("port", _port);
AppendIf("username", _username);
AppendIf("password", _password);
AppendIf("connectionFactory", _connectionFactory);
AppendIf("clientId", _clientId);
AppendBool("useTls", _useTls);
AppendIf("keepAlive", _keepAlive);
if (_cleanSession.HasValue)
Append("cleanSession", _cleanSession.Value.ToString().ToLowerInvariant());
if (_sessionExpiryInterval.HasValue)
Append("sessionExpiryInterval", _sessionExpiryInterval.Value.ToString(System.Globalization.CultureInfo.InvariantCulture));
if (_maxReconnectDelay.HasValue)
Append("maxReconnectDelay", _maxReconnectDelay.Value.ToString(System.Globalization.CultureInfo.InvariantCulture));
// Subscribe/Publish common
AppendIntOrExpression("qos", _qos);
// Subscribe-only
AppendIf("sharedSubscription", _sharedSubscription);
AppendIf("concurrentConsumers", _concurrentConsumers);
// Publish-only
AppendBool("retain", _retain);
AppendIntOrExpression("messageExpiryInterval", _messageExpiryInterval);
AppendIf("contentType", _contentType);
AppendIf("responseTopic", _responseTopic);
return sb.ToString();
}
/// Implicit conversion to URI string.
public static implicit operator string(MqttBuilder builder) => builder.Build();
///
public override string ToString() => Build();
}
Path: redb-route/redb.Route.MqttNet/MqttComponent.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/redb.Route.MqttNet/MqttComponent.cs
----
using Microsoft.Extensions.Logging;
using redb.Route.Abstractions;
using redb.Route.Extensions;
using redb.Route.Core;
using redb.Route.MqttNet.Connection;
namespace redb.Route.MqttNet;
///
/// MQTT component registered with scheme "mqtt". Creates endpoints from URIs.
///
public class MqttComponent : ComponentBase
{
///
public override string Scheme => "mqtt";
/// The broker registry for named broker lookups.
internal IMqttBrokerRegistry? BrokerRegistry { get; set; }
/// The client factory for creating MQTT connections.
internal IMqttClientFactory? ClientFactory { get; set; }
///
public override IEndpoint CreateEndpoint(EndpointUri uri)
{
ArgumentNullException.ThrowIfNull(uri);
var options = new MqttEndpointOptions();
options.BindFromUri(uri.RawParameters);
// Resolve the named ConnectionFactory BEFORE Validate(): the factory may be the only
// source of the broker address and credentials, and Validate() requires a broker.
if (!string.IsNullOrEmpty(options.ConnectionFactory))
{
// A set-but-unknown name fails loud -- never a silent fallback to URI params.
var factory = Context.GetRequiredFromRegistry(options.ConnectionFactory);
factory.ApplyTo(options, uri);
}
options.Validate();
return new MqttEndpoint(uri, this, options);
}
}
///
/// MQTT endpoint. Creates consumer (subscriber) or producer (publisher) based on mode.
///
public class MqttEndpoint : EndpointBase
{
/// Creates a new MQTT endpoint.
public MqttEndpoint(EndpointUri uri, MqttComponent component, MqttEndpointOptions options)
: base(uri, component, options) { }
/// The owning MQTT component.
internal MqttComponent MqttComponent => (MqttComponent)Component;
/// Endpoint options.
internal MqttEndpointOptions EndpointOptions => Options;
/// The topic from the URI path.
public string Topic => Uri.Path;
///
public override IProducer CreateProducer()
{
return new MqttProducer(this, Options);
}
///
public override IConsumer CreateConsumer(IProcessor processor)
{
ArgumentNullException.ThrowIfNull(processor);
if (Options.Mode != MqttMode.Subscribe)
throw new InvalidOperationException(
$"MQTT consumer requires Mode=Subscribe, but Mode={Options.Mode}.");
return new MqttConsumer(this, processor, Options);
}
}
Path: redb-route/redb.Route.MqttNet/MqttConnectionFactory.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/redb.Route.MqttNet/MqttConnectionFactory.cs
----
using redb.Route.Abstractions;
using redb.Route.Core;
namespace redb.Route.MqttNet;
///
/// Named connection factory for MQTT. Register it in the route registry and reference it by name
/// from the endpoint URI (connectionFactory=my-broker) so broker credentials never have to
/// appear in the URI, and therefore can never reach logs, telemetry, or the Tsak dashboard.
///
/// Example:
///
/// context.AddToRegistry("iot-broker", new MqttConnectionFactory
/// {
/// Server = "mqtt.corp.local",
/// Port = 8883,
/// UseTls = true,
/// Username = "svc-ingest",
/// Password = Environment.GetEnvironmentVariable("MQTT_PASSWORD")
/// });
///
/// // route carries no credentials at all:
/// r.From("mqtt://sensors/+/temp?connectionFactory=iot-broker")
///
///
///
public sealed class MqttConnectionFactory
{
/// Broker address in host:port form (alternative to ).
public string? Broker { get; set; }
/// Broker hostname or IP.
public string? Server { get; set; }
/// Broker port (1883 plain, 8883 TLS).
public int Port { get; set; }
/// Username for broker authentication.
public string? Username { get; set; }
/// Password for broker authentication.
[Sensitive]
public string? Password { get; set; }
/// MQTT client identifier.
public string? ClientId { get; set; }
/// Connect over TLS.
public bool UseTls { get; set; }
/// Keep-alive interval in seconds (default 60).
public int KeepAlive { get; set; } = 60;
/// Start a clean session (default true).
public bool CleanSession { get; set; } = true;
/// MQTT 5 Session Expiry Interval in seconds (default 0: the session ends with the connection).
public int SessionExpiryInterval { get; set; }
///
/// Copies this factory's connection and credential settings onto the endpoint options, but only
/// for parameters the endpoint URI did not set explicitly — an inline URI value always wins,
/// so existing routes keep their behaviour.
///
internal void ApplyTo(MqttEndpointOptions options, EndpointUri uri)
{
var supplied = uri.RawParameters;
if (!supplied.ContainsKey(nameof(options.Broker))) options.Broker = Broker;
if (!supplied.ContainsKey(nameof(options.Server))) options.Server = Server;
if (!supplied.ContainsKey(nameof(options.Port))) options.Port = Port;
if (!supplied.ContainsKey(nameof(options.Username))) options.Username = Username;
if (!supplied.ContainsKey(nameof(options.Password))) options.Password = Password;
if (!supplied.ContainsKey(nameof(options.ClientId))) options.ClientId = ClientId;
if (!supplied.ContainsKey(nameof(options.UseTls))) options.UseTls = UseTls;
if (!supplied.ContainsKey(nameof(options.KeepAlive))) options.KeepAlive = KeepAlive;
if (!supplied.ContainsKey(nameof(options.CleanSession))) options.CleanSession = CleanSession;
if (!supplied.ContainsKey(nameof(options.SessionExpiryInterval))) options.SessionExpiryInterval = SessionExpiryInterval;
}
}
Path: redb-route/redb.Route.MqttNet/MqttConsumer.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/redb.Route.MqttNet/MqttConsumer.cs
----
using System.Buffers;
using System.Diagnostics;
using System.Text;
using Microsoft.Extensions.Logging;
using MQTTnet;
using MQTTnet.Formatter;
using MQTTnet.Packets;
using MQTTnet.Protocol;
using redb.Route.Abstractions;
using redb.Route.Core;
using redb.Route.MqttNet.Connection;
using redb.Route.Telemetry;
namespace redb.Route.MqttNet;
///
/// MQTT consumer that subscribes to a topic and forwards messages to the route processor, on the core's
/// : MQTTnet's calls a handler for every message.
///
/// Every message is acknowledged by the consumer after the route, never by MQTTnet on receipt, in serial and concurrent
/// mode alike. 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, and it sends no more unacknowledged messages than
/// the receive window. A failed message is therefore acknowledged when the broker would never send it again (QoS 0, or
/// a session that ends with the connection), and on a kept session it is left unacknowledged and the consumer
/// disconnects and connects again after a backoff, so that the broker sends it again. This follows Apache Camel's
/// paho-mqtt5 consumer as corrected by CAMEL-25793; unlike Paho, MQTTnet holds back the PUBREC of a QoS 2 message until
/// the acknowledgement, so a QoS 2 message comes again as well.
///
///
/// A connection the broker or the network drops is reported to the consumer's : the
/// consumer connects again on the RedbRoute:Reconnect schedule and subscribes again when the broker did not keep
/// the session, while the endpoint's health shows the loss. MQTTnet 5 has no client that does this by itself.
///
///
internal sealed class MqttConsumer : PushConsumer
{
/// The first pause before a reconnect after a failed message; it doubles per failed message in a row.
internal const int MinReconnectDelayMs = 1000;
private readonly MqttEndpoint _endpoint;
private readonly MqttEndpointOptions _options;
private IMqttClient? _client;
private ConnectionSupervisor? _supervisor;
// Concurrent mode (ConcurrentConsumers > 1): MQTTnet calls the handler for one message at a time, so the handler hands
// each message to a task of its own and returns; _admission bounds those tasks and holds the handler back when they
// are all busy, so a fast broker does not pile messages up in the process.
private SemaphoreSlim? _admission;
// Reconnect after a failed message on a kept session. _connection counts the connections of the client: a message is
// acknowledged only on the connection it arrived on, its packet id means nothing on a later one (the broker sends it
// again there). _failedReconnects counts the failed messages in a row that made the consumer reconnect, for the
// backoff; a success resets it. _reconnecting is 1 while a reconnect is scheduled or running.
private int _connection;
private int _failedReconnects;
private int _reconnecting;
private CancellationTokenSource? _reconnectCts;
private Task? _reconnectTask;
// 1 while the consumer disconnects the client itself (the reconnect after a failed message, the stop): the client's
// Disconnected event then is not a loss.
private int _ownDisconnect;
/// The failed messages in a row that made the consumer reconnect (for tests).
internal int FailedReconnects => Volatile.Read(ref _failedReconnects);
internal MqttConsumer(MqttEndpoint endpoint, IProcessor processor, MqttEndpointOptions options)
: base(processor)
{
_endpoint = endpoint;
_options = options;
}
///
protected override IEndpoint ConsumerEndpoint => _endpoint;
///
protected override string ConsumerName => $"mqtt:{GetEffectiveTopic()}";
// ── PushConsumer steps ──
///
protected override async Task SubscribeAsync(CancellationToken ct)
{
Volatile.Write(ref _failedReconnects, 0);
Volatile.Write(ref _reconnecting, 0);
Volatile.Write(ref _ownDisconnect, 0);
_reconnectCts = new CancellationTokenSource();
var concurrency = _options.ResolvedConcurrentConsumers;
_admission = concurrency > 1 ? new SemaphoreSlim(concurrency, concurrency) : null;
var factory = _endpoint.MqttComponent.ClientFactory ?? new DefaultMqttClientFactory();
try
{
_client = await factory.CreateConnectedClientAsync(ResolveBrokerOptions(), _options.ClientId, ct)
.ConfigureAwait(false);
_supervisor = SuperviseConnection($"{ConsumerName} consumer connection");
_client.DisconnectedAsync += OnDisconnected;
await _client.SubscribeAsync(BuildSubscribeOptions(), ct).ConfigureAwait(false);
// Attach handler AFTER subscribe to avoid receiving unrelated events on shared client
_client.ApplicationMessageReceivedAsync += OnMessageReceived;
}
catch (Exception ex)
{
Logger?.LogError(ex, "MQTT consumer Start failed for topic {Topic}", GetEffectiveTopic());
ReleaseClient();
throw;
}
Logger?.LogInformation("MQTT consumer started: {Server}:{Port} topic={Topic}", _options.Server, _options.Port,
GetEffectiveTopic());
}
///
protected override async Task StopAcceptingAsync(CancellationToken ct)
{
// A message that fails from here on is left as it is: no reconnect is started, a scheduled one is cancelled. A
// message that arrives is refused and left unacknowledged.
_reconnectCts?.Cancel();
if (_reconnectTask is { } reconnect)
{
try { await reconnect.ConfigureAwait(false); }
catch (Exception ex) { Logger?.LogDebug(ex, "MQTT: reconnect ended with an error during stop"); }
_reconnectTask = null;
}
}
///
protected override async Task UnsubscribeAsync(CancellationToken ct)
{
var client = _client;
if (client is null)
return;
if (client.IsConnected)
{
// A kept session keeps its subscription, as in Camel: the unacknowledged messages of the session come to the
// next start.
if (!IsSessionKeptAfterDisconnect())
{
try
{
await client.UnsubscribeAsync(
new MqttClientUnsubscribeOptionsBuilder()
.WithTopicFilter(GetEffectiveTopic())
.Build(), ct).ConfigureAwait(false);
}
catch (Exception ex) { Logger?.LogWarning(ex, "MQTT: error unsubscribing during stop"); }
}
Volatile.Write(ref _ownDisconnect, 1);
try
{
await client.DisconnectAsync(
new MqttClientDisconnectOptionsBuilder()
.WithReason(MqttClientDisconnectOptionsReason.NormalDisconnection)
.Build(), ct).ConfigureAwait(false);
}
catch (Exception ex) { Logger?.LogWarning(ex, "MQTT: error disconnecting during stop"); }
}
ReleaseClient();
Logger?.LogInformation("MQTT consumer stopped: {Server}:{Port}", _options.Server, _options.Port);
}
private void ReleaseClient()
{
if (_client is { } client)
{
client.ApplicationMessageReceivedAsync -= OnMessageReceived;
client.DisconnectedAsync -= OnDisconnected;
client.Dispose();
_client = null;
}
_supervisor = null;
_reconnectCts?.Dispose();
_reconnectCts = null;
}
// ── Messages ──
private async Task OnMessageReceived(MqttApplicationMessageReceivedEventArgs args)
{
// The consumer settles every message itself, after the route; a message the stop leaves unprocessed is not
// acknowledged either.
args.AutoAcknowledge = false;
if (IsStopping)
return;
var connection = Volatile.Read(ref _connection);
// Serial (default): one message at a time, in the handler.
if (_admission is not { } admission)
{
await DispatchAndSettleAsync(args, connection).ConfigureAwait(false);
return;
}
// Concurrent: wait for a free place, then run the message on a task of its own so the client delivers the next.
try
{
await admission.WaitAsync(StopToken).ConfigureAwait(false);
}
catch (OperationCanceledException)
{
return; // the stop began: left unacknowledged
}
_ = Task.Run(async () =>
{
try { await DispatchAndSettleAsync(args, connection).ConfigureAwait(false); }
finally { admission.Release(); }
});
}
private async Task DispatchAndSettleAsync(MqttApplicationMessageReceivedEventArgs args, int connection)
{
using var span = StartReceiveSpan(args.ApplicationMessage);
var dispatch = await DispatchAsync(() => CreateExchange(args.ApplicationMessage), span).ConfigureAwait(false);
switch (dispatch.Outcome)
{
case PushOutcome.Accepted:
if (await AcknowledgeAsync(args, connection).ConfigureAwait(false))
Volatile.Write(ref _failedReconnects, 0);
break;
case PushOutcome.Rejected:
await SettleFailureAsync(args, connection, dispatch.Failure!).ConfigureAwait(false);
break;
default:
// Refused or returned by the stop: left unacknowledged, the broker sends it again on a kept session.
break;
}
}
///
/// Settles a message the route failed on. When the broker would never send it again (QoS 0, or a session that ends
/// with the connection) it is acknowledged, which frees its place in the receive window: holding it back would retry
/// nothing and, repeated, stop the consumer. On a kept session it stays unacknowledged and the consumer reconnects,
/// so that the broker sends it again.
///
private async Task SettleFailureAsync(MqttApplicationMessageReceivedEventArgs args, int connection, Exception failure)
{
var message = args.ApplicationMessage;
if (IsStopping)
{
Logger?.LogError(failure,
"MQTT message processing failed: topic={Topic}; not acknowledged, the consumer is stopping", message.Topic);
return;
}
if (message.QualityOfServiceLevel == MqttQualityOfServiceLevel.AtMostOnce || !IsSessionKeptAfterDisconnect())
{
Logger?.LogError(failure,
"MQTT message processing failed: topic={Topic}; acknowledged, the broker does not send it again " +
"(QoS {Qos}, session not kept after disconnect: cleanSession=false and sessionExpiryInterval > 0 keep it)",
message.Topic, (int)message.QualityOfServiceLevel);
await AcknowledgeAsync(args, connection).ConfigureAwait(false);
return;
}
Logger?.LogError(failure,
"MQTT message processing failed: topic={Topic}; left unacknowledged, the consumer reconnects so that the " +
"broker sends it again", message.Topic);
ScheduleReconnect(connection);
}
///
/// Acknowledges a message on the connection it arrived on; returns whether it was. A message of an earlier connection
/// is left: its packet id belongs to that connection, and the broker sends it again on the current one.
///
private async Task AcknowledgeAsync(MqttApplicationMessageReceivedEventArgs args, int connection)
{
if (connection != Volatile.Read(ref _connection))
{
Logger?.LogDebug(
"MQTT: message on topic {Topic} is not acknowledged: it arrived on a connection the consumer has closed " +
"since, the broker sends it again", args.ApplicationMessage.Topic);
return false;
}
try
{
await args.AcknowledgeAsync(CancellationToken.None).ConfigureAwait(false);
return true;
}
catch (Exception ex)
{
Logger?.LogWarning(ex, "MQTT: acknowledge failed: topic={Topic}", args.ApplicationMessage.Topic);
return false;
}
}
///
/// Whether the broker keeps the session after the connection closes: no clean start, and under MQTT 5 a Session
/// Expiry Interval above 0 (an absent interval is 0, 3.1.2.11.2). Read from the client's own options, so a custom
/// that speaks MQTT 3.1.1 counts by its clean-session flag alone.
///
private bool IsSessionKeptAfterDisconnect()
{
var options = _client?.Options;
if (options is null || options.CleanSession)
return false;
return options.ProtocolVersion != MqttProtocolVersion.V500 || options.SessionExpiryInterval > 0;
}
// ── A lost connection ──
///
/// The client lost its connection. A disconnect the consumer made itself (the stop, the reconnect after a failed
/// message) and a connect attempt that failed (the client was not connected) are not a loss. A loss is reported to
/// the supervisor once, and the consumer connects again on its schedule.
///
private Task OnDisconnected(MqttClientDisconnectedEventArgs args)
{
if (IsStopping || !args.ClientWasConnected || Volatile.Read(ref _ownDisconnect) == 1)
return Task.CompletedTask;
ReportLost(args.Exception ?? new InvalidOperationException(
$"the connection to the broker was closed ({args.Reason}{(args.ReasonString is { } text ? $": {text}" : "")})"));
return Task.CompletedTask;
}
private void ReportLost(Exception cause)
{
if (_supervisor is { } supervisor && supervisor.Lost(cause))
_ = ResubscribeAsync(supervisor, ConnectAgainAsync);
}
///
/// One attempt to bring the subscription back after a loss: connects the client again, bounded by the supervisor's
/// attempt timeout, and subscribes again when the broker did not keep the session. The messages of the lost
/// connection are no longer acknowledged: the broker sends them again on a kept session.
///
private async Task ConnectAgainAsync(CancellationToken ct)
{
var client = _client ?? throw new InvalidOperationException($"{ConsumerName}: the client is gone");
var supervisor = _supervisor ?? throw new InvalidOperationException($"{ConsumerName}: the consumer is stopping");
Interlocked.Increment(ref _connection);
var sessionPresent = false;
if (!client.IsConnected)
{
// A connect given up at the attempt timeout may still finish; the next attempt finds the client connected.
var result = await supervisor.AttemptAsync(c => client.ConnectAsync(client.Options, c), static _ => { }, ct)
.ConfigureAwait(false);
sessionPresent = result.IsSessionPresent;
}
// The subscription is part of a kept session; subscribing again would make the broker send the retained message
// of the topic again.
if (!sessionPresent)
await client.SubscribeAsync(BuildSubscribeOptions(), ct).ConfigureAwait(false);
}
// ── Reconnect after a failed message ──
///
/// The pause before the reconnect for the given failed message in a row: 1 second, doubled for each further one, up
/// to , but never below 1 second, so a message that always fails does not reconnect in
/// a tight loop (Camel's reconnectDelay).
///
internal static TimeSpan ReconnectDelay(int attempt, int maxDelayMs)
{
var delay = (long)MinReconnectDelayMs << Math.Min(Math.Max(attempt, 1) - 1, 20);
return TimeSpan.FromMilliseconds(Math.Max(MinReconnectDelayMs, Math.Min(delay, Math.Max(0, maxDelayMs))));
}
/// Schedules a reconnect after the backoff, unless one is already scheduled or the consumer is stopping.
private void ScheduleReconnect(int connection)
{
var cts = _reconnectCts;
if (IsStopping || cts is null || connection != Volatile.Read(ref _connection))
return; // a message of a closed connection: the reconnect that closed it covers it
if (Interlocked.CompareExchange(ref _reconnecting, 1, 0) != 0)
return; // the scheduled reconnect covers this message too
var attempt = Interlocked.Increment(ref _failedReconnects);
var delay = ReconnectDelay(attempt, _options.MaxReconnectDelay);
Logger?.LogWarning("MQTT consumer on topic {Topic} reconnects in {Delay} ms (reconnect {Attempt} in a row)",
GetEffectiveTopic(), (long)delay.TotalMilliseconds, attempt);
_reconnectTask = Task.Run(() => ReconnectAfterFailureAsync(delay, cts.Token));
}
///
/// The reconnect after a failed message on a kept session: disconnects and connects again so that the broker sends the
/// unacknowledged message again. A connect that fails here is a lost connection: the supervisor takes it over.
///
private async Task ReconnectAfterFailureAsync(TimeSpan delay, CancellationToken ct)
{
try
{
await Task.Delay(delay, ct).ConfigureAwait(false);
}
catch (OperationCanceledException)
{
Volatile.Write(ref _reconnecting, 0);
return;
}
var client = _client;
if (client is null || ct.IsCancellationRequested)
{
Volatile.Write(ref _reconnecting, 0);
return;
}
// A new connection from here: the messages of the old one are no longer acknowledged (the broker sends them again).
var connection = Interlocked.Increment(ref _connection);
Volatile.Write(ref _ownDisconnect, 1);
try
{
try
{
if (client.IsConnected)
await client.DisconnectAsync(new MqttClientDisconnectOptionsBuilder()
.WithReason(MqttClientDisconnectOptionsReason.NormalDisconnection)
.Build(), ct).ConfigureAwait(false);
}
catch (Exception ex) when (ex is not OperationCanceledException)
{
Logger?.LogWarning(ex, "MQTT: disconnect before the reconnect failed");
}
catch (OperationCanceledException)
{
return;
}
// The disconnect covers every message that failed until now; a message the broker sends again on the new
// connection may fail before this method returns and must be able to schedule the next reconnect.
Volatile.Write(ref _reconnecting, 0);
var result = await client.ConnectAsync(client.Options, ct).ConfigureAwait(false);
// The subscription is part of a kept session; subscribing again would make the broker send the retained
// message of the topic again.
if (!result.IsSessionPresent)
{
Logger?.LogWarning(
"MQTT: the broker did not keep the session of the consumer on topic {Topic}: the failed message and " +
"the other unacknowledged ones are not sent again; subscribing again", GetEffectiveTopic());
await client.SubscribeAsync(BuildSubscribeOptions(), ct).ConfigureAwait(false);
}
else
{
Logger?.LogInformation("MQTT consumer on topic {Topic} connected again (connection {Connection})",
GetEffectiveTopic(), connection);
}
}
catch (OperationCanceledException) when (ct.IsCancellationRequested)
{
}
catch (Exception ex)
{
// The broker is not there to connect to: from here it is a lost connection, reconnected on the schedule.
Volatile.Write(ref _ownDisconnect, 0);
ReportLost(ex);
}
finally
{
Volatile.Write(ref _reconnecting, 0);
Volatile.Write(ref _ownDisconnect, 0);
}
}
///
/// The span of one message. The trace context travels in MQTT 5 user properties and is read only when this
/// connection speaks v5; without it (or under 3.1.1) the span is a root, never a child of the activity the
/// client's receive loop holds.
///
private TransportSpan StartReceiveSpan(MqttApplicationMessage message)
{
TraceHeaderReader read = _client?.Options?.ProtocolVersion == MqttProtocolVersion.V500
? ReadUserProperty
: static (_, _) => null;
return RouteTelemetryExtensions.StartConsumerSpan(
(_endpoint.Component as ComponentBase)?.Context,
$"{message.Topic} receive", ActivityKind.Consumer, "messaging.system", "mqtt",
_endpoint.Uri.NormalizedKey, message, read,
destination: message.Topic, operation: "receive");
}
#pragma warning disable CS0618 // MQTTnet marks Value as obsolete in favor of ValueBuffer
private static string? ReadUserProperty(MqttApplicationMessage message, string name)
=> message.UserProperties?.FirstOrDefault(p => p.Name == name)?.Value;
#pragma warning restore CS0618
private Exchange CreateExchange(MqttApplicationMessage message)
{
// Body: raw payload bytes (consumers pass byte[], deserialization is deferred)
object? body = message.Payload.Length > 0
? message.Payload.ToArray()
: null;
var exchange = Exchange.Create(new Message(body), _endpoint.ScopeFactory);
exchange.In.Headers[MqttHeaders.Topic] = message.Topic;
exchange.In.Headers[MqttHeaders.Qos] = (int)message.QualityOfServiceLevel;
exchange.In.Headers[MqttHeaders.Retain] = message.Retain;
if (message.ContentType != null)
{
exchange.In.Headers[MqttHeaders.ContentType] = message.ContentType;
exchange.In.ContentType = message.ContentType;
}
if (message.ResponseTopic != null)
exchange.In.Headers[MqttHeaders.ResponseTopic] = message.ResponseTopic;
if (message.CorrelationData is { Length: > 0 })
exchange.In.Headers[MqttHeaders.CorrelationData] = Encoding.UTF8.GetString(message.CorrelationData);
if (message.MessageExpiryInterval > 0)
exchange.In.Headers[MqttHeaders.MessageExpiryInterval] = (int)message.MessageExpiryInterval;
if (_options.Broker != null)
exchange.In.Headers[MqttHeaders.Broker] = _options.Broker;
if (_options.ClientId != null)
exchange.In.Headers[MqttHeaders.ClientId] = _options.ClientId;
// MQTT 5.0 User Properties → Dictionary
if (message.UserProperties is { Count: > 0 })
{
var userProps = new Dictionary(message.UserProperties.Count);
#pragma warning disable CS0618 // MQTTnet marks Value as obsolete in favor of ValueBuffer
foreach (var prop in message.UserProperties)
userProps[prop.Name] = prop.Value;
#pragma warning restore CS0618
exchange.In.Headers[MqttHeaders.UserProperties] = userProps;
}
return exchange;
}
private MqttClientSubscribeOptions BuildSubscribeOptions()
=> new MqttClientSubscribeOptionsBuilder().WithTopicFilter(BuildTopicFilter()).Build();
private MqttTopicFilter BuildTopicFilter()
{
var topic = GetEffectiveTopic();
var qos = _options.Qos switch
{
0 => MqttQualityOfServiceLevel.AtMostOnce,
1 => MqttQualityOfServiceLevel.AtLeastOnce,
2 => MqttQualityOfServiceLevel.ExactlyOnce,
_ => MqttQualityOfServiceLevel.AtMostOnce
};
return new MqttTopicFilter { Topic = topic, QualityOfServiceLevel = qos };
}
private string GetEffectiveTopic()
{
var topic = _endpoint.Topic;
// MQTT 5.0 shared subscriptions: $share/{group}/{topic}
if (_options.SharedSubscription != null)
return $"$share/{_options.SharedSubscription}/{topic}";
return topic;
}
private MqttBrokerOptions ResolveBrokerOptions()
{
if (_options.Broker != null)
{
var registry = _endpoint.MqttComponent.BrokerRegistry
?? throw new InvalidOperationException(
$"Broker '{_options.Broker}' is specified but no IMqttBrokerRegistry is registered.");
return registry.GetOptions(_options.Broker);
}
if (_options.Server != null)
{
return new MqttBrokerOptions
{
Server = _options.Server,
Port = _options.Port > 0 ? _options.Port : 1883,
Username = _options.Username,
Password = _options.Password,
ClientId = _options.ClientId,
UseTls = _options.UseTls,
KeepAlive = _options.KeepAlive,
CleanSession = _options.CleanSession,
SessionExpiryInterval = _options.SessionExpiryInterval
};
}
throw new InvalidOperationException("Either Broker or Server must be configured.");
}
}
Path: redb-route/redb.Route.MqttNet/MqttEndpointOptions.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/redb.Route.MqttNet/MqttEndpointOptions.cs
----
using redb.Route.Core;
namespace redb.Route.MqttNet;
///
/// Endpoint options for the MQTT component. Bound from URI parameters via reflection.
///
public sealed class MqttEndpointOptions : EndpointOptions
{
/// Subscribe or Publish mode.
public MqttMode Mode { get; set; } = MqttMode.Subscribe;
// ── Connection ────────────────────────────────────────────────────
/// Named broker reference (registered via AddBroker()).
public string? Broker { get; set; }
/// Inline broker URL (e.g. tcp://localhost:1883). Alternative to named Broker.
public string? Server { get; set; }
/// Server port. Defaults to 1883 (or 8883 for TLS).
public int Port { get; set; }
/// Username for broker authentication.
public string? Username { get; set; }
/// Password for broker authentication.
[Sensitive]
public string? Password { get; set; }
/// Client ID. Auto-generated if not set.
public string? ClientId { get; set; }
///
/// Named from the route registry. Lets broker credentials
/// live in the registry instead of the endpoint URI, so they never reach logs or dashboards.
///
[RegistryReference(typeof(MqttConnectionFactory))]
public string? ConnectionFactory { get; set; }
/// Enable TLS/SSL.
public bool UseTls { get; set; }
/// Keep-alive interval in seconds. Default 60.
public int KeepAlive { get; set; } = 60;
/// Clean session / clean start. Default true.
public bool CleanSession { get; set; } = true;
///
/// MQTT 5 Session Expiry Interval in seconds (Apache Camel paho-mqtt5 sessionExpiryInterval): how long the
/// broker keeps the session after the connection closes. Default 0: the session ends with the connection, even with
/// false (MQTT 5, 3.1.2.11.2). A kept session needs cleanSession=false and a value
/// above 0; only then does the broker send an unacknowledged message again after a reconnect.
///
public int SessionExpiryInterval { get; set; }
///
/// The longest pause, in milliseconds, before the consumer connects again after a failed message on a kept session
/// (Apache Camel paho-mqtt5 maxReconnectDelay). The pause starts at 1 second and doubles with each failed
/// message in a row, up to this value; a success resets it. Default 128000.
///
public int MaxReconnectDelay { get; set; } = 128_000;
// ── Subscribe (consumer) ──────────────────────────────────────────
/// Quality of Service level (0, 1, 2). Default 0.
public int Qos { get; set; }
/// QoS level as expression (e.g. ${header['qos']}). Resolved at runtime, overrides if set.
public string? QosExpression { get; set; }
/// MQTT 5.0 shared subscription group name. Enables load-balanced consuming.
public string? SharedSubscription { get; set; }
///
/// Number of concurrent processing workers for received messages (default 1 = serial).
/// When > 1, received messages are dispatched to a bounded pool of N workers, so up to N
/// messages are processed in parallel. Each message is acknowledged only AFTER its worker
/// finishes processing (manual ack), preserving at-least-once delivery for QoS 1/2 — unlike a
/// generic .Threads(N) in the route, which would acknowledge on hand-off (before processing).
/// Ordering is not preserved when > 1.
///
// A string so "auto" binds verbatim instead of silently degrading to the int default.
public string? ConcurrentConsumers { get; set; }
/// Resolved consumer parallelism: 1, N, or auto = max(CPU, 2) (see ).
public int ResolvedConcurrentConsumers => ConcurrencyOption.Resolve(ConcurrentConsumers, "concurrentConsumers");
// ── Publish (producer) ────────────────────────────────────────────
/// Retain message on broker. Default false.
public bool Retain { get; set; }
/// Message expiry interval in seconds (MQTT 5.0). 0 = no expiry.
public int MessageExpiryInterval { get; set; }
/// Message expiry as expression (e.g. ${body['ttl']}). Resolved at runtime, overrides if set.
public string? MessageExpiryIntervalExpression { get; set; }
/// Content type for published messages (MQTT 5.0).
public string? ContentType { get; set; }
/// Response topic for request/response pattern (MQTT 5.0).
public string? ResponseTopic { get; set; }
///
public override void Validate()
{
if (Broker is null && Server is null)
throw new ArgumentException("Either Broker or Server is required for MQTT endpoint.");
if (Qos < 0 || Qos > 2)
throw new ArgumentException($"QoS must be 0, 1, or 2. Got: {Qos}");
_ = ConcurrencyOption.Resolve(ConcurrentConsumers, "concurrentConsumers"); // loud on garbage
if (SessionExpiryInterval < 0)
throw new ArgumentException($"MQTT sessionExpiryInterval must be >= 0 seconds. Got: {SessionExpiryInterval}");
if (MaxReconnectDelay < 0)
throw new ArgumentException($"MQTT maxReconnectDelay must be >= 0 milliseconds. Got: {MaxReconnectDelay}");
}
}
Path: redb-route/redb.Route.MqttNet/MqttHeaders.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/redb.Route.MqttNet/MqttHeaders.cs
----
namespace redb.Route.MqttNet;
///
/// Constants for exchange headers set by the MQTT component.
/// All prefixed with "redbMqtt." to avoid collisions with other connectors.
///
public static class MqttHeaders
{
/// Common prefix for all MQTT headers.
public const string Prefix = "redbMqtt.";
// ── Topic ─────────────────────────────────────────────────────────
///
/// Topic the message was received on (consumer) or sent to (producer). Informational: the connector writes it, a
/// publish never reads it. To publish elsewhere than the endpoint's topic, set .
///
public const string Topic = "redbMqtt.topic";
///
/// Topic a publish goes to instead of the endpoint's topic, set by the route. The connector never writes it, so a
/// received topic or an earlier publish cannot steer the next one (Apache Camel keeps CamelMqttTopic and
/// CamelPahoOverrideTopic apart the same way).
///
public const string OverrideTopic = "redbMqtt.overrideTopic";
///
/// QoS level of the received or published message. Informational: the connector writes it, a publish never reads
/// it. To publish with another QoS than the endpoint's, set .
///
public const string Qos = "redbMqtt.qos";
///
/// QoS level (an , 0 to 2) a publish uses instead of the endpoint's, set by the route. The connector
/// never writes it, so the QoS of a received message does not carry over to a republish.
///
public const string OverrideQos = "redbMqtt.overrideQos";
///
/// Whether the received or published message had the retain flag set. Informational: the connector writes it, a
/// publish never reads it. To set the retain flag of a publish, set .
///
public const string Retain = "redbMqtt.retain";
///
/// Retain flag (a ) a publish uses instead of the endpoint's, set by the route. The connector never
/// writes it, so a retained message received and republished is not retained again unless the route asks for it.
///
public const string OverrideRetain = "redbMqtt.overrideRetain";
// ── Payload ───────────────────────────────────────────────────────
/// MQTT payload content type (MQTT 5.0).
public const string ContentType = "redbMqtt.contentType";
/// Response topic (MQTT 5.0 request/response).
public const string ResponseTopic = "redbMqtt.responseTopic";
/// Correlation data (MQTT 5.0 request/response).
public const string CorrelationData = "redbMqtt.correlationData";
/// Message expiry interval in seconds (MQTT 5.0).
public const string MessageExpiryInterval = "redbMqtt.messageExpiryInterval";
// ── Connection ────────────────────────────────────────────────────
/// Broker name used for the connection.
public const string Broker = "redbMqtt.broker";
/// Client ID of the MQTT connection.
public const string ClientId = "redbMqtt.clientId";
// ── MQTT 5.0 User Properties ──────────────────────────────────────
/// MQTT 5.0 User Properties as Dictionary<string,string>.
public const string UserProperties = "redbMqtt.userProperties";
}
Path: redb-route/redb.Route.MqttNet/MqttMode.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/redb.Route.MqttNet/MqttMode.cs
----
namespace redb.Route.MqttNet;
///
/// MQTT endpoint mode: Subscribe (consumer) or Publish (producer).
///
public enum MqttMode
{
/// Subscribe to one or more topics — used with From().
Subscribe,
/// Publish messages to a topic — used with To().
Publish
}
Path: redb-route/redb.Route.MqttNet/MqttProducer.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/redb.Route.MqttNet/MqttProducer.cs
----
using System.Diagnostics;
using System.Globalization;
using System.Text;
using Microsoft.Extensions.Logging;
using MQTTnet;
using MQTTnet.Formatter;
using MQTTnet.Packets;
using MQTTnet.Protocol;
using redb.Route.Abstractions;
using redb.Route.Core;
using redb.Route.MqttNet.Connection;
using redb.Route.Telemetry;
namespace redb.Route.MqttNet;
///
/// MQTT producer that publishes messages to a topic.
/// The exchange body is serialized to UTF-8 bytes as the MQTT payload.
///
internal sealed class MqttProducer : ConnectableProducer
{
private readonly MqttEndpoint _endpoint;
private readonly MqttEndpointOptions _options;
private IMqttClient? _client;
internal MqttProducer(MqttEndpoint endpoint, MqttEndpointOptions options)
{
_endpoint = endpoint;
_options = options;
}
///
protected override IEndpoint ProducerEndpoint => _endpoint;
///
protected override string ProducerName => $"mqtt:{_options.Server}:{_options.Port}";
///
protected override async Task ConnectAsync(CancellationToken ct)
{
var brokerOptions = ResolveBrokerOptions();
var factory = _endpoint.MqttComponent.ClientFactory ?? new DefaultMqttClientFactory();
_client = await factory.CreateConnectedClientAsync(brokerOptions, _options.ClientId, ct)
.ConfigureAwait(false);
}
///
protected override async Task DisconnectAsync(CancellationToken ct)
{
if (_client != null)
{
if (_client.IsConnected)
{
try
{
await _client.DisconnectAsync(
new MqttClientDisconnectOptionsBuilder()
.WithReason(MqttClientDisconnectOptionsReason.NormalDisconnection)
.Build(), ct).ConfigureAwait(false);
}
catch (Exception ex) { Logger?.LogDebug(ex, "MQTT: error disconnecting during stop"); }
}
_client.Dispose();
_client = null;
}
}
///
public override async Task Process(IExchange exchange, CancellationToken ct = default)
{
if (_client == null || !_client.IsConnected)
throw new InvalidOperationException("MQTT producer is not connected. Call Start() first.");
var topic = ResolvePublishTopic(exchange);
using var activity = RouteTelemetryExtensions.StartTransportSpan(
(_endpoint.Component as ComponentBase)?.Context,
$"{topic} publish", ActivityKind.Producer,
"messaging.system", "mqtt",
_endpoint.Uri.NormalizedKey,
destination: topic,
operation: "publish");
var payload = SerializeBody(exchange.In.Body);
var qos = ResolveQos(exchange);
var builder = new MqttApplicationMessageBuilder()
.WithTopic(topic)
.WithPayload(payload)
.WithQualityOfServiceLevel(qos)
.WithRetainFlag(ResolveRetain(exchange));
// MQTT 5.0 properties
var contentType = ResolveHeaderString(exchange, MqttHeaders.ContentType)
?? _options.ResolveOption(_options.ContentType, exchange);
if (contentType != null)
builder.WithContentType(contentType);
var responseTopic = ResolveHeaderString(exchange, MqttHeaders.ResponseTopic)
?? _options.ResolveOption(_options.ResponseTopic, exchange);
if (responseTopic != null)
builder.WithResponseTopic(responseTopic);
var correlationData = ResolveHeaderString(exchange, MqttHeaders.CorrelationData);
if (correlationData != null)
builder.WithCorrelationData(Encoding.UTF8.GetBytes(correlationData));
var expiryInterval = ResolveExpiryInterval(exchange);
if (expiryInterval > 0)
builder.WithMessageExpiryInterval((uint)expiryInterval);
// User properties from exchange headers. A copy: the trace context below is this send's, not the exchange's.
var userProps = exchange.In.Headers.TryGetValue(MqttHeaders.UserProperties, out var userPropsObj)
&& userPropsObj is Dictionary headerProps
? new Dictionary(headerProps)
: null;
// The trace context travels in user properties, which exist only in MQTT 5: under 3.1.1 MQTTnet refuses
// them, so nothing is written. The write replaces a traceparent copied from an earlier hop.
if (_client.Options?.ProtocolVersion == MqttProtocolVersion.V500)
{
userProps ??= new Dictionary();
RouteTelemetryExtensions.InjectTraceContext(activity, userProps,
static (props, name, value) => props[name] = value);
}
if (userProps is not null)
{
foreach (var (key, value) in userProps)
builder.WithUserProperty(key, new ReadOnlyMemory(Encoding.UTF8.GetBytes(value)));
}
var message = builder.Build();
try
{
await _client.PublishAsync(message, ct).ConfigureAwait(false);
}
catch (Exception ex) when (ex is not OperationCanceledException || !ct.IsCancellationRequested)
{
// Only our own token cancelling the publish is a stop; any other failure marks the span.
activity.RecordFailure(ex);
Logger?.LogError(ex, "MQTT publish failed: topic={Topic}, QoS={Qos}, server={Server}:{Port}, connected={IsConnected}",
topic, qos, _options.Server, _options.Port, _client?.IsConnected);
throw;
}
_endpoint.RecordBytesOut(message.Payload.Length);
// Set result headers
exchange.In.Headers[MqttHeaders.Topic] = topic;
exchange.In.Headers[MqttHeaders.Qos] = (int)qos;
exchange.In.Headers[MqttHeaders.Retain] = ResolveRetain(exchange);
if (_options.Broker != null)
exchange.In.Headers[MqttHeaders.Broker] = _options.Broker;
}
private string ResolvePublishTopic(IExchange exchange)
{
// Only the route's own override: redbMqtt.topic is what the connector last received or sent, never a target.
if (exchange.In.Headers.TryGetValue(MqttHeaders.OverrideTopic, out var topicObj)
&& topicObj is string topicStr && !string.IsNullOrEmpty(topicStr))
return topicStr;
return _options.ResolveOption(_endpoint.Topic, exchange) ?? _endpoint.Topic;
}
private MqttQualityOfServiceLevel ResolveQos(IExchange exchange)
{
// 1. The route's own override: redbMqtt.qos is what the connector last received or sent, never a setting.
// An int from C#, or its text from markup (); anything else is the route's mistake.
if (exchange.In.Headers.TryGetValue(MqttHeaders.OverrideQos, out var qosObj) && qosObj is not null)
{
var level = qosObj switch
{
int i => i,
string s when int.TryParse(s, NumberStyles.None, CultureInfo.InvariantCulture, out var parsed) => parsed,
_ => -1
};
if (level is < 0 or > 2)
throw new InvalidOperationException(
$"Header '{MqttHeaders.OverrideQos}' must be 0, 1 or 2 (an int or its text), got '{qosObj}' ({qosObj.GetType().Name}).");
return (MqttQualityOfServiceLevel)level;
}
// 2. Expression (e.g. "${body['qos']}")
if (!string.IsNullOrEmpty(_options.QosExpression))
{
var resolved = _options.ResolveOption(_options.QosExpression, exchange);
if (resolved != null && int.TryParse(resolved, out var exprQos))
{
return exprQos switch
{
0 => MqttQualityOfServiceLevel.AtMostOnce,
1 => MqttQualityOfServiceLevel.AtLeastOnce,
2 => MqttQualityOfServiceLevel.ExactlyOnce,
_ => MqttQualityOfServiceLevel.AtMostOnce
};
}
}
// 3. Static default
return _options.Qos switch
{
0 => MqttQualityOfServiceLevel.AtMostOnce,
1 => MqttQualityOfServiceLevel.AtLeastOnce,
2 => MqttQualityOfServiceLevel.ExactlyOnce,
_ => MqttQualityOfServiceLevel.AtMostOnce
};
}
private bool ResolveRetain(IExchange exchange)
{
// Only the route's own override: redbMqtt.retain is the flag of the last receive or publish.
// A bool from C#, or its text from markup ().
if (exchange.In.Headers.TryGetValue(MqttHeaders.OverrideRetain, out var retainObj) && retainObj is not null)
{
return retainObj switch
{
bool b => b,
string s when bool.TryParse(s, out var parsed) => parsed,
_ => throw new InvalidOperationException(
$"Header '{MqttHeaders.OverrideRetain}' must be true or false (a bool or its text), got '{retainObj}' ({retainObj.GetType().Name}).")
};
}
return _options.Retain;
}
private int ResolveExpiryInterval(IExchange exchange)
{
// 1. Header override
if (exchange.In.Headers.TryGetValue(MqttHeaders.MessageExpiryInterval, out var expiryObj) && expiryObj is int expiryInt)
return expiryInt;
// 2. Expression (e.g. "${body['ttl']}")
if (!string.IsNullOrEmpty(_options.MessageExpiryIntervalExpression))
{
var resolved = _options.ResolveOption(_options.MessageExpiryIntervalExpression, exchange);
if (resolved != null && int.TryParse(resolved, out var exprExpiry))
return exprExpiry;
}
// 3. Static default
return _options.MessageExpiryInterval;
}
private static string? ResolveHeaderString(IExchange exchange, string header)
{
if (exchange.In.Headers.TryGetValue(header, out var val) && val is string s && !string.IsNullOrEmpty(s))
return s;
return null;
}
private static byte[] SerializeBody(object? body)
{
return body switch
{
null => [],
byte[] bytes => bytes,
ReadOnlyMemory rom => rom.ToArray(),
ArraySegment seg => seg.ToArray(),
string str => Encoding.UTF8.GetBytes(str),
_ => Encoding.UTF8.GetBytes(BodyText.Of(body))
};
}
private MqttBrokerOptions ResolveBrokerOptions()
{
if (_options.Broker != null)
{
var registry = _endpoint.MqttComponent.BrokerRegistry
?? throw new InvalidOperationException(
$"Broker '{_options.Broker}' is specified but no IMqttBrokerRegistry is registered.");
return registry.GetOptions(_options.Broker);
}
if (_options.Server != null)
{
return new MqttBrokerOptions
{
Server = _options.Server,
Port = _options.Port > 0 ? _options.Port : 1883,
Username = _options.Username,
Password = _options.Password,
ClientId = _options.ClientId,
UseTls = _options.UseTls,
KeepAlive = _options.KeepAlive,
CleanSession = _options.CleanSession,
SessionExpiryInterval = _options.SessionExpiryInterval
};
}
throw new InvalidOperationException("Either Broker or Server must be configured.");
}
}
Path: redb-route/redb.Route.MqttNet/README.md
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/redb.Route.MqttNet/README.md
----
# redb.Route.MqttNet
MQTT 5.0 transport for redb.Route via MQTTnet. Subscribe consumer, publish producer, shared subscriptions, QoS levels, retained messages, and TLS.
[](https://www.nuget.org/packages/redb.Route.MqttNet)
[](../../LICENSE)
## Installation
```bash
dotnet add package redb.Route.MqttNet
```
## Usage
### Fluent DSL
```csharp
using redb.Route.MqttNet;
// Subscribe to topic
From(Mqtt.Subscribe("sensors/temperature/#")
.Server("mqtt.example.com").Port(1883)
.ClientId("route-consumer")
.Qos(1))
.Log("Temperature: ${body}")
.To("direct://process");
// Publish to topic
From("direct://alerts")
.To(Mqtt.Publish("alerts/critical")
.Server("mqtt.example.com")
.Username("svc").Password("secret")
.Qos(2)
.Retain());
// Shared subscription (load balancing across consumers)
From(Mqtt.Subscribe("orders/new")
.Server("broker.local")
.SharedSubscription("order-processors")
.UseTls())
.To("direct://handle-order");
// Broker configuration (shared across routes)
From(Mqtt.Subscribe("events/#")
.Broker("main")
.Qos(1))
.To("seda://events");
```
## Fluent Builder API
| Category | Methods |
|----------|---------|
| **Connection** | `.Broker(name)`, `.Server()`, `.Port()`, `.Username()`, `.Password()`, `.ClientId()`, `.UseTls()`, `.KeepAlive()`, `.CleanSession()`, `.SessionExpiryInterval()`, `.MaxReconnectDelay()` |
| **QoS** | `.Qos(level)` — AtMostOnce, AtLeastOnce, ExactlyOnce |
| **Subscribe** | `Mqtt.Subscribe(topic)`, `.SharedSubscription(group)`, `.ConcurrentConsumers(n)` |
| **Publish** | `Mqtt.Publish(topic)`, `.Retain()`, `.MessageExpiryInterval()`, `.ContentType()`, `.ResponseTopic()` |
> Most builder methods accept both constant values and `IExpression` for runtime resolution via the expression engine.
## Headers
| Header | Written by | Read by the publish |
|--------|------------|---------------------|
| `redbMqtt.topic` | the consumer (received topic), the producer (topic it published to) | no |
| `redbMqtt.overrideTopic` | the route only | yes: the topic instead of the endpoint's |
| `redbMqtt.qos`, `redbMqtt.retain` | the consumer (received message), the producer (its publish) | no |
| `redbMqtt.overrideQos` (0, 1 or 2), `redbMqtt.overrideRetain` (true or false), typed or as text | the route only | yes: QoS and retain flag instead of the endpoint's |
| `redbMqtt.contentType`, `redbMqtt.responseTopic`, `redbMqtt.correlationData`, `redbMqtt.messageExpiryInterval` | the consumer | yes, passed through: the MQTT 5 properties of the publish |
| `redbMqtt.userProperties` | the consumer | yes, passed through: MQTT 5 user properties |
| `redbMqtt.broker`, `redbMqtt.clientId` | the consumer, the producer | no |
The topic a publish goes to is the endpoint's (an expression such as `sensors/${header.room}` included), or
`redbMqtt.overrideTopic` when the route set it. `redbMqtt.topic` only tells where the last message came from or went,
so two publishes in one route each reach their own endpoint, and a received message republished to a fixed topic goes
there, not back to the topic it came from.
QoS and the retain flag work the same way: the endpoint's (`qos`, `qosExpression`, `retain`), or
`redbMqtt.overrideQos` / `redbMqtt.overrideRetain` when the route set them. A retained message received and
republished is not retained again, and goes out with the endpoint's QoS, not the QoS it arrived with.
The MQTT 5 properties are the exception: a message received and republished keeps its content type, response topic,
correlation data, expiry interval and user properties, so request/response and metadata survive a hop. A route that
does not want them on the publish removes those headers first.
### Concurrent processing
`.ConcurrentConsumers(n)` (default `1` = serial) processes up to `n` received messages in parallel on a
worker pool. Each message is settled **only after** its worker finishes, as in serial mode (see
[Acknowledgement and failed messages](#acknowledgement-and-failed-messages)). Ordering is not
preserved when `n > 1`.
```csharp
From(Mqtt.Subscribe("telemetry/#").Broker("main").Qos(1).ConcurrentConsumers(5))
.Process(IngestReading);
```
See the framework-wide **Concurrency & Parallelism** guide (`CONCURRENCY.md` in the
[redb.Route repository](https://github.com/redbase-app/redb)) for how this compares to the `.Threads(N)`
processing EIP.
## Acknowledgement and failed messages
The client speaks **MQTT 5.0** (MQTTnet's default protocol). The consumer acknowledges every QoS 1 and QoS 2 message
itself, **after** the route, in serial and concurrent mode alike; MQTTnet does not acknowledge on receipt. MQTT has no
negative acknowledgement: the broker sends an unacknowledged message again only when the client connects again to a
session the broker kept, and it sends a client no more unacknowledged messages than its receive window. So a message
the route fails on (an exception it did not handle, or `.RollbackAll()`) is settled by one rule, the one of Apache
Camel's paho-mqtt5 consumer as corrected by CAMEL-25793:
| The failed message | What the consumer does |
|---|---|
| QoS 0, or the session ends with the connection (`cleanSession=true`, the default, or `sessionExpiryInterval=0`) | **Acknowledges it and logs an error.** |
| QoS 1 or QoS 2 on a kept session (`cleanSession=false` and `sessionExpiryInterval` above 0) | Leaves it unacknowledged, disconnects and connects again after a pause, so that the broker sends it again. |
What this means for a route:
- **Acknowledged and logged** means the broker will not send the message again: it is gone from MQTT. Holding the
acknowledgement back would not bring it back either, it would only fill the receive window until the consumer stops
getting messages. Where a failed message must be kept, the route keeps it with its own error handling: an error
handler with redelivery, and a dead letter channel that stores it.
- On a kept session the message comes again after the reconnect and runs through the route again; so do the other
messages that were not acknowledged yet when the consumer disconnected, also ones whose route had already finished.
A route on a kept session must therefore tolerate a repeat, for example with an idempotent consumer.
- The pause before the reconnect is 1 second and doubles with each failed message in a row, up to `maxReconnectDelay`
(default 128000 ms); a message that succeeds resets it. A message that always fails is therefore tried at that pace,
not in a tight loop. A failure while the consumer is stopping starts no reconnect and is not acknowledged.
- A kept session needs a fixed `clientId`: the broker finds the session by it. The consumer does not unsubscribe on
stop when the session is kept, so the messages that wait in it reach the next start.
```
mqtt:orders/#?mode=Subscribe&broker=main&qos=1&clientId=orders-in&cleanSession=false&sessionExpiryInterval=3600
```
## A lost connection
When the broker or the network drops the consumer's connection (a broker restart, a server-side disconnect, a reset),
the consumer connects again and subscribes again when the broker did not keep the session; a kept session keeps its
subscription, and the broker sends the messages that were not acknowledged on the lost connection again. While the
connection is away the endpoint's health is `Warning`, then `Critical` once an attempt to connect failed; a Warning is
logged when it is lost and an Information when it is back, and `Reconnects` counts each return. Attempts follow
`RedbRoute:Reconnect` (delay, multiplier, cap, attempt timeout); a loss is not counted in `Errors`. The reconnect after
a failed message (see above) that cannot reach the broker becomes such a loss. A disconnect the consumer makes itself,
on stop or for a failed message, is not one.
## Part of
[redb.Route](../README.md) — ESB & EIP Framework for .NET
## Named connection factory
Keep credentials out of the route URI: register a factory in the context registry and
reference it by name. A set-but-unknown name fails loud at startup — a typo can never
silently fall back to inline URI parameters.
```csharp
context.AddToRegistry("prod", new MqttConnectionFactory
{
Server = "mqtt.internal",
Username = "svc",
Password = secrets.MqttPassword,
});
// mqtt://sensors/+?connectionFactory=prod
```
## Concurrency
The default is **1** concurrent consumer — the industry norm (Camel, Spring, the Azure SDK all
ship 1): a single consumer preserves ordering and your handlers need no thread safety.
Parallelism is an explicit opt-in:
```
concurrentConsumers=4 # a fixed worker count
concurrentConsumers=auto # max(CPU count, 2) — the NServiceBus formula
```
Anything else — `0`, a negative, a typo — fails at endpoint creation naming the option (the old
int-typed option silently fell back to 1). Raising the value trades ordering for throughput:
messages from the same queue are processed out of order, and your processors must be safe to
run in parallel.
## Tracing
On the `redb.Route` activity source (`AddSource("redb.Route")`), with `messaging.system` = `mqtt` and
`redb.route.endpoint`:
- **Context.** The W3C context (`traceparent`, `tracestate`, `baggage`) travels in MQTT 5 user properties, and only when
the connection speaks v5 (the MQTTnet default). Under 3.1.1 nothing is written — MQTTnet refuses user properties
there — and nothing is read.
- **Producer.** One `Producer` span per publish, `{topic} publish`, whose context is written to the message. The write
replaces a `traceparent` already in `redbMqtt.userProperties` (copied from an earlier hop); the exchange's header is
left as it was. An error when the publish fails, unless our own token cancelled it.
- **Consumer.** One `Consumer` span per routed message, `{topic} receive`, a child of the sender's context when the
message carries one; otherwise a root, never a child of the activity the client's receive loop holds. Nothing
arriving opens none. A failed route marks it an error; our own stop does not.
- `RouteEngineOptions.EnableTelemetry = false` opens neither span; a context the route received is still passed on.
Path: redb-route/redb.Route.MqttNet/redb.Route.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/redb.Route.MqttNet/redb.Route.MqttNet.csproj
----
redb.Route.MqttNet
MQTT transport for redb.Route ESB framework via MQTTnet. Subscribe consumer, publish producer, shared subscriptions, QoS, retained messages, TLS.
esb;messaging;mqtt;mqttnet;iot;redb
README.md