Reliable MQTT auto-reconnect #1

Merged
zyberzero merged 3 commits from mqtt-auto-reconnect into main 2026-11-03 17:56:35 +00:00
Showing only changes of commit 917a149bc2 - Show all commits
+79 -21
View File
@@ -11,8 +11,9 @@ namespace FrameProcessor.Mqtt;
/// <summary>
/// Persistent MQTT client wrapped in a hosted service. Connects on startup and
/// reconnects in the background after disconnects. Connection state is surfaced
/// via <see cref="IsConnected"/> for the <c>/health</c> endpoint.
/// reconnects in the background after disconnects using
/// <see cref="MqttOptions.ReconnectBackoffSeconds"/> (SPEC.md §5.2). Connection state
/// is surfaced via <see cref="IsConnected"/> for the <c>/health</c> endpoint.
///
/// On publish failure the (mac → topic, payload) pair is enqueued for retry; a
/// background loop drains the queue using <see cref="MqttOptions.RetryBackoffSeconds"/>.
@@ -21,8 +22,6 @@ namespace FrameProcessor.Mqtt;
/// </summary>
public sealed class MqttPublisher : BackgroundService
{
private static readonly TimeSpan ReconnectDelay = TimeSpan.FromSeconds(5);
private readonly IOptions<MqttOptions> _options;
private readonly ILogger<MqttPublisher> _logger;
private readonly IMqttClient _client;
@@ -30,12 +29,15 @@ public sealed class MqttPublisher : BackgroundService
private readonly ConcurrentDictionary<MacAddress, byte> _pending = new();
private readonly Channel<bool> _wakeup = Channel.CreateBounded<bool>(
new BoundedChannelOptions(1) { FullMode = BoundedChannelFullMode.DropWrite });
private readonly Channel<bool> _reconnect = Channel.CreateBounded<bool>(
new BoundedChannelOptions(1) { FullMode = BoundedChannelFullMode.DropWrite });
public MqttPublisher(IOptions<MqttOptions> options, ILogger<MqttPublisher> logger)
{
_options = options;
_logger = logger;
_client = new MqttFactory().CreateMqttClient();
_client.DisconnectedAsync += OnDisconnectedAsync;
}
public bool IsConnected => _client.IsConnected;
@@ -57,6 +59,7 @@ public sealed class MqttPublisher : BackgroundService
"Initial MQTT connect to {Host}:{Port} failed; background reconnect will retry",
_options.Value.Host,
_options.Value.Port);
_reconnect.Writer.TryWrite(true);
}
await base.StartAsync(cancellationToken).ConfigureAwait(false);
@@ -68,46 +71,98 @@ public sealed class MqttPublisher : BackgroundService
try
{
while (!stoppingToken.IsCancellationRequested)
await RunReconnectLoopAsync(stoppingToken).ConfigureAwait(false);
}
finally
{
await retryLoop.ConfigureAwait(false);
}
}
private Task OnDisconnectedAsync(MqttClientDisconnectedEventArgs e)
{
// Failed connect attempts also raise this event; those are logged by the reconnect loop.
if (e.ClientWasConnected)
{
_logger.LogWarning(
e.Exception,
"MQTT disconnected from {Host}:{Port} (reason {Reason})",
_options.Value.Host,
_options.Value.Port,
e.Reason);
}
// Never connect from the handler — only the reconnect loop calls ConnectAsync.
_reconnect.Writer.TryWrite(true);
return Task.CompletedTask;
}
private async Task RunReconnectLoopAsync(CancellationToken stoppingToken)
{
var backoff = _options.Value.ReconnectBackoffSeconds;
// Safety net in case a disconnect event is ever missed.
var idleCheck = TimeSpan.FromSeconds(backoff[^1]);
while (!stoppingToken.IsCancellationRequested)
{
using (var idleCts = CancellationTokenSource.CreateLinkedTokenSource(stoppingToken))
{
idleCts.CancelAfter(idleCheck);
try
{
await Task.Delay(ReconnectDelay, stoppingToken).ConfigureAwait(false);
await _reconnect.Reader.ReadAsync(idleCts.Token).ConfigureAwait(false);
}
catch (OperationCanceledException) when (!stoppingToken.IsCancellationRequested)
{
// Idle check elapsed; fall through and verify the connection.
}
catch (OperationCanceledException)
{
return;
}
}
if (_client.IsConnected)
{
continue;
}
var attempt = 0;
while (!_client.IsConnected && !stoppingToken.IsCancellationRequested)
{
attempt++;
try
{
await _client.ConnectAsync(BuildClientOptions(), stoppingToken).ConfigureAwait(false);
_logger.LogInformation(
"MQTT reconnected to {Host}:{Port}",
"MQTT reconnected to {Host}:{Port} after {Attempt} attempt(s)",
_options.Value.Host,
_options.Value.Port);
_options.Value.Port,
attempt);
// Drain any queued publishes immediately now that the link is back up.
_wakeup.Writer.TryWrite(true);
}
catch (Exception ex) when (!stoppingToken.IsCancellationRequested)
{
var delaySeconds = backoff[Math.Min(attempt - 1, backoff.Length - 1)];
_logger.LogWarning(
ex,
"MQTT reconnect to {Host}:{Port} failed",
"MQTT reconnect attempt {Attempt} to {Host}:{Port} failed: {Error}; next in {Delay}s",
attempt,
_options.Value.Host,
_options.Value.Port);
_options.Value.Port,
ex.GetBaseException().Message,
delaySeconds);
try
{
await Task.Delay(TimeSpan.FromSeconds(delaySeconds), stoppingToken).ConfigureAwait(false);
}
catch (OperationCanceledException)
{
return;
}
}
catch (OperationCanceledException)
{
return;
}
}
}
finally
{
await retryLoop.ConfigureAwait(false);
}
}
/// <summary>
@@ -273,6 +328,7 @@ public sealed class MqttPublisher : BackgroundService
public override void Dispose()
{
_client.DisconnectedAsync -= OnDisconnectedAsync;
_client.Dispose();
base.Dispose();
}
@@ -283,7 +339,9 @@ public sealed class MqttPublisher : BackgroundService
var builder = new MqttClientOptionsBuilder()
.WithTcpServer(opts.Host, opts.Port)
.WithClientId(opts.ClientId)
.WithCleanSession(false);
.WithCleanSession(false)
.WithKeepAlivePeriod(TimeSpan.FromSeconds(opts.KeepAliveSeconds))
.WithTimeout(TimeSpan.FromSeconds(opts.ConnectTimeoutSeconds));
if (!string.IsNullOrEmpty(opts.Username))
{