Files
lmxopcua/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/Drivers/NativeAlarmInitialStateSignalTests.cs
T
Joseph Doherty f08ca7d9e3 fix(grpc-data): A1 review S2 + F5 re-arm + nits — native known is withdrawn on comms loss
- The Bad connectivity edge (and a Good edge with no Bad edge since the last Good one, or from a new child
  incarnation) sends MarkConditionsKnown(Known: false) for the driver's condition nodes, ahead of the quality
  annotation, so an alarm raised during an outage never reads known-inactive, Good after the reconnect. Stopping a
  child (a respawn) withdraws too.
- DriverInstanceActor stamps a connection epoch (bumped on every Connected entry) on the initial-state signal and
  on ConnectivityChanged(Connected); a signal raised under an earlier connection is dropped by the child and the host.
- G3 never discards a deferred withdrawal.
- F5 'still unknown' follows the node manager: a native transition takes its ref out of Pending.
- Re-arm F5 at the alarm-ref reindex for refs a deploy adds while connected (defensive: today such a deploy
  respawns the driver because its RawTags are folded into its config).
- Nits: signals/edges from a retired or non-current child never (re)create a tracker; the injected clock replaces
  DateTime.UtcNow.
- Primary demote/re-promote: checked, not a stale-known window — drivers and their condition writes run ungated on
  both pair members.
2026-11-24 10:37:02 -05:00

206 lines
12 KiB
C#

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;
/// <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));
}
// ---------------------------------------------------------------- review S2 / re-arm F5 / nits
/// <summary>
/// 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.
/// </summary>
[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<OpcUaPublishActor.MarkConditionsKnown>(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<OpcUaPublishActor.MarkConditionsKnown>(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<OpcUaPublishActor.MarkConditionsKnown>(m => m.Known, TimeSpan.FromSeconds(5), cancellationToken: Ct)
.ConditionIds.ShouldBe([A, B], ignoreOrder: true);
}
/// <summary>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.)</summary>
[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<OpcUaPublishActor.MarkConditionsKnown>(m => m.Known, TimeSpan.FromSeconds(5), cancellationToken: Ct);
rig.Hub.Unsignalled.ShouldBeEmpty();
Redeploy(rig, ["hi", "lo"]);
rig.Publish.FishForMessage<OpcUaPublishActor.MarkConditionsKnown>(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);
}
/// <summary>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.</summary>
[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<OpcUaPublishActor.AlarmStateUpdate>(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
}
/// <summary>Review nit — a signal from anything but the current child (a stopped incarnation, a stray sender) is
/// dropped and never (re)creates a tracker.</summary>
[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));
}
}