Files
lmxopcua/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/OpcUa/OpcUaPublishActorConditionKnownTests.cs
T
Joseph Doherty 16166c21e5 fix(grpc-data): A1 review S3 + S4 + nits — snapshot start cursor, readiness cut with the snapshot, failed applies
- S3a: SnapshotConditions reads a start cursor under Lock before enumerating keys; every slice carries it, so a
  condition materialised and activated between the enumeration and slice 1's hold is covered by deltas after it.
- S3b: each hold captures the apply generation (bumped when a rebuild begins) and the complete flag; slices carry
  them and ConditionSnapshotSlice.IsCompleteSnapshot / ConditionStateHub.IsSnapshotCompleteFor detect a rebuild
  that straddles a multi-slice snapshot. An empty scope still takes one hold.
- S3c: maxConditionsPerHold is clamped to MaxConditionsPerHoldLimit (5,000).
- S4: CompleteAddressSpaceApply(bool succeeded) (new default sink member, forwarded by the deferred and SDK sinks);
  the publish actor passes !Degraded. A failed/degraded rebuild keeps readiness false and its pending removals,
  emitting no removal records; the next successful apply completes it.
- Nits: ConditionStateRecord.UnshelveTimeUtc (timed-shelve expiry); ConditionStateHub.Read has a bounded default.
2026-11-24 10:43:04 -05:00

284 lines
16 KiB
C#

