388291d18a
S-1: ModbusRtuOverTcpTransport.SendOnceAsync tears the socket down on any exit after the write without a validated reply (caller cancellation included), so a late reply can no longer answer the next request at Good. S-2: SubscribeAsync/SubscribeAcquisitionAsync drop the deadband baselines of their refs before polling starts. S-8: a family-recognised prefix whose body the family parser rejects no longer falls through to the generic mnemonic table.
179 lines
7.8 KiB
C#
179 lines
7.8 KiB
C#
using System.Net;
|
|
using System.Net.Sockets;
|
|
using Shouldly;
|
|
using Xunit;
|
|
|
|
namespace ZB.MOM.WW.OtOpcUa.Driver.Modbus.Tests;
|
|
|
|
/// <summary>
|
|
/// #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.
|
|
/// </summary>
|
|
[Trait("Category", "Unit")]
|
|
public sealed class ModbusCallerCancelDesyncTests
|
|
{
|
|
/// <summary>
|
|
/// Loopback device. The reply to request index 0 is withheld until <see cref="ReleaseFirst"/>; 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.
|
|
/// </summary>
|
|
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<bool> 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<OperationCanceledException>(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<OperationCanceledException>(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");
|
|
}
|
|
}
|