e68d856fcb
- P-6: the wire adapter throws refused fixed-tree calls as FocasWireException carrying the rc (was InvalidOperationException, so a refusing control looked silent, degraded and was reconnect-looped by the #527 watchdog); a refused axis is per-node BadNoData and the tick continues. - P-7: bootstrap capability probes latch only an ANSWER (rc, or session still up); a transport failure/timeout or a session dropped mid-pass retries the bootstrap. - P-21: CoalesceRejected latches only range-shaped codes (not EW_BUSY/EW_SOCKET/EW_UNEXP/EW_HANDLE/unknown). Macro/param multi-block batching deferred (unproven on hardware). - P-10: any fault once a request is on the wire closes the session (bad magic/version, unexpected PDU, malformed blocks); replies must echo the request's command ids in order (verified against every 31i-B capture). A refusal never closes the session. - P-8: close handshake bounded to 1 s and run under the request gate (sync + async dispose). - P-11: data-path callers check the backoff before ConnectGate and fail fast behind an in-flight reconnect to a device whose last connect failed. - P-9: axes/spindles carry their wire slot (FocasAxisName/FocasSpindleName.Slot); cnc_rddynamic2 and the spindle-meter lookup use it. - P-20: a truncated (>= 32) alarm list never clears/retriggers a told-active condition unless it shows a new key; unseen told keys are kept. - P-25: a refused connect-time sysinfo is not cached; a short PARAM payload reads BadTypeMismatch. Tests: loopback MockFocasWireServer drives the real wire client; every fix mutation-checked (reverting it fails its test). FOCAS.Tests 619/619, FOCAS.IntegrationTests 19/19 vs the sim on 10.100.0.35, Runtime.Tests FOCAS 7/7, FOCAS.Cli.Tests 57/57.
307 lines
16 KiB
C#
307 lines
16 KiB
C#
using System.Diagnostics;
|
|
using Shouldly;
|
|
using Xunit;
|
|
using ZB.MOM.WW.OtOpcUa.Driver.FOCAS.Wire;
|
|
|
|
namespace ZB.MOM.WW.OtOpcUa.Driver.FOCAS.Tests;
|
|
|
|
/// <summary>
|
|
/// #985 — the FOCAS wire client against a scripted loopback CNC (<see cref="MockFocasWireServer"/>): a protocol
|
|
/// fault mid-request closes the session instead of leaving it desynchronised (P-10), the close handshake is
|
|
/// bounded (P-8), a refused setup sysinfo is not cached (P-25), and a fixed-tree refusal is thrown as a refusal
|
|
/// carrying its rc (P-6).
|
|
/// </summary>
|
|
[Trait("Category", "Unit")]
|
|
public sealed class FocasWireSessionIntegrityTests
|
|
{
|
|
private static readonly TimeSpan ConnectTimeout = TimeSpan.FromSeconds(3);
|
|
|
|
private static async Task<FocasWireClient> ConnectAsync(MockFocasWireServer srv)
|
|
{
|
|
var wire = new FocasWireClient();
|
|
await wire.ConnectAsync("127.0.0.1", srv.Port, ConnectTimeout);
|
|
return wire;
|
|
}
|
|
|
|
// ---- P-10: protocol faults close the session; replies are matched to requests ----
|
|
|
|
/// <summary>
|
|
/// The finding's repro: one stray non-data PDU ahead of the real reply. Before the fix the client threw
|
|
/// "unexpected PDU type" but KEPT the session, so the next request consumed the previous request's reply —
|
|
/// macro #200 published macro #100's value at Good.
|
|
/// </summary>
|
|
[Fact]
|
|
public async Task A_stray_PDU_closes_the_session_so_the_next_read_never_gets_the_previous_reply()
|
|
{
|
|
await using var srv = new MockFocasWireServer();
|
|
var strayOnce = 1;
|
|
srv.OnData = reqs => reqs[0].Command == 0x0015 && Interlocked.Exchange(ref strayOnce, 0) == 1
|
|
? [.. MockFocasWireServer.Pdu(0x02, []), .. srv.Reply(reqs)]
|
|
: srv.Reply(reqs);
|
|
var client = new WireFocasClient();
|
|
await client.ConnectAsync(FocasHostAddress.TryParse(srv.HostAddress)!, ConnectTimeout, CancellationToken.None);
|
|
|
|
var first = await client.ReadAsync(FocasAddress.TryParse("MACRO:100")!, FocasDataType.Int32, CancellationToken.None);
|
|
first.status.ShouldBe(FocasStatusMapper.BadCommunicationError);
|
|
client.IsConnected.ShouldBeFalse("a protocol fault mid-request must tear the session down");
|
|
|
|
var second = await client.ReadAsync(FocasAddress.TryParse("MACRO:200")!, FocasDataType.Int32, CancellationToken.None);
|
|
second.value.ShouldNotBe(100, "request N+1 must never be answered with request N's reply");
|
|
second.status.ShouldBe(FocasStatusMapper.BadCommunicationError);
|
|
|
|
// …and the next connect is a fresh session whose reads answer for themselves (positive control).
|
|
await client.ConnectAsync(FocasHostAddress.TryParse(srv.HostAddress)!, ConnectTimeout, CancellationToken.None);
|
|
var third = await client.ReadAsync(FocasAddress.TryParse("MACRO:200")!, FocasDataType.Int32, CancellationToken.None);
|
|
third.status.ShouldBe(FocasStatusMapper.Good);
|
|
third.value.ShouldBe(200);
|
|
srv.Initiates.ShouldBe(4, "two sockets per session, two sessions");
|
|
client.Dispose();
|
|
}
|
|
|
|
/// <summary>A reply whose block is a DIFFERENT command than the request asked for is refused and closes the session.</summary>
|
|
[Fact]
|
|
public async Task A_reply_for_another_command_closes_the_session()
|
|
{
|
|
await using var srv = new MockFocasWireServer();
|
|
srv.OnData = reqs => reqs[0].Command == 0x0015
|
|
? MockFocasWireServer.DataPdu((0x0057, 0, new byte[2]))
|
|
: srv.Reply(reqs);
|
|
using var wire = await ConnectAsync(srv);
|
|
|
|
var ex = await Should.ThrowAsync<FocasWireException>(() => wire.ReadMacroAsync(100, TestContext.Current.CancellationToken));
|
|
ex.IsTransient.ShouldBeTrue();
|
|
ex.Message.ShouldContain("0x0057");
|
|
wire.IsConnected.ShouldBeFalse();
|
|
}
|
|
|
|
/// <summary>More reply blocks than request blocks is refused and closes the session.</summary>
|
|
[Fact]
|
|
public async Task A_reply_with_more_blocks_than_requested_closes_the_session()
|
|
{
|
|
await using var srv = new MockFocasWireServer();
|
|
srv.OnData = reqs => reqs[0].Command == 0x0015
|
|
? MockFocasWireServer.DataPdu((0x0015, 0, MockFocasWireServer.MacroPayload(1, 0)), (0x0015, 0, MockFocasWireServer.MacroPayload(2, 0)))
|
|
: srv.Reply(reqs);
|
|
using var wire = await ConnectAsync(srv);
|
|
|
|
await Should.ThrowAsync<FocasWireException>(() => wire.ReadMacroAsync(100, TestContext.Current.CancellationToken));
|
|
wire.IsConnected.ShouldBeFalse();
|
|
}
|
|
|
|
/// <summary>Bad magic (body left unread) closes the session — it used to propagate with the session still "connected".</summary>
|
|
[Fact]
|
|
public async Task Bad_magic_closes_the_session()
|
|
{
|
|
await using var srv = new MockFocasWireServer();
|
|
srv.OnData = reqs => reqs[0].Command == 0x0015
|
|
? MockFocasWireServer.Pdu(0x21, new byte[30], magic: [0xde, 0xad, 0xbe, 0xef])
|
|
: srv.Reply(reqs);
|
|
using var wire = await ConnectAsync(srv);
|
|
|
|
var ex = await Should.ThrowAsync<FocasWireException>(() => wire.ReadMacroAsync(100, TestContext.Current.CancellationToken));
|
|
ex.IsTransient.ShouldBeTrue();
|
|
wire.IsConnected.ShouldBeFalse();
|
|
}
|
|
|
|
/// <summary>
|
|
/// A CNC REFUSAL (an rc inside a well-formed reply) is an answer, not a protocol fault: the session stays up
|
|
/// — a production control that refuses a function must never be reconnected over it.
|
|
/// </summary>
|
|
[Fact]
|
|
public async Task A_refusal_keeps_the_session()
|
|
{
|
|
await using var srv = new MockFocasWireServer();
|
|
srv.Responder = r => r.Command == 0x0015 ? ((short)1, []) : MockFocasWireServer.DefaultResponder(r);
|
|
using var wire = await ConnectAsync(srv);
|
|
|
|
var result = await wire.ReadMacroAsync(100, TestContext.Current.CancellationToken);
|
|
result.Rc.ShouldBe((short)1);
|
|
wire.IsConnected.ShouldBeTrue();
|
|
}
|
|
|
|
[Fact]
|
|
public void Reply_matching_accepts_an_echo_and_a_shorter_reply_and_refuses_the_rest()
|
|
{
|
|
RequestBlock[] request = [new(0x0019), new(0x00e1), new(0x0098)];
|
|
FocasWireClient.VerifyResponseMatchesRequest(request,
|
|
[new ResponseBlock(0x0019, 0, []), new ResponseBlock(0x00e1, 0, []), new ResponseBlock(0x0098, 0, [])]);
|
|
// Shorter is tolerated exactly as before the check existed (not evidence-backed to refuse).
|
|
FocasWireClient.VerifyResponseMatchesRequest(request, [new ResponseBlock(0x0019, 1, [])]);
|
|
FocasWireClient.VerifyResponseMatchesRequest(request, []);
|
|
Should.Throw<FocasWireException>(() => FocasWireClient.VerifyResponseMatchesRequest(request,
|
|
[new ResponseBlock(0x0019, 0, []), new ResponseBlock(0x0098, 0, [])]));
|
|
Should.Throw<FocasWireException>(() => FocasWireClient.VerifyResponseMatchesRequest([new(0x0015)],
|
|
[new ResponseBlock(0x0015, 0, []), new ResponseBlock(0x0015, 0, [])]));
|
|
}
|
|
|
|
/// <summary>Every real 31i-B capture echoes its request's command ids — the evidence the matching rests on.</summary>
|
|
[Theory]
|
|
[InlineData("ref-dynamic2-axis1.bin", new ushort[] { 0x001a, 0x001c, 0x001d, 0x0024, 0x0025, 0x0026, 0x0026, 0x0026, 0x0026 })]
|
|
[InlineData("ref-statinfo.bin", new ushort[] { 0x0019, 0x00e1, 0x0098 })]
|
|
[InlineData("svmeter-pair-0x0056-0x0089.bin", new ushort[] { 0x0056, 0x0089 })]
|
|
[InlineData("param-100-0x000e.bin", new ushort[] { 0x000e })]
|
|
public void Real_captures_pass_reply_matching(string capture, ushort[] requestCommands) =>
|
|
FocasWireClient.VerifyResponseMatchesRequest(
|
|
[.. requestCommands.Select(c => new RequestBlock(c))], WireFixtures.Blocks(capture));
|
|
|
|
// ---- P-8: the close handshake is bounded ----
|
|
|
|
/// <summary>The finding's repro: a CNC that answers data but never the close PDU must not hang Dispose.</summary>
|
|
[Fact]
|
|
public async Task Dispose_completes_within_the_bound_when_the_cnc_never_answers_close()
|
|
{
|
|
await using var srv = new MockFocasWireServer { AnswerClose = false };
|
|
var wire = await ConnectAsync(srv);
|
|
(await wire.ReadMacroAsync(1, TestContext.Current.CancellationToken)).IsOk.ShouldBeTrue();
|
|
|
|
var sw = Stopwatch.StartNew();
|
|
var dispose = Task.Run(wire.Dispose, TestContext.Current.CancellationToken);
|
|
(await Task.WhenAny(dispose, Task.Delay(TimeSpan.FromSeconds(10), TestContext.Current.CancellationToken))).ShouldBe(dispose, "Dispose hung on the close reply");
|
|
sw.Elapsed.ShouldBeLessThan(FocasWireClient.CloseHandshakeTimeout + TimeSpan.FromSeconds(2));
|
|
await WaitUntil(() => srv.Closes == 1);
|
|
wire.IsConnected.ShouldBeFalse();
|
|
}
|
|
|
|
[Fact]
|
|
public async Task DisposeAsync_completes_within_the_bound_when_the_cnc_never_answers_close()
|
|
{
|
|
await using var srv = new MockFocasWireServer { AnswerClose = false };
|
|
var wire = await ConnectAsync(srv);
|
|
|
|
var dispose = wire.DisposeAsync().AsTask();
|
|
(await Task.WhenAny(dispose, Task.Delay(TimeSpan.FromSeconds(10), TestContext.Current.CancellationToken))).ShouldBe(dispose, "DisposeAsync hung on the close reply");
|
|
await WaitUntil(() => srv.Closes == 1);
|
|
}
|
|
|
|
/// <summary>
|
|
/// The close exchange runs under the request gate: with a request in flight against a stalled CNC, Dispose
|
|
/// never writes a close PDU into the middle of it, still completes within the bound, and fails the request.
|
|
/// </summary>
|
|
[Fact]
|
|
public async Task Dispose_with_a_request_stalled_in_flight_does_not_interleave_and_is_bounded()
|
|
{
|
|
await using var srv = new MockFocasWireServer();
|
|
srv.OnData = reqs => reqs[0].Command == 0x0015 ? null : srv.Reply(reqs); // the macro read stalls
|
|
var wire = await ConnectAsync(srv);
|
|
var stalled = wire.ReadMacroAsync(1, TestContext.Current.CancellationToken);
|
|
await WaitUntil(() => srv.DataRequests >= 3); // sysinfo + setup + the stalled macro
|
|
|
|
var dispose = Task.Run(wire.Dispose, TestContext.Current.CancellationToken);
|
|
(await Task.WhenAny(dispose, Task.Delay(TimeSpan.FromSeconds(10), TestContext.Current.CancellationToken))).ShouldBe(dispose, "Dispose hung behind the stalled request");
|
|
await Should.ThrowAsync<Exception>(() => stalled);
|
|
srv.Closes.ShouldBe(0, "no close PDU may be written into the middle of an in-flight request");
|
|
}
|
|
|
|
// ---- P-25: a refused setup sysinfo is not cached ----
|
|
|
|
[Fact]
|
|
public async Task A_refused_setup_sysinfo_is_not_cached_for_the_session()
|
|
{
|
|
await using var srv = new MockFocasWireServer();
|
|
var sysinfoReads = 0;
|
|
srv.Responder = r => r.Command == 0x0018
|
|
? Interlocked.Increment(ref sysinfoReads) == 1 ? ((short)-1, []) : ((short)0, MockFocasWireServer.SysInfoPayload())
|
|
: MockFocasWireServer.DefaultResponder(r);
|
|
using var wire = await ConnectAsync(srv);
|
|
|
|
var info = await wire.ReadSysInfoAsync(TestContext.Current.CancellationToken);
|
|
info.IsOk.ShouldBeTrue("the connect-time EW_BUSY must not be served from the cache for the life of the session");
|
|
info.Value!.Series.ShouldBe("G431");
|
|
sysinfoReads.ShouldBe(2);
|
|
}
|
|
|
|
/// <summary>Positive control: an ANSWERED setup sysinfo is still cached — later reads cost no wire traffic.</summary>
|
|
[Fact]
|
|
public async Task An_answered_setup_sysinfo_is_still_cached()
|
|
{
|
|
await using var srv = new MockFocasWireServer();
|
|
using var wire = await ConnectAsync(srv);
|
|
var before = srv.CountOf(0x0018);
|
|
|
|
(await wire.ReadSysInfoAsync(TestContext.Current.CancellationToken)).IsOk.ShouldBeTrue();
|
|
(await wire.ReadSysInfoAsync(TestContext.Current.CancellationToken)).IsOk.ShouldBeTrue();
|
|
srv.CountOf(0x0018).ShouldBe(before);
|
|
before.ShouldBe(1);
|
|
}
|
|
|
|
// ---- P-6: fixed-tree refusals carry their rc ----
|
|
|
|
/// <summary>
|
|
/// The adapter used to throw a plain InvalidOperationException for a non-OK rc, which the driver's refusal
|
|
/// test could not recognise — a control that refused cnc_rddynamic2 looked silent and degraded.
|
|
/// </summary>
|
|
[Fact]
|
|
public async Task A_refused_fixed_tree_call_is_thrown_as_a_refusal_carrying_its_rc()
|
|
{
|
|
await using var srv = new MockFocasWireServer();
|
|
srv.Responder = r => r.Command is 0x001a or 0x0019 or 0x0120
|
|
? ((short)1, [])
|
|
: MockFocasWireServer.DefaultResponder(r);
|
|
var client = new WireFocasClient();
|
|
await client.ConnectAsync(FocasHostAddress.TryParse(srv.HostAddress)!, ConnectTimeout, CancellationToken.None);
|
|
|
|
var dyn = await Should.ThrowAsync<FocasWireException>(() => client.ReadDynamicAsync(1, CancellationToken.None));
|
|
dyn.Rc.ShouldBe((short)1);
|
|
FocasAlarmProjection.IsCncRefusal(dyn).ShouldBeTrue();
|
|
(await Should.ThrowAsync<FocasWireException>(() => client.GetStatusAsync(CancellationToken.None))).Rc.ShouldBe((short)1);
|
|
(await Should.ThrowAsync<FocasWireException>(() => client.GetTimerAsync(FocasTimerKind.PowerOn, CancellationToken.None))).Rc.ShouldBe((short)1);
|
|
client.IsConnected.ShouldBeTrue("a refusal leaves the session up");
|
|
client.Dispose();
|
|
}
|
|
|
|
// ---- P-25: a short parameter payload is not a Good 0 ----
|
|
|
|
[Theory]
|
|
[InlineData(FocasDataType.Int32, 2)]
|
|
[InlineData(FocasDataType.Int16, 1)]
|
|
[InlineData(FocasDataType.Float32, 3)]
|
|
[InlineData(FocasDataType.Float64, 4)]
|
|
[InlineData(FocasDataType.Byte, 0)]
|
|
[InlineData(FocasDataType.Bit, 3)]
|
|
public void A_parameter_payload_shorter_than_its_type_is_BadTypeMismatch(FocasDataType type, int length)
|
|
{
|
|
var (value, status) = WireFocasClient.DecodeParameter(new byte[length], type, type == FocasDataType.Bit ? 1 : null);
|
|
status.ShouldBe(FocasStatusMapper.BadTypeMismatch);
|
|
value.ShouldBeNull();
|
|
}
|
|
|
|
[Fact]
|
|
public void A_full_parameter_payload_still_decodes_big_endian_at_offset_0()
|
|
{
|
|
WireFocasClient.DecodeParameter([0x00, 0x00, 0x01, 0x02], FocasDataType.Int32, null)
|
|
.ShouldBe(((object?)0x0102, FocasStatusMapper.Good));
|
|
WireFocasClient.DecodeParameter([0xff, 0xfe], FocasDataType.Int16, null)
|
|
.ShouldBe(((object?)(short)-2, FocasStatusMapper.Good));
|
|
WireFocasClient.DecodeParameter([0x80], FocasDataType.Byte, null)
|
|
.ShouldBe(((object?)(sbyte)-128, FocasStatusMapper.Good));
|
|
WireFocasClient.DecodeParameter([0x00, 0x00, 0x00, 0x04], FocasDataType.Bit, 2)
|
|
.ShouldBe(((object?)true, FocasStatusMapper.Good));
|
|
}
|
|
|
|
[Fact]
|
|
public async Task A_short_parameter_reply_reads_BadTypeMismatch_end_to_end()
|
|
{
|
|
await using var srv = new MockFocasWireServer();
|
|
srv.Responder = r => r.Command == 0x000e && r.Arg1 == 6711
|
|
? ((short)0, new byte[] { 0x00, 0x07 })
|
|
: MockFocasWireServer.DefaultResponder(r);
|
|
var client = new WireFocasClient();
|
|
await client.ConnectAsync(FocasHostAddress.TryParse(srv.HostAddress)!, ConnectTimeout, CancellationToken.None);
|
|
|
|
var (value, status) = await client.ReadAsync(FocasAddress.TryParse("PARAM:6711")!, FocasDataType.Int32, CancellationToken.None);
|
|
status.ShouldBe(FocasStatusMapper.BadTypeMismatch, "two bytes cannot be an Int32 — it used to read Good 0");
|
|
value.ShouldBeNull();
|
|
client.Dispose();
|
|
}
|
|
|
|
private static async Task WaitUntil(Func<bool> condition)
|
|
{
|
|
var deadline = DateTime.UtcNow + TimeSpan.FromSeconds(5);
|
|
while (!condition())
|
|
{
|
|
if (DateTime.UtcNow > deadline) throw new TimeoutException("condition not reached");
|
|
await Task.Delay(10, TestContext.Current.CancellationToken);
|
|
}
|
|
}
|
|
}
|