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.");
}
}