test(grpc-data): A1 native initial-state signal through the real driver actors — known only on signal, F2 delayed ordering, F5, backstop, G5; reusable NativeAlarmSignalTestBase + FakeSignallingAlarmDriver

This commit is contained in:
Joseph Doherty
2026-11-24 09:35:05 -05:00
parent ffdaa73d0c
commit 47bf3a1cad
2 changed files with 380 additions and 0 deletions
@@ -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;
/// <summary>
/// A1 (plan §5.1 T1/T2/F2/F5/G5) — the native "standing alarms delivered" signal through the real
/// <c>DriverInstanceActor</c> → <c>DriverHostActor</c> chain, against a fake driver. Asserts on the order the publish
/// actor receives the alarm projections and the <see cref="OpcUaPublishActor.MarkConditionsKnown"/> that summarises
/// them.
/// </summary>
[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<OpcUaPublishActor.AlarmStateUpdate>(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<OpcUaPublishActor.MarkConditionsKnown>(_ => true, TimeSpan.FromSeconds(5), cancellationToken: TestContext.Current.CancellationToken);
mark.Source.ShouldBe(DriverId);
mark.Realm.ShouldBe(AddressSpaceRealm.Raw);
mark.ConditionIds.ShouldBe([A, B], ignoreOrder: true);
}
/// <summary>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.</summary>
[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);
}
/// <summary>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.</summary>
[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<OpcUaPublishActor.MarkConditionsKnown>(_ => true, TimeSpan.FromSeconds(5), cancellationToken: TestContext.Current.CancellationToken);
AwaitCondition(() => !rig.Hub.Unsignalled.ContainsKey(DriverId), TimeSpan.FromSeconds(5), Ct);
}
/// <summary>The OpcUaClient-only backstop: an unsignalable report is marked known after the settle window from
/// quality Good — not at once.</summary>
[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<OpcUaPublishActor.MarkConditionsKnown>(_ => 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));
}
/// <summary>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.</summary>
[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<OpcUaPublishActor.MarkConditionsKnown>().Count().ShouldBe(1);
traffic[0].ShouldBeOfType<OpcUaPublishActor.AlarmStateUpdate>().AlarmNodeId.ShouldBe(A);
rig.Driver.Unsubscribe();
rig.Driver.Signal([A, B]).ShouldBeFalse();
AssertNoMark(rig.Publish, TimeSpan.FromMilliseconds(300));
}
}
@@ -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;
/// <summary>
/// A1 (plan §5.1) reusable rig for native "standing alarms delivered" signal tests: a real
/// <see cref="DriverHostActor"/> + real <see cref="DriverInstanceActor"/> around a
/// <see cref="FakeSignallingAlarmDriver"/>, with the OPC UA publish actor replaced by a probe so the exact order of
/// <see cref="OpcUaPublishActor.AlarmStateUpdate"/> and <see cref="OpcUaPublishActor.MarkConditionsKnown"/> 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.
/// </summary>
public abstract class NativeAlarmSignalTestBase : RuntimeActorTestBase
{
/// <summary>The driver instance id the rig deploys.</summary>
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));
/// <summary>The RawPath of alarm tag <paramref name="tag"/> under the rig's folder/driver/device.</summary>
/// <param name="tag">The tag name.</param>
/// <returns>The RawPath (= the driver ConditionId = the condition NodeId).</returns>
protected static string RawPathOf(string tag) => $"Plant/Drv/dev1/{tag}";
/// <summary>One started rig.</summary>
/// <param name="Host">The driver host.</param>
/// <param name="Publish">The publish-actor probe (rebuild already drained).</param>
/// <param name="Driver">The fake driver the host spawned.</param>
/// <param name="Hub">The hub the F5 diagnostic is raised on.</param>
protected sealed record Rig(IActorRef Host, TestProbe Publish, FakeSignallingAlarmDriver Driver, ConditionStateHub Hub);
/// <summary>Deploys <paramref name="alarmTags"/> as native alarm tags of one enabled driver of
/// <paramref name="driverType"/>, waits for the apply, the driver's connection and its alarm subscription.</summary>
/// <param name="driverType">The driver type (decides the backstop / F5 timeout).</param>
/// <param name="alarmTags">The alarm tag names.</param>
/// <param name="configure">Adjusts the signal options (timeouts).</param>
/// <param name="driver">A pre-built fake (e.g. with a subscribe delay), or null for a default one.</param>
/// <returns>The rig.</returns>
protected Rig StartRig(string driverType, IReadOnlyList<string> alarmTags,
Func<ConditionSignalOptions, ConditionSignalOptions>? 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<string> { "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<ApplyAck>(_ => 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);
}
/// <summary>Negative control: for <paramref name="duration"/>, the probe receives no
/// <see cref="OpcUaPublishActor.MarkConditionsKnown"/> (other traffic — quality annotations — is ignored).</summary>
/// <param name="publish">The probe.</param>
/// <param name="duration">How long to watch.</param>
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)})");
}
}
/// <summary>The publish-actor messages that are alarm-state updates or marks, in arrival order, until
/// <paramref name="until"/> matches (inclusive).</summary>
/// <param name="publish">The probe.</param>
/// <param name="until">Stop condition.</param>
/// <param name="timeout">Overall wait.</param>
/// <returns>The ordered messages.</returns>
protected static List<object> CollectAlarmTraffic(TestProbe publish, Func<object, bool> until, TimeSpan? timeout = null)
{
var seen = new List<object>();
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<OtOpcUaConfigDbContext> db, string driverType, IReadOnlyList<string> 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<object>(),
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<string> SupportedTypes => [driver.DriverType];
}
}
/// <summary>
/// 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). <see cref="OnSubscribed"/> plays the post-subscribe replay (e.g. Galaxy's snapshot + sentinel).
/// </summary>
public sealed class FakeSignallingAlarmDriver(string driverInstanceId, string driverType) : IDriver, IAlarmSource, IAlarmInitialStateSignal
{
private volatile bool _subscribed;
private volatile IReadOnlyList<string> _refs = [];
/// <inheritdoc />
public string DriverInstanceId => driverInstanceId;
/// <inheritdoc />
public string DriverType => driverType;
/// <summary>Whether an alarm subscription is live.</summary>
public bool Subscribed => _subscribed;
/// <summary>The refs of the live alarm subscription.</summary>
public IReadOnlyList<string> SubscribedRefs => _refs;
/// <summary>How long <see cref="SubscribeAlarmsAsync"/> holds the <see cref="DriverInstanceActor"/> mailbox AFTER the
/// subscription went live — the F2 "delay the DriverInstanceActor" lever.</summary>
public TimeSpan SubscribeDelay { get; init; }
/// <summary>Run on a feed thread once a subscription goes live (the post-subscribe replay).</summary>
public Action<FakeSignallingAlarmDriver>? OnSubscribed { get; set; }
/// <inheritdoc />
public event EventHandler<AlarmEventArgs>? OnAlarmEvent;
/// <inheritdoc />
public event EventHandler<AlarmInitialStateEventArgs>? InitialAlarmStateDelivered;
/// <inheritdoc />
public Task InitializeAsync(string driverConfigJson, CancellationToken cancellationToken) => Task.CompletedTask;
/// <inheritdoc />
public Task ReinitializeAsync(string driverConfigJson, CancellationToken cancellationToken) => Task.CompletedTask;
/// <inheritdoc />
public Task ShutdownAsync(CancellationToken cancellationToken) => Task.CompletedTask;
/// <inheritdoc />
public DriverHealth GetHealth() => new(DriverState.Healthy, null, null);
/// <inheritdoc />
public async Task<IAlarmSubscriptionHandle> SubscribeAlarmsAsync(IReadOnlyList<string> 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();
}
/// <inheritdoc />
public Task UnsubscribeAlarmsAsync(IAlarmSubscriptionHandle handle, CancellationToken cancellationToken)
{
_subscribed = false;
return Task.CompletedTask;
}
/// <inheritdoc />
public Task AcknowledgeAsync(IReadOnlyList<AlarmAcknowledgeRequest> acknowledgements, CancellationToken cancellationToken) =>
Task.CompletedTask;
/// <summary>Drop the subscription (the suppression gate closes).</summary>
public void Unsubscribe() => _subscribed = false;
/// <summary>Raise one alarm transition — a no-op (false) while no subscription is live (G5).</summary>
/// <param name="conditionId">The ConditionId (= RawPath).</param>
/// <param name="kind">The transition.</param>
/// <param name="message">The message.</param>
/// <returns>Whether it was raised.</returns>
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;
}
/// <summary>Raise the initial-state signal — a no-op (false) while no subscription is live (G5).</summary>
/// <param name="conditionIds">The conditions it covers.</param>
/// <param name="unsignalable">Report InitialStateUnsignalable instead.</param>
/// <returns>Whether it was raised.</returns>
public bool Signal(IReadOnlyList<string> conditionIds, bool unsignalable = false)
{
if (!_subscribed) return false;
InitialAlarmStateDelivered?.Invoke(this, new AlarmInitialStateEventArgs(conditionIds, unsignalable));
return true;
}
/// <summary>A Galaxy-shaped snapshot: one Raise per standing alarm, then the sentinel signal over every subscribed
/// condition, all on the calling (feed) thread.</summary>
/// <param name="standing">The standing (active) conditions.</param>
public void ReplaySnapshot(IReadOnlyList<string> standing)
{
foreach (var id in standing) Raise(id);
Signal(SubscribedRefs);
}
private sealed class Handle : IAlarmSubscriptionHandle
{
public string DiagnosticId => "fake-alarm-sub";
}
}