using ZB.MOM.WW.ScadaBridge.Commons.Interfaces.Services; using Akka.Actor; using Akka.TestKit.Xunit2; using NSubstitute; using ZB.MOM.WW.ScadaBridge.Commons.Interfaces.Protocol; using ZB.MOM.WW.ScadaBridge.Commons.Messages.DataConnection; using ZB.MOM.WW.ScadaBridge.Commons.Types.Alarms; using ZB.MOM.WW.ScadaBridge.Commons.Types.Enums; using ZB.MOM.WW.ScadaBridge.DataConnectionLayer.Actors; using ZB.MOM.WW.ScadaBridge.HealthMonitoring; namespace ZB.MOM.WW.ScadaBridge.DataConnectionLayer.Tests; /// /// The alarm subscriber first-segment bucket index must make EXACTLY the routing /// decisions a linear scan over every subscribed source makes. The expectation in each case /// is computed with an independent oracle — since the 2026-12-02 review (DCL-5) the rule is /// "the reference is the source itself or lies beneath it at a separator", no longer a raw /// string StartsWith that let Tank1 receive Tank10's alarms — so the test /// pins equivalence rather than restating the implementation. /// public class DataConnectionActorAlarmIndexTests : TestKit { private readonly ISiteHealthCollector _health = Substitute.For(); private readonly IDataConnectionFactory _factory = Substitute.For(); private readonly DataConnectionOptions _options = new() { ReconnectInterval = TimeSpan.FromMilliseconds(100), TagResolutionRetryInterval = TimeSpan.FromMilliseconds(200), WriteTimeout = TimeSpan.FromSeconds(5) }; // Sources chosen to exercise every index path: // - "Area1" → NO separator: the residue list (can match other buckets) // - "Area1.Tank" → bucket "Area1", shared prefix with the next one // - "Area1.Tank1.Sub" → bucket "Area1", deeper // - "Area2.Tank" → a different bucket private static readonly string[] Sources = ["Area1", "Area1.Tank", "Area1.Tank1.Sub", "Area2.Tank"]; private static readonly (string SourceRef, string SourceObjectRef)[] Transitions = [ ("Area1.Tank1.Hi", "Area1.Tank1"), // Area1 (residue) ONLY — "Area1.Tank" is a sibling, not a parent (DCL-5) ("Area1.Tank1.Sub.Hi", "Area1.Tank1.Sub"), // Area1 + Area1.Tank1.Sub ("Area1.Tank.Hi", "Area1.Tank"), // Area1 + Area1.Tank ("Area1X.Pump.Hi", "Area1X.Pump"), // sub-segment prefix of Area1: nobody (DCL-5) ("Area2.Tank9.Hi", "Area2.Tank9"), // Area2.Tank only ("Zone.A.Hi", "Zone.A"), // nobody ]; private static NativeAlarmTransition Transition(string sourceRef, string sourceObj) => new(sourceRef, sourceObj, "AnalogLimit.Hi", AlarmTransitionKind.Raise, new AlarmConditionState(true, false, null, AlarmShelveState.Unshelved, false, 500), "Process", "hi", "hi", "", "", null, DateTimeOffset.UtcNow, "92", "90"); /// The linear-scan oracle: the source itself, or a descendant at a '.' separator. private static bool LinearScanMatches(string sourceRef, string transitionSourceRef, string transitionSourceObjectRef) => Under(transitionSourceObjectRef, sourceRef) || Under(transitionSourceRef, sourceRef); private static bool Under(string reference, string source) => reference == source || reference.StartsWith(source + ".", StringComparison.Ordinal); /// Verifies that the bucket index routes exactly as the previous linear scan did. [Fact] public void BucketIndex_RoutesExactlyLikeTheLinearScan() { AlarmTransitionCallback? cb = null; var adapter = Substitute.For(); adapter.ConnectAsync(Arg.Any>(), Arg.Any()) .Returns(Task.CompletedTask); ((IAlarmSubscribableConnection)adapter) .SubscribeAlarmsAsync(Arg.Any(), Arg.Any(), Arg.Do(c => cb = c), Arg.Any()) .Returns(ci => Task.FromResult("alarm-" + ci.ArgAt(0))); var actor = Sys.ActorOf(Props.Create(() => new DataConnectionActor( "conn", adapter, _options, _health, _factory, "OpcUa")), "alarm-index"); // One probe per source so the routing decision per source is observable. var probes = Sources.ToDictionary(s => s, _ => CreateTestProbe()); foreach (var source in Sources) { actor.Tell(new SubscribeAlarmsRequest("c", "inst-" + source, "conn", source, null, DateTimeOffset.UtcNow), probes[source].Ref); probes[source].ExpectMsg(m => m.Success, TimeSpan.FromSeconds(5)); } Assert.NotNull(cb); foreach (var (sourceRef, sourceObjectRef) in Transitions) { cb!(Transition(sourceRef, sourceObjectRef)); foreach (var source in Sources) { if (LinearScanMatches(source, sourceRef, sourceObjectRef)) { probes[source].ExpectMsg( u => u.Transition.SourceReference == sourceRef, TimeSpan.FromSeconds(5)); } } } // Nothing extra was delivered to anybody. foreach (var source in Sources) probes[source].ExpectNoMsg(TimeSpan.FromMilliseconds(200)); } /// Verifies that a snapshot-complete message is still broadcast to every subscriber, bypassing the index. [Fact] public void SnapshotComplete_StillBroadcastsToEverySubscriber_BypassingTheIndex() { // The framing sentinel carries an EMPTY source reference, so it matches no bucket. // It must still reach every alarm subscriber, or statically-active conditions // delivered only in the snapshot would buffer forever. AlarmTransitionCallback? cb = null; var adapter = Substitute.For(); adapter.ConnectAsync(Arg.Any>(), Arg.Any()) .Returns(Task.CompletedTask); ((IAlarmSubscribableConnection)adapter) .SubscribeAlarmsAsync(Arg.Any(), Arg.Any(), Arg.Do(c => cb = c), Arg.Any()) .Returns(ci => Task.FromResult("alarm-" + ci.ArgAt(0))); var actor = Sys.ActorOf(Props.Create(() => new DataConnectionActor( "conn", adapter, _options, _health, _factory, "OpcUa")), "alarm-index-snapshot"); var probes = Sources.ToDictionary(s => s, _ => CreateTestProbe()); foreach (var source in Sources) { actor.Tell(new SubscribeAlarmsRequest("c", "inst-" + source, "conn", source, null, DateTimeOffset.UtcNow), probes[source].Ref); probes[source].ExpectMsg(m => m.Success, TimeSpan.FromSeconds(5)); } Assert.NotNull(cb); cb!(new NativeAlarmTransition( "", "", "", AlarmTransitionKind.SnapshotComplete, new AlarmConditionState(false, true, null, AlarmShelveState.Unshelved, false, 0), "", "", "", "", "", null, DateTimeOffset.UtcNow, "", "")); foreach (var source in Sources) { probes[source].ExpectMsg( u => u.Transition.Kind == AlarmTransitionKind.SnapshotComplete, TimeSpan.FromSeconds(5)); } } /// Verifies that an unsubscribed source is dropped from the index. [Fact] public void UnsubscribedSource_IsDroppedFromTheIndex() { AlarmTransitionCallback? cb = null; var adapter = Substitute.For(); adapter.ConnectAsync(Arg.Any>(), Arg.Any()) .Returns(Task.CompletedTask); ((IAlarmSubscribableConnection)adapter) .SubscribeAlarmsAsync(Arg.Any(), Arg.Any(), Arg.Do(c => cb = c), Arg.Any()) .Returns(ci => Task.FromResult("alarm-" + ci.ArgAt(0))); var actor = Sys.ActorOf(Props.Create(() => new DataConnectionActor( "conn", adapter, _options, _health, _factory, "OpcUa")), "alarm-index-unsub"); var probe = CreateTestProbe(); actor.Tell(new SubscribeAlarmsRequest("c", "inst", "conn", "Area1.Tank", null, DateTimeOffset.UtcNow), probe.Ref); probe.ExpectMsg(m => m.Success, TimeSpan.FromSeconds(5)); actor.Tell(new UnsubscribeAlarmsRequest("c2", "inst", "conn", "Area1.Tank", DateTimeOffset.UtcNow), probe.Ref); Thread.Sleep(200); Assert.NotNull(cb); cb!(Transition("Area1.Tank.Hi", "Area1.Tank")); probe.ExpectNoMsg(TimeSpan.FromMilliseconds(300)); } /// /// DCL-5: sibling sources whose names share a prefix (ns=2;s=Tank1 / ns=2;s=Tank10, /// MxGateway Pump1 / Pump10) must not receive each other's alarms. Pre-fix every /// Tank10 transition was also delivered to — and mirrored by — the Tank1 instance. /// [Theory] [InlineData("ns=2;s=Tank1", "ns=2;s=Tank10")] [InlineData("Pump1", "Pump10")] public void SiblingSourcesSharingAPrefix_DoNotReceiveEachOthersAlarms(string shortSource, string longSource) { AlarmTransitionCallback? cb = null; var adapter = Substitute.For(); adapter.ConnectAsync(Arg.Any>(), Arg.Any()) .Returns(Task.CompletedTask); ((IAlarmSubscribableConnection)adapter) .SubscribeAlarmsAsync(Arg.Any(), Arg.Any(), Arg.Do(c => cb = c), Arg.Any()) .Returns(ci => Task.FromResult("alarm-" + ci.ArgAt(0))); var actor = Sys.ActorOf(Props.Create(() => new DataConnectionActor( "conn", adapter, _options, _health, _factory, "OpcUa"))); var shortProbe = CreateTestProbe(); var longProbe = CreateTestProbe(); actor.Tell(new SubscribeAlarmsRequest("c1", "inst-short", "conn", shortSource, null, DateTimeOffset.UtcNow), shortProbe.Ref); shortProbe.ExpectMsg(m => m.Success, TimeSpan.FromSeconds(5)); actor.Tell(new SubscribeAlarmsRequest("c2", "inst-long", "conn", longSource, null, DateTimeOffset.UtcNow), longProbe.Ref); longProbe.ExpectMsg(m => m.Success, TimeSpan.FromSeconds(5)); cb!(Transition(longSource + ".Hi", longSource)); longProbe.ExpectMsg(TimeSpan.FromSeconds(5)); shortProbe.ExpectNoMsg(TimeSpan.FromMilliseconds(300)); // pre-fix: delivered here too // The short source still gets its own alarms. cb!(Transition(shortSource + ".Hi", shortSource)); shortProbe.ExpectMsg(TimeSpan.FromSeconds(5)); } /// The separator-aware containment rule behind alarm routing. [Theory] [InlineData("Tank1", "Tank1", true)] [InlineData("Tank1.Hi", "Tank1", true)] [InlineData("Area/Tank1", "Area", true)] [InlineData("Tank10", "Tank1", false)] [InlineData("Tank10.Hi", "Tank1", false)] [InlineData("ns=2;s=Tank10", "ns=2;s=Tank1", false)] [InlineData("Area1.Tank", "Area1.", true)] [InlineData("anything", "", true)] [InlineData("Tank", "Tank1", false)] public void IsUnderAlarmSource_IsSeparatorAware(string reference, string source, bool expected) => Assert.Equal(expected, DataConnectionActor.IsUnderAlarmSource(reference, source)); }