fix(modbus): transport self-heals with one throttled in-gate connect; PDU length check

P3: a torn-down socket is re-dialled inside the gate (one attempt per backoff
window) instead of failing fast with 'Transport not connected' until the 90 s
comms-loss watchdog re-initialised the driver.
L3: ConnectAsync disposes the previous/failed TcpClient, DNS runs under the
per-op timeout, and the reconnect never sleeps inside the gate (the old
10-attempt backoff held it for ~81 s).
H9: an MBAP response with no PDU, or an exception PDU with no code, is a
TruncatedFrame desync rather than an IndexOutOfRangeException.

Refs #741
Claude-Session: https://claude.ai/code/session_01Ub9hGmYLQvn9XETzw7CMsT
This commit is contained in:
Joseph Doherty
2026-10-22 15:02:11 -04:00
parent 7bcb6331ed
commit 530f1b2f0b
8 changed files with 655 additions and 70 deletions
@@ -56,6 +56,9 @@ public sealed class ModbusTcpTransport : IModbusTransport
_life = new ModbusSocketLifecycle(host, port, timeout, autoReconnect, keepAlive, idleDisconnect, reconnect);
}
/// <summary>The socket lifecycle this transport composes (test seam for its clock).</summary>
internal ModbusSocketLifecycle Lifecycle => _life;
/// <inheritdoc />
public Task ConnectAsync(CancellationToken ct) => _life.ConnectAsync(ct);
@@ -63,7 +66,6 @@ public sealed class ModbusTcpTransport : IModbusTransport
public async Task<byte[]> SendAsync(byte unitId, byte[] pdu, CancellationToken ct)
{
if (_disposed) throw new ObjectDisposedException(nameof(ModbusTcpTransport));
if (_life.Stream is null) throw new InvalidOperationException("Transport not connected");
await _gate.WaitAsync(ct).ConfigureAwait(false);
try
@@ -72,11 +74,16 @@ public sealed class ModbusTcpTransport : IModbusTransport
// threshold, tear it down + reconnect before this PDU lands. Defends against silent
// NAT / firewall reaping where the socket looks alive locally but the upstream side
// dropped it minutes ago.
if (_life.ShouldReconnectForIdle())
{
if (_life.Stream is not null && _life.ShouldReconnectForIdle())
await _life.TearDownAsync().ConfigureAwait(false);
await _life.ConnectWithBackoffAsync(ct).ConfigureAwait(false);
}
// Self-heal: a socket torn down by an earlier failure (two lost replies in a row, a refused
// reconnect) is re-dialled HERE, once, throttled by the backoff window. This used to throw
// "Transport not connected" before the gate, so the transport never recovered on its own and
// every call failed fast until the 90 s comms-loss watchdog re-initialised the whole driver.
var freshlyConnected = _life.Stream is null;
if (freshlyConnected)
await _life.EnsureConnectedAsync(ct).ConfigureAwait(false);
try
{
@@ -84,13 +91,16 @@ public sealed class ModbusTcpTransport : IModbusTransport
_life.MarkSuccess();
return result;
}
catch (Exception ex) when (_life.AutoReconnect && ModbusSocketLifecycle.IsSocketLevelFailure(ex))
catch (Exception ex) when (!freshlyConnected && _life.AutoReconnect
&& !ct.IsCancellationRequested
&& ModbusSocketLifecycle.IsSocketLevelFailure(ex))
{
// Mid-transaction drop: tear down the dead socket, reconnect (with backoff if
// configured), resend. Single retry — if it fails again, let it propagate so
// health/status reflect reality.
// Mid-transaction drop on a socket that had been live: tear down the dead socket, make ONE
// throttled reconnect attempt (never a sleep inside the gate), resend. Single retry — if it
// fails again, let it propagate so health/status reflect reality. A socket this call just
// dialled is not retried: it proved nothing about a stale connection.
await _life.TearDownAsync().ConfigureAwait(false);
await _life.ConnectWithBackoffAsync(ct).ConfigureAwait(false);
await _life.EnsureConnectedAsync(ct).ConfigureAwait(false);
var result = await SendOnceAsync(unitId, pdu, ct).ConfigureAwait(false);
_life.MarkSuccess();
return result;
@@ -162,10 +172,22 @@ public sealed class ModbusTcpTransport : IModbusTransport
var respPdu = new byte[respLen - 1];
await ReadExactlyAsync(stream, respPdu, cts.Token).ConfigureAwait(false);
// Length check before indexing: a PDU must carry at least its function code, and an exception
// PDU its exception code too. Indexing past the end used to throw IndexOutOfRangeException —
// not an IOException, so no teardown/retry, and a malformed reply read as a driver bug.
if (respPdu.Length < 1)
throw new ModbusTransportDesyncException(
ModbusTransportDesyncException.DesyncReason.TruncatedFrame,
"Modbus response carried no PDU (MBAP length 1)");
// Exception PDU: function code has high bit set. This is a well-formed protocol-level
// error — the socket is still coherent, so it MUST propagate without teardown.
if ((respPdu[0] & 0x80) != 0)
{
if (respPdu.Length < 2)
throw new ModbusTransportDesyncException(
ModbusTransportDesyncException.DesyncReason.TruncatedFrame,
$"Modbus exception response fc=0x{respPdu[0]:X2} carried no exception code");
var fc = (byte)(respPdu[0] & 0x7F);
var ex = respPdu[1];
throw new ModbusException(fc, ex, $"Modbus exception fc={fc} code={ex}");