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)); private IDbContextFactory? _rigDb; private TestProbe? _rigCoordinator; private string? _rigDriverType; private int _redeploys; /// 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, Rev); _rigDb = db; _rigDriverType = driverType; driver ??= new FakeSignallingAlarmDriver(DriverId, driverType); var hub = new ConditionStateHub(); var options = new ConditionSignalOptions { Hub = hub }; options = configure?.Invoke(options) ?? options; var coordinator = _rigCoordinator = 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); } /// Re-deploys the last started rig with (a new revision) and waits for the apply. /// The rig. /// The alarm tag names the new revision carries. protected void Redeploy(Rig rig, IReadOnlyList alarmTags) { var rev = RevisionHash.Parse(new string((char)('d' + _redeploys++ % 3), 64)); var deploymentId = Seed(_rigDb!, _rigDriverType!, alarmTags, rev); rig.Host.Tell(new DispatchDeployment(deploymentId, rev, CorrelationId.NewId())); _rigCoordinator!.FishForMessage(a => a.DeploymentId == deploymentId, TimeSpan.FromSeconds(10), cancellationToken: TestContext.Current.CancellationToken).Outcome.ShouldBe(ApplyAckOutcome.Applied); } /// The rig's current driver child (the DriverInstanceActor the host spawned). /// The rig. /// Its actor ref. protected IActorRef ChildOf(Rig rig) => Sys.ActorSelection(rig.Host.Path + "/drv-*").ResolveOne(TimeSpan.FromSeconds(5)).GetAwaiter().GetResult(); /// Negative control: for , the probe receives no /// that marks known (other traffic — quality annotations, /// withdrawals — 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 { Known: true } 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, RevisionHash rev) { 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"; } }