From 917a149bc2367d90a667466b5c7fd35a8f674fe2 Mon Sep 17 00:00:00 2001 From: Fritiof Hedman Date: Tue, 3 Nov 2026 18:51:43 +0100 Subject: [PATCH] Reconnect MQTT on disconnect events with backoff Replace the hardcoded 5 s IsConnected poll with a loop driven by DisconnectedAsync (plus an idle safety check), retrying on the ReconnectBackoffSeconds schedule. Disconnects are now logged with their reason, and keep-alive and connect timeout come from config so dead links are detected and connect attempts can't block for 100 s. Co-Authored-By: Claude Opus 5.5 (1M context) --- src/FrameProcessor/Mqtt/MqttPublisher.cs | 100 ++++++++++++++++++----- 1 file changed, 79 insertions(+), 21 deletions(-) diff --git a/src/FrameProcessor/Mqtt/MqttPublisher.cs b/src/FrameProcessor/Mqtt/MqttPublisher.cs index 83d20ca..be2cf49 100644 --- a/src/FrameProcessor/Mqtt/MqttPublisher.cs +++ b/src/FrameProcessor/Mqtt/MqttPublisher.cs @@ -11,8 +11,9 @@ namespace FrameProcessor.Mqtt; /// /// Persistent MQTT client wrapped in a hosted service. Connects on startup and -/// reconnects in the background after disconnects. Connection state is surfaced -/// via for the /health endpoint. +/// reconnects in the background after disconnects using +/// (SPEC.md §5.2). Connection state +/// is surfaced via for the /health endpoint. /// /// On publish failure the (mac → topic, payload) pair is enqueued for retry; a /// background loop drains the queue using . @@ -21,8 +22,6 @@ namespace FrameProcessor.Mqtt; /// public sealed class MqttPublisher : BackgroundService { - private static readonly TimeSpan ReconnectDelay = TimeSpan.FromSeconds(5); - private readonly IOptions _options; private readonly ILogger _logger; private readonly IMqttClient _client; @@ -30,12 +29,15 @@ public sealed class MqttPublisher : BackgroundService private readonly ConcurrentDictionary _pending = new(); private readonly Channel _wakeup = Channel.CreateBounded( new BoundedChannelOptions(1) { FullMode = BoundedChannelFullMode.DropWrite }); + private readonly Channel _reconnect = Channel.CreateBounded( + new BoundedChannelOptions(1) { FullMode = BoundedChannelFullMode.DropWrite }); public MqttPublisher(IOptions options, ILogger 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); - } } /// @@ -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)) {