Reliable MQTT auto-reconnect #1

Merged
zyberzero merged 3 commits from mqtt-auto-reconnect into main 2026-11-03 17:56:35 +00:00
6 changed files with 123 additions and 27 deletions

No files matched your search

+7 -1
View File
@@ -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
+9 -3
View File
@@ -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<Pending>` 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 <net> <frame-processor container>` → 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.
+16 -2
View File
@@ -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": {
+4 -1
View File
@@ -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": {
@@ -32,4 +32,13 @@ public sealed class MqttOptions
[MinLength(1)]
public int[] RetryBackoffSeconds { get; set; } = Array.Empty<int>();
[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;
}
+78 -20
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,45 +71,97 @@ public sealed class MqttPublisher : BackgroundService
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)
{
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);
}
}
}
finally
_options.Value.Port,
ex.GetBaseException().Message,
delaySeconds);
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()
{
_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))
{