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.
490 lines
24 KiB
C#
490 lines
24 KiB
C#
using System.Buffers.Binary;
|
|
using System.Diagnostics;
|
|
using Shouldly;
|
|
using Xunit;
|
|
using ZB.MOM.WW.OtOpcUa.Core.Abstractions;
|
|
using ZB.MOM.WW.OtOpcUa.Driver.FOCAS.Wire;
|
|
|
|
namespace ZB.MOM.WW.OtOpcUa.Driver.FOCAS.Tests;
|
|
|
|
/// <summary>
|
|
/// #985 — the FOCAS driver's health contract and device isolation: a CNC refusal of the fixed tree leaves the
|
|
/// driver Healthy while a real outage degrades it (P-6), a transient failure during the capability bootstrap is
|
|
/// not latched as "unsupported" (P-7), axes and spindles are addressed by their wire slot (P-9), a dead CNC does
|
|
/// not stall other devices' reads (P-11), and a handle recycle against a CNC that never answers the close PDU
|
|
/// completes instead of holding the connect gate forever (P-8).
|
|
/// </summary>
|
|
[Trait("Category", "Unit")]
|
|
public sealed class FocasRefusalAndIsolationTests
|
|
{
|
|
private static readonly TimeSpan Stale = TimeSpan.FromMilliseconds(400);
|
|
|
|
// ---- P-6 end to end: the real wire client against a CNC that refuses cnc_rddynamic2 ----
|
|
|
|
/// <summary>Two axis-name records, X and Y.</summary>
|
|
private static byte[] AxisNamesXY() => [0x58, 0, 0, 0, 0x59, 0, 0, 0];
|
|
|
|
private static FocasDriver FixedOnlyWireDriver(MockFocasWireServer srv) => new(new FocasDriverOptions
|
|
{
|
|
Devices = [new FocasDeviceOptions(srv.HostAddress)],
|
|
RawTags = [FocasRawTags.Entry(new FocasTagDefinition("raw/X", srv.HostAddress, "FIXED:Axes/X/AbsolutePosition", FocasDataType.Float64))],
|
|
Probe = new FocasProbeOptions { Enabled = false },
|
|
Timeout = TimeSpan.FromSeconds(2),
|
|
FixedTree = new FocasFixedTreeOptions
|
|
{
|
|
PollInterval = TimeSpan.FromMilliseconds(20),
|
|
ProgramPollInterval = TimeSpan.Zero,
|
|
TimerPollInterval = TimeSpan.Zero,
|
|
},
|
|
}, "focas-985-p6", new WireFocasClientFactory())
|
|
{
|
|
FixedTreeStaleBudgetOverride = Stale,
|
|
};
|
|
|
|
/// <summary>
|
|
/// The finding's repro on the REAL wire client: a fixed-only driver on a control that answers every
|
|
/// <c>cnc_rddynamic2</c> with <c>EW_FUNC</c>. The adapter used to throw a plain InvalidOperationException, so
|
|
/// the refusal read as silence and the driver degraded past the stale budget (then the #527 watchdog
|
|
/// reconnect-looped it). Now it stays Healthy with LastSuccessfulRead advancing, the refused axis reads
|
|
/// BadNoData — and (positive control) the same driver DOES degrade once the CNC really goes away.
|
|
/// </summary>
|
|
[Fact]
|
|
public async Task A_cnc_refusing_the_dynamic_read_stays_Healthy_but_a_real_outage_degrades()
|
|
{
|
|
await using var srv = new MockFocasWireServer();
|
|
srv.Responder = r => r.Command switch
|
|
{
|
|
0x0089 => (0, AxisNamesXY()),
|
|
0x001a or 0x001c or 0x001d or 0x0024 or 0x0025 or 0x0026 => (1, []), // EW_FUNC
|
|
_ => MockFocasWireServer.DefaultResponder(r),
|
|
};
|
|
await using var drv = FixedOnlyWireDriver(srv);
|
|
await drv.InitializeAsync("{}", CancellationToken.None);
|
|
await WaitUntil(() => drv.GetDeviceState(srv.HostAddress)?.FixedTreeCache is not null);
|
|
|
|
var started = DateTime.UtcNow;
|
|
var first = drv.GetHealth().LastSuccessfulRead!.Value;
|
|
// Refused ticks for well past the staleness budget …
|
|
await WaitUntil(() => DateTime.UtcNow - started > Stale * 3
|
|
&& srv.CountOf(0x001a) >= 10);
|
|
// … and the driver is still Healthy, crediting each answer.
|
|
drv.GetHealth().State.ShouldBe(DriverState.Healthy);
|
|
drv.GetHealth().LastSuccessfulRead!.Value.ShouldBeGreaterThan(first);
|
|
var read = await drv.ReadAsync(["raw/X"], CancellationToken.None);
|
|
read[0].StatusCode.ShouldBe(FocasStatusMapper.BadNoData, "a refused axis has no value — never a stale Good");
|
|
|
|
// Positive control: the CNC goes away for real → Degraded with LastSuccessfulRead frozen.
|
|
srv.Stop();
|
|
await WaitUntil(() => drv.GetHealth().State == DriverState.Degraded, TimeSpan.FromSeconds(10));
|
|
}
|
|
|
|
// ---- P-6: one refused axis does not abort the tick ----
|
|
|
|
private sealed class RefuseAxisCnc(int refusedAxis) : FakeFocasClient
|
|
{
|
|
public override Task<FocasDynamicSnapshot> ReadDynamicAsync(int axisIndex, CancellationToken ct) =>
|
|
axisIndex == refusedAxis
|
|
? throw new FocasWireException("cnc_rddynamic2 failed EW_4.", rc: 4)
|
|
: base.ReadDynamicAsync(axisIndex, ct);
|
|
}
|
|
|
|
[Fact]
|
|
public async Task One_refused_axis_reads_BadNoData_while_the_others_keep_polling()
|
|
{
|
|
const string host = "focas://10.0.0.5:8193";
|
|
var factory = new FakeFocasClientFactory
|
|
{
|
|
Customise = () =>
|
|
{
|
|
var c = new RefuseAxisCnc(refusedAxis: 2);
|
|
c.DynamicByAxis[1] = new FocasDynamicSnapshot(1, 0, 0, 0, 0, 0, 0, 100, 0, 0, 0);
|
|
c.DynamicByAxis[3] = new FocasDynamicSnapshot(3, 0, 0, 0, 0, 0, 0, 300, 0, 0, 0);
|
|
return c;
|
|
},
|
|
};
|
|
await using var drv = new FocasDriver(new FocasDriverOptions
|
|
{
|
|
Devices = [new FocasDeviceOptions(host)],
|
|
RawTags = FocasRawTags.Entries([
|
|
new FocasTagDefinition("x", host, "FIXED:Axes/X/AbsolutePosition", FocasDataType.Float64),
|
|
new FocasTagDefinition("y", host, "FIXED:Axes/Y/AbsolutePosition", FocasDataType.Float64),
|
|
new FocasTagDefinition("z", host, "FIXED:Axes/Z/AbsolutePosition", FocasDataType.Float64),
|
|
]),
|
|
Probe = new FocasProbeOptions { Enabled = false },
|
|
FixedTree = new FocasFixedTreeOptions
|
|
{
|
|
PollInterval = TimeSpan.FromMilliseconds(20), ProgramPollInterval = TimeSpan.Zero, TimerPollInterval = TimeSpan.Zero,
|
|
},
|
|
}, "focas-985-axis", factory);
|
|
await drv.InitializeAsync("{}", CancellationToken.None);
|
|
await WaitUntil(() => drv.GetDeviceState(host)?.LastFixedPollUtc is not null
|
|
&& drv.GetDeviceState(host)!.LastFixedSnapshots.Count >= 12);
|
|
|
|
var r = await drv.ReadAsync(["x", "y", "z"], CancellationToken.None);
|
|
r[0].Value.ShouldBe(100.0);
|
|
r[1].StatusCode.ShouldBe(FocasStatusMapper.BadNoData);
|
|
r[2].Value.ShouldBe(300.0, "the axis after a refused one still polls (a refusal used to abort the tick)");
|
|
drv.GetHealth().State.ShouldBe(DriverState.Healthy);
|
|
}
|
|
|
|
// ---- P-7: a transient failure during the capability bootstrap is not latched ----
|
|
|
|
private sealed class Shared
|
|
{
|
|
public int ServoCalls;
|
|
public bool RefuseStatus;
|
|
/// <summary>Bootstrap passes started (only the bootstrap reads sysinfo).</summary>
|
|
public int BootstrapPasses;
|
|
}
|
|
|
|
/// <summary>
|
|
/// A CNC whose <c>cnc_rdsvmeter</c> stalls once at bootstrap: the timeout closes the session (IsConnected
|
|
/// false), and every later capability probe then fails the way the wire adapter does when disconnected —
|
|
/// empty lists and "not connected" throws.
|
|
/// </summary>
|
|
private sealed class FlakyBootstrapCnc : FakeFocasClient
|
|
{
|
|
private readonly Shared _shared;
|
|
|
|
public FlakyBootstrapCnc(Shared shared)
|
|
{
|
|
_shared = shared;
|
|
ServoLoads.Add(new FocasServoLoad("X", 12.5));
|
|
SpindleLoads.Add(40.0);
|
|
SpindleMotorSpeeds.Add(55.0);
|
|
}
|
|
|
|
private InvalidOperationException NotConnected() => new("FOCAS wire session not connected.");
|
|
|
|
public override Task<FocasSysInfo> GetSysInfoAsync(CancellationToken ct)
|
|
{
|
|
Interlocked.Increment(ref _shared.BootstrapPasses);
|
|
return base.GetSysInfoAsync(ct);
|
|
}
|
|
|
|
public override Task<IReadOnlyList<FocasServoLoad>> GetServoLoadsAsync(CancellationToken ct)
|
|
{
|
|
if (Interlocked.Increment(ref _shared.ServoCalls) == 1)
|
|
{
|
|
IsConnected = false; // the stalled call's timeout tore the transport down
|
|
throw new FocasWireException("FOCAS wire request failed", new OperationCanceledException(), isTransient: true);
|
|
}
|
|
return IsConnected ? base.GetServoLoadsAsync(ct) : Task.FromResult<IReadOnlyList<FocasServoLoad>>([]);
|
|
}
|
|
|
|
public override Task<IReadOnlyList<double?>> GetSpindleLoadsAsync(CancellationToken ct) =>
|
|
IsConnected ? base.GetSpindleLoadsAsync(ct) : Task.FromResult<IReadOnlyList<double?>>([]);
|
|
|
|
public override Task<FocasProgramInfo> GetProgramInfoAsync(CancellationToken ct) =>
|
|
IsConnected ? base.GetProgramInfoAsync(ct) : throw NotConnected();
|
|
|
|
public override Task<FocasTimer> GetTimerAsync(FocasTimerKind kind, CancellationToken ct) =>
|
|
IsConnected ? base.GetTimerAsync(kind, ct) : throw NotConnected();
|
|
|
|
public override Task<FocasStatus> GetStatusAsync(CancellationToken ct)
|
|
{
|
|
if (!IsConnected) throw NotConnected();
|
|
if (_shared.RefuseStatus) throw new FocasWireException("cnc_statinfo failed EW_1.", rc: 1);
|
|
return base.GetStatusAsync(ct);
|
|
}
|
|
}
|
|
|
|
private static FocasDriver BootstrapDriver(string host, Shared shared) => new(new FocasDriverOptions
|
|
{
|
|
Devices = [new FocasDeviceOptions(host)],
|
|
RawTags = [FocasRawTags.Entry(new FocasTagDefinition("raw/X", host, "FIXED:Axes/X/AbsolutePosition", FocasDataType.Float64))],
|
|
Probe = new FocasProbeOptions { Enabled = false },
|
|
FixedTree = new FocasFixedTreeOptions
|
|
{
|
|
PollInterval = TimeSpan.FromMilliseconds(20), ProgramPollInterval = TimeSpan.Zero, TimerPollInterval = TimeSpan.Zero,
|
|
},
|
|
}, "focas-985-p7", new FakeFocasClientFactory { Customise = () => new FlakyBootstrapCnc(shared) });
|
|
|
|
/// <summary>
|
|
/// The finding's repro: a stalled <c>cnc_rdsvmeter</c> at startup used to record ServoLoad, ProgramInfo,
|
|
/// Timers, Status and SpindleLoad all false for the life of the device. Now the pass is retried and the
|
|
/// capabilities the CNC really has are all published.
|
|
/// </summary>
|
|
[Fact]
|
|
public async Task A_transient_failure_mid_bootstrap_is_retried_not_latched_as_unsupported()
|
|
{
|
|
const string host = "focas://10.0.0.7:8193";
|
|
var shared = new Shared();
|
|
await using var drv = BootstrapDriver(host, shared);
|
|
await drv.InitializeAsync("{}", CancellationToken.None);
|
|
await WaitUntil(() => drv.GetDeviceState(host)?.FixedTreeCache is not null, TimeSpan.FromSeconds(8));
|
|
|
|
Volatile.Read(ref shared.BootstrapPasses).ShouldBeGreaterThanOrEqualTo(2, "the bootstrap must have retried after the transient failure");
|
|
var caps = drv.GetDeviceState(host)!.FixedTreeCache!.Capabilities;
|
|
caps.ShouldBe(new FocasDriver.FocasFixedTreeCapabilities(
|
|
Spindles: true, SpindleLoad: true, SpindleMotorSpeed: true, ServoLoad: true,
|
|
ProgramInfo: true, Timers: true, Status: true));
|
|
}
|
|
|
|
/// <summary>Positive control: a REFUSAL (rc, session up) is a capability answer — latched false, no retry.</summary>
|
|
[Fact]
|
|
public async Task A_refused_capability_probe_is_latched_unsupported_on_the_first_pass()
|
|
{
|
|
const string host = "focas://10.0.0.8:8193";
|
|
var shared = new Shared { ServoCalls = 1, RefuseStatus = true }; // no stall; cnc_statinfo refused
|
|
await using var drv = BootstrapDriver(host, shared);
|
|
await drv.InitializeAsync("{}", CancellationToken.None);
|
|
await WaitUntil(() => drv.GetDeviceState(host)?.FixedTreeCache is not null);
|
|
|
|
var caps = drv.GetDeviceState(host)!.FixedTreeCache!.Capabilities;
|
|
caps.Status.ShouldBeFalse();
|
|
caps.ServoLoad.ShouldBeTrue();
|
|
caps.ProgramInfo.ShouldBeTrue();
|
|
Volatile.Read(ref shared.BootstrapPasses).ShouldBe(1, "one pass — a refusal is not retried");
|
|
}
|
|
|
|
[Fact]
|
|
public async Task Capability_answer_classification()
|
|
{
|
|
var up = new FakeFocasClient();
|
|
await up.ConnectAsync(new FocasHostAddress("h", 8193), TimeSpan.FromSeconds(1), TestContext.Current.CancellationToken);
|
|
var down = new FakeFocasClient();
|
|
|
|
FocasDriver.IsCapabilityAnswer(up, new FocasWireException("refused", rc: 1)).ShouldBeTrue();
|
|
FocasDriver.IsCapabilityAnswer(down, new FocasWireException("refused", rc: 1)).ShouldBeTrue("an rc is an answer even if the session later dropped");
|
|
FocasDriver.IsCapabilityAnswer(up, new InvalidOperationException("cnc_statinfo refused")).ShouldBeTrue("session still up ⇒ an answer");
|
|
FocasDriver.IsCapabilityAnswer(down, new InvalidOperationException("not connected")).ShouldBeFalse();
|
|
FocasDriver.IsCapabilityAnswer(up, new OperationCanceledException()).ShouldBeFalse("a per-call timeout says nothing about the capability");
|
|
FocasDriver.IsCapabilityAnswer(up, new FocasWireException("io", new IOException(), isTransient: true)).ShouldBeFalse();
|
|
FocasDriver.IsCapabilityAnswer(up, new ObjectDisposedException("client")).ShouldBeFalse();
|
|
}
|
|
|
|
// ---- P-9: axis and spindle wire slots ----
|
|
|
|
[Fact]
|
|
public void Wire_axis_names_keep_their_slot_across_a_blank_record()
|
|
{
|
|
// Axis-name payload X, Y, <blank>, Z → Z is wire slot 4, not list position 3.
|
|
byte[] payload = [0x58, 0, 0, 0, 0x59, 0, 0, 0, 0, 0, 0, 0, 0x5a, 0, 0, 0];
|
|
var records = FocasWireClient.ReadNameRecords(payload, 32, (i, n) => new WireAxisRecord(i, n));
|
|
var axes = WireFocasClient.MapAxisNames(records);
|
|
axes.Select(a => (a.Display, a.Slot)).ShouldBe([("X", 1), ("Y", 2), ("Z", 4)]);
|
|
|
|
// Spindle payload with a blank FIRST slot: S2 is wire slot 2.
|
|
byte[] spindles = [0, 0, 0, 0, 0x53, 0x32, 0, 0];
|
|
var sp = WireFocasClient.MapSpindleNames(FocasWireClient.ReadNameRecords(spindles, 8, (i, n) => new WireSpindleRecord(i, n)));
|
|
sp.Single().Display.ShouldBe("S2");
|
|
sp.Single().Slot.ShouldBe(2);
|
|
}
|
|
|
|
private sealed class SlotRecordingCnc : FakeFocasClient
|
|
{
|
|
public readonly List<int> RequestedAxes = [];
|
|
|
|
public override Task<FocasDynamicSnapshot> ReadDynamicAsync(int axisIndex, CancellationToken ct)
|
|
{
|
|
lock (RequestedAxes) RequestedAxes.Add(axisIndex);
|
|
return base.ReadDynamicAsync(axisIndex, ct);
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// The finding's repro: a control reporting names in slots 1, 2 and 4. The third named axis used to be polled
|
|
/// as axis 3 — another axis's positions at Good. A spindle in wire slot 2 must read meter record 2.
|
|
/// </summary>
|
|
[Fact]
|
|
public async Task Axes_and_spindles_are_addressed_by_their_wire_slot()
|
|
{
|
|
const string host = "focas://10.0.0.9:8193";
|
|
SlotRecordingCnc? cnc = null;
|
|
var factory = new FakeFocasClientFactory
|
|
{
|
|
Customise = () =>
|
|
{
|
|
var c = new SlotRecordingCnc();
|
|
c.AxisNames.Clear();
|
|
c.AxisNames.AddRange([new FocasAxisName("X", "", 1), new FocasAxisName("Y", "", 2), new FocasAxisName("Z", "", 4)]);
|
|
c.DynamicByAxis[3] = new FocasDynamicSnapshot(3, 0, 0, 0, 0, 0, 0, 333, 0, 0, 0);
|
|
c.DynamicByAxis[4] = new FocasDynamicSnapshot(4, 0, 0, 0, 0, 0, 0, 444, 0, 0, 0);
|
|
c.SpindleNames.Clear();
|
|
c.SpindleNames.Add(new FocasSpindleName("S", "2", "", "", Slot: 2));
|
|
c.SpindleLoads.AddRange([11.0, 22.0]); // meter records are slot-ordered: slot 1, slot 2
|
|
return cnc = c;
|
|
},
|
|
};
|
|
await using var drv = new FocasDriver(new FocasDriverOptions
|
|
{
|
|
Devices = [new FocasDeviceOptions(host)],
|
|
RawTags = FocasRawTags.Entries([
|
|
new FocasTagDefinition("z", host, "FIXED:Axes/Z/AbsolutePosition", FocasDataType.Float64),
|
|
new FocasTagDefinition("s2", host, "FIXED:Spindle/S2/Load", FocasDataType.Float64),
|
|
]),
|
|
Probe = new FocasProbeOptions { Enabled = false },
|
|
FixedTree = new FocasFixedTreeOptions
|
|
{
|
|
PollInterval = TimeSpan.FromMilliseconds(20), ProgramPollInterval = TimeSpan.Zero, TimerPollInterval = TimeSpan.Zero,
|
|
},
|
|
}, "focas-985-p9", factory);
|
|
await drv.InitializeAsync("{}", CancellationToken.None);
|
|
await WaitUntil(() => cnc is not null && Snapshot(cnc).Count >= 3 && drv.GetDeviceState(host)?.LastFixedPollUtc is not null);
|
|
|
|
Snapshot(cnc!).Distinct().Order().ToArray().ShouldBe(new[] { 1, 2, 4 }, "Z is wire slot 4 — axis 3 must never be requested");
|
|
var r = await drv.ReadAsync(["z", "s2"], CancellationToken.None);
|
|
r[0].Value.ShouldBe(444.0);
|
|
r[1].Value.ShouldBe(22.0, "spindle S2 sits in meter record 2, not 1");
|
|
|
|
static List<int> Snapshot(SlotRecordingCnc c) { lock (c.RequestedAxes) return [.. c.RequestedAxes]; }
|
|
}
|
|
|
|
[Fact]
|
|
public void A_client_without_slots_falls_back_to_list_position()
|
|
{
|
|
var cache = new FocasDriver.FocasFixedTreeCache(
|
|
new FocasSysInfo(0, 2, "M", "M", "30i", "A", 2),
|
|
[new FocasAxisName("X", ""), new FocasAxisName("Y", "")],
|
|
[new FocasSpindleName("S", "1", "", "")],
|
|
new FocasDriver.FocasFixedTreeCapabilities(true, true, true, true, true, true));
|
|
cache.AxisNumber(1).ShouldBe(2);
|
|
cache.SpindleMeterIndex(0).ShouldBe(0);
|
|
}
|
|
|
|
// ---- P-11: one dead CNC does not stall the others ----
|
|
|
|
private sealed class DeadOrAliveCnc(string deadHost, TimeSpan connectStall, Action onDeadConnect) : FakeFocasClient
|
|
{
|
|
public override async Task ConnectAsync(FocasHostAddress address, TimeSpan timeout, CancellationToken ct)
|
|
{
|
|
if (address.Host == deadHost)
|
|
{
|
|
onDeadConnect();
|
|
await Task.Delay(connectStall, ct); // a black-holed host: the connect only times out
|
|
throw new IOException("connect timed out");
|
|
}
|
|
await base.ConnectAsync(address, timeout, ct);
|
|
Values["R100"] = (sbyte)7;
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// The finding's repro: the probe (which bypasses the backoff) holds a dead CNC's connect gate for its whole
|
|
/// connect timeout; the data path used to queue behind it — and ReadAsync awaits every device — so the healthy
|
|
/// CNC's read stalled by the same amount. Now the dead device fails fast and the healthy one returns at once.
|
|
/// </summary>
|
|
[Fact]
|
|
public async Task A_dead_cnc_mid_probe_connect_does_not_stall_a_healthy_devices_read()
|
|
{
|
|
const string dead = "focas://10.0.0.5:8193";
|
|
const string alive = "focas://10.0.0.6:8193";
|
|
var deadConnects = 0;
|
|
var stall = TimeSpan.FromSeconds(3);
|
|
await using var drv = new FocasDriver(new FocasDriverOptions
|
|
{
|
|
Devices = [new FocasDeviceOptions(dead), new FocasDeviceOptions(alive)],
|
|
RawTags = FocasRawTags.Entries([
|
|
new FocasTagDefinition("dead", dead, "R100", FocasDataType.Byte),
|
|
new FocasTagDefinition("alive", alive, "R100", FocasDataType.Byte),
|
|
]),
|
|
Probe = new FocasProbeOptions { Enabled = true, Interval = TimeSpan.FromMilliseconds(20), Timeout = TimeSpan.FromSeconds(10) },
|
|
Timeout = TimeSpan.FromSeconds(10),
|
|
}, "focas-985-p11", new FakeFocasClientFactory
|
|
{
|
|
Customise = () => new DeadOrAliveCnc("10.0.0.5", stall, () => Interlocked.Increment(ref deadConnects)),
|
|
});
|
|
await drv.InitializeAsync("{}", CancellationToken.None);
|
|
|
|
// The probe's second connect to the dead CNC is in flight (its first already failed).
|
|
await WaitUntil(() => Volatile.Read(ref deadConnects) >= 2, TimeSpan.FromSeconds(10));
|
|
|
|
var sw = Stopwatch.StartNew();
|
|
var r = await drv.ReadAsync(["dead", "alive"], CancellationToken.None);
|
|
sw.Stop();
|
|
|
|
r[1].StatusCode.ShouldBe(FocasStatusMapper.Good);
|
|
r[1].Value.ShouldBe((sbyte)7);
|
|
r[0].StatusCode.ShouldBe(FocasStatusMapper.BadCommunicationError);
|
|
sw.Elapsed.ShouldBeLessThan(TimeSpan.FromSeconds(1), "the healthy CNC must not wait out the dead one's connect");
|
|
}
|
|
|
|
/// <summary>
|
|
/// Positive control for the fast-fail: with no failure on record the data path still WAITS for an in-flight
|
|
/// connect (the hw2 Makino race fix — two loops sharing one connect — must not regress into throttling).
|
|
/// </summary>
|
|
[Fact]
|
|
public async Task A_first_connect_in_flight_is_waited_for_not_throttled()
|
|
{
|
|
const string host = "focas://10.0.0.11:8193";
|
|
var gate = new TaskCompletionSource();
|
|
var factory = new FakeFocasClientFactory { Customise = () => new SlowFirstConnectCnc(gate.Task) };
|
|
await using var drv = new FocasDriver(new FocasDriverOptions
|
|
{
|
|
Devices = [new FocasDeviceOptions(host)],
|
|
RawTags = [FocasRawTags.Entry(new FocasTagDefinition("r", host, "R100", FocasDataType.Byte))],
|
|
Probe = new FocasProbeOptions { Enabled = false },
|
|
}, "focas-985-p11b", factory);
|
|
await drv.InitializeAsync("{}", CancellationToken.None);
|
|
|
|
var first = drv.ReadAsync(["r"], CancellationToken.None);
|
|
await WaitUntil(() => factory.Clients.Count == 1);
|
|
var second = drv.ReadAsync(["r"], CancellationToken.None);
|
|
gate.SetResult();
|
|
(await first)[0].StatusCode.ShouldBe(FocasStatusMapper.Good);
|
|
(await second)[0].StatusCode.ShouldBe(FocasStatusMapper.Good, "the queued caller shares the connect");
|
|
factory.Clients.Count.ShouldBe(1);
|
|
}
|
|
|
|
private sealed class SlowFirstConnectCnc(Task release) : FakeFocasClient
|
|
{
|
|
public override async Task ConnectAsync(FocasHostAddress address, TimeSpan timeout, CancellationToken ct)
|
|
{
|
|
await release.WaitAsync(ct);
|
|
await base.ConnectAsync(address, timeout, ct);
|
|
Values["R100"] = (sbyte)1;
|
|
}
|
|
}
|
|
|
|
// ---- P-8: a recycle against a CNC that never answers the close PDU ----
|
|
|
|
/// <summary>
|
|
/// The finding's repro: the hourly handle recycle disposes the session UNDER the device's connect gate, and the
|
|
/// dispose blocked forever on a close reply that never came — every later poll parked on the gate with no
|
|
/// result and no health write. Now each recycle completes within the bound and reads keep succeeding on fresh
|
|
/// sessions.
|
|
/// </summary>
|
|
[Fact]
|
|
public async Task Handle_recycle_completes_when_the_cnc_never_answers_close()
|
|
{
|
|
await using var srv = new MockFocasWireServer { AnswerClose = false };
|
|
await using var drv = new FocasDriver(new FocasDriverOptions
|
|
{
|
|
Devices = [new FocasDeviceOptions(srv.HostAddress)],
|
|
RawTags = [FocasRawTags.Entry(new FocasTagDefinition("m", srv.HostAddress, "MACRO:500", FocasDataType.Int32))],
|
|
Probe = new FocasProbeOptions { Enabled = false },
|
|
Timeout = TimeSpan.FromMilliseconds(500),
|
|
HandleRecycle = new FocasHandleRecycleOptions { Enabled = true, Interval = TimeSpan.FromMilliseconds(200) },
|
|
}, "focas-985-p8", new WireFocasClientFactory());
|
|
await drv.InitializeAsync("{}", CancellationToken.None);
|
|
|
|
var deadline = DateTime.UtcNow + TimeSpan.FromSeconds(20);
|
|
var goodAfterSecondRecycle = false;
|
|
while (DateTime.UtcNow < deadline && !goodAfterSecondRecycle)
|
|
{
|
|
var read = drv.ReadAsync(["m"], CancellationToken.None);
|
|
(await Task.WhenAny(read, Task.Delay(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken))).ShouldBe(read,
|
|
"a read parked behind a recycle that never finished its close handshake");
|
|
var r = await read;
|
|
if (srv.Closes >= 2 && r[0].StatusCode == FocasStatusMapper.Good)
|
|
{
|
|
r[0].Value.ShouldBe(500);
|
|
goodAfterSecondRecycle = true;
|
|
}
|
|
await Task.Delay(50, TestContext.Current.CancellationToken);
|
|
}
|
|
goodAfterSecondRecycle.ShouldBeTrue("recycles must complete and reads must succeed on the fresh sessions");
|
|
}
|
|
|
|
private static async Task WaitUntil(Func<bool> condition, TimeSpan? timeout = null)
|
|
{
|
|
var deadline = DateTime.UtcNow + (timeout ?? TimeSpan.FromSeconds(5));
|
|
while (!condition())
|
|
{
|
|
if (DateTime.UtcNow > deadline) throw new TimeoutException("condition not reached");
|
|
await Task.Delay(10, TestContext.Current.CancellationToken);
|
|
}
|
|
}
|
|
}
|