using System.Text.Json;
using Akka.Actor;
using Microsoft.Extensions.Logging.Abstractions;
using Shouldly;
using Xunit;
using ZB.MOM.WW.OtOpcUa.Commons.OpcUa;
using ZB.MOM.WW.OtOpcUa.Commons.Types;
using ZB.MOM.WW.OtOpcUa.OpcUaServer;
using ZB.MOM.WW.OtOpcUa.Runtime.OpcUa;
using ZB.MOM.WW.OtOpcUa.Runtime.Tests.Harness;
namespace ZB.MOM.WW.OtOpcUa.Runtime.Tests.OpcUa;
/// <summary>
/// A1 (plan §5.1 F2/G3): <see cref="OpcUaPublishActor.MarkConditionsKnown"/> is an alarm message. Live it applies in
/// arrival order; while a plan is in flight it is deferred beside the alarm states and replayed AFTER them — and a
/// source that lost a deferred projection (overflow or out-of-scope skip) has its deferred marks discarded.
/// </summary>
[Trait("Feature", "GrpcData")]
[Trait("Phase", "A1")]
[Trait("Category", "Unit")]
public sealed class OpcUaPublishActorConditionKnownTests : RuntimeActorTestBase
{
private static readonly TimeSpan PlanBudget = TimeSpan.FromSeconds(30);
private const string Src = OpcUaPublishActor.ScriptedSource;
private static readonly AlarmConditionSnapshot Active =
new(Active: true, Acknowledged: false, Confirmed: true, Enabled: true, AlarmShelvingKind.Unshelved, 500, "high");
[Fact]
public void Live_a_mark_applies_after_the_alarm_state_sent_before_it()
{
var sink = new OrderSink("al-1");
var actor = Sys.ActorOf(OpcUaPublishActor.PropsForTests(sink, new AddressSpaceApplier(sink, NullLogger<AddressSpaceApplier>.Instance), new OpcUaPublishActor.TestHooks()));
actor.Tell(new OpcUaPublishActor.AlarmStateUpdate("al-1", Active, DateTime.UtcNow, AddressSpaceRealm.Uns, Src));
actor.Tell(new OpcUaPublishActor.MarkConditionsKnown(Src, ["al-1"], AddressSpaceRealm.Uns));
AwaitAssert(() => sink.IsKnown("al-1").ShouldBeTrue(), PlanBudget, cancellationToken: TestContext.Current.CancellationToken);
sink.Log.ShouldBe(["alarm:al-1:True", "known:al-1"]);
}
/// <summary>T2 (iv) at the publish actor: the apply is artificially delayed (the plan is held open); the alarm and
/// the mark both arrive during it; on replay the mark still lands after the Active projection.</summary>
[Fact]
public void During_a_plan_the_deferred_mark_replays_after_the_deferred_alarm()
{
var sink = new OrderSink();
using var gate = new ManualResetEventSlim(false);
var actor = Spawn(sink, gate);
actor.Tell(Rebuild());
actor.Tell(new OpcUaPublishActor.AlarmStateUpdate("al-1", Active, DateTime.UtcNow, AddressSpaceRealm.Uns, Src));
actor.Tell(new OpcUaPublishActor.MarkConditionsKnown(Src, ["al-1"], AddressSpaceRealm.Uns));
AwaitAssert(() => sink.Skipped.ShouldContain("alarm:al-1"), PlanBudget, cancellationToken: TestContext.Current.CancellationToken);
sink.IsKnown("al-1").ShouldBeFalse(); // the condition does not exist yet
gate.Set();
ExpectMsg<OpcUaPublishActor.RebuildCompleted>(PlanBudget, cancellationToken: TestContext.Current.CancellationToken);
sink.IsKnown("al-1").ShouldBeTrue();
sink.Log.IndexOf("known:al-1").ShouldBeGreaterThan(sink.Log.IndexOf("alarm:al-1:True"));
}
/// <summary>T2 (x) G3 — overflow: the deferred alarm does not fit, so the same source's deferred mark is discarded
/// and the condition stays unknown until the next signal.</summary>
[Fact]
public void A_deferred_alarm_overflow_discards_the_sources_deferred_mark()
{
var sink = new OrderSink();
using var gate = new ManualResetEventSlim(false);
var actor = Sys.ActorOf(OpcUaPublishActor.PropsForTests(
sink, new AddressSpaceApplier(sink, NullLogger<AddressSpaceApplier>.Instance),
new OpcUaPublishActor.TestHooks { BeforePlan = () => gate.Wait() }, deferredWriteCapacity: 1));
actor.Tell(Rebuild());
// Fill the one-key buffer, so the alarm state is dropped.
actor.Tell(new OpcUaPublishActor.AttributeValueBatchUpdate([new ValueWrite("Plant/x", 1, OpcUaStatus.Good, DateTime.UtcNow, AddressSpaceRealm.Raw)]));
actor.Tell(new OpcUaPublishActor.AlarmStateUpdate("al-1", Active, DateTime.UtcNow, AddressSpaceRealm.Uns, Src));
actor.Tell(new OpcUaPublishActor.MarkConditionsKnown(Src, ["al-1"], AddressSpaceRealm.Uns));
AwaitAssert(() => sink.Skipped.ShouldContain("alarm:al-1"), PlanBudget, cancellationToken: TestContext.Current.CancellationToken);
gate.Set();
ExpectMsg<OpcUaPublishActor.RebuildCompleted>(PlanBudget, cancellationToken: TestContext.Current.CancellationToken);
sink.ConditionExists("al-1").ShouldBeTrue();
sink.IsKnown("al-1").ShouldBeFalse("never known over a projection that did not land");
// The next signal (after its projection) makes it known.
actor.Tell(new OpcUaPublishActor.AlarmStateUpdate("al-1", Active, DateTime.UtcNow, AddressSpaceRealm.Uns, Src));
actor.Tell(new OpcUaPublishActor.MarkConditionsKnown(Src, ["al-1"], AddressSpaceRealm.Uns));
AwaitAssert(() => sink.IsKnown("al-1").ShouldBeTrue(), PlanBudget, cancellationToken: TestContext.Current.CancellationToken);
}
/// <summary>T2 (x) G3 — out-of-scope skip: a deferred projection of the source is skipped on replay (its condition is
/// not in the applied scope), so the source's mark is discarded even for a condition that does exist.</summary>
[Fact]
public void An_out_of_scope_skip_discards_the_sources_deferred_mark_but_not_another_sources()
{
var sink = new OrderSink();
using var gate = new ManualResetEventSlim(false);
var actor = Spawn(sink, gate);
actor.Tell(Rebuild());
actor.Tell(new OpcUaPublishActor.AlarmStateUpdate("al-ghost", Active, DateTime.UtcNow, AddressSpaceRealm.Uns, Src));
actor.Tell(new OpcUaPublishActor.MarkConditionsKnown(Src, ["al-1"], AddressSpaceRealm.Uns));
actor.Tell(new OpcUaPublishActor.MarkConditionsKnown("drv-1", ["al-1"], AddressSpaceRealm.Uns));
AwaitAssert(() => sink.Skipped.ShouldContain("alarm:al-ghost"), PlanBudget, cancellationToken: TestContext.Current.CancellationToken);
gate.Set();
ExpectMsg<OpcUaPublishActor.RebuildCompleted>(PlanBudget, cancellationToken: TestContext.Current.CancellationToken);
sink.Marks.ShouldBe(["drv-1"]); // the scripted source's mark was discarded; the unrelated source's applied
}
[Fact]
public void A_withdrawal_reaches_MarkConditionsUnknown()
{
var sink = new OrderSink("al-1");
var actor = Sys.ActorOf(OpcUaPublishActor.PropsForTests(sink, new AddressSpaceApplier(sink, NullLogger<AddressSpaceApplier>.Instance), new OpcUaPublishActor.TestHooks()));
actor.Tell(new OpcUaPublishActor.MarkConditionsKnown(Src, ["al-1"], AddressSpaceRealm.Uns));
actor.Tell(new OpcUaPublishActor.MarkConditionsKnown(Src, ["al-1"], AddressSpaceRealm.Uns, Known: false));
AwaitAssert(() => sink.Log.ShouldBe(["known:al-1", "unknown:al-1"]), PlanBudget, cancellationToken: TestContext.Current.CancellationToken);
}
/// <summary>Review S2: a deferred WITHDRAWAL (<c>Known: false</c>) is never discarded by G3 — it only makes conditions
/// unknown, which is always safe — so it replays after the plan even for a source that lost a deferred projection.</summary>
[Fact]
public void A_deferred_withdrawal_is_replayed_even_for_a_source_that_lost_a_projection()
{
var sink = new OrderSink("al-1");
using var gate = new ManualResetEventSlim(false);
var actor = Sys.ActorOf(OpcUaPublishActor.PropsForTests(
sink, new AddressSpaceApplier(sink, NullLogger<AddressSpaceApplier>.Instance),
new OpcUaPublishActor.TestHooks { BeforePlan = () => gate.Wait() }, deferredWriteCapacity: 1));
actor.Tell(Rebuild());
actor.Tell(new OpcUaPublishActor.AttributeValueBatchUpdate([new ValueWrite("Plant/x", 1, OpcUaStatus.Good, DateTime.UtcNow, AddressSpaceRealm.Raw)]));
actor.Tell(new OpcUaPublishActor.AlarmStateUpdate("al-1", Active, DateTime.UtcNow, AddressSpaceRealm.Uns, Src));
actor.Tell(new OpcUaPublishActor.MarkConditionsKnown(Src, ["al-1"], AddressSpaceRealm.Uns, Known: false));
// Applied live (to the pre-plan node) as well as deferred.
AwaitAssert(() => sink.Log.ShouldContain("unknown:al-1"), PlanBudget, cancellationToken: TestContext.Current.CancellationToken);
var unknownBeforeReplay = sink.Log.Count(l => l == "unknown:al-1");
gate.Set();
ExpectMsg<OpcUaPublishActor.RebuildCompleted>(PlanBudget, cancellationToken: TestContext.Current.CancellationToken);
AwaitAssert(() => sink.Log.Count(l => l == "unknown:al-1").ShouldBe(unknownBeforeReplay + 1), PlanBudget,
cancellationToken: TestContext.Current.CancellationToken);
}
/// <summary>Review S4: a throwing apply completes with <c>succeeded: false</c> (the node manager then keeps the
/// rebuild's readiness withheld and emits no removals); a clean one with <c>true</c>.</summary>
[Fact]
public void A_throwing_apply_completes_the_address_space_apply_as_failed()
{
var sink = new OrderSink();
var fail = true;
var actor = Sys.ActorOf(OpcUaPublishActor.PropsForTests(
sink, new AddressSpaceApplier(sink, NullLogger<AddressSpaceApplier>.Instance),
new OpcUaPublishActor.TestHooks { BeforePlan = () => { if (fail) throw new InvalidOperationException("boom"); } }));
actor.Tell(Rebuild());
ExpectMsg<OpcUaPublishActor.RebuildCompleted>(PlanBudget, cancellationToken: TestContext.Current.CancellationToken);
AwaitAssert(() => sink.Completions.ShouldBe([false]), PlanBudget, cancellationToken: TestContext.Current.CancellationToken);
fail = false;
actor.Tell(Rebuild());
ExpectMsg<OpcUaPublishActor.RebuildCompleted>(PlanBudget, cancellationToken: TestContext.Current.CancellationToken);
AwaitAssert(() => sink.Completions.ShouldBe([false, true]), PlanBudget, cancellationToken: TestContext.Current.CancellationToken);
}
private IActorRef Spawn(OrderSink sink, ManualResetEventSlim gate) =>
Sys.ActorOf(OpcUaPublishActor.PropsForTests(
sink, new AddressSpaceApplier(sink, NullLogger<AddressSpaceApplier>.Instance),
new OpcUaPublishActor.TestHooks { BeforePlan = () => gate.Wait() }));
private static OpcUaPublishActor.RebuildAddressSpace Rebuild() =>
new(CorrelationId.NewId(), DeploymentId.NewId(), ScriptedAlarmArtifact(), ReportOutcome: true);
private static byte[] ScriptedAlarmArtifact() =>
JsonSerializer.SerializeToUtf8Bytes(new
{
UnsAreas = new[] { new { UnsAreaId = "area-1", ClusterId = "c1", Name = "Area" } },
UnsLines = new[] { new { UnsLineId = "line-1", UnsAreaId = "area-1", Name = "Line" } },
Equipment = new[] { new { EquipmentId = "eq-1", DriverInstanceId = (string?)null, UnsLineId = "line-1", Name = "Eq", MachineCode = "EQ-1" } },
RawFolders = Array.Empty<object>(),
DriverInstances = Array.Empty<object>(),
Devices = Array.Empty<object>(),
TagGroups = Array.Empty<object>(),
Tags = Array.Empty<object>(),
ScriptedAlarms = new[]
{
new
{
ScriptedAlarmId = "al-1", EquipmentId = "eq-1", Name = "High", AlarmType = "AlarmCondition",
Severity = 500, MessageTemplate = "high", PredicateScriptId = "s-1", HistorizeToAveva = false,
Retain = true, Enabled = true,
},
},
Scripts = new[] { new { ScriptId = "s-1", SourceCode = "return false;" } },
});
/// <summary>Records the order alarm states and marks land in; like the node manager, both are no-ops for a
/// condition that does not exist.</summary>
private sealed class OrderSink : IOpcUaAddressSpaceSink
{
private readonly object _gate = new();
private readonly HashSet<string> _conditions = new();
private readonly HashSet<string> _known = new();
private readonly List<string> _log = new();
private readonly List<string> _skipped = new();
private readonly List<string> _marks = new();
public OrderSink(params string[] existing) => _conditions.UnionWith(existing);
public List<string> Log { get { lock (_gate) return [.. _log]; } }
public List<string> Skipped { get { lock (_gate) return [.. _skipped]; } }
public List<string> Marks { get { lock (_gate) return [.. _marks]; } }
public bool IsKnown(string id) { lock (_gate) return _known.Contains(id); }
public bool ConditionExists(string id) { lock (_gate) return _conditions.Contains(id); }
public void WriteAlarmCondition(string alarmNodeId, AlarmConditionSnapshot state, DateTime ts, AddressSpaceRealm realm)
{
lock (_gate)
{
if (!_conditions.Contains(alarmNodeId)) { _skipped.Add("alarm:" + alarmNodeId); return; }
_log.Add($"alarm:{alarmNodeId}:{state.Active}");
_known.Add(alarmNodeId);
}
}
public void MarkConditionsKnown(string source, IReadOnlyList<string> conditionIds, AddressSpaceRealm realm)
{
lock (_gate)
{
foreach (var id in conditionIds.Where(_conditions.Contains))
{
_log.Add("known:" + id);
_marks.Add(source);
_known.Add(id);
}
}
}
public void MarkConditionsUnknown(string source, IReadOnlyList<string> conditionIds, AddressSpaceRealm realm)
{
lock (_gate)
{
foreach (var id in conditionIds.Where(_conditions.Contains))
{
_log.Add("unknown:" + id);
_known.Remove(id);
}
}
}
public void MaterialiseAlarmCondition(string alarmNodeId, string equipmentNodeId, string displayName, string alarmType, int severity, AddressSpaceRealm realm, bool isNative = false)
{
lock (_gate) _conditions.Add(alarmNodeId);
}
public List<bool> Completions { get { lock (_gate) return [.. _completions]; } }
private readonly List<bool> _completions = new();
public void CompleteAddressSpaceApply(bool succeeded)
{
lock (_gate) _completions.Add(succeeded);
}
public void RebuildAddressSpace()
{
lock (_gate) { _conditions.Clear(); _known.Clear(); }
}
public void WriteValue(string nodeId, object? value, uint statusCode, DateTime ts, AddressSpaceRealm realm) { }
public void WriteAlarmQuality(string alarmNodeId, uint statusCode, DateTime ts, AddressSpaceRealm realm) { }
public void EnsureFolder(string folderNodeId, string? parentNodeId, string displayName, AddressSpaceRealm realm) { }
public void EnsureVariable(string variableNodeId, string? parentFolderNodeId, string displayName, string dataType, bool writable, AddressSpaceRealm realm, string? historianTagname = null, bool isArray = false, uint? arrayLength = null, bool refuseArrayOnScalar = false) { }
public void RaiseNodesAddedModelChange(string affectedNodeId, AddressSpaceRealm realm) { }
public void WireAlarmNotifiers(string alarmNodeId, AddressSpaceRealm alarmRealm, IReadOnlyList<string> notifierFolderNodeIds, AddressSpaceRealm notifierFolderRealm) { }
public void AddReference(string sourceNodeId, AddressSpaceRealm sourceRealm, string targetNodeId, AddressSpaceRealm targetRealm, string referenceType = "Organizes") { }
}
}