using Akka.Actor; using Akka.TestKit; using Serilog; using Shouldly; using Xunit; using ZB.MOM.WW.OtOpcUa.Commons.OpcUa; using ZB.MOM.WW.OtOpcUa.Core.ScriptedAlarms; using ZB.MOM.WW.OtOpcUa.Core.Scripting; using ZB.MOM.WW.OtOpcUa.OpcUaServer; using ZB.MOM.WW.OtOpcUa.Runtime.ScriptedAlarms; using ZB.MOM.WW.OtOpcUa.Runtime.Tests.Harness; using ZB.MOM.WW.OtOpcUa.Runtime.VirtualTags; namespace ZB.MOM.WW.OtOpcUa.Runtime.Tests.ScriptedAlarms; /// /// Gitea #937 — the host answers a directly-asked command with the engine's verdict, publishes its load outcome for /// the node manager's pre-check, and applies a command reaching it twice (ask + broadcast, same CommandId) once. /// public sealed class ScriptedAlarmCommandVerdictTests : RuntimeActorTestBase { private static readonly TimeSpan Timeout = TimeSpan.FromSeconds(30); private static CancellationToken Ct => TestContext.Current.CancellationToken; private static EquipmentScriptedAlarmPlan Plan(string id, string source = "return (int)ctx.GetTag(\"M.T\").Value > 90;") => new(ScriptedAlarmId: id, EquipmentId: "Plant/Line1/M", Name: id, AlarmType: "AlarmCondition", Severity: 800, MessageTemplate: "condition", PredicateScriptId: $"{id}-script", PredicateSource: source, DependencyRefs: ["M.T"], HistorizeToAveva: false, Retain: true, Enabled: true); private static EquipmentScriptedAlarmPlan BadPlan(string id) => Plan(id, "return unknownIdentifier;"); private (IActorRef Host, ScriptedAlarmEngine Engine, ScriptedAlarmCommandReadinessView Readiness, TestProbe Mux) Spawn() { var publish = CreateTestProbe(); var mux = CreateTestProbe(); var upstream = new DependencyMuxTagUpstreamSource(); var logger = new LoggerConfiguration().CreateLogger(); var engine = new ScriptedAlarmEngine(upstream, new InMemoryAlarmStateStore(), new ScriptLoggerFactory(logger), logger); var readiness = new ScriptedAlarmCommandReadinessView(); var host = Sys.ActorOf(ScriptedAlarmHostActor.Props(publish.Ref, mux.Ref, () => (upstream, engine), readiness: readiness)); return (host, engine, readiness, mux); } private static Task Ask(IActorRef host, string alarmId, string operation, string? comment = null, string? commandId = null) => host.Ask(new ScriptedAlarmHostActor.ExecuteAlarmCommand( new AlarmCommand(alarmId, operation, "alice", comment, null, commandId)), Timeout, Ct); [Fact] public async Task After_a_failed_load_a_command_is_refused_and_the_readiness_view_says_so() { var (host, _, readiness, mux) = Spawn(); host.Tell(new ScriptedAlarmHostActor.ApplyScriptedAlarms([Plan("alm-1")])); mux.ExpectMsg(Timeout, cancellationToken: Ct); readiness.Refusal().ShouldBeNull(); // Positive control: a good generation applies (an ack of an inactive alarm is an applied no-op). (await Ask(host, "alm-1", "AddComment", "first")).Verdict.ShouldBe(AlarmCommandVerdict.Applied); // A deploy that fails to compile leaves the engine with no complete generation. host.Tell(new ScriptedAlarmHostActor.ApplyScriptedAlarms([Plan("alm-1"), BadPlan("bad-1")])); AwaitCondition(() => readiness.Refusal() is not null, Timeout, cancellationToken: Ct); var refused = await Ask(host, "alm-1", "Acknowledge"); refused.Verdict.ShouldBe(AlarmCommandVerdict.NotApplied); refused.Reason.ShouldBe(ScriptedAlarmCommandReadinessView.LoadFailedRefusal); // The alarm that broke the load is still this host's (in the plan, absent from the half-built engine set). (await Ask(host, "bad-1", "Acknowledge")).Verdict.ShouldBe(AlarmCommandVerdict.NotApplied); // The next good deploy clears it. host.Tell(new ScriptedAlarmHostActor.ApplyScriptedAlarms([Plan("alm-1")])); AwaitCondition(() => readiness.Refusal() is null, Timeout, cancellationToken: Ct); (await Ask(host, "alm-1", "AddComment", "second")).Verdict.ShouldBe(AlarmCommandVerdict.Applied); } /// /// #937 review r2 M2: an ask still queued past its asker's deadline never touches the engine (no growth of late work /// behind a stalled store) and is NOT remembered — the broadcast copy of the same command still applies here. /// [Fact] public async Task An_expired_ask_skips_the_engine_and_leaves_the_broadcast_copy_to_apply() { var (host, engine, _, mux) = Spawn(); host.Tell(new ScriptedAlarmHostActor.ApplyScriptedAlarms([Plan("alm-1")])); mux.ExpectMsg(Timeout, cancellationToken: Ct); var cmd = new AlarmCommand("alm-1", "AddComment", "alice", "late", null, "cmd-late"); var expired = await host.Ask( new ScriptedAlarmHostActor.ExecuteAlarmCommand(cmd, DateTime.UtcNow.AddSeconds(-1)), Timeout, Ct); expired.Verdict.ShouldBe(AlarmCommandVerdict.OutcomeUnknown); engine.GetState("alm-1")!.Comments.ShouldBeEmpty("the expired ask never reached the engine"); host.Tell(cmd); // the broadcast copy (same CommandId) // Positive control behind it in the mailbox: a fresh ask (in time) applies, so the copy was processed first. (await Ask(host, "alm-1", "AddComment", "after", "cmd-after")).Verdict.ShouldBe(AlarmCommandVerdict.Applied); engine.GetState("alm-1")!.Comments.Select(c => c.Text).ShouldBe(["late", "after"]); } [Fact] public async Task An_alarm_this_host_does_not_own_is_answered_not_applied() { var (host, _, _, mux) = Spawn(); host.Tell(new ScriptedAlarmHostActor.ApplyScriptedAlarms([Plan("alm-1")])); mux.ExpectMsg(Timeout, cancellationToken: Ct); var outcome = await Ask(host, "someone-elses", "Acknowledge"); outcome.Verdict.ShouldBe(AlarmCommandVerdict.NotApplied); } [Theory] [InlineData(true)] [InlineData(false)] public async Task A_command_arriving_as_both_ask_and_broadcast_is_applied_once(bool broadcastFirst) { var (host, engine, _, mux) = Spawn(); host.Tell(new ScriptedAlarmHostActor.ApplyScriptedAlarms([Plan("alm-1")])); mux.ExpectMsg(Timeout, cancellationToken: Ct); var broadcast = new AlarmCommand("alm-1", "AddComment", "alice", "note", null, "cmd-1"); AlarmCommandOutcome outcome; if (broadcastFirst) { host.Tell(broadcast); outcome = await Ask(host, "alm-1", "AddComment", "note", "cmd-1"); } else { outcome = await Ask(host, "alm-1", "AddComment", "note", "cmd-1"); host.Tell(broadcast); } outcome.Verdict.ShouldBe(AlarmCommandVerdict.Applied); // Positive control: a different id IS applied — so the count below proves de-duplication, not a dropped copy. (await Ask(host, "alm-1", "AddComment", "other", "cmd-2")).Verdict.ShouldBe(AlarmCommandVerdict.Applied); engine.GetState("alm-1")!.Comments.Select(c => c.Text).ShouldBe(["note", "other"]); } }