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
+78 -20
View File
@@ -11,8 +11,9 @@ namespace FrameProcessor.Mqtt;
/// <summary> /// <summary>
/// Persistent MQTT client wrapped in a hosted service. Connects on startup and /// Persistent MQTT client wrapped in a hosted service. Connects on startup and
/// reconnects in the background after disconnects. Connection state is surfaced /// reconnects in the background after disconnects using
/// via <see cref="IsConnected"/> for the <c>/health</c> endpoint. /// <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 /// On publish failure the (mac → topic, payload) pair is enqueued for retry; a
/// background loop drains the queue using <see cref="MqttOptions.RetryBackoffSeconds"/>. /// background loop drains the queue using <see cref="MqttOptions.RetryBackoffSeconds"/>.
@@ -21,8 +22,6 @@ namespace FrameProcessor.Mqtt;
/// </summary> /// </summary>
public sealed class MqttPublisher : BackgroundService public sealed class MqttPublisher : BackgroundService
{ {
private static readonly TimeSpan ReconnectDelay = TimeSpan.FromSeconds(5);
private readonly IOptions<MqttOptions> _options; private readonly IOptions<MqttOptions> _options;
private readonly ILogger<MqttPublisher> _logger; private readonly ILogger<MqttPublisher> _logger;
private readonly IMqttClient _client; private readonly IMqttClient _client;
@@ -30,12 +29,15 @@ public sealed class MqttPublisher : BackgroundService
private readonly ConcurrentDictionary<MacAddress, byte> _pending = new(); private readonly ConcurrentDictionary<MacAddress, byte> _pending = new();
private readonly Channel<bool> _wakeup = Channel.CreateBounded<bool>( private readonly Channel<bool> _wakeup = Channel.CreateBounded<bool>(
new BoundedChannelOptions(1) { FullMode = BoundedChannelFullMode.DropWrite }); 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) public MqttPublisher(IOptions<MqttOptions> options, ILogger<MqttPublisher> logger)
{ {
_options = options; _options = options;
_logger = logger; _logger = logger;
_client = new MqttFactory().CreateMqttClient(); _client = new MqttFactory().CreateMqttClient();
_client.DisconnectedAsync += OnDisconnectedAsync;
} }
public bool IsConnected => _client.IsConnected; 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", "Initial MQTT connect to {Host}:{Port} failed; background reconnect will retry",
_options.Value.Host, _options.Value.Host,
_options.Value.Port); _options.Value.Port);
_reconnect.Writer.TryWrite(true);
} }
await base.StartAsync(cancellationToken).ConfigureAwait(false); await base.StartAsync(cancellationToken).ConfigureAwait(false);
@@ -68,45 +71,97 @@ public sealed class MqttPublisher : BackgroundService
try try
{ {
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) while (!stoppingToken.IsCancellationRequested)
{ {
using (var idleCts = CancellationTokenSource.CreateLinkedTokenSource(stoppingToken))
{
idleCts.CancelAfter(idleCheck);
try 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) catch (OperationCanceledException)
{ {
return; return;
} }
if (_client.IsConnected)
{
continue;
} }
var attempt = 0;
while (!_client.IsConnected && !stoppingToken.IsCancellationRequested)
{
attempt++;
try try
{ {
await _client.ConnectAsync(BuildClientOptions(), stoppingToken).ConfigureAwait(false); await _client.ConnectAsync(BuildClientOptions(), stoppingToken).ConfigureAwait(false);
_logger.LogInformation( _logger.LogInformation(
"MQTT reconnected to {Host}:{Port}", "MQTT reconnected to {Host}:{Port} after {Attempt} attempt(s)",
_options.Value.Host, _options.Value.Host,
_options.Value.Port); _options.Value.Port,
attempt);
// Drain any queued publishes immediately now that the link is back up. // Drain any queued publishes immediately now that the link is back up.
_wakeup.Writer.TryWrite(true); _wakeup.Writer.TryWrite(true);
} }
catch (Exception ex) when (!stoppingToken.IsCancellationRequested) catch (Exception ex) when (!stoppingToken.IsCancellationRequested)
{ {
var delaySeconds = backoff[Math.Min(attempt - 1, backoff.Length - 1)];
_logger.LogWarning( _logger.LogWarning(
ex, "MQTT reconnect attempt {Attempt} to {Host}:{Port} failed: {Error}; next in {Delay}s",
"MQTT reconnect to {Host}:{Port} failed", attempt,
_options.Value.Host, _options.Value.Host,
_options.Value.Port); _options.Value.Port,
} ex.GetBaseException().Message,
} delaySeconds);
}
finally try
{ {
await retryLoop.ConfigureAwait(false); await Task.Delay(TimeSpan.FromSeconds(delaySeconds), stoppingToken).ConfigureAwait(false);
}
catch (OperationCanceledException)
{
return;
}
}
catch (OperationCanceledException)
{
return;
}
}
} }
} }
@@ -273,6 +328,7 @@ public sealed class MqttPublisher : BackgroundService
public override void Dispose() public override void Dispose()
{ {
_client.DisconnectedAsync -= OnDisconnectedAsync;
_client.Dispose(); _client.Dispose();
base.Dispose(); base.Dispose();
} }
@@ -283,7 +339,9 @@ public sealed class MqttPublisher : BackgroundService
var builder = new MqttClientOptionsBuilder() var builder = new MqttClientOptionsBuilder()
.WithTcpServer(opts.Host, opts.Port) .WithTcpServer(opts.Host, opts.Port)
.WithClientId(opts.ClientId) .WithClientId(opts.ClientId)
.WithCleanSession(false); .WithCleanSession(false)
.WithKeepAlivePeriod(TimeSpan.FromSeconds(opts.KeepAliveSeconds))
.WithTimeout(TimeSpan.FromSeconds(opts.ConnectTimeoutSeconds));
if (!string.IsNullOrEmpty(opts.Username)) if (!string.IsNullOrEmpty(opts.Username))
{ {