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": {