From 8dd42d24bc7e06c485060897275e73b1d59fbb32 Mon Sep 17 00:00:00 2001 From: Fritiof Hedman Date: Tue, 3 Nov 2026 18:51:43 +0100 Subject: [PATCH 1/3] Specify MQTT reconnect behavior MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Add SPEC.md §5.2 describing reconnect requirements (backoff, keep-alive detection, disconnect logging, unique ClientId), the new Mqtt config keys, the matching PLAN.md design and verification steps, and IMPLEMENTATION.md increment 6.6. Also drop the stale WithReconnectDelay reference, which only exists on ManagedMqttClient. Co-Authored-By: Claude Opus 5.5 (1M context) --- IMPLEMENTATION.md | 8 +++++++- PLAN.md | 12 +++++++++--- SPEC.md | 18 ++++++++++++++++-- 3 files changed, 32 insertions(+), 6 deletions(-) diff --git a/IMPLEMENTATION.md b/IMPLEMENTATION.md index e5b54d9..add3577 100644 --- a/IMPLEMENTATION.md +++ b/IMPLEMENTATION.md @@ -153,7 +153,7 @@ Each type lives in `src/FrameProcessor/Domain/`. Tests in `tests/FrameProcessor. ### [x] 6.1 `MqttPublisher` hosted service - Singleton `IHostedService` wrapping `IMqttClient` (MQTTnet v4). -- `WithReconnectDelay`, `WithCleanSession(false)`, credentials/TLS from `MqttOptions`. +- `WithCleanSession(false)`, credentials/TLS from `MqttOptions`. (Reconnect is hand-rolled — see 6.6.) - Exposes `bool IsConnected` for `/health`. - On `StartAsync`: connect; on failure, log and continue (background reconnect handles it). @@ -173,6 +173,12 @@ Each type lives in `src/FrameProcessor/Domain/`. Tests in `tests/FrameProcessor. - On reconnect, drain immediately. - **Manual check:** stop broker, upload → 200 with `mqttPublished: false`; restart broker → `mosquitto_sub` sees the message within backoff window. +### [ ] 6.6 Reliable auto-reconnect (`SPEC.md` §5.2) +- `MqttOptions`: `ReconnectBackoffSeconds`, `KeepAliveSeconds`, `ConnectTimeoutSeconds`; wire keep-alive + connect timeout into `BuildClientOptions()`. +- `DisconnectedAsync` handler logs the reason and signals a `_reconnect` channel; only `ExecuteAsync` calls `ConnectAsync`. +- Reconnect loop uses the backoff schedule (capped, reset on success) instead of the hardcoded 5 s poll; wakes the retry queue on success. +- **Manual check:** `PLAN.md` verification items 7, 7a, 7b. + --- ## Phase 7 — URL-fetch ingestion diff --git a/PLAN.md b/PLAN.md index 8a7e192..6b3b3ea 100644 --- a/PLAN.md +++ b/PLAN.md @@ -88,7 +88,10 @@ frames.json // mounted; not in image "UseTls": false, "BaseTopic": "frames", "PublishQos": 1, - "RetryBackoffSeconds": [1, 2, 5, 15, 60] + "RetryBackoffSeconds": [1, 2, 5, 15, 60], + "ReconnectBackoffSeconds": [1, 2, 5, 15, 30], + "KeepAliveSeconds": 15, + "ConnectTimeoutSeconds": 10 }, "ApiKey": "change-me", "Storage": { @@ -170,7 +173,8 @@ For each upload: ## MQTT - `MQTTnet` v4 with `IMqttClient` wrapped in a hosted service (`MqttPublisher : IHostedService`). -- Single persistent connection with `WithReconnectDelay` and `WithCleanSession(false)`. Connection state surfaced to `/health`. +- Single persistent connection with `WithCleanSession(false)`, `WithKeepAlivePeriod(KeepAliveSeconds)` and `WithTimeout(ConnectTimeoutSeconds)`. Connection state surfaced to `/health`. +- **Reconnect** (SPEC.md §5.2): `IMqttClient` has no built-in reconnect, so `MqttPublisher` owns it. A `DisconnectedAsync` handler logs the reason and signals a bounded(1) `_reconnect` channel — it never calls `ConnectAsync` itself, so connects are never concurrent. `ExecuteAsync` waits on that signal (or a safety timeout equal to the last backoff value, in case an event is missed), then retries `ConnectAsync` on the `ReconnectBackoffSeconds` schedule until connected. On success it resets the schedule and wakes the retry loop so queued publishes drain immediately. - Publish: `topic = {BaseTopic}/{normalized-mac}`, payload bytes `"update"`, QoS 1, not retained. - **Failure handling**: `MqttPublisher.PublishAsync` returns a `Result` (success/failure). If failure, the publisher enqueues the (topic, payload) into an in-memory `Channel` and a background loop drains it with the configured backoff sequence. The upload response includes `mqttPublished: false` so callers know. @@ -203,6 +207,8 @@ No controller/integration tests in v1 — pipeline correctness is the load-beari 4. Subscribe with `mosquitto_sub -t 'frames/#' -v` → confirm `frames/aabbccddeeff update` appears within ~1s of the upload. 5. Repeat with `/image-url` and a public image URL. 6. Concurrency check: fire two `curl` uploads to the same frame in parallel → both return 200, only one final PNG on disk, two MQTT publishes (in serial order). -7. Stop the broker, upload an image → response is 200 with `mqttPublished: false`, PNG saved, log shows retry attempts. Start the broker → background retry publishes successfully. +7. Stop the broker, upload an image → response is 200 with `mqttPublished: false`, PNG saved, log shows the disconnect reason and backoff reconnect attempts. Start the broker → service reconnects without a restart, `/health` flips back to `mqttConnected: true`, and the queued publish goes out immediately. +7a. Half-open link: `docker network disconnect ` → disconnect logged within ~1.5 × `KeepAliveSeconds`; reconnect the network → service recovers on its own. +7b. ClientId collision: run a second instance with the same `ClientId` against the same broker → logs show `SessionTakenOver`. Use a distinct `Mqtt__ClientId` for local dev. 8. Run `dotnet test` → golden-image fixtures pass. 9. Power on the actual Spectra 6 frame mounted with the new firmware → it fetches the PNG and renders it correctly with the expected color mapping. diff --git a/SPEC.md b/SPEC.md index e2dae8e..00c3759 100644 --- a/SPEC.md +++ b/SPEC.md @@ -114,7 +114,7 @@ Fetch the most recent processed PNG for a frame. ## 5. MQTT contract - **Broker:** configured in `appsettings.json` (host, port, credentials, TLS). -- **Client:** persistent connection with automatic reconnect; clean session = false. +- **Client:** persistent connection with automatic reconnect (see §5.2); clean session = false. - **Publish:** - **Topic:** `{baseTopic}/{normalized-mac}` — `baseTopic` is configurable (default `frames`); `normalized-mac` is lowercase hex with no separators (e.g., `aabbccddeeff`). - **Payload:** the UTF-8 bytes of the literal string `update`. @@ -127,6 +127,17 @@ The service is a publisher only. It does not subscribe to any topics. If a publish attempt fails, the (topic, payload) is enqueued for retry. Retries occur on a configurable backoff schedule (default `[1, 2, 5, 15, 60]` seconds). A successful publish drains the corresponding queue entry. Multiple queued publishes for the same frame collapse to the most recent one. +### 5.2 Connection & reconnect + +- The service connects at startup. A failed initial connect does not block startup; the service serves HTTP while reconnecting in the background. +- If the connection drops for any reason (broker restart, network loss, keep-alive timeout, session takeover, auth failure), the service reconnects **without operator action and without a process restart**. +- Reconnect attempts follow `ReconnectBackoffSeconds` (default `[1, 2, 5, 15, 30]` seconds), capped at the last value. The schedule resets after a successful connect. +- A silently dead link (half-open TCP) is detected via MQTT keep-alive within roughly 1.5 × `KeepAliveSeconds`. Each connect attempt is bounded by `ConnectTimeoutSeconds`. +- Every disconnect is logged with its reason; every failed reconnect attempt is logged with the attempt number and the delay until the next one. +- `/health` `mqttConnected` reflects the live connection state. +- Queued retries (§5.1) drain immediately after a successful reconnect. +- `ClientId` must be unique per broker. Two instances sharing one will repeatedly disconnect each other (`SessionTakenOver`). + ## 6. Configuration ### 6.1 Application configuration — `appsettings.json` @@ -142,7 +153,10 @@ If a publish attempt fails, the (topic, payload) is enqueued for retry. Retries "UseTls": false, "BaseTopic": "frames", "PublishQos": 1, - "RetryBackoffSeconds": [1, 2, 5, 15, 60] + "RetryBackoffSeconds": [1, 2, 5, 15, 60], + "ReconnectBackoffSeconds": [1, 2, 5, 15, 30], + "KeepAliveSeconds": 15, + "ConnectTimeoutSeconds": 10 }, "ApiKey": "change-me", "Storage": { From e22b2038d0bd6efb0e014e7adc5f2ac27886d78a Mon Sep 17 00:00:00 2001 From: Fritiof Hedman Date: Tue, 3 Nov 2026 18:51:43 +0100 Subject: [PATCH 2/3] Add MQTT reconnect, keep-alive and connect timeout options Co-Authored-By: Claude Opus 5.5 (1M context) --- appsettings.json | 5 ++++- src/FrameProcessor/Configuration/MqttOptions.cs | 9 +++++++++ 2 files changed, 13 insertions(+), 1 deletion(-) diff --git a/appsettings.json b/appsettings.json index 9492e16..673c7da 100644 --- a/appsettings.json +++ b/appsettings.json @@ -8,7 +8,10 @@ "UseTls": false, "BaseTopic": "frames", "PublishQos": 1, - "RetryBackoffSeconds": [1, 2, 5, 15, 60] + "RetryBackoffSeconds": [1, 2, 5, 15, 60], + "ReconnectBackoffSeconds": [1, 2, 5, 15, 30], + "KeepAliveSeconds": 15, + "ConnectTimeoutSeconds": 10 }, "ApiKey": "change-me", "Storage": { diff --git a/src/FrameProcessor/Configuration/MqttOptions.cs b/src/FrameProcessor/Configuration/MqttOptions.cs index 6c7c845..fb2eb96 100644 --- a/src/FrameProcessor/Configuration/MqttOptions.cs +++ b/src/FrameProcessor/Configuration/MqttOptions.cs @@ -32,4 +32,13 @@ public sealed class MqttOptions [MinLength(1)] public int[] RetryBackoffSeconds { get; set; } = Array.Empty(); + + [MinLength(1)] + public int[] ReconnectBackoffSeconds { get; set; } = [1, 2, 5, 15, 30]; + + [Range(1, 3600)] + public int KeepAliveSeconds { get; set; } = 15; + + [Range(1, 300)] + public int ConnectTimeoutSeconds { get; set; } = 10; } From 917a149bc2367d90a667466b5c7fd35a8f674fe2 Mon Sep 17 00:00:00 2001 From: Fritiof Hedman Date: Tue, 3 Nov 2026 18:51:43 +0100 Subject: [PATCH 3/3] 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)) {