using System.Net;
using System.Net.Sockets;
using Shouldly;
using Xunit;
namespace ZB.MOM.WW.OtOpcUa.Driver.Modbus.Tests;
///
/// #981 / S-1 — a CALLER-cancelled transaction must never leave its reply in flight on a reused socket.
/// RTU has no transaction id, so a late reply would be read as the NEXT request's answer and published at
/// Good; the plain TCP transport matches transaction ids, but a cancel mid-frame can still leave half a
/// frame buffered. Both transports therefore discard the socket on any exit after the request was written
/// without a complete validated reply. Real loopback sockets: the teardown is only observable there.
///
[Trait("Category", "Unit")]
public sealed class ModbusCallerCancelDesyncTests
{
///
/// Loopback device. The reply to request index 0 is withheld until ; every
/// other request is answered immediately. An FC03 reply carries the requested start address as its
/// single register value, so a test can tell WHOSE reply it received. Speaks RTU or MBAP framing.
///
private sealed class LateReplyServer : IAsyncDisposable
{
private readonly TcpListener _listener = new(IPAddress.Loopback, 0);
private readonly CancellationTokenSource _stop = new();
private readonly TaskCompletionSource _firstReceived = new(TaskCreationOptions.RunContinuationsAsynchronously);
private readonly TaskCompletionSource _releaseFirst = new(TaskCreationOptions.RunContinuationsAsynchronously);
private readonly bool _rtu;
private int _requests;
private int _accepted;
public LateReplyServer(bool rtu)
{
_rtu = rtu;
_listener.Start();
_ = Task.Run(AcceptLoopAsync);
}
public int Port => ((IPEndPoint)_listener.LocalEndpoint).Port;
public int Accepted => Volatile.Read(ref _accepted);
public Task FirstReceived => _firstReceived.Task;
public void ReleaseFirst() => _releaseFirst.TrySetResult();
private async Task AcceptLoopAsync()
{
while (!_stop.IsCancellationRequested)
{
TcpClient client;
try { client = await _listener.AcceptTcpClientAsync(_stop.Token); }
catch { return; }
Interlocked.Increment(ref _accepted);
_ = Task.Run(() => ServeAsync(client));
}
}
private async Task ServeAsync(TcpClient client)
{
using var _ = client;
try
{
var s = client.GetStream();
while (!_stop.IsCancellationRequested)
{
// RTU request: unit, FC, addr(2), qty(2), crc(2) = 8. MBAP: 7-byte header + 5-byte PDU.
var req = new byte[_rtu ? 8 : 12];
if (!await ReadExactly(s, req)) return;
var idx = Interlocked.Increment(ref _requests) - 1;
var pduOffset = _rtu ? 1 : 7;
var addr = (ushort)((req[pduOffset + 1] << 8) | req[pduOffset + 2]);
if (idx == 0)
{
_firstReceived.TrySetResult();
await _releaseFirst.Task.WaitAsync(_stop.Token);
}
var pdu = new byte[] { 0x03, 0x02, (byte)(addr >> 8), (byte)addr };
byte[] reply;
if (_rtu)
{
reply = ModbusCrc.Append(new byte[] { req[0] }.Concat(pdu).ToArray());
}
else
{
reply = new byte[7 + pdu.Length];
Array.Copy(req, reply, 4); // TxId + protocol id
reply[5] = (byte)(1 + pdu.Length);
reply[6] = req[6];
Array.Copy(pdu, 0, reply, 7, pdu.Length);
}
await s.WriteAsync(reply, _stop.Token);
await s.FlushAsync(_stop.Token);
}
}
catch { /* connection torn down */ }
}
private static async Task ReadExactly(NetworkStream s, byte[] buf)
{
var read = 0;
while (read < buf.Length)
{
var n = await s.ReadAsync(buf.AsMemory(read));
if (n == 0) return false;
read += n;
}
return true;
}
public ValueTask DisposeAsync()
{
_stop.Cancel();
_releaseFirst.TrySetResult();
_listener.Stop();
return ValueTask.CompletedTask;
}
}
private static byte[] ReadPdu(ushort addr) => new byte[] { 0x03, (byte)(addr >> 8), (byte)addr, 0x00, 0x01 };
[Fact]
public async Task RtuOverTcp_caller_cancel_mid_transaction_then_next_read_gets_its_own_reply()
{
var ct = TestContext.Current.CancellationToken;
await using var server = new LateReplyServer(rtu: true);
await using var transport = new ModbusRtuOverTcpTransport("127.0.0.1", server.Port, TimeSpan.FromSeconds(5));
await transport.ConnectAsync(ct);
using var cancel = new CancellationTokenSource();
var first = transport.SendAsync(1, ReadPdu(5), cancel.Token);
await server.FirstReceived.WaitAsync(TimeSpan.FromSeconds(5), ct);
await cancel.CancelAsync();
await Should.ThrowAsync(first);
// The device answers the cancelled request late; the reply lands in whatever socket the transport kept.
server.ReleaseFirst();
await Task.Delay(200, ct);
var pdu = await transport.SendAsync(1, ReadPdu(9), ct);
pdu.ShouldBe(new byte[] { 0x03, 0x02, 0x00, 0x09 }, "the second read must carry ITS reply (register 9), never the cancelled request's (5)");
server.Accepted.ShouldBe(2, "the cancelled transaction's socket must have been discarded and re-dialled");
}
[Fact]
public async Task Tcp_caller_cancel_mid_transaction_then_next_read_gets_its_own_reply_on_a_fresh_socket()
{
var ct = TestContext.Current.CancellationToken;
await using var server = new LateReplyServer(rtu: false);
await using var transport = new ModbusTcpTransport("127.0.0.1", server.Port, TimeSpan.FromSeconds(5));
await transport.ConnectAsync(ct);
using var cancel = new CancellationTokenSource();
var first = transport.SendAsync(1, ReadPdu(5), cancel.Token);
await server.FirstReceived.WaitAsync(TimeSpan.FromSeconds(5), ct);
await cancel.CancelAsync();
await Should.ThrowAsync(first);
server.ReleaseFirst();
await Task.Delay(200, ct);
var pdu = await transport.SendAsync(1, ReadPdu(9), ct);
pdu.ShouldBe(new byte[] { 0x03, 0x02, 0x00, 0x09 });
server.Accepted.ShouldBe(2, "a cancelled in-flight transaction must not leave a half-read/late frame on the reused socket");
}
[Fact]
public async Task RtuOverTcp_uncancelled_reads_reuse_one_socket_positive_control()
{
var ct = TestContext.Current.CancellationToken;
await using var server = new LateReplyServer(rtu: true);
server.ReleaseFirst();
await using var transport = new ModbusRtuOverTcpTransport("127.0.0.1", server.Port, TimeSpan.FromSeconds(5));
await transport.ConnectAsync(ct);
(await transport.SendAsync(1, ReadPdu(5), ct)).ShouldBe(new byte[] { 0x03, 0x02, 0x00, 0x05 });
(await transport.SendAsync(1, ReadPdu(9), ct)).ShouldBe(new byte[] { 0x03, 0x02, 0x00, 0x09 });
server.Accepted.ShouldBe(1, "the teardown must be tied to the cancelled exit, not to every call");
}
///
/// #1055: with auto-reconnect OFF a caller-cancelled RTU transaction used to leave the transport dead (the
/// discarded socket was never re-dialled) until the 90 s watchdog re-initialised the driver. The discard was
/// ours, so one redial is owed; a real link fault under auto-reconnect OFF must still stay down.
///
[Fact]
public async Task RtuOverTcp_AutoReconnectOff_caller_cancel_still_redials_for_the_next_read()
{
var ct = TestContext.Current.CancellationToken;
await using var server = new LateReplyServer(rtu: true);
await using var transport = new ModbusRtuOverTcpTransport("127.0.0.1", server.Port, TimeSpan.FromSeconds(5), autoReconnect: false);
await transport.ConnectAsync(ct);
using var cancel = new CancellationTokenSource();
var first = transport.SendAsync(1, ReadPdu(5), cancel.Token);
await server.FirstReceived.WaitAsync(TimeSpan.FromSeconds(5), ct);
await cancel.CancelAsync();
await Should.ThrowAsync(first);
server.ReleaseFirst();
(await transport.SendAsync(1, ReadPdu(9), ct)).ShouldBe(new byte[] { 0x03, 0x02, 0x00, 0x09 });
server.Accepted.ShouldBe(2);
}
[Fact]
public async Task RtuOverTcp_AutoReconnectOff_link_fault_stays_down_and_the_cancel_allowance_is_spent_once()
{
var ct = TestContext.Current.CancellationToken;
var server = new LateReplyServer(rtu: true);
await using var transport = new ModbusRtuOverTcpTransport("127.0.0.1", server.Port, TimeSpan.FromSeconds(5), autoReconnect: false);
await transport.ConnectAsync(ct);
using var cancel = new CancellationTokenSource();
var first = transport.SendAsync(1, ReadPdu(5), cancel.Token);
await server.FirstReceived.WaitAsync(TimeSpan.FromSeconds(5), ct);
await cancel.CancelAsync();
await Should.ThrowAsync(first);
// The device goes away: the one owed redial fails, and the next call must fail fast, not dial again.
await server.DisposeAsync();
await Should.ThrowAsync(transport.SendAsync(1, ReadPdu(9), ct));
await Should.ThrowAsync(transport.SendAsync(1, ReadPdu(9), ct));
}
}