using System.Collections.Concurrent; using Opc.Ua; using Shouldly; using Xunit; using ZB.MOM.WW.OtOpcUa.Commons.OpcUa; using ZB.MOM.WW.OtOpcUa.Configuration.Enums; using static ZB.MOM.WW.OtOpcUa.OpcUaServer.IntegrationTests.ServerEventRig; namespace ZB.MOM.WW.OtOpcUa.OpcUaServer.IntegrationTests; /// /// Gitea #937 over the wire — a scripted condition's Part 9 method returns the scripted-alarm engine's verdict. Before /// #937 the command was a fire-and-forget topic publish and every allowed call returned Good, including one the engine /// then rejected because its last load had failed. /// public sealed class ScriptedCommandVerdictWireTests { private const NodePermissions All = NodePermissions.Browse | NodePermissions.Read | NodePermissions.Subscribe | NodePermissions.AlarmRead | NodePermissions.AlarmAcknowledge | NodePermissions.AlarmConfirm | NodePermissions.AlarmShelve | NodePermissions.MethodCall; /// The engine refuses (no complete generation): the client's Acknowledge fails BadInvalidState with its reason. [Theory] [InlineData("Acknowledge")] [InlineData("AddComment")] [InlineData("OneShotShelve")] [InlineData("Disable")] public async Task A_command_the_engine_refuses_returns_BadInvalidState(string method) { var ct = TestContext.Current.CancellationToken; var rig = await StartAsync($"Verdict937Refused{method}", encrypted: false, ct); try { rig.Enforce(false, [Key()], ClusterGrant(KeyPrincipal, "acl-key", All)); rig.MaterialiseScripted(); var asked = new ConcurrentQueue(); rig.Nm.AlarmCommandAsker = (cmd, _) => { asked.Enqueue(cmd); return Task.FromResult(new AlarmCommandOutcome(cmd.AlarmId, cmd.Operation, AlarmCommandVerdict.NotApplied, "engine blind")); }; using var session = await rig.ConnectAsync(anonymous: false, ct); var events = new RecordedEvents(); var subscription = await RecordedEvents.SubscribeAsync(session, events, ct); var item = RecordedEvents.AddEventItem(subscription, ObjectIds.Server); await subscription.ApplyChangesAsync(ct); rig.Project(false, ConditionMethodEventTests.PreState(method, native: false) with { Message = "base" }); await RecordedEvents.WaitUntilAsync(() => events.Has(item, "base")); var refused = await Should.ThrowAsync(ConditionMethodEventTests.CallAsync( session, ConditionNodeId(session, false), method, events.LatestEventId(item, "base"), ct)); refused.StatusCode.ShouldBe(StatusCodes.BadInvalidState); asked.Count.ShouldBe(1, "the command reached the engine exactly once"); asked.Single().CommandId.ShouldNotBeNullOrEmpty("the local host de-duplicates the broadcast copy by it"); await subscription.DeleteAsync(true, ct); } finally { await rig.DisposeAsync(); } } /// Positive control: an applied verdict is Good, and the method still reports exactly one event. [Fact] public async Task A_command_the_engine_applies_returns_Good_with_one_event() { var ct = TestContext.Current.CancellationToken; var rig = await StartAsync("Verdict937Applied", encrypted: false, ct); try { rig.Enforce(false, [Key()], ClusterGrant(KeyPrincipal, "acl-key", All)); rig.MaterialiseScripted(); var current = ConditionMethodEventTests.PreState("Acknowledge", native: false) with { Message = "base" }; var routed = new ConcurrentQueue(); rig.Nm.AlarmCommandRouter = routed.Enqueue; rig.Nm.AlarmCommandAsker = (cmd, _) => { // What the engine does: apply, then re-project (the method's own event already covered it). current = current with { Acknowledged = true }; rig.ProjectLater(native: false, current); return Task.FromResult(new AlarmCommandOutcome(cmd.AlarmId, cmd.Operation, AlarmCommandVerdict.Applied)); }; using var session = await rig.ConnectAsync(anonymous: false, ct); var events = new RecordedEvents(); var subscription = await RecordedEvents.SubscribeAsync(session, events, ct); var item = RecordedEvents.AddEventItem(subscription, ObjectIds.Server); await subscription.ApplyChangesAsync(ct); rig.Project(false, current); await RecordedEvents.WaitUntilAsync(() => events.Has(item, "base")); await ConditionMethodEventTests.CallAsync(session, ConditionNodeId(session, false), "Acknowledge", events.LatestEventId(item, "base"), ct); await rig.DrainProjectionsAsync(); rig.Project(false, current = current with { Message = "sentinel" }); await RecordedEvents.WaitUntilAsync(() => events.Has(item, "sentinel")); events.ConditionEvents(item, "base").Count.ShouldBe(2, "the base transition plus exactly one Acknowledge event"); routed.ShouldBeEmpty("the asker replaces the fire-and-forget router inside a Call"); await subscription.DeleteAsync(true, ct); } finally { await rig.DisposeAsync(); } } /// No answer inside the bound: BadTimeout with OutcomeUnknown — never reported as refused. [Fact] public async Task An_unanswered_command_returns_BadTimeout_outcome_unknown() { var ct = TestContext.Current.CancellationToken; var rig = await StartAsync("Verdict937Timeout", encrypted: false, ct); try { rig.Enforce(false, [Key()], ClusterGrant(KeyPrincipal, "acl-key", All)); rig.MaterialiseScripted(); rig.Nm.ScriptedCommandTimeout = TimeSpan.FromMilliseconds(500); var never = new TaskCompletionSource(); rig.Nm.AlarmCommandAsker = (_, _) => never.Task; using var session = await rig.ConnectAsync(anonymous: false, ct); var events = new RecordedEvents(); var subscription = await RecordedEvents.SubscribeAsync(session, events, ct); var item = RecordedEvents.AddEventItem(subscription, ObjectIds.Server); await subscription.ApplyChangesAsync(ct); rig.Project(false, ConditionMethodEventTests.PreState("Acknowledge", native: false) with { Message = "base" }); await RecordedEvents.WaitUntilAsync(() => events.Has(item, "base")); var started = DateTime.UtcNow; var unknown = await Should.ThrowAsync(ConditionMethodEventTests.CallAsync( session, ConditionNodeId(session, false), "Acknowledge", events.LatestEventId(item, "base"), ct)); unknown.StatusCode.ShouldBe(StatusCodes.BadTimeout); (DateTime.UtcNow - started).ShouldBeLessThan(TimeSpan.FromSeconds(10), "bounded"); await subscription.DeleteAsync(true, ct); } finally { await rig.DisposeAsync(); } } /// /// The synchronous pre-check: while the last load failed, the call is refused BadInvalidState BEFORE the SDK applies /// anything — nothing is asked or routed, and no condition event is reported (sentinel-checked). /// [Fact] public async Task The_preflight_refuses_before_any_state_change() { var ct = TestContext.Current.CancellationToken; var rig = await StartAsync("Verdict937Preflight", encrypted: false, ct); try { rig.Enforce(false, [Key()], ClusterGrant(KeyPrincipal, "acl-key", All)); rig.MaterialiseScripted(); var asked = 0; var routed = 0; rig.Nm.AlarmCommandAsker = (cmd, _) => { Interlocked.Increment(ref asked); return Task.FromResult(new AlarmCommandOutcome(cmd.AlarmId, cmd.Operation, AlarmCommandVerdict.Applied)); }; rig.Nm.AlarmCommandRouter = _ => Interlocked.Increment(ref routed); string? refusal = "the last scripted-alarm deploy failed"; rig.Nm.ScriptedAlarmCommandPreflight = () => refusal; var current = ConditionMethodEventTests.PreState("Acknowledge", native: false) with { Message = "base" }; using var session = await rig.ConnectAsync(anonymous: false, ct); var events = new RecordedEvents(); var subscription = await RecordedEvents.SubscribeAsync(session, events, ct); var item = RecordedEvents.AddEventItem(subscription, ObjectIds.Server); await subscription.ApplyChangesAsync(ct); rig.Project(false, current); await RecordedEvents.WaitUntilAsync(() => events.Has(item, "base")); var refused = await Should.ThrowAsync(ConditionMethodEventTests.CallAsync( session, ConditionNodeId(session, false), "Acknowledge", events.LatestEventId(item, "base"), ct)); refused.StatusCode.ShouldBe(StatusCodes.BadInvalidState); rig.Project(false, current with { Message = "sentinel" }); await RecordedEvents.WaitUntilAsync(() => events.Has(item, "sentinel")); events.ConditionEvents(item, "base").Count.ShouldBe(1, "no Acknowledge event was reported"); events.ConditionEvents(item, "sentinel")[0][RecordedEvents.AckedField].ClrValue()!.ShouldBe(false, "the node was not acknowledged"); Volatile.Read(ref asked).ShouldBe(0); Volatile.Read(ref routed).ShouldBe(0); // Positive control: once a load succeeds the same call goes through. refusal = null; await ConditionMethodEventTests.CallAsync(session, ConditionNodeId(session, false), "Acknowledge", events.LatestEventId(item, "sentinel"), ct); Volatile.Read(ref asked).ShouldBe(1); await subscription.DeleteAsync(true, ct); } finally { await rig.DisposeAsync(); } } /// /// A NATIVE condition's AddComment is applied at the node (no scripted engine owns it): neither the scripted pre-check /// nor the verdict ask applies, even while the scripted engine is blind (caught live by A02 on fu937-1). /// [Fact] public async Task A_native_AddComment_is_not_subject_to_the_scripted_verdict() { var ct = TestContext.Current.CancellationToken; var rig = await StartAsync("Verdict937NativeComment", encrypted: false, ct); try { rig.Enforce(false, [Key()], ClusterGrant(KeyPrincipal, "acl-key", All)); rig.MaterialiseNative(); var asked = 0; rig.Nm.AlarmCommandAsker = (cmd, _) => { Interlocked.Increment(ref asked); return Task.FromResult(new AlarmCommandOutcome(cmd.AlarmId, cmd.Operation, AlarmCommandVerdict.NotApplied, "not mine")); }; rig.Nm.ScriptedAlarmCommandPreflight = () => "the scripted engine is blind"; using var session = await rig.ConnectAsync(anonymous: false, ct); var events = new RecordedEvents(); var subscription = await RecordedEvents.SubscribeAsync(session, events, ct); var item = RecordedEvents.AddEventItem(subscription, ObjectIds.Server); await subscription.ApplyChangesAsync(ct); rig.Project(true, ConditionMethodEventTests.PreState("AddComment", native: true) with { Message = "base" }); await RecordedEvents.WaitUntilAsync(() => events.Has(item, "base")); await ConditionMethodEventTests.CallAsync(session, ConditionNodeId(session, true), "AddComment", events.LatestEventId(item, "base"), ct); Volatile.Read(ref asked).ShouldBe(0); await subscription.DeleteAsync(true, ct); } finally { await rig.DisposeAsync(); } } /// A2b: a remote (gRPC data) condition method on a scripted condition carries the same verdict. [Fact] public async Task A_remote_condition_method_reports_the_engine_refusal_as_dispatched() { var ct = TestContext.Current.CancellationToken; var rig = await StartAsync("Verdict937Remote", encrypted: false, ct); try { rig.MaterialiseScripted(); rig.Project(false, ConditionMethodEventTests.PreState("Acknowledge", native: false) with { Message = "base" }); await rig.DrainProjectionsAsync(); rig.Nm.AlarmCommandAsker = (cmd, _) => Task.FromResult(new AlarmCommandOutcome(cmd.AlarmId, cmd.Operation, AlarmCommandVerdict.NotApplied, "engine blind")); var marker = rig.Nm.SnapshotConditions((_, id) => id == ScriptedAlarmId, 10) .SelectMany(s => s.Records).Single(c => c.ConditionId == ScriptedAlarmId).Activation; var call = new OriginConditionMethodCall(AddressSpaceRealm.Uns, ScriptedAlarmId, "Acknowledge", "ack", marker, "svc", null); var refused = await rig.Nm.ExecuteConditionMethodAsync(call, TimeSpan.FromSeconds(5)); refused.Applied.ShouldBeFalse(); refused.Dispatched.ShouldBeTrue(); refused.Unknown.ShouldBeFalse(); refused.StatusCode.ShouldBe(StatusCodes.BadInvalidState.Code); refused.Diagnostic.ShouldBe("engine blind"); } finally { await rig.DisposeAsync(); } } }