diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/Drivers/NativeAlarmInitialStateSignalTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/Drivers/NativeAlarmInitialStateSignalTests.cs new file mode 100644 index 000000000..e6a900a16 --- /dev/null +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/Drivers/NativeAlarmInitialStateSignalTests.cs @@ -0,0 +1,115 @@ +using Shouldly; +using Xunit; +using ZB.MOM.WW.OtOpcUa.Commons.OpcUa; +using ZB.MOM.WW.OtOpcUa.Core.Abstractions; +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)); + } +} diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/Drivers/NativeAlarmSignalTestBase.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/Drivers/NativeAlarmSignalTestBase.cs new file mode 100644 index 000000000..f3c09d527 --- /dev/null +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/Drivers/NativeAlarmSignalTestBase.cs @@ -0,0 +1,265 @@ +using System.Text.Json; +using Akka.Actor; +using Akka.TestKit; +using Microsoft.EntityFrameworkCore; +using Shouldly; +using Xunit; +using ZB.MOM.WW.OtOpcUa.Commons.Engines; +using ZB.MOM.WW.OtOpcUa.Commons.Messages.Deploy; +using ZB.MOM.WW.OtOpcUa.Commons.OpcUa; +using ZB.MOM.WW.OtOpcUa.Commons.Types; +using ZB.MOM.WW.OtOpcUa.Configuration; +using ZB.MOM.WW.OtOpcUa.Configuration.Entities; +using ZB.MOM.WW.OtOpcUa.Configuration.Enums; +using ZB.MOM.WW.OtOpcUa.Core.Abstractions; +using ZB.MOM.WW.OtOpcUa.Runtime.DataConnections; +using ZB.MOM.WW.OtOpcUa.Runtime.Drivers; +using ZB.MOM.WW.OtOpcUa.Runtime.OpcUa; +using ZB.MOM.WW.OtOpcUa.Runtime.Tests.Harness; + +namespace ZB.MOM.WW.OtOpcUa.Runtime.Tests.Drivers; + +/// +/// A1 (plan §5.1) reusable rig for native "standing alarms delivered" signal tests: a real +/// + real around a +/// , with the OPC UA publish actor replaced by a probe so the exact order of +/// and is +/// observable. The driver agent's per-driver tests (ii, iii, vi–ix) inherit this and swap the fake for each real +/// driver's shape. +/// +public abstract class NativeAlarmSignalTestBase : RuntimeActorTestBase +{ + /// The driver instance id the rig deploys. + protected const string DriverId = "drv-sig"; + private static readonly NodeId RigNode = NodeId.Parse("a1-signal-rig"); + private static readonly RevisionHash Rev = RevisionHash.Parse(new string('c', 64)); + + /// The RawPath of alarm tag under the rig's folder/driver/device. + /// The tag name. + /// The RawPath (= the driver ConditionId = the condition NodeId). + protected static string RawPathOf(string tag) => $"Plant/Drv/dev1/{tag}"; + + /// One started rig. + /// The driver host. + /// The publish-actor probe (rebuild already drained). + /// The fake driver the host spawned. + /// The hub the F5 diagnostic is raised on. + protected sealed record Rig(IActorRef Host, TestProbe Publish, FakeSignallingAlarmDriver Driver, ConditionStateHub Hub); + + /// Deploys as native alarm tags of one enabled driver of + /// , waits for the apply, the driver's connection and its alarm subscription. + /// The driver type (decides the backstop / F5 timeout). + /// The alarm tag names. + /// Adjusts the signal options (timeouts). + /// A pre-built fake (e.g. with a subscribe delay), or null for a default one. + /// The rig. + protected Rig StartRig(string driverType, IReadOnlyList alarmTags, + Func? configure = null, FakeSignallingAlarmDriver? driver = null) + { + var db = NewInMemoryDbFactory(); + var deploymentId = Seed(db, driverType, alarmTags); + driver ??= new FakeSignallingAlarmDriver(DriverId, driverType); + var hub = new ConditionStateHub(); + var options = new ConditionSignalOptions { Hub = hub }; + options = configure?.Invoke(options) ?? options; + + var coordinator = CreateTestProbe(); + var publish = this.CreateCleanOutcomePublishProbe(); + var host = Sys.ActorOf(DriverHostActor.Props( + db, RigNode, coordinator.Ref, + driverFactory: new SingleDriverFactory(driver), + localRoles: new HashSet { "driver" }, + dependencyMux: CreateTestProbe().Ref, + opcUaPublishActor: publish.Ref, + virtualTagEvaluator: NullVirtualTagEvaluator.Instance, + virtualTagHostOverride: CreateTestProbe().Ref, + conditionSignals: options)); + + host.Tell(new DispatchDeployment(deploymentId, Rev, CorrelationId.NewId())); + coordinator.FishForMessage(_ => true, TimeSpan.FromSeconds(10), cancellationToken: TestContext.Current.CancellationToken).Outcome.ShouldBe(ApplyAckOutcome.Applied); + AwaitCondition(() => driver.Subscribed, TimeSpan.FromSeconds(10), TestContext.Current.CancellationToken); + return new Rig(host, publish, driver, hub); + } + + /// Negative control: for , the probe receives no + /// (other traffic — quality annotations — is ignored). + /// The probe. + /// How long to watch. + protected static void AssertNoMark(TestProbe publish, TimeSpan duration) + { + var deadline = DateTime.UtcNow + duration; + while (DateTime.UtcNow < deadline) + { + var m = publish.ReceiveOne(deadline - DateTime.UtcNow); + if (m is OpcUaPublishActor.MarkConditionsKnown mark) + throw new ShouldAssertException($"unexpected MarkConditionsKnown({string.Join(",", mark.ConditionIds)})"); + } + } + + /// The publish-actor messages that are alarm-state updates or marks, in arrival order, until + /// matches (inclusive). + /// The probe. + /// Stop condition. + /// Overall wait. + /// The ordered messages. + protected static List CollectAlarmTraffic(TestProbe publish, Func until, TimeSpan? timeout = null) + { + var seen = new List(); + var deadline = DateTime.UtcNow + (timeout ?? TimeSpan.FromSeconds(10)); + while (DateTime.UtcNow < deadline) + { + var m = publish.ReceiveOne(deadline - DateTime.UtcNow); + if (m is null) break; + if (m is not (OpcUaPublishActor.AlarmStateUpdate or OpcUaPublishActor.MarkConditionsKnown)) continue; + seen.Add(m); + if (until(m)) return seen; + } + + throw new ShouldAssertException($"stop condition not met; saw {seen.Count} alarm message(s)"); + } + + private static DeploymentId Seed(IDbContextFactory db, string driverType, IReadOnlyList alarmTags) + { + var artifact = JsonSerializer.SerializeToUtf8Bytes(new + { + RawFolders = new[] { new { RawFolderId = "rf-plant", ParentRawFolderId = (string?)null, Name = "Plant", ClusterId = "c1" } }, + DriverInstances = new[] + { + new { DriverInstanceId = DriverId, RawFolderId = "rf-plant", Name = "Drv", DriverType = driverType, DriverConfig = "{}", ClusterId = "c1", Enabled = true }, + }, + Devices = new[] { new { DeviceId = "dev-1", DriverInstanceId = DriverId, Name = "dev1", DeviceConfig = "{}" } }, + TagGroups = Array.Empty(), + Tags = alarmTags.Select((t, i) => new + { + TagId = $"tag-{i}", DeviceId = "dev-1", TagGroupId = (string?)null, Name = t, DataType = "Boolean", + AccessLevel = 0, TagConfig = JsonSerializer.Serialize(new { alarm = new { alarmType = "OffNormalAlarm", severity = 700 } }), + }).ToArray(), + }); + + var id = DeploymentId.NewId(); + using var ctx = db.CreateDbContext(); + ctx.Deployments.Add(new Deployment + { + DeploymentId = id.Value, RevisionHash = Rev.Value, Status = DeploymentStatus.Sealed, CreatedBy = "test", + SealedAtUtc = DateTime.UtcNow, ArtifactBlob = artifact, + }); + ctx.SaveChanges(); + return id; + } + + private sealed class SingleDriverFactory(IDriver driver) : IDriverFactory + { + public IDriver? TryCreate(string driverType, string driverInstanceId, string driverConfigJson) => driver; + public IReadOnlyCollection SupportedTypes => [driver.DriverType]; + } +} + +/// +/// A fake native alarm source that obeys the §5.1 contract: alarm events AND the initial-state signal are raised +/// on the driver's own thread, the signal after the events it covers, and only while an alarm subscription is live +/// (G5). plays the post-subscribe replay (e.g. Galaxy's snapshot + sentinel). +/// +public sealed class FakeSignallingAlarmDriver(string driverInstanceId, string driverType) : IDriver, IAlarmSource, IAlarmInitialStateSignal +{ + private volatile bool _subscribed; + private volatile IReadOnlyList _refs = []; + + /// + public string DriverInstanceId => driverInstanceId; + + /// + public string DriverType => driverType; + + /// Whether an alarm subscription is live. + public bool Subscribed => _subscribed; + + /// The refs of the live alarm subscription. + public IReadOnlyList SubscribedRefs => _refs; + + /// How long holds the mailbox AFTER the + /// subscription went live — the F2 "delay the DriverInstanceActor" lever. + public TimeSpan SubscribeDelay { get; init; } + + /// Run on a feed thread once a subscription goes live (the post-subscribe replay). + public Action? OnSubscribed { get; set; } + + /// + public event EventHandler? OnAlarmEvent; + + /// + public event EventHandler? InitialAlarmStateDelivered; + + /// + public Task InitializeAsync(string driverConfigJson, CancellationToken cancellationToken) => Task.CompletedTask; + + /// + public Task ReinitializeAsync(string driverConfigJson, CancellationToken cancellationToken) => Task.CompletedTask; + + /// + public Task ShutdownAsync(CancellationToken cancellationToken) => Task.CompletedTask; + + /// + public DriverHealth GetHealth() => new(DriverState.Healthy, null, null); + + /// + public async Task SubscribeAlarmsAsync(IReadOnlyList sourceNodeIds, CancellationToken cancellationToken) + { + _refs = sourceNodeIds; + _subscribed = true; + if (OnSubscribed is { } replay) _ = Task.Run(() => replay(this), CancellationToken.None); + if (SubscribeDelay > TimeSpan.Zero) await Task.Delay(SubscribeDelay, CancellationToken.None).ConfigureAwait(false); + return new Handle(); + } + + /// + public Task UnsubscribeAlarmsAsync(IAlarmSubscriptionHandle handle, CancellationToken cancellationToken) + { + _subscribed = false; + return Task.CompletedTask; + } + + /// + public Task AcknowledgeAsync(IReadOnlyList acknowledgements, CancellationToken cancellationToken) => + Task.CompletedTask; + + /// Drop the subscription (the suppression gate closes). + public void Unsubscribe() => _subscribed = false; + + /// Raise one alarm transition — a no-op (false) while no subscription is live (G5). + /// The ConditionId (= RawPath). + /// The transition. + /// The message. + /// Whether it was raised. + public bool Raise(string conditionId, AlarmTransitionKind kind = AlarmTransitionKind.Raise, string message = "standing") + { + if (!_subscribed) return false; + OnAlarmEvent?.Invoke(this, new AlarmEventArgs(new Handle(), conditionId, conditionId, "OffNormalAlarm", message, + AlarmSeverity.High, DateTime.UtcNow, Kind: kind)); + return true; + } + + /// Raise the initial-state signal — a no-op (false) while no subscription is live (G5). + /// The conditions it covers. + /// Report InitialStateUnsignalable instead. + /// Whether it was raised. + public bool Signal(IReadOnlyList conditionIds, bool unsignalable = false) + { + if (!_subscribed) return false; + InitialAlarmStateDelivered?.Invoke(this, new AlarmInitialStateEventArgs(conditionIds, unsignalable)); + return true; + } + + /// A Galaxy-shaped snapshot: one Raise per standing alarm, then the sentinel signal over every subscribed + /// condition, all on the calling (feed) thread. + /// The standing (active) conditions. + public void ReplaySnapshot(IReadOnlyList standing) + { + foreach (var id in standing) Raise(id); + Signal(SubscribedRefs); + } + + private sealed class Handle : IAlarmSubscriptionHandle + { + public string DiagnosticId => "fake-alarm-sub"; + } +}