Files
lmxopcua/tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests/NodeManagerWriteRevertTests.cs
T
Joseph Doherty 2d20aeb779 fix(opcua,drivers): carry driver status sub-codes to clients (#519) + health-write ordering (#517)
#519 — a driver's OPC UA status code now reaches a client with its sub-code intact.
DriverInstanceActor projected the driver's uint onto a 3-state Good/Uncertain/Bad enum
and OtOpcUaNodeManager re-expanded Bad to a bare 0x80000000, so BadNoCommunication,
BadTypeMismatch and BadNotSupported were indistinguishable on the wire and every
driver's status constants (incl. the 16 #497 had just corrected) were diagnostic in
logs only. Resolved by option (b): the raw uint rides AttributeValuePublished ->
AttributeValueUpdate -> IOpcUaAddressSpaceSink.WriteValue, OpcUaQuality is deleted, and
severity classification is a helper (OpcUaStatus.IsGood/IsUncertain/IsBad).

The surface was wider than the issue costed (41 files, not "the sink and 3
implementations"): OpcUaQuality had non-driver producers with no uint to carry.
Each got its natural code — BadInternalError for a failed virtual-tag script,
BadNoCommunication for driver comms loss — and ScriptedAlarmHostActor's pair of
mutually-inverse uint<->enum mappers is deleted, having round-tripped a code the
engine already held. AddressSpaceApplier's removal writes deliberately keep the
generic Bad: not losing a code the driver had is this issue; inventing one for the
deploy path is a separate call.

Behaviour change: WriteAlarmQuality fires its Part 9 event on a status-code change
rather than a severity-bucket change. While the annotation was 3-state those were the
same predicate; now a move between two Bad reasons changes what a subscriber reads.

New SDK-free named constants live on Commons.OpcUa.OpcUaStatus, and
StatusCodeParityTests is widened to cover them — that guard is reflection-driven, so
it can only see a named constant, never an inline literal.

#517 — the symptom is real but the issue named the wrong path and its fix was unsafe.
ShutdownAsync cannot race: DriverInstanceActor calls it from PostStop, after the
mailbox drains. (Core/Hosting/DriverHost, the one class with a concurrent GetHealth,
has no production call site.) InitializeAsync can: it runs on a fire-and-forget
Task.Run, and MTConnectDriver writes Healthy then starts loops that can throw into a
catch which disposes the client before writing Faulted.

Moving the write earlier, as suggested, inverts the terminal state — teardown drains
in-flight loops that write health as they unwind, so a late loop could leave Healthy at
rest with every connection closed. The fix is a bracket (conservative before, terminal
after), applied to MTConnect's init-failure path only; shutdown keeps its single
trailing write, and the rule plus the reachability table are documented on
IDriver.ShutdownAsync.

CalculationDriver.GetHealth returned a hard-coded Healthy that consulted nothing —
Healthy before initialize, after shutdown and after dispose. Now derived from _running.
Its test, named Health_is_always_Connected, asserted the defect and is replaced.

Every new guard was falsified by breaking the production code and watching it go red.
The two sub-code tests each assert two different Bad codes, since a single-code
assertion could pass against a hard-coded constant under the old projection.

Pre-existing failures, verified unchanged on a stashed tree and not chased: 4 in
Driver.AbLegacy.IntegrationTests (slc500/micrologix/plc5 fixtures not up) and 3 in
Host.IntegrationTests.

Closes #517
Closes #519

Claude-Session: https://claude.ai/code/session_015p7wGqy3YpZNCpDzTpGMKo
2026-07-31 05:25:27 -04:00

292 lines
15 KiB
C#

using Microsoft.Extensions.Logging.Abstractions;
using Opc.Ua;
using Shouldly;
using Xunit;
using ZB.MOM.WW.OtOpcUa.Commons.OpcUa;
namespace ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests;
/// <summary>
/// Write-outcome self-correction — the BEHAVIOURAL half of the failed-device-write surfacing
/// (the pure decision tables live in <see cref="EquipmentWriteGateTests"/>). Boots a real
/// <see cref="OtOpcUaSdkServer"/> through <see cref="OpcUaApplicationHost"/> (the same harness
/// <see cref="NodeManagerHistorizeTests"/> uses) so the continuation runs against a live node
/// manager (real <c>Lock</c> + <c>SystemContext</c> + <c>Server</c>), and drives
/// <see cref="OtOpcUaNodeManager.RevertOptimisticWriteIfNeeded"/> +
/// <see cref="OtOpcUaNodeManager.BuildWriteFailureAuditEvent"/> directly:
/// <list type="bullet">
/// <item>Item B (Bad-quality blip + settle): a FAILED outcome on a node still holding the
/// optimistic value settles the node back to its prior value/status; SUCCESS / a moved-on poll
/// leave the node untouched.</item>
/// <item>Item C (AuditWriteUpdateEvent): the built audit event-state carries SourceNode=node,
/// AttributeId=Value, OldValue=prior, NewValue=attempted, ClientUserId=writer, Status=false, and
/// the device Reason in its Message. (The end-to-end <c>Server.ReportEvent</c> dispatch needs a
/// subscribed event monitored-item to observe — the nearest deterministic seam is the builder.)</item>
/// </list>
/// <para>
/// Coverage boundary (deliberate): Item C asserts the audit-event <i>builder</i> in isolation,
/// not its single call-site wiring inside <see cref="OtOpcUaNodeManager.RevertOptimisticWriteIfNeeded"/>
/// (line ~1107). Observing that wiring end-to-end would require a subscribed event monitored-item;
/// the one in-lock builder call is covered by inspection + the production-proven path (shipped
/// <c>bb59fd4e</c>). If a second audit call-site is ever added, promote this to an observed-event test.
/// </para>
/// </summary>
public sealed class NodeManagerWriteRevertTests : IDisposable
{
private static CancellationToken Ct => TestContext.Current.CancellationToken;
private readonly string _pkiRoot = Path.Combine(
Path.GetTempPath(),
$"otopcua-write-revert-{Guid.NewGuid():N}");
// ───────────────────────────── Item B — Bad-quality blip + settle ─────────────────────────────
/// <summary>(B1) A FAILED device-write outcome on a node that still holds the optimistic value SETTLES the
/// node back to its captured prior value + prior status (the transient Bad blip coalesces within one
/// publishing interval — see the method remarks — so we assert the observable settled state).</summary>
[Fact]
public async Task Failed_outcome_settles_node_back_to_prior_value_and_status()
{
var (host, server) = await BootAsync();
var nm = server.NodeManager!;
nm.EnsureVariable("eq-1/sp", parentFolderNodeId: null, displayName: "Sp", dataType: "Int32", writable: true, realm: AddressSpaceRealm.Uns);
// Prior state = Good 7; the SDK then optimistically applied 42 (the write the device will reject).
nm.WriteValue("eq-1/sp", 7, OpcUaStatus.Good, DateTime.UtcNow, realm: AddressSpaceRealm.Uns);
var node = nm.TryGetVariable("eq-1/sp")!;
node.Value = 42; // simulate the SDK's optimistic apply of the rejected write
nm.RevertOptimisticWriteIfNeeded(
"eq-1/sp",
outcome: new NodeWriteOutcome(false, "device rejected register 42"),
optimisticValue: 42,
priorValue: 7,
priorStatus: StatusCodes.Good,
clientUserId: "op", realm: AddressSpaceRealm.Uns);
node.Value.ShouldBe(7); // settled back to prior value
node.StatusCode.ShouldBe((StatusCode)StatusCodes.Good); // settled back to prior status (NOT stuck Bad)
await host.DisposeAsync();
}
/// <summary>(B2) A SUCCESS outcome NEVER reverts — the optimistic value stands (the next poll re-confirms
/// it via the normal WriteValue path).</summary>
[Fact]
public async Task Successful_outcome_leaves_optimistic_value()
{
var (host, server) = await BootAsync();
var nm = server.NodeManager!;
nm.EnsureVariable("eq-1/sp", parentFolderNodeId: null, displayName: "Sp", dataType: "Int32", writable: true, realm: AddressSpaceRealm.Uns);
nm.WriteValue("eq-1/sp", 7, OpcUaStatus.Good, DateTime.UtcNow, realm: AddressSpaceRealm.Uns);
var node = nm.TryGetVariable("eq-1/sp")!;
node.Value = 42;
nm.RevertOptimisticWriteIfNeeded(
"eq-1/sp",
outcome: new NodeWriteOutcome(true, null),
optimisticValue: 42, priorValue: 7, priorStatus: StatusCodes.Good, clientUserId: "op", realm: AddressSpaceRealm.Uns);
node.Value.ShouldBe(42); // success ⇒ optimistic value stands
await host.DisposeAsync();
}
/// <summary>(B3) A failed outcome where a fresh driver poll already moved the node OFF the optimistic value
/// does NOT clobber the poll — the node keeps the fresh polled value (the still-holds-optimistic guard).</summary>
[Fact]
public async Task Failed_outcome_does_not_clobber_a_fresh_poll()
{
var (host, server) = await BootAsync();
var nm = server.NodeManager!;
nm.EnsureVariable("eq-1/sp", parentFolderNodeId: null, displayName: "Sp", dataType: "Int32", writable: true, realm: AddressSpaceRealm.Uns);
nm.WriteValue("eq-1/sp", 7, OpcUaStatus.Good, DateTime.UtcNow, realm: AddressSpaceRealm.Uns);
var node = nm.TryGetVariable("eq-1/sp")!;
node.Value = 99; // a fresh poll already republished the confirmed register value (NOT the optimistic 42)
nm.RevertOptimisticWriteIfNeeded(
"eq-1/sp",
outcome: new NodeWriteOutcome(false, "device rejected"),
optimisticValue: 42, priorValue: 7, priorStatus: StatusCodes.Good, clientUserId: "op", realm: AddressSpaceRealm.Uns);
node.Value.ShouldBe(99); // poll value preserved — not reverted to 7
await host.DisposeAsync();
}
/// <summary>(B4) An unknown node id (rebuilt/removed in the interim) is a no-op — the continuation must not
/// throw out of its fire-and-forget body.</summary>
[Fact]
public async Task Failed_outcome_on_missing_node_is_a_noop()
{
var (host, server) = await BootAsync();
var nm = server.NodeManager!;
Should.NotThrow(() => nm.RevertOptimisticWriteIfNeeded(
"eq-1/gone",
outcome: new NodeWriteOutcome(false, "device rejected"),
optimisticValue: 42, priorValue: 7, priorStatus: StatusCodes.Good, clientUserId: "op", realm: AddressSpaceRealm.Uns));
await host.DisposeAsync();
}
// ─────────────────── v3 Batch 4 (review M2) — realm-qualified dual-node self-correction ───────────────────
/// <summary>(M2a) A failed write driven through a UNS NodeId reverts ONLY the UNS node back to its prior
/// value; the raw node that shares the SAME bare id (but lives in the Raw realm) is NEVER touched and keeps
/// its driver value. The revert routes by (realm, bareId), so it can't clobber the sibling node.</summary>
[Fact]
public async Task Failed_uns_write_reverts_uns_node_and_leaves_raw_node_untouched()
{
var (host, server) = await BootAsync();
var nm = server.NodeManager!;
// Same bare id "A/B/C/D" in BOTH realms — the raw device node and the UNS reference node.
nm.EnsureVariable("A/B/C/D", parentFolderNodeId: null, displayName: "Raw", dataType: "Int32", writable: true, realm: AddressSpaceRealm.Raw);
nm.EnsureVariable("A/B/C/D", parentFolderNodeId: null, displayName: "Uns", dataType: "Int32", writable: true, realm: AddressSpaceRealm.Uns);
var now = DateTime.UtcNow;
nm.WriteValue("A/B/C/D", 10, OpcUaStatus.Good, now, AddressSpaceRealm.Raw); // raw driver value
nm.WriteValue("A/B/C/D", 10, OpcUaStatus.Good, now, AddressSpaceRealm.Uns); // fanned UNS value
var raw = nm.TryGetVariable("A/B/C/D", AddressSpaceRealm.Raw)!;
var uns = nm.TryGetVariable("A/B/C/D", AddressSpaceRealm.Uns)!;
uns.Value = 42; // the SDK optimistically applied the client's UNS write
nm.RevertOptimisticWriteIfNeeded(
"A/B/C/D", outcome: new NodeWriteOutcome(false, "device rejected"),
optimisticValue: 42, priorValue: 10, priorStatus: StatusCodes.Good, clientUserId: "op",
realm: AddressSpaceRealm.Uns);
uns.Value.ShouldBe(10); // UNS node reverted to prior
raw.Value.ShouldBe(10); // raw node NEVER changed (realm-qualified revert)
await host.DisposeAsync();
}
/// <summary>(M2b) A raw-realm revert reverts the RAW node and leaves the same-bare-id UNS node untouched.
/// This locks the realm arg: were it omitted (defaulting to Uns) the revert would target the UNS node — whose
/// value is not the optimistic one, so the still-holds-optimistic guard skips it — leaving the raw node stuck
/// at the rejected value and FAILING the raw-reverts assertion below.</summary>
[Fact]
public async Task Raw_realm_revert_reverts_raw_node_only()
{
var (host, server) = await BootAsync();
var nm = server.NodeManager!;
nm.EnsureVariable("A/B/C/D", parentFolderNodeId: null, displayName: "Raw", dataType: "Int32", writable: true, realm: AddressSpaceRealm.Raw);
nm.EnsureVariable("A/B/C/D", parentFolderNodeId: null, displayName: "Uns", dataType: "Int32", writable: true, realm: AddressSpaceRealm.Uns);
var now = DateTime.UtcNow;
nm.WriteValue("A/B/C/D", 10, OpcUaStatus.Good, now, AddressSpaceRealm.Raw);
nm.WriteValue("A/B/C/D", 10, OpcUaStatus.Good, now, AddressSpaceRealm.Uns);
var raw = nm.TryGetVariable("A/B/C/D", AddressSpaceRealm.Raw)!;
var uns = nm.TryGetVariable("A/B/C/D", AddressSpaceRealm.Uns)!;
raw.Value = 42; // optimistic write to the RAW node
nm.RevertOptimisticWriteIfNeeded(
"A/B/C/D", outcome: new NodeWriteOutcome(false, "device rejected"),
optimisticValue: 42, priorValue: 10, priorStatus: StatusCodes.Good, clientUserId: "op",
realm: AddressSpaceRealm.Raw);
raw.Value.ShouldBe(10); // raw reverted (would stay 42 if the realm were dropped to Uns)
uns.Value.ShouldBe(10); // UNS node untouched
await host.DisposeAsync();
}
// ───────────────────────────── Item C — AuditWriteUpdateEvent builder ─────────────────────────────
/// <summary>(C1) The built audit event reflects the rejected write: SourceNode = the node, AttributeId =
/// Value, OldValue = prior, NewValue = attempted, ClientUserId = the writer, the AuditEvent Status boolean
/// = false (failed), and the device Reason is carried in the Message.</summary>
[Fact]
public async Task Built_audit_event_reflects_the_failed_write()
{
var (host, server) = await BootAsync();
var nm = server.NodeManager!;
nm.EnsureVariable("eq-1/sp", parentFolderNodeId: null, displayName: "Sp", dataType: "Int32", writable: true, realm: AddressSpaceRealm.Uns);
nm.WriteValue("eq-1/sp", 7, OpcUaStatus.Good, DateTime.UtcNow, realm: AddressSpaceRealm.Uns);
var node = nm.TryGetVariable("eq-1/sp")!;
var audit = nm.BuildWriteFailureAuditEvent(
node,
outcome: new NodeWriteOutcome(false, "FC06 rejected"),
optimisticValue: 42,
priorValue: 7,
clientUserId: "op");
audit.ShouldNotBeNull();
audit.SourceNode.Value.ShouldBe(node.NodeId);
audit.AttributeId.Value.ShouldBe((uint)Attributes.Value);
audit.OldValue.Value.ShouldBe(7);
audit.NewValue.Value.ShouldBe(42);
audit.ClientUserId.Value.ShouldBe("op");
audit.Status.Value.ShouldBeFalse(); // AuditEvent Status = false ⇒ the write failed
audit.Message.Value.Text.ShouldContain("FC06 rejected"); // device Reason carried in the Message
await host.DisposeAsync();
}
/// <summary>(C2) When the device gives no Reason, the audit Message still carries a sensible default
/// ("device write rejected") rather than an empty/null message.</summary>
[Fact]
public async Task Built_audit_event_uses_default_reason_when_none_supplied()
{
var (host, server) = await BootAsync();
var nm = server.NodeManager!;
nm.EnsureVariable("eq-1/sp", parentFolderNodeId: null, displayName: "Sp", dataType: "Int32", writable: true, realm: AddressSpaceRealm.Uns);
nm.WriteValue("eq-1/sp", 7, OpcUaStatus.Good, DateTime.UtcNow, realm: AddressSpaceRealm.Uns);
var node = nm.TryGetVariable("eq-1/sp")!;
var audit = nm.BuildWriteFailureAuditEvent(
node,
outcome: new NodeWriteOutcome(false, null),
optimisticValue: 42, priorValue: 7, clientUserId: "op");
audit.Message.Value.Text.ShouldContain("device write rejected");
await host.DisposeAsync();
}
private async Task<(OpcUaApplicationHost Host, OtOpcUaSdkServer Server)> BootAsync()
{
var host = new OpcUaApplicationHost(
new OpcUaApplicationHostOptions
{
ApplicationName = "OtOpcUa.WriteRevertTest",
ApplicationUri = $"urn:OtOpcUa.WriteRevertTest:{Guid.NewGuid():N}",
OpcUaPort = AllocateFreePort(),
PublicHostname = "localhost",
PkiStoreRoot = _pkiRoot,
},
NullLogger<OpcUaApplicationHost>.Instance);
var server = new OtOpcUaSdkServer();
await host.StartAsync(server, Ct);
return (host, server);
}
private static int AllocateFreePort()
{
using var listener = new System.Net.Sockets.TcpListener(System.Net.IPAddress.Loopback, 0);
listener.Start();
var port = ((System.Net.IPEndPoint)listener.LocalEndpoint).Port;
listener.Stop();
return port;
}
/// <summary>Cleans up the PKI root directory.</summary>
public void Dispose()
{
if (Directory.Exists(_pkiRoot))
{
try { Directory.Delete(_pkiRoot, recursive: true); }
catch { /* best-effort cleanup */ }
}
}
}