using Shouldly; using Xunit; using ZB.MOM.WW.OtOpcUa.Commons.OpcUa; using ZB.MOM.WW.OtOpcUa.Commons.Messages.Admin; using ZB.MOM.WW.OtOpcUa.Core.Abstractions; using ZB.MOM.WW.OtOpcUa.Runtime.Drivers; using ZB.MOM.WW.OtOpcUa.Runtime.OpcUa; namespace ZB.MOM.WW.OtOpcUa.Runtime.Tests.Drivers; /// /// A1 (plan §5.1 T1/T2/F2/F5/G5) — the native "standing alarms delivered" signal through the real /// DriverInstanceActor → DriverHostActor chain, against a fake driver. Asserts on the order the publish /// actor receives the alarm projections and the that summarises /// them. /// [Trait("Feature", "GrpcData")] [Trait("Phase", "A1")] [Trait("Category", "Unit")] public sealed class NativeAlarmInitialStateSignalTests : NativeAlarmSignalTestBase { private static readonly string A = RawPathOf("hi"); private static readonly string B = RawPathOf("lo"); private static CancellationToken Ct => TestContext.Current.CancellationToken; [Fact] public void Conditions_become_known_only_on_the_signal_and_after_the_projection_it_covers() { var rig = StartRig(DriverTypeNames.Galaxy, ["hi", "lo"]); rig.Driver.Raise(A).ShouldBeTrue(); rig.Publish.FishForMessage(u => u.AlarmNodeId == A, TimeSpan.FromSeconds(5), cancellationToken: TestContext.Current.CancellationToken) .Source.ShouldBe(DriverId); // Negative control: the replay is not a signal — nothing is marked known yet. AssertNoMark(rig.Publish, TimeSpan.FromMilliseconds(300)); rig.Driver.Signal([A, B]).ShouldBeTrue(); var mark = rig.Publish.FishForMessage(_ => true, TimeSpan.FromSeconds(5), cancellationToken: TestContext.Current.CancellationToken); mark.Source.ShouldBe(DriverId); mark.Realm.ShouldBe(AddressSpaceRealm.Raw); mark.ConditionIds.ShouldBe([A, B], ignoreOrder: true); } /// T2 (iv), Galaxy-shaped, artificially delayed: the snapshot + sentinel are raised while the /// DriverInstanceActor's mailbox is held (its alarm subscribe is still awaiting), so every message queues behind it; /// the mark still reaches the publish actor after the Active projection it summarises. [Fact] public void A_delayed_driver_actor_still_delivers_the_mark_after_the_snapshot_projections() { var driver = new FakeSignallingAlarmDriver(DriverId, DriverTypeNames.Galaxy) { SubscribeDelay = TimeSpan.FromMilliseconds(800) }; driver.OnSubscribed = d => d.ReplaySnapshot([A]); var rig = StartRig(DriverTypeNames.Galaxy, ["hi", "lo"], driver: driver); var traffic = CollectAlarmTraffic(rig.Publish, m => m is OpcUaPublishActor.MarkConditionsKnown); var activeAt = traffic.FindIndex(m => m is OpcUaPublishActor.AlarmStateUpdate { State.Active: true } u && u.AlarmNodeId == A); activeAt.ShouldBeGreaterThanOrEqualTo(0); activeAt.ShouldBeLessThan(traffic.Count - 1); // the mark is last ((OpcUaPublishActor.MarkConditionsKnown)traffic[^1]).ConditionIds.ShouldBe([A, B], ignoreOrder: true); } /// T2 (v) F5: a signal that never completes ⇒ after the timeout the conditions are still unknown (no mark), /// the diagnostic is raised, and a late signal marks them and clears it. [Fact] public void A_signal_that_never_completes_raises_the_diagnostic_and_a_late_signal_clears_it() { var rig = StartRig(DriverTypeNames.Galaxy, ["hi", "lo"], o => o.WithSignalTimeout(DriverTypeNames.Galaxy, TimeSpan.FromMilliseconds(300))); AwaitCondition(() => rig.Hub.Unsignalled.ContainsKey(DriverId), TimeSpan.FromSeconds(5), Ct); rig.Hub.Unsignalled[DriverId].Conditions.ShouldBe(2); AssertNoMark(rig.Publish, TimeSpan.FromMilliseconds(200)); // never known-inactive rig.Driver.Signal([A, B]); rig.Publish.FishForMessage(_ => true, TimeSpan.FromSeconds(5), cancellationToken: TestContext.Current.CancellationToken); AwaitCondition(() => !rig.Hub.Unsignalled.ContainsKey(DriverId), TimeSpan.FromSeconds(5), Ct); } /// The OpcUaClient-only backstop: an unsignalable report is marked known after the settle window from /// quality Good — not at once. [Fact] public void An_unsignalable_OpcUaClient_subscription_is_known_after_the_backstop() { var rig = StartRig(DriverTypeNames.OpcUaClient, ["hi"], o => o.WithOpcUaClientSettle(TimeSpan.FromMilliseconds(1500))); rig.Driver.Signal([A], unsignalable: true); AssertNoMark(rig.Publish, TimeSpan.FromMilliseconds(300)); // not immediately var mark = rig.Publish.FishForMessage(_ => true, TimeSpan.FromSeconds(5), cancellationToken: TestContext.Current.CancellationToken); mark.ConditionIds.ShouldBe([A]); } [Fact] public void Another_driver_type_has_no_backstop_and_stays_unknown() { var rig = StartRig(DriverTypeNames.Galaxy, ["hi"]); rig.Driver.Signal([A], unsignalable: true); AssertNoMark(rig.Publish, TimeSpan.FromMilliseconds(800)); } /// T2 (xi) G5: a signal raised while the feed is suppressed (no alarm subscription) is not delivered; after /// subscribe the first signal follows the replayed standing alarms. [Fact] public void A_suppressed_signal_is_not_delivered_and_the_first_signal_follows_the_replay() { var driver = new FakeSignallingAlarmDriver(DriverId, DriverTypeNames.Galaxy); driver.Signal([A]).ShouldBeFalse("no alarm subscription yet: the gate OnAlarmEvent obeys"); driver.OnSubscribed = d => d.ReplaySnapshot([A]); var rig = StartRig(DriverTypeNames.Galaxy, ["hi", "lo"], driver: driver); var traffic = CollectAlarmTraffic(rig.Publish, m => m is OpcUaPublishActor.MarkConditionsKnown); traffic.OfType().Count().ShouldBe(1); traffic[0].ShouldBeOfType().AlarmNodeId.ShouldBe(A); rig.Driver.Unsubscribe(); rig.Driver.Signal([A, B]).ShouldBeFalse(); AssertNoMark(rig.Publish, TimeSpan.FromMilliseconds(300)); } // ---------------------------------------------------------------- review S2 / re-arm F5 / nits /// /// Review S2 — comms loss and a Connected→Reconnecting→Connected bounce: the Bad edge withdraws "known"; the /// reconnect's Good quality annotation arrives with nothing marked known (an alarm raised during the outage must /// not read known-inactive, Good); a signal queued under the earlier connection is dropped; the reconnected /// driver's own signal marks them known again. /// [Fact] public void Comms_loss_withdraws_known_and_a_signal_from_before_the_bounce_is_dropped() { var rig = StartRig(DriverTypeNames.Galaxy, ["hi", "lo"]); rig.Driver.Signal([A, B]).ShouldBeTrue(); rig.Publish.FishForMessage(m => m.Known, TimeSpan.FromSeconds(5), cancellationToken: Ct); var child = ChildOf(rig); rig.Host.Tell(new ReconnectDriver("c1", DriverId, "test", Guid.NewGuid()), TestActor); var withdrawal = rig.Publish.FishForMessage(m => !m.Known, TimeSpan.FromSeconds(5), cancellationToken: Ct); withdrawal.Source.ShouldBe(DriverId); withdrawal.ConditionIds.ShouldBe([A, B], ignoreOrder: true); // The child retries the connection on its reconnect interval; until its Good edge nothing is marked known. var deadline = DateTime.UtcNow + TimeSpan.FromSeconds(30); while (true) { var m = rig.Publish.ReceiveOne(deadline - DateTime.UtcNow, Ct); m.ShouldNotBeNull("the reconnect's Good quality annotation never arrived"); if (m is OpcUaPublishActor.MarkConditionsKnown { Known: true } mark) throw new ShouldAssertException($"marked known before the reconnected driver signalled: {string.Join(",", mark.ConditionIds)}"); if (m is OpcUaPublishActor.AlarmQualityUpdate { StatusCode: OpcUaStatus.Good }) break; } // A signal raised under the first connection, delivered after the bounce: dropped. rig.Host.Tell(new DriverInstanceActor.AlarmInitialStatePublished(DriverId, new AlarmInitialStateEventArgs([A, B]), ConnectionEpoch: 1), child); AssertNoMark(rig.Publish, TimeSpan.FromMilliseconds(400)); // Positive control: the reconnected driver's own signal marks them known. AwaitCondition(() => rig.Driver.Signal([A, B]), TimeSpan.FromSeconds(10), Ct); rig.Publish.FishForMessage(m => m.Known, TimeSpan.FromSeconds(5), cancellationToken: Ct) .ConditionIds.ShouldBe([A, B], ignoreOrder: true); } /// /// Review round 2 F1 — the exact scenario: comms lost (Bad edge withdraws), an operator acks while the driver is /// Reconnecting, so the ack fails and the host reverts the condition. That revert is the projector's cached state, /// not a driver transition: it must not establish the condition (EstablishesState false). And the reconnect's Good /// edge withdraws again, unconditionally, ahead of the Good quality annotation — so an alarm that re-raised /// upstream during the outage cannot read known-inactive, Good until the replay. /// [Fact] public void An_ack_revert_during_an_outage_does_not_establish_and_the_Good_edge_withdraws_again() { var rig = StartRig(DriverTypeNames.Galaxy, ["hi"]); rig.Driver.Raise(A).ShouldBeTrue(); rig.Driver.Signal([A]).ShouldBeTrue(); rig.Publish.FishForMessage(m => m.Known, TimeSpan.FromSeconds(5), cancellationToken: Ct); rig.Host.Tell(new ReconnectDriver("c1", DriverId, "test", Guid.NewGuid()), TestActor); rig.Publish.FishForMessage(m => !m.Known, TimeSpan.FromSeconds(5), cancellationToken: Ct); rig.Host.Tell(new DriverHostActor.RouteNativeAlarmAck(A, null, "operator"), TestActor); var revert = rig.Publish.FishForMessage(u => u.AlarmNodeId == A && !u.State.Acknowledged, TimeSpan.FromSeconds(5), cancellationToken: Ct); revert.EstablishesState.ShouldBeFalse("an ack-revert re-projects cached state; it establishes nothing"); // The reconnect: a withdrawal must precede the Good quality annotation. var withdrawnAgain = false; var deadline = DateTime.UtcNow + TimeSpan.FromSeconds(30); while (true) { var m = rig.Publish.ReceiveOne(deadline - DateTime.UtcNow, Ct); m.ShouldNotBeNull("the reconnect's Good quality annotation never arrived"); if (m is OpcUaPublishActor.MarkConditionsKnown { Known: false } w && w.ConditionIds.Contains(A)) withdrawnAgain = true; if (m is OpcUaPublishActor.MarkConditionsKnown { Known: true }) throw new ShouldAssertException("marked known before the driver signalled"); if (m is OpcUaPublishActor.AlarmQualityUpdate { StatusCode: OpcUaStatus.Good }) break; } withdrawnAgain.ShouldBeTrue("the Good edge withdraws unconditionally"); } /// Review round 2 F2: an unsignalable report belongs to the subscription that made it. After a Bad edge the /// reconnected subscription has not reported, so the backstop must not arm from the stale set — a refresh that then /// fails leaves the conditions unknown (F5), never known-by-timer. [Fact] public void An_unsignalable_report_does_not_survive_a_Bad_edge() { // The settle outlasts the window before the Bad edge, so the report is still pending (an elapsed backstop clears it). var rig = StartRig(DriverTypeNames.OpcUaClient, ["hi"], o => o.WithOpcUaClientSettle(TimeSpan.FromSeconds(3))); rig.Driver.Signal([A], unsignalable: true).ShouldBeTrue(); rig.Host.Tell(new ReconnectDriver("c1", DriverId, "test", Guid.NewGuid()), TestActor); rig.Publish.FishForMessage(q => q.StatusCode != OpcUaStatus.Good, TimeSpan.FromSeconds(5), cancellationToken: Ct); // The reconnect's Good edge (the child retries on its reconnect interval). rig.Publish.FishForMessage(q => q.StatusCode == OpcUaStatus.Good, TimeSpan.FromSeconds(30), cancellationToken: Ct); AssertNoMark(rig.Publish, TimeSpan.FromSeconds(4.5)); // a stale set would arm the 3 s backstop from this Good edge } /// Open question answered — re-arm F5 for refs a deploy adds while the driver is connected. Today every such /// deploy changes the driver's config (its authored RawTags are folded into it), so the driver is respawned: the /// stopped incarnation's conditions are withdrawn, and the new incarnation's Good edge puts EVERY ref — the added one /// included — in the F5 window, so a driver that never signals raises the diagnostic for all of them. (The reindex /// re-arm covers a future in-place deploy.) [Fact] public void A_deploy_that_adds_alarm_refs_while_connected_covers_them_with_F5() { var rig = StartRig(DriverTypeNames.Galaxy, ["hi"], o => o.WithSignalTimeout(DriverTypeNames.Galaxy, TimeSpan.FromMilliseconds(400))); rig.Driver.Signal([A]).ShouldBeTrue(); rig.Publish.FishForMessage(m => m.Known, TimeSpan.FromSeconds(5), cancellationToken: Ct); rig.Hub.Unsignalled.ShouldBeEmpty(); Redeploy(rig, ["hi", "lo"]); rig.Publish.FishForMessage(m => !m.Known && m.ConditionIds.Contains(A), TimeSpan.FromSeconds(5), cancellationToken: Ct); AwaitCondition(() => rig.Hub.Unsignalled.ContainsKey(DriverId), TimeSpan.FromSeconds(5), Ct); rig.Hub.Unsignalled[DriverId].Conditions.ShouldBe(2); AwaitCondition(() => rig.Driver.Signal([A, B]), TimeSpan.FromSeconds(5), Ct); AwaitCondition(() => !rig.Hub.Unsignalled.ContainsKey(DriverId), TimeSpan.FromSeconds(5), Ct); } /// Review S2 — F5's "still unknown" set follows the node manager: a native transition (which the node /// manager treats as an established state) takes its condition out of the F5 count. [Fact] public void A_native_transition_leaves_the_F5_pending_set_like_the_node_manager() { var rig = StartRig(DriverTypeNames.Galaxy, ["hi", "lo"], o => o.WithSignalTimeout(DriverTypeNames.Galaxy, TimeSpan.FromMilliseconds(600))); rig.Driver.Raise(A).ShouldBeTrue(); rig.Publish.FishForMessage(u => u.AlarmNodeId == A, TimeSpan.FromSeconds(5), cancellationToken: Ct); AwaitCondition(() => rig.Hub.Unsignalled.ContainsKey(DriverId), TimeSpan.FromSeconds(5), Ct); rig.Hub.Unsignalled[DriverId].Conditions.ShouldBe(1); // only B is still unknown } /// Review nit — a signal from anything but the current child (a stopped incarnation, a stray sender) is /// dropped and never (re)creates a tracker. [Fact] public void A_signal_from_a_sender_that_is_not_the_current_child_is_dropped() { var rig = StartRig(DriverTypeNames.Galaxy, ["hi"]); rig.Host.Tell(new DriverInstanceActor.AlarmInitialStatePublished(DriverId, new AlarmInitialStateEventArgs([A])), TestActor); AssertNoMark(rig.Publish, TimeSpan.FromMilliseconds(400)); } }