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) <noreply@anthropic.com>
This commit is contained in:
1 parent
e22b2038d0
commit
917a149bc2
1 file changed
+79
-21
@@ -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,46 +71,98 @@ public sealed class MqttPublisher : BackgroundService
|
|||||||
|
|
||||||
try
|
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
|
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)
|
var attempt = 0;
|
||||||
{
|
while (!_client.IsConnected && !stoppingToken.IsCancellationRequested)
|
||||||
continue;
|
{
|
||||||
}
|
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);
|
||||||
|
|
||||||
|
try
|
||||||
|
{
|
||||||
|
await Task.Delay(TimeSpan.FromSeconds(delaySeconds), stoppingToken).ConfigureAwait(false);
|
||||||
|
}
|
||||||
|
catch (OperationCanceledException)
|
||||||
|
{
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
catch (OperationCanceledException)
|
||||||
|
{
|
||||||
|
return;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
finally
|
|
||||||
{
|
|
||||||
await retryLoop.ConfigureAwait(false);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
@@ -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))
|
||||||
{
|
{
|
||||||
|
|||||||
Reference in new issue
Block a user