diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests/ConditionMethodNodeManagerTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests/ConditionMethodNodeManagerTests.cs new file mode 100644 index 000000000..d198308d1 --- /dev/null +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests/ConditionMethodNodeManagerTests.cs @@ -0,0 +1,278 @@ +using Opc.Ua; +using Shouldly; +using Xunit; +using ZB.MOM.WW.OtOpcUa.Commons.OpcUa; +using ZB.MOM.WW.OtOpcUa.Core.Abstractions; + +namespace ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests; + +/// +/// A2b origin execution (plan §5.6 "Origin"): runs a remote +/// condition method through the SAME wrapped SDK handler a local client's call runs — one event, the native +/// re-assert, the routers — and refuses (no state change) on Warm Standby, off-Primary, native Confirm and an +/// activation-marker mismatch. +/// +[Trait("Feature", "GrpcData")] +[Trait("Phase", "A2")] +[Trait("Category", "Unit")] +public sealed class ConditionMethodNodeManagerTests : IDisposable +{ + private const string Device = "Plant/Galaxy/dev1"; + private const string Native = "Plant/Galaxy/dev1/TankHi"; + private const string Equipment = "Area/Line/Eq"; + private const string Scripted = "scripted-eq-hi"; + private const uint BadEventIdUnknown = 0x809A0000u; + + private static CancellationToken Ct => TestContext.Current.CancellationToken; + private readonly string _pkiRoot = Path.Combine(Path.GetTempPath(), $"otopcua-a2b-{Guid.NewGuid():N}"); + + private static AlarmConditionSnapshot State(bool active, bool acked, string message = "hi") => new( + Active: active, Acknowledged: acked, Confirmed: true, Enabled: true, Shelving: AlarmShelvingKind.Unshelved, + Severity: 700, Message: message, StatusCode: OpcUaStatus.Good); + + private static OriginConditionMethodCall Call(OtOpcUaNodeManager nm, string id, AddressSpaceRealm realm, string method, + string? comment = null, ConditionActivationMarker? marker = null) => + new(realm, id, method, comment, marker ?? nm.GetActivationMarker(id, realm)!.Value, "peer-svc", "0a1b2c3d4e5f6071"); + + [Fact] + public async Task A_remote_native_ack_is_reported_once_to_origin_subscribers_and_routed_to_the_driver() + { + var (host, nm, sink) = await BootAsync(); + Materialise(nm); + var routed = new List(); + nm.NativeAlarmAckRouter = routed.Add; + nm.WriteAlarmCondition(Native, State(true, false), DateTime.UtcNow, AddressSpaceRealm.Raw); + var alarm = nm.TryGetAlarmCondition(Native, AddressSpaceRealm.Raw)!; + var events = CountEvents(alarm); + + var outcome = nm.TryExecuteConditionMethod(Call(nm, Native, AddressSpaceRealm.Raw, "Acknowledge", "remote ok")); + + outcome.ShouldBe(new OriginConditionMethodOutcome(true, true, StatusCodes.Good.Code, null)); + events().ShouldBe(1); // exactly one ack event at the origin + alarm.AckedState!.Id!.Value.ShouldBeTrue(); + alarm.ConfirmedState!.Id!.Value.ShouldBeTrue(); // the native re-assert + alarm.ClientUserId!.Value.ShouldBe("peer-svc"); // the service principal, never remote text + routed.ShouldHaveSingleItem().ShouldSatisfyAllConditions( + a => a.ConditionNodeId.ShouldBe(Native), a => a.OperatorUser.ShouldBe("peer-svc"), + a => a.ApiKeyId.ShouldBe("0a1b2c3d4e5f6071"), a => a.Comment.ShouldBe("remote ok")); + sink.Records.Last().ShouldSatisfyAllConditions(r => r.Acknowledged.ShouldBeTrue(), r => r.Comment.ShouldBe("remote ok")); + ConditionStateNodeManagerTests.AssertParity(nm, sink); + await host.DisposeAsync(); + } + + [Fact] + public async Task A_driver_failure_reverts_on_the_origin_and_in_the_condition_stream_and_invalidates_the_old_marker() + { + var (host, nm, sink) = await BootAsync(); + Materialise(nm); + nm.NativeAlarmAckRouter = _ => { }; + nm.WriteAlarmCondition(Native, State(true, false), DateTime.UtcNow, AddressSpaceRealm.Raw); + var alarm = nm.TryGetAlarmCondition(Native, AddressSpaceRealm.Raw)!; + var marker = nm.GetActivationMarker(Native, AddressSpaceRealm.Raw)!.Value; + nm.TryExecuteConditionMethod(Call(nm, Native, AddressSpaceRealm.Raw, "Acknowledge")).Applied.ShouldBeTrue(); + var events = CountEvents(alarm); + + // #760: DriverHostActor's revert re-projects the condition unacknowledged through the same sink write. + nm.WriteAlarmCondition(Native, State(true, false), DateTime.UtcNow, AddressSpaceRealm.Raw); + + events().ShouldBe(1); // the origin's subscribers see the revert + alarm.AckedState!.Id!.Value.ShouldBeFalse(); + sink.Records.Last().ShouldSatisfyAllConditions(r => r.Acknowledged.ShouldBeFalse(), + r => r.Activation.Sequence.ShouldBe(marker.Sequence + 1)); // the stream carries the revert as a new occurrence + nm.TryExecuteConditionMethod(Call(nm, Native, AddressSpaceRealm.Raw, "Acknowledge", marker: marker)) + .ShouldSatisfyAllConditions(o => o.Applied.ShouldBeFalse(), o => o.StatusCode.ShouldBe(BadEventIdUnknown)); + await host.DisposeAsync(); + } + + [Fact] + public async Task A_remote_native_AddComment_is_stored_and_reported_once() + { + var (host, nm, sink) = await BootAsync(); + Materialise(nm); + var commands = new List(); + nm.AlarmCommandRouter = commands.Add; + nm.WriteAlarmCondition(Native, State(true, false), DateTime.UtcNow, AddressSpaceRealm.Raw); + var alarm = nm.TryGetAlarmCondition(Native, AddressSpaceRealm.Raw)!; + var events = CountEvents(alarm); + + nm.TryExecuteConditionMethod(Call(nm, Native, AddressSpaceRealm.Raw, "AddComment", "shift note")).Applied.ShouldBeTrue(); + + alarm.Comment!.Value.Text.ShouldBe("shift note"); + events().ShouldBe(1); + sink.Records.Last().Comment.ShouldBe("shift note"); + // AlarmCommand is unchanged (§6): the service principal as User, the Part 9 comment, nothing else. + commands.ShouldHaveSingleItem().ShouldBe(new AlarmCommand(Native, "AddComment", "peer-svc", "shift note", null)); + await host.DisposeAsync(); + } + + [Fact] + public async Task A_remote_scripted_ack_routes_an_unchanged_AlarmCommand_and_confirm_is_supported() + { + var (host, nm, _) = await BootAsync(); + Materialise(nm); + var commands = new List(); + nm.AlarmCommandRouter = commands.Add; + nm.WriteAlarmCondition(Scripted, State(true, false), DateTime.UtcNow, AddressSpaceRealm.Uns); + + var ack = nm.TryExecuteConditionMethod(Call(nm, Scripted, AddressSpaceRealm.Uns, "Acknowledge", "c1")); + var confirm = nm.TryExecuteConditionMethod(Call(nm, Scripted, AddressSpaceRealm.Uns, "Confirm")); + + ack.ShouldBe(new OriginConditionMethodOutcome(true, false, StatusCodes.Good.Code, null)); + confirm.Applied.ShouldBeTrue(); + commands.Select(c => (c.Operation, c.User, c.Comment)).ShouldBe([("Acknowledge", "peer-svc", "c1"), ("Confirm", "peer-svc", null)]); + await host.DisposeAsync(); + } + + [Fact] + public async Task Native_Confirm_and_an_unknown_condition_are_refused_with_no_state_change() + { + var (host, nm, sink) = await BootAsync(); + Materialise(nm); + nm.WriteAlarmCondition(Native, State(true, false), DateTime.UtcNow, AddressSpaceRealm.Raw); + var before = sink.Records.Count; + + nm.TryExecuteConditionMethod(Call(nm, Native, AddressSpaceRealm.Raw, "Confirm")) + .ShouldSatisfyAllConditions(o => o.Applied.ShouldBeFalse(), o => o.StatusCode.ShouldBe(StatusCodes.BadNotSupported.Code)); + nm.TryExecuteConditionMethod(new(AddressSpaceRealm.Raw, "Plant/Nope", "Acknowledge", null, new("x", 0), "peer-svc", null)) + .StatusCode.ShouldBe(StatusCodes.BadNodeIdUnknown.Code); + sink.Records.Count.ShouldBe(before); + await host.DisposeAsync(); + } + + [Fact] + public async Task Off_Primary_and_Warm_Standby_refuse_before_any_state_change() + { + var (host, nm, sink) = await BootAsync(); + Materialise(nm); + var routed = new List(); + nm.NativeAlarmAckRouter = routed.Add; + nm.WriteAlarmCondition(Native, State(true, false), DateTime.UtcNow, AddressSpaceRealm.Raw); + var before = sink.Records.Count; + + nm.NativeAlarmAckPrimaryGate = () => false; + nm.TryExecuteConditionMethod(Call(nm, Native, AddressSpaceRealm.Raw, "Acknowledge")) + .ShouldSatisfyAllConditions(o => o.Applied.ShouldBeFalse(), o => o.StatusCode.ShouldBe(StatusCodes.BadInvalidState.Code)); + // Primary-only for BOTH kinds (§5.6): the scripted condition is refused off-Primary too. + nm.WriteAlarmCondition(Scripted, State(true, false), DateTime.UtcNow, AddressSpaceRealm.Uns); + var scriptedBefore = sink.Records.Count; + nm.TryExecuteConditionMethod(Call(nm, Scripted, AddressSpaceRealm.Uns, "Acknowledge")).Applied.ShouldBeFalse(); + + nm.TryGetAlarmCondition(Native, AddressSpaceRealm.Raw)!.AckedState!.Id!.Value.ShouldBeFalse(); + routed.ShouldBeEmpty(); + sink.Records.Count.ShouldBe(scriptedBefore); + before.ShouldBeLessThan(scriptedBefore); + await host.DisposeAsync(); + + var (warmHost, warm, warmSink) = await BootAsync(warm: true); + warm.Standby.DataProjected.ShouldBeTrue(); // a Warm standby projects data and refuses mutations + Materialise(warm); + warm.WriteAlarmCondition(Native, State(true, false), DateTime.UtcNow, AddressSpaceRealm.Raw); + var warmBefore = warmSink.Records.Count; + warm.TryExecuteConditionMethod(Call(warm, Native, AddressSpaceRealm.Raw, "Acknowledge")) + .ShouldSatisfyAllConditions(o => o.Applied.ShouldBeFalse(), o => o.StatusCode.ShouldBe(StatusCodes.BadInvalidState.Code)); + warm.TryGetAlarmCondition(Native, AddressSpaceRealm.Raw)!.AckedState!.Id!.Value.ShouldBeFalse(); + warmSink.Records.Count.ShouldBe(warmBefore); + await warmHost.DisposeAsync(); + } + + [Fact] + public async Task T3_an_unchanged_reprojection_keeps_the_marker_ackable_and_a_changed_message_reraise_does_not() + { + var (host, nm, _) = await BootAsync(); + Materialise(nm); + nm.NativeAlarmAckRouter = _ => { }; + nm.AlarmCommandRouter = _ => { }; + + // Native: a message-only re-projection (Active/Acked unchanged) keeps the old marker valid. + nm.WriteAlarmCondition(Native, State(true, false, "hi"), DateTime.UtcNow, AddressSpaceRealm.Raw); + var old = nm.GetActivationMarker(Native, AddressSpaceRealm.Raw)!.Value; + nm.WriteAlarmCondition(Native, State(true, false, "hi (updated)"), DateTime.UtcNow, AddressSpaceRealm.Raw); + nm.TryExecuteConditionMethod(Call(nm, Native, AddressSpaceRealm.Raw, "Acknowledge", marker: old)).Applied.ShouldBeTrue(); + + // A changed-message re-raise un-acknowledges: a new occurrence, so the pre-re-raise marker is refused. + var acked = nm.GetActivationMarker(Native, AddressSpaceRealm.Raw)!.Value; + nm.WriteAlarmCondition(Native, State(true, false, "re-raised"), DateTime.UtcNow, AddressSpaceRealm.Raw); + nm.TryExecuteConditionMethod(Call(nm, Native, AddressSpaceRealm.Raw, "Acknowledge", marker: acked)) + .StatusCode.ShouldBe(BadEventIdUnknown); + nm.TryGetAlarmCondition(Native, AddressSpaceRealm.Raw)!.AckedState!.Id!.Value.ShouldBeFalse(); + + // Scripted: a re-assert of the same state keeps the marker; another incarnation never matches. + nm.WriteAlarmCondition(Scripted, State(true, false), DateTime.UtcNow, AddressSpaceRealm.Uns); + var scripted = nm.GetActivationMarker(Scripted, AddressSpaceRealm.Uns)!.Value; + nm.WriteAlarmCondition(Scripted, State(true, false), DateTime.UtcNow, AddressSpaceRealm.Uns); + nm.TryExecuteConditionMethod(Call(nm, Scripted, AddressSpaceRealm.Uns, "Acknowledge", + marker: scripted with { Incarnation = "another-incarnation" })).StatusCode.ShouldBe(BadEventIdUnknown); + nm.TryExecuteConditionMethod(Call(nm, Scripted, AddressSpaceRealm.Uns, "Acknowledge", marker: scripted)).Applied.ShouldBeTrue(); + await host.DisposeAsync(); + } + + [Fact] + public async Task The_pre_authorization_never_leaks_to_a_local_session_call() + { + // A local client's call still goes through the session gate: an identity with no AlarmAck role is denied. + var (host, nm, _) = await BootAsync(); + Materialise(nm); + var routed = new List(); + nm.NativeAlarmAckRouter = routed.Add; + nm.WriteAlarmCondition(Native, State(true, false), DateTime.UtcNow, AddressSpaceRealm.Raw); + var alarm = nm.TryGetAlarmCondition(Native, AddressSpaceRealm.Raw)!; + + var result = alarm.Acknowledge!.OnCall!(nm.SystemContext, alarm.Acknowledge, alarm.NodeId, alarm.EventId!.Value, new LocalizedText("x")); + + ServiceResult.IsBad(result).ShouldBeTrue(); + routed.ShouldBeEmpty(); + alarm.AckedState!.Id!.Value.ShouldBeFalse(); + await host.DisposeAsync(); + } + + // ---------------------------------------------------------------- helpers + + private static Func CountEvents(AlarmConditionState alarm) + { + var count = 0; + var inner = alarm.OnReportEvent; + alarm.OnReportEvent = (context, node, e) => { Interlocked.Increment(ref count); inner?.Invoke(context, node, e); }; + return () => Volatile.Read(ref count); + } + + private static void Materialise(OtOpcUaNodeManager nm) + { + nm.EnsureFolder(Device, null, "dev1", AddressSpaceRealm.Raw); + nm.MaterialiseAlarmCondition(Native, Device, "TankHi", "OffNormalAlarm", 700, AddressSpaceRealm.Raw, isNative: true); + nm.EnsureFolder(Equipment, null, "Eq", AddressSpaceRealm.Uns); + nm.MaterialiseAlarmCondition(Scripted, Equipment, "Hi", "AlarmCondition", 500, AddressSpaceRealm.Uns); + nm.CompleteAddressSpaceApply(); + } + + private async Task<(OpcUaApplicationHost Host, OtOpcUaNodeManager Nm, RecordingConditionSink Sink)> BootAsync(bool warm = false) + { + var applicationUri = $"urn:OtOpcUa.A2bTest:{Guid.NewGuid():N}"; + var started = await OpcUaHostStart.StartAsync( + port => new OpcUaApplicationHost( + new OpcUaApplicationHostOptions + { + ApplicationName = "OtOpcUa.A2bTest", + ApplicationUri = applicationUri, + OpcUaPort = port, + PublicHostname = "localhost", + PkiStoreRoot = Path.Combine(_pkiRoot, Guid.NewGuid().ToString("N")), + Redundancy = new OpcUaRedundancyOptions { Mode = warm ? "Warm" : "Unset" }, + PeerApplicationUris = warm ? ["urn:peer"] : [], + }, + Microsoft.Extensions.Logging.Abstractions.NullLogger.Instance), + () => new OtOpcUaSdkServer(), Ct); + var nm = started.Server.NodeManager!; + var sink = new RecordingConditionSink(); + nm.ConditionStateSink = sink; + return (started.Host, nm, sink); + } + + public void Dispose() + { + if (Directory.Exists(_pkiRoot)) + { + try { Directory.Delete(_pkiRoot, recursive: true); } + catch { /* best-effort cleanup */ } + } + } +}