feat: preserve grpc write admission and uncertain outcomes

This commit is contained in:
Joseph Doherty
2026-11-16 03:56:13 -05:00
parent 8f28a0eabf
commit 862dbc8e90
37 changed files with 3686 additions and 70 deletions
@@ -24,6 +24,13 @@ public interface IModbusTransport : IAsyncDisposable
Task<byte[]> SendAsync(byte unitId, byte[] pdu, CancellationToken ct);
}
/// <summary>Transport that can issue one transaction without resending it after an ambiguous failure.</summary>
public interface IModbusWriteOnceTransport : IModbusTransport
{
/// <summary>Sends once; reconnecting before the first send is permitted, replay after send is not.</summary>
Task<byte[]> SendWithoutRetryAsync(byte unitId, byte[] pdu, CancellationToken ct);
}
/// <summary>Represents a Modbus protocol exception.</summary>
public sealed class ModbusException(byte functionCode, byte exceptionCode, string message)
: Exception(message)
@@ -5,6 +5,7 @@ using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Abstractions;
using ZB.MOM.WW.OtOpcUa.Commons.Observability;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections;
namespace ZB.MOM.WW.OtOpcUa.Driver.Modbus;
@@ -20,7 +21,7 @@ namespace ZB.MOM.WW.OtOpcUa.Driver.Modbus;
/// <see cref="PollGroupEngine"/> since Modbus has no native push model.
/// </remarks>
public sealed class ModbusDriver
: IDriver, ITagDiscovery, IReadable, IWritable, IBatchSubscribable, IHostConnectivityProbe, IPerCallHostResolver, ISkippedTagReporter, IDisposable, IAsyncDisposable
: IDriver, ITagDiscovery, IReadable, IWritable, IWriteOutcomeCapability, IBatchSubscribable, IHostConnectivityProbe, IPerCallHostResolver, ISkippedTagReporter, IDisposable, IAsyncDisposable
{
/// <summary>Authored tags this driver could not build into its poll table.</summary>
private readonly SkippedTagLedger _skippedTags = new();
@@ -1477,6 +1478,112 @@ public sealed class ModbusDriver
// ---- IWritable ----
/// <inheritdoc />
public async Task<IReadOnlyList<DataWriteOutcome>> WriteWithOutcomesAsync(
IReadOnlyList<WriteRequest> writes, CancellationToken cancellationToken)
{
var (generation, transport, table) = CaptureLifecycle();
var results = new DataWriteOutcome[writes.Count];
var batch = new BatchOutcome();
for (var i = 0; i < writes.Count; i++)
{
var write = writes[i];
if (!table.TryGetValue(write.FullReference, out var tag))
{
results[i] = new(DataWriteState.RejectedBeforeDispatch, StatusBadNodeIdUnknown, "Unknown tag.");
continue;
}
if (!tag.Writable || tag.Region is ModbusRegion.DiscreteInputs or ModbusRegion.InputRegisters)
{
results[i] = new(DataWriteState.RejectedBeforeDispatch, StatusBadNotWritable, "Tag is not writable.");
continue;
}
if (transport is not IModbusWriteOnceTransport once)
{
results[i] = new(DataWriteState.RejectedBeforeDispatch, StatusBadNotSupported, "Transport cannot guarantee a single send.");
continue;
}
if (cancellationToken.IsCancellationRequested)
{
results[i] = new(DataWriteState.RejectedBeforeDispatch, StatusBadTimeout, "Canceled before dispatch.");
continue;
}
if (_options.WriteOnChangeOnly && IsRedundantWrite(write.FullReference, write.Value))
{
results[i] = new(DataWriteState.AcceptedUnconfirmed, 0, "Write suppressed without a new device acknowledgement.");
continue;
}
var unit = ResolveUnitId(tag);
if (batch.IsFailedFast(unit))
{
results[i] = new(DataWriteState.RejectedBeforeDispatch, StatusBadCommunicationError, "Batch stopped before dispatch.");
continue;
}
var tracked = new SingleSendWriteTransport(once);
try
{
await WriteOneAsync(tracked, tag, write.Value, cancellationToken).ConfigureAwait(false);
results[i] = tracked.ValidWriteAcknowledged
? new(DataWriteState.DriverConfirmedSuccess, 0, null)
: new(DataWriteState.OutcomeUnknown, StatusBadCommunicationError, "No confirmed write response.");
batch.Answered = true;
if (_options.WriteOnChangeOnly && tracked.ValidWriteAcknowledged)
lock (_lastWrittenLock) _lastWrittenByRef[write.FullReference] = write.Value;
}
catch (Exception ex)
{
var status = MapWriteFailure(ex, unit, write.FullReference, batch, cancellationToken);
var state = tracked.DefinitiveRefusal ? DataWriteState.DriverConfirmedFailure :
!tracked.WriteAttempted && ex is (ModbusWriteRefusedException or OverflowException or FormatException or
InvalidCastException or ArgumentException or NotSupportedException)
? DataWriteState.RejectedBeforeDispatch : DataWriteState.OutcomeUnknown;
results[i] = new(state, status, ex.Message);
InvalidateWriteCache(write.FullReference);
}
}
ReportOutcome(generation, batch, DateTime.UtcNow);
return results;
}
/// <summary>Tracks actual write PDUs and validates their protocol responses without altering the legacy path.</summary>
private sealed class SingleSendWriteTransport(IModbusWriteOnceTransport transport) : IModbusTransport
{
public bool WriteAttempted { get; private set; }
public bool ValidWriteAcknowledged { get; private set; }
public bool DefinitiveRefusal { get; private set; }
public Task ConnectAsync(CancellationToken ct) => throw new NotSupportedException();
public ValueTask DisposeAsync() => ValueTask.CompletedTask;
public async Task<byte[]> SendAsync(byte unitId, byte[] pdu, CancellationToken ct)
{
var isWrite = pdu[0] is 0x05 or 0x06 or 0x0F or 0x10 or 0x17;
if (isWrite)
{
WriteAttempted = true;
ValidWriteAcknowledged = false;
DefinitiveRefusal = false;
}
byte[] reply;
try { reply = await transport.SendWithoutRetryAsync(unitId, pdu, ct).ConfigureAwait(false); }
catch (ModbusException ex)
{
// A response for another function cannot establish that this write was refused.
// In particular, don't let FC23's illegal-function fallback replay an ambiguous write.
if (isWrite && ex.FunctionCode != pdu[0])
throw new InvalidDataException("Modbus exception function did not match the write request.", ex);
DefinitiveRefusal = isWrite && ex.FunctionCode == pdu[0] && ex.ExceptionCode is (1 or 2 or 3);
throw;
}
if (!isWrite) return reply;
var valid = pdu[0] == 0x17
? reply.Length == 2 + 2 * ((pdu[3] << 8) | pdu[4]) && reply[0] == pdu[0] && reply[1] == reply.Length - 2
: reply.Length == 5 && reply.AsSpan().SequenceEqual(pdu.AsSpan(0, 5));
if (!valid) throw new InvalidDataException("Modbus write acknowledgement did not match the request.");
ValidWriteAcknowledged = true;
return reply;
}
}
/// <inheritdoc />
public async Task<IReadOnlyList<WriteResult>> WriteAsync(
IReadOnlyList<WriteRequest> writes, CancellationToken cancellationToken)
@@ -41,7 +41,7 @@ namespace ZB.MOM.WW.OtOpcUa.Driver.Modbus;
/// skipped (a raw injected stream cannot reconnect).
/// </para>
/// </remarks>
public sealed class ModbusRtuOverTcpTransport : IModbusTransport
public sealed class ModbusRtuOverTcpTransport : IModbusWriteOnceTransport
{
private readonly ModbusSocketLifecycle? _life;
private readonly Stream? _testStream;
@@ -89,7 +89,12 @@ public sealed class ModbusRtuOverTcpTransport : IModbusTransport
_life is null ? Task.CompletedTask : _life.ConnectAsync(ct);
/// <inheritdoc />
public async Task<byte[]> SendAsync(byte unitId, byte[] pdu, CancellationToken ct)
public Task<byte[]> SendAsync(byte unitId, byte[] pdu, CancellationToken ct) => SendCoreAsync(unitId, pdu, ct, true);
/// <inheritdoc />
public Task<byte[]> SendWithoutRetryAsync(byte unitId, byte[] pdu, CancellationToken ct) => SendCoreAsync(unitId, pdu, ct, false);
private async Task<byte[]> SendCoreAsync(byte unitId, byte[] pdu, CancellationToken ct, bool allowRetry)
{
if (Volatile.Read(ref _disposed) != 0) throw new ObjectDisposedException(nameof(ModbusRtuOverTcpTransport));
if (_life is null && _testStream is null) throw new InvalidOperationException("Transport not connected");
@@ -117,7 +122,7 @@ public sealed class ModbusRtuOverTcpTransport : IModbusTransport
_life?.MarkSuccess();
return result;
}
catch (Exception ex) when (!freshlyConnected && _life is not null && _life.AutoReconnect
catch (Exception ex) when (allowRetry && !freshlyConnected && _life is not null && _life.AutoReconnect
&& !ct.IsCancellationRequested
&& ModbusSocketLifecycle.IsSocketLevelFailure(ex))
{
@@ -131,6 +136,11 @@ public sealed class ModbusRtuOverTcpTransport : IModbusTransport
_life.MarkSuccess();
return result;
}
catch (Exception ex) when (!allowRetry && (ex is OperationCanceledException || ModbusSocketLifecycle.IsSocketLevelFailure(ex)))
{
if (_life is not null) await _life.TearDownAsync().ConfigureAwait(false);
throw;
}
}
finally
{
@@ -31,7 +31,7 @@ namespace ZB.MOM.WW.OtOpcUa.Driver.Modbus;
/// socket in reasonable time even when the application is mostly idle.
/// </para>
/// </remarks>
public sealed class ModbusTcpTransport : IModbusTransport
public sealed class ModbusTcpTransport : IModbusWriteOnceTransport
{
private readonly ModbusSocketLifecycle _life;
private readonly TimeSpan _timeout;
@@ -68,7 +68,12 @@ public sealed class ModbusTcpTransport : IModbusTransport
public Task ConnectAsync(CancellationToken ct) => _life.ConnectAsync(ct);
/// <inheritdoc />
public async Task<byte[]> SendAsync(byte unitId, byte[] pdu, CancellationToken ct)
public Task<byte[]> SendAsync(byte unitId, byte[] pdu, CancellationToken ct) => SendCoreAsync(unitId, pdu, ct, true);
/// <inheritdoc />
public Task<byte[]> SendWithoutRetryAsync(byte unitId, byte[] pdu, CancellationToken ct) => SendCoreAsync(unitId, pdu, ct, false);
private async Task<byte[]> SendCoreAsync(byte unitId, byte[] pdu, CancellationToken ct, bool allowRetry)
{
if (Volatile.Read(ref _disposed) != 0) throw new ObjectDisposedException(nameof(ModbusTcpTransport));
@@ -92,11 +97,11 @@ public sealed class ModbusTcpTransport : IModbusTransport
try
{
var result = await SendOnceAsync(unitId, pdu, ct).ConfigureAwait(false);
var result = await SendOnceAsync(unitId, pdu, ct, strictResponse: !allowRetry).ConfigureAwait(false);
_life.MarkSuccess();
return result;
}
catch (Exception ex) when (!freshlyConnected && _life.AutoReconnect
catch (Exception ex) when (allowRetry && !freshlyConnected && _life.AutoReconnect
&& !ct.IsCancellationRequested
&& ModbusSocketLifecycle.IsSocketLevelFailure(ex))
{
@@ -106,10 +111,16 @@ public sealed class ModbusTcpTransport : IModbusTransport
// dialled is not retried: it proved nothing about a stale connection.
await _life.TearDownAsync().ConfigureAwait(false);
await _life.EnsureConnectedAsync(ct).ConfigureAwait(false);
var result = await SendOnceAsync(unitId, pdu, ct).ConfigureAwait(false);
var result = await SendOnceAsync(unitId, pdu, ct, strictResponse: false).ConfigureAwait(false);
_life.MarkSuccess();
return result;
}
catch (Exception ex) when (!allowRetry && (ex is OperationCanceledException || ModbusSocketLifecycle.IsSocketLevelFailure(ex)))
{
// The response might still arrive; do not reuse this socket and never replay the PDU.
await _life.TearDownAsync().ConfigureAwait(false);
throw;
}
}
finally
{
@@ -138,7 +149,7 @@ public sealed class ModbusTcpTransport : IModbusTransport
/// per-op timeout (the caller token is NOT cancelled) is a desync.
/// </para>
/// </remarks>
private async Task<byte[]> SendOnceAsync(byte unitId, byte[] pdu, CancellationToken ct)
private async Task<byte[]> SendOnceAsync(byte unitId, byte[] pdu, CancellationToken ct, bool strictResponse)
{
var stream = _life.Stream;
if (stream is null) throw new InvalidOperationException("Transport not connected");
@@ -169,6 +180,9 @@ public sealed class ModbusTcpTransport : IModbusTransport
var header = _header;
await ReadExactlyAsync(stream, header, cts.Token).ConfigureAwait(false);
if (strictResponse && (header[2] != 0 || header[3] != 0 || header[6] != unitId))
throw new ModbusTransportDesyncException(ModbusTransportDesyncException.DesyncReason.UnitMismatch,
"Modbus response protocol or unit does not match the request.");
var respTxId = (ushort)((header[0] << 8) | header[1]);
if (respTxId != txId)
throw new ModbusTransportDesyncException(