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.OpcUa; 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; /// /// A1 (grpc-data plan §5.1 T2/F2): reaches the publish actor as /// on the same chain as the host's /// s — after the projection it summarises, and after the post-load /// re-assert when it was raised by a (re)load. /// [Trait("Feature", "GrpcData")] [Trait("Phase", "A1")] [Trait("Category", "Unit")] public sealed class ScriptedAlarmHostInputsEstablishedTests : RuntimeActorTestBase { private readonly string _pkiRoot = Path.Combine(Path.GetTempPath(), $"otopcua-a1host-{Guid.NewGuid():N}"); private static readonly TimeSpan Timeout = TimeSpan.FromSeconds(30); private static CancellationToken Ct => TestContext.Current.CancellationToken; private static EquipmentScriptedAlarmPlan Plan() => new( ScriptedAlarmId: "alm-1", EquipmentId: "Plant/Line1/M", Name: "HighTemp", AlarmType: "AlarmCondition", Severity: 800, MessageTemplate: "condition", PredicateScriptId: "alm-1-script", PredicateSource: "return (int)ctx.GetTag(\"M.T\").Value > 90;", DependencyRefs: ["M.T"], HistorizeToAveva: false, Retain: true, Enabled: true); private IActorRef Spawn(TestProbe publish, TestProbe mux) => Spawn(publish, mux, new InMemoryAlarmStateStore(), out _); private IActorRef Spawn(TestProbe publish, TestProbe mux, IAlarmStateStore store, out ScriptedAlarmEngine engine) { var upstream = new DependencyMuxTagUpstreamSource(); var logger = new LoggerConfiguration().CreateLogger(); engine = new ScriptedAlarmEngine(upstream, store, new ScriptLoggerFactory(logger), logger); return Sys.ActorOf(ScriptedAlarmHostActor.Props(publish.Ref, mux.Ref, upstream, engine, null)); } /// /// Review B1 (T2 case i): a restart restores a persisted UNACKED alarm (Active is not persisted). The post-load /// re-assert projects it Active=false while its input is still never-pushed, and an operator ack before the input /// arrives projects it again. Neither projection may make the condition known — that would be a /// known=true, Active=false record no predicate decided. Known comes only from the engine's flip after the /// first real evaluation. The host's publish-probe traffic is applied to a real node manager + hub. /// [Fact] public async Task A_restored_unacked_alarm_is_not_known_through_its_reassert_or_an_early_ack() { var store = new InMemoryAlarmStateStore(); await store.SaveAsync(AlarmConditionState.Fresh("alm-1", DateTime.UtcNow) with { Acked = AlarmAckedState.Unacknowledged }, Ct); var (opcHost, nm) = await BootNodeManagerAsync(); var hub = new ZB.MOM.WW.OtOpcUa.Runtime.DataConnections.ConditionStateHub(); nm.ConditionStateSink = hub; nm.EnsureFolder("Plant/Line1/M", null, "M", AddressSpaceRealm.Uns); nm.MaterialiseAlarmCondition("alm-1", "Plant/Line1/M", "HighTemp", "AlarmCondition", 800, AddressSpaceRealm.Uns); nm.CompleteAddressSpaceApply(); var publish = CreateTestProbe(); var mux = CreateTestProbe(); var host = Spawn(publish, mux, store, out var engine); host.Tell(new ScriptedAlarmHostActor.ApplyScriptedAlarms([Plan()])); mux.ExpectMsg(Timeout, cancellationToken: Ct); // The post-load re-assert of the restored unacked state, input still never-pushed. var reassert = publish.ExpectMsg(Timeout, cancellationToken: Ct); reassert.State.Active.ShouldBeFalse(); reassert.State.Acknowledged.ShouldBeFalse(); Apply(nm, reassert); nm.IsConditionStateKnown("alm-1", AddressSpaceRealm.Uns).ShouldBeFalse(); // An operator ack before the input arrives. await engine.AcknowledgeAsync("alm-1", "op", null, Ct); var ack = publish.ExpectMsg(Timeout, cancellationToken: Ct); ack.State.Acknowledged.ShouldBeTrue(); Apply(nm, ack); nm.IsConditionStateKnown("alm-1", AddressSpaceRealm.Uns).ShouldBeFalse(); publish.ExpectNoMsg(TimeSpan.FromMilliseconds(300), Ct); hub.ReadAll(0)!.ShouldNotContain(r => r.ConditionId == "alm-1" && r.StateKnown); // The late input: the first real evaluation marks it known. host.Tell(new VirtualTagActor.DependencyValueChanged("M.T", 50, DateTime.UtcNow)); var mark = publish.FishForMessage(m => m is OpcUaPublishActor.MarkConditionsKnown, Timeout, cancellationToken: Ct); Apply(nm, mark); nm.IsConditionStateKnown("alm-1", AddressSpaceRealm.Uns).ShouldBeTrue(); hub.ReadAll(0)!.Last(r => r.ConditionId == "alm-1").ShouldSatisfyAllConditions( r => r.StateKnown.ShouldBeTrue(), r => r.Active.ShouldBeFalse()); await opcHost.DisposeAsync(); } private static void Apply(OtOpcUaNodeManager nm, object message) { switch (message) { case OpcUaPublishActor.AlarmStateUpdate u: nm.WriteAlarmCondition(u.AlarmNodeId, u.State, u.TimestampUtc, u.Realm); break; case OpcUaPublishActor.MarkConditionsKnown m when m.Known: nm.MarkConditionsKnown(m.Source, m.ConditionIds, m.Realm); break; case OpcUaPublishActor.MarkConditionsKnown m: nm.MarkConditionsUnknown(m.Source, m.ConditionIds, m.Realm); break; } } private async Task<(OpcUaApplicationHost Host, OtOpcUaNodeManager Nm)> BootNodeManagerAsync() { var started = await OpcUaHostStart.StartAsync( port => new OpcUaApplicationHost( new OpcUaApplicationHostOptions { ApplicationName = "OtOpcUa.A1HostTest", ApplicationUri = $"urn:OtOpcUa.A1HostTest:{Guid.NewGuid():N}", OpcUaPort = port, PublicHostname = "localhost", PkiStoreRoot = _pkiRoot, }, Microsoft.Extensions.Logging.Abstractions.NullLogger.Instance), () => new OtOpcUaSdkServer(), Ct); return (started.Host, started.Server.NodeManager!); } /// Cleans up the PKI root directory. protected override void Dispose(bool disposing) { base.Dispose(disposing); if (disposing && Directory.Exists(_pkiRoot)) { try { Directory.Delete(_pkiRoot, recursive: true); } catch { /* best-effort cleanup */ } } } /// T2 (i) at the host: the input arrives late ⇒ no mark before the first real evaluation; then the Active /// projection, then the mark. [Fact] public void A_late_input_marks_the_condition_known_after_its_Active_projection() { var publish = CreateTestProbe(); var mux = CreateTestProbe(); var host = Spawn(publish, mux); host.Tell(new ScriptedAlarmHostActor.ApplyScriptedAlarms([Plan()])); mux.ExpectMsg(Timeout, cancellationToken: Ct); publish.ExpectNoMsg(TimeSpan.FromMilliseconds(300), Ct); // never-pushed input: no known-inactive host.Tell(new VirtualTagActor.DependencyValueChanged("M.T", 99, DateTime.UtcNow)); publish.ExpectMsg(Timeout, cancellationToken: Ct).State.Active.ShouldBeTrue(); var mark = publish.ExpectMsg(Timeout, cancellationToken: Ct); mark.ConditionIds.ShouldBe(["alm-1"]); mark.Realm.ShouldBe(AddressSpaceRealm.Uns); mark.Source.ShouldBe(OpcUaPublishActor.ScriptedSource); mark.Known.ShouldBeTrue(); } /// T2 (iv), scripted: a reload (what follows a rebuild that re-created the condition unknown) re-raises the /// flip from inside LoadAsync — before the load pipes back — but the mark is held until the post-load re-assert of /// the still-active condition has been sent, so it never lands on the freshly materialised (inactive) node. [Fact] public void A_reload_holds_the_mark_until_after_the_reassert() { var publish = CreateTestProbe(); var mux = CreateTestProbe(); var host = Spawn(publish, mux); host.Tell(new ScriptedAlarmHostActor.ApplyScriptedAlarms([Plan()])); mux.ExpectMsg(Timeout, cancellationToken: Ct); host.Tell(new VirtualTagActor.DependencyValueChanged("M.T", 99, DateTime.UtcNow)); publish.ExpectMsg(Timeout, cancellationToken: Ct); publish.ExpectMsg(Timeout, cancellationToken: Ct); host.Tell(new ScriptedAlarmHostActor.ApplyScriptedAlarms([Plan()])); var reassert = publish.ExpectMsg(Timeout, cancellationToken: Ct); reassert.State.Active.ShouldBeTrue(); publish.ExpectMsg(Timeout, cancellationToken: Ct).ConditionIds.ShouldBe(["alm-1"]); } }