375 lines
18 KiB
C#
375 lines
18 KiB
C#
using Opc.Ua;
|
||
using Shouldly;
|
||
using Xunit;
|
||
using ZB.MOM.WW.OtOpcUa.Commons.OpcUa;
|
||
using ZB.MOM.WW.OtOpcUa.Core.Abstractions;
|
||
|
||
namespace ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests;
|
||
|
||
/// <summary>
|
||
/// A1 origin condition state (plan §5.1) at the node manager: the delta callback, <c>state_known</c>, the activation
|
||
/// marker (T3) and the sliced snapshot. The parity cases (a)–(g) assert on NODE state: after each scenario the
|
||
/// delta stream folded per condition equals a fresh snapshot of the live nodes.
|
||
/// </summary>
|
||
[Trait("Feature", "GrpcData")]
|
||
[Trait("Phase", "A1")]
|
||
[Trait("Category", "Unit")]
|
||
public sealed class ConditionStateNodeManagerTests : IDisposable
|
||
{
|
||
private const string Device = "Plant/Galaxy/dev1";
|
||
private const string Native = "Plant/Galaxy/dev1/TankHi";
|
||
private const string Native2 = "Plant/Galaxy/dev1/TankLo";
|
||
private const string Equipment = "Area/Line/Eq";
|
||
private const string Scripted = "scripted-eq-hi";
|
||
|
||
private static CancellationToken Ct => TestContext.Current.CancellationToken;
|
||
private readonly string _pkiRoot = Path.Combine(Path.GetTempPath(), $"otopcua-a1-{Guid.NewGuid():N}");
|
||
|
||
private static AlarmConditionSnapshot State(bool active, bool acked, string message = "hi", uint status = OpcUaStatus.Good,
|
||
AlarmConditionClass? cls = null) => new(
|
||
Active: active, Acknowledged: acked, Confirmed: true, Enabled: true, Shelving: AlarmShelvingKind.Unshelved,
|
||
Severity: 700, Message: message, StatusCode: status, ConditionClass: cls);
|
||
|
||
// ---------------------------------------------------------------- parity (a)–(g)
|
||
|
||
[Fact]
|
||
public async Task a_Cold_start_before_any_publish_lists_every_condition_unknown()
|
||
{
|
||
var (host, nm, sink) = await BootAsync();
|
||
MaterialiseAll(nm);
|
||
nm.CompleteAddressSpaceApply();
|
||
|
||
var snap = Flatten(nm.SnapshotConditions((_, _) => true));
|
||
snap.Count.ShouldBe(3); // the snapshot defines the SET, normal conditions included
|
||
snap.ShouldAllBe(r => !r.StateKnown);
|
||
// Falsely-normal guard: no record ever claimed known before a source established a state.
|
||
sink.Records.ShouldNotContain(r => r.StateKnown);
|
||
AssertParity(nm, sink);
|
||
await host.DisposeAsync();
|
||
}
|
||
|
||
[Fact]
|
||
public async Task b_Standby_promotion_with_standing_active_alarms_keeps_the_hub_current()
|
||
{
|
||
var (host, nm, sink) = await BootAsync(warm: true);
|
||
nm.Standby.AlarmsSuppressed = true; // what a Warm OpcUaPublishActor sets while this node is not Primary
|
||
nm.Standby.AlarmsSuppressed.ShouldBeTrue();
|
||
MaterialiseAll(nm);
|
||
nm.CompleteAddressSpaceApply();
|
||
|
||
// While Warm the event is suppressed, but the delta is raised before that return.
|
||
nm.WriteAlarmCondition(Native, State(true, false), DateTime.UtcNow, AddressSpaceRealm.Raw);
|
||
sink.Records.Last().ShouldSatisfyAllConditions(
|
||
r => r.ConditionId.ShouldBe(Native), r => r.Active.ShouldBeTrue(), r => r.StateKnown.ShouldBeTrue());
|
||
|
||
nm.Standby.AlarmsSuppressed = false; // promotion
|
||
AssertParity(nm, sink);
|
||
Flatten(nm.SnapshotConditions((_, id) => id == Native)).Single().Active.ShouldBeTrue();
|
||
await host.DisposeAsync();
|
||
}
|
||
|
||
[Fact]
|
||
public async Task c_Rebuild_with_carried_over_alarms_is_known_at_once_and_never_announced_removed()
|
||
{
|
||
var (host, nm, sink) = await BootAsync();
|
||
MaterialiseAll(nm);
|
||
nm.CompleteAddressSpaceApply();
|
||
nm.WriteAlarmCondition(Native, State(true, false), DateTime.UtcNow, AddressSpaceRealm.Raw);
|
||
var marker = nm.GetActivationMarker(Native, AddressSpaceRealm.Raw).ShouldNotBeNull();
|
||
var before = sink.Records.Count;
|
||
|
||
nm.RebuildAddressSpace();
|
||
sink.ApplyComplete.ShouldBe(false);
|
||
// Native2 (never known) comes back too; the scripted one does NOT come back.
|
||
nm.EnsureFolder(Device, null, "dev1", AddressSpaceRealm.Raw);
|
||
nm.MaterialiseAlarmCondition(Native, Device, "TankHi", "OffNormalAlarm", 700, AddressSpaceRealm.Raw, isNative: true);
|
||
nm.MaterialiseAlarmCondition(Native2, Device, "TankLo", "OffNormalAlarm", 700, AddressSpaceRealm.Raw, isNative: true);
|
||
|
||
// Carried over ⇒ known at once, same occurrence marker (T3).
|
||
nm.IsConditionStateKnown(Native, AddressSpaceRealm.Raw).ShouldBeTrue();
|
||
nm.GetActivationMarker(Native, AddressSpaceRealm.Raw).ShouldBe(marker);
|
||
// A carried NORMAL condition that was never known stays unknown (no falsely-normal known).
|
||
nm.IsConditionStateKnown(Native2, AddressSpaceRealm.Raw).ShouldBeFalse();
|
||
|
||
nm.CompleteAddressSpaceApply();
|
||
sink.ApplyComplete.ShouldBe(true);
|
||
var rebuild = sink.Records.Skip(before).ToList();
|
||
rebuild.ShouldNotContain(r => r.Removed && r.ConditionId == Native);
|
||
rebuild.ShouldContain(r => r.Removed && r.ConditionId == Scripted);
|
||
rebuild.Where(r => r.ConditionId == Native).ShouldAllBe(r => r.Active && r.StateKnown);
|
||
AssertParity(nm, sink);
|
||
await host.DisposeAsync();
|
||
}
|
||
|
||
[Fact]
|
||
public async Task d_A_local_client_native_ack_applied_by_the_SDK_reaches_the_hub()
|
||
{
|
||
var (host, nm, sink) = await BootAsync();
|
||
MaterialiseAll(nm);
|
||
nm.WriteAlarmCondition(Native, State(true, false), DateTime.UtcNow, AddressSpaceRealm.Raw);
|
||
var alarm = nm.TryGetAlarmCondition(Native, AddressSpaceRealm.Raw).ShouldNotBeNull();
|
||
|
||
// The SDK's own Acknowledge handler, behind our method-transition wrapper; the driver route is stubbed Good.
|
||
alarm.OnAcknowledge = (_, _, _, _) => ServiceResult.Good;
|
||
var result = alarm.Acknowledge!.OnCall!(nm.SystemContext, alarm.Acknowledge, alarm.NodeId,
|
||
alarm.EventId!.Value, new LocalizedText("ok"));
|
||
ServiceResult.IsGood(result).ShouldBeTrue(result.ToString());
|
||
|
||
alarm.AckedState!.Id!.Value.ShouldBeTrue();
|
||
sink.Records.Last().ShouldSatisfyAllConditions(r => r.ConditionId.ShouldBe(Native), r => r.Acknowledged.ShouldBeTrue());
|
||
AssertParity(nm, sink);
|
||
await host.DisposeAsync();
|
||
}
|
||
|
||
[Fact]
|
||
public async Task e_A_ConditionClass_only_change_raises_a_state_only_record_and_no_event()
|
||
{
|
||
var (host, nm, sink) = await BootAsync();
|
||
MaterialiseAll(nm);
|
||
nm.WriteAlarmCondition(Native, State(true, false), DateTime.UtcNow, AddressSpaceRealm.Raw);
|
||
var alarm = nm.TryGetAlarmCondition(Native, AddressSpaceRealm.Raw).ShouldNotBeNull();
|
||
var eventId = alarm.EventId!.Value.ToArray();
|
||
var count = sink.Records.Count;
|
||
|
||
nm.WriteAlarmCondition(Native, State(true, false, cls: AlarmConditionClass.Safety), DateTime.UtcNow, AddressSpaceRealm.Raw);
|
||
|
||
alarm.EventId!.Value.ToArray().ShouldBe(eventId); // the delta gate fired nothing
|
||
sink.Records.Count.ShouldBe(count + 1);
|
||
sink.Records.Last().ConditionClassName.ShouldBe("SafetyConditionClass");
|
||
AssertParity(nm, sink);
|
||
await host.DisposeAsync();
|
||
}
|
||
|
||
[Fact]
|
||
public async Task f_An_ack_revert_reaches_the_hub_and_is_a_new_occurrence()
|
||
{
|
||
var (host, nm, sink) = await BootAsync();
|
||
MaterialiseAll(nm);
|
||
nm.WriteAlarmCondition(Native, State(true, false), DateTime.UtcNow, AddressSpaceRealm.Raw);
|
||
nm.WriteAlarmCondition(Native, State(true, true), DateTime.UtcNow, AddressSpaceRealm.Raw); // ack applied
|
||
var acked = nm.GetActivationMarker(Native, AddressSpaceRealm.Raw)!.Value.Sequence;
|
||
|
||
nm.WriteAlarmCondition(Native, State(true, false), DateTime.UtcNow, AddressSpaceRealm.Raw); // #760 revert
|
||
|
||
sink.Records.Last().Acknowledged.ShouldBeFalse();
|
||
nm.GetActivationMarker(Native, AddressSpaceRealm.Raw)!.Value.Sequence.ShouldBe(acked + 1); // F4: Acked true→false
|
||
AssertParity(nm, sink);
|
||
await host.DisposeAsync();
|
||
}
|
||
|
||
[Fact]
|
||
public async Task g_A_quality_only_update_reaches_the_hub()
|
||
{
|
||
var (host, nm, sink) = await BootAsync();
|
||
MaterialiseAll(nm);
|
||
nm.WriteAlarmCondition(Native, State(false, true), DateTime.UtcNow, AddressSpaceRealm.Raw);
|
||
|
||
nm.WriteAlarmQuality(Native, StatusCodes.BadNoCommunication.Code, DateTime.UtcNow, AddressSpaceRealm.Raw);
|
||
|
||
sink.Records.Last().Quality.ShouldBe(StatusCodes.BadNoCommunication.Code);
|
||
AssertParity(nm, sink);
|
||
await host.DisposeAsync();
|
||
}
|
||
|
||
// ---------------------------------------------------------------- known / T1 / T3
|
||
|
||
[Fact]
|
||
public async Task T1_A_signal_after_the_snapshot_cut_arrives_as_a_state_only_known_record()
|
||
{
|
||
var (host, nm, sink) = await BootAsync();
|
||
MaterialiseAll(nm);
|
||
nm.CompleteAddressSpaceApply();
|
||
var slice = nm.SnapshotConditions((r, _) => r == AddressSpaceRealm.Raw).Single();
|
||
slice.Records.ShouldAllBe(r => !r.StateKnown);
|
||
// Negative control: nothing claims known before the signal.
|
||
sink.Records.Where(r => r.Version > slice.Watermark).ShouldBeEmpty();
|
||
|
||
nm.MarkConditionsKnown("drv", [Native, Native2], AddressSpaceRealm.Raw).ShouldBe(2);
|
||
|
||
var after = sink.Records.Where(r => r.Version > slice.Watermark).ToList();
|
||
after.Count.ShouldBe(2); // positive control: the records arrive with no further origin activity
|
||
after.ShouldAllBe(r => r.StateKnown && !r.Active);
|
||
// A repeat signal is a no-op.
|
||
nm.MarkConditionsKnown("drv", [Native], AddressSpaceRealm.Raw).ShouldBe(0);
|
||
sink.Records.Count(r => r.Version > slice.Watermark).ShouldBe(2);
|
||
await host.DisposeAsync();
|
||
}
|
||
|
||
[Fact]
|
||
public async Task Marking_unknown_withdraws_known_and_rematerialise_clears_it()
|
||
{
|
||
var (host, nm, sink) = await BootAsync();
|
||
MaterialiseAll(nm);
|
||
nm.MarkConditionsKnown("scripted", [Scripted], AddressSpaceRealm.Uns);
|
||
nm.MarkConditionsUnknown("scripted", [Scripted], AddressSpaceRealm.Uns).ShouldBe(1);
|
||
nm.IsConditionStateKnown(Scripted, AddressSpaceRealm.Uns).ShouldBeFalse();
|
||
sink.Records.Last().StateKnown.ShouldBeFalse();
|
||
nm.MarkConditionsUnknown("scripted", [Scripted], AddressSpaceRealm.Uns).ShouldBe(0);
|
||
await host.DisposeAsync();
|
||
}
|
||
|
||
[Fact]
|
||
public async Task T3_The_marker_moves_only_on_a_new_occurrence()
|
||
{
|
||
var (host, nm, _) = await BootAsync();
|
||
MaterialiseAll(nm);
|
||
ulong Seq() => nm.GetActivationMarker(Native, AddressSpaceRealm.Raw)!.Value.Sequence;
|
||
Seq().ShouldBe(0ul);
|
||
nm.WriteAlarmCondition(Native, State(true, false), DateTime.UtcNow, AddressSpaceRealm.Raw);
|
||
Seq().ShouldBe(1ul);
|
||
nm.WriteAlarmCondition(Native, State(true, false, message: "changed"), DateTime.UtcNow, AddressSpaceRealm.Raw);
|
||
nm.WriteAlarmCondition(Native, State(true, false, message: "changed"), DateTime.UtcNow, AddressSpaceRealm.Raw);
|
||
Seq().ShouldBe(1ul); // message-only change and same-state re-projection
|
||
nm.WriteAlarmCondition(Native, State(false, true), DateTime.UtcNow, AddressSpaceRealm.Raw);
|
||
Seq().ShouldBe(1ul);
|
||
nm.WriteAlarmCondition(Native, State(false, false), DateTime.UtcNow, AddressSpaceRealm.Raw); // InactiveUnacknowledged
|
||
Seq().ShouldBe(2ul);
|
||
await host.DisposeAsync();
|
||
}
|
||
|
||
[Fact]
|
||
public async Task A_scripted_condition_keeps_its_marker_across_a_rebuild_reassert()
|
||
{
|
||
var (host, nm, _) = await BootAsync();
|
||
MaterialiseAll(nm);
|
||
nm.WriteAlarmCondition(Scripted, State(true, false), DateTime.UtcNow, AddressSpaceRealm.Uns);
|
||
var marker = nm.GetActivationMarker(Scripted, AddressSpaceRealm.Uns);
|
||
|
||
nm.RebuildAddressSpace();
|
||
MaterialiseAll(nm);
|
||
nm.IsConditionStateKnown(Scripted, AddressSpaceRealm.Uns).ShouldBeFalse(); // scripted: re-established by its engine
|
||
nm.WriteAlarmCondition(Scripted, State(true, false), DateTime.UtcNow, AddressSpaceRealm.Uns); // the re-assert
|
||
nm.CompleteAddressSpaceApply();
|
||
|
||
nm.GetActivationMarker(Scripted, AddressSpaceRealm.Uns).ShouldBe(marker);
|
||
await host.DisposeAsync();
|
||
}
|
||
|
||
// ---------------------------------------------------------------- snapshot structure
|
||
|
||
[Fact]
|
||
public async Task A_snapshot_never_copies_more_than_MaxConditions_under_one_Lock_hold()
|
||
{
|
||
var (host, nm, sink) = await BootAsync();
|
||
nm.EnsureFolder(Device, null, "dev1", AddressSpaceRealm.Raw);
|
||
for (var i = 0; i < 25; i++)
|
||
nm.MaterialiseAlarmCondition($"{Device}/A{i:00}", Device, $"A{i:00}", "OffNormalAlarm", 500, AddressSpaceRealm.Raw, isNative: true);
|
||
|
||
var holds = new List<int>();
|
||
nm.OnConditionSnapshotHold = n =>
|
||
{
|
||
Monitor.IsEntered(nm.Lock).ShouldBeFalse(); // reported after the hold is released
|
||
holds.Add(n);
|
||
// A delta raised BETWEEN holds: into the second slice (A15) and into the first, already-cut one (A00).
|
||
if (holds.Count == 1)
|
||
{
|
||
nm.WriteAlarmCondition($"{Device}/A15", State(true, false), DateTime.UtcNow, AddressSpaceRealm.Raw);
|
||
nm.WriteAlarmCondition($"{Device}/A00", State(true, false), DateTime.UtcNow, AddressSpaceRealm.Raw);
|
||
}
|
||
};
|
||
|
||
var slices = nm.SnapshotConditions((_, _) => true, maxConditionsPerHold: 10);
|
||
|
||
holds.ShouldBe([10, 10, 5]);
|
||
slices.Count.ShouldBe(3);
|
||
// Atomic cut: A15's change is inside slice 2 (≤ its watermark); A00's is after slice 1's watermark.
|
||
slices[1].Records.Single(r => r.ConditionId.EndsWith("A15")).Active.ShouldBeTrue();
|
||
slices[0].Records.Single(r => r.ConditionId.EndsWith("A00")).Active.ShouldBeFalse();
|
||
sink.Records.Single(r => r.ConditionId.EndsWith("A00") && r.Active).Version.ShouldBeGreaterThan(slices[0].Watermark);
|
||
sink.Records.Single(r => r.ConditionId.EndsWith("A15") && r.Active).Version.ShouldBeLessThanOrEqualTo(slices[1].Watermark);
|
||
await host.DisposeAsync();
|
||
}
|
||
|
||
// ---------------------------------------------------------------- helpers
|
||
|
||
private static void MaterialiseAll(OtOpcUaNodeManager nm)
|
||
{
|
||
nm.EnsureFolder(Device, null, "dev1", AddressSpaceRealm.Raw);
|
||
nm.MaterialiseAlarmCondition(Native, Device, "TankHi", "OffNormalAlarm", 700, AddressSpaceRealm.Raw, isNative: true);
|
||
nm.MaterialiseAlarmCondition(Native2, Device, "TankLo", "OffNormalAlarm", 700, AddressSpaceRealm.Raw, isNative: true);
|
||
nm.EnsureFolder(Equipment, null, "Eq", AddressSpaceRealm.Uns);
|
||
nm.MaterialiseAlarmCondition(Scripted, Equipment, "Hi", "AlarmCondition", 500, AddressSpaceRealm.Uns);
|
||
}
|
||
|
||
private static List<ConditionStateRecord> Flatten(IReadOnlyList<ConditionSnapshotSlice> slices) =>
|
||
slices.SelectMany(s => s.Records).ToList();
|
||
|
||
/// <summary>Hub snapshot == node state: the delta stream folded per condition equals a fresh snapshot of the nodes.</summary>
|
||
internal static void AssertParity(OtOpcUaNodeManager nm, RecordingConditionSink sink)
|
||
{
|
||
var fold = new Dictionary<(AddressSpaceRealm, string), ConditionStateRecord>();
|
||
foreach (var r in sink.Records)
|
||
{
|
||
if (r.Removed) fold.Remove((r.Realm, r.ConditionId));
|
||
else fold[(r.Realm, r.ConditionId)] = r;
|
||
}
|
||
|
||
var nodes = nm.SnapshotConditions((_, _) => true).SelectMany(s => s.Records).ToList();
|
||
fold.Count.ShouldBe(nodes.Count);
|
||
foreach (var node in nodes)
|
||
{
|
||
fold.TryGetValue((node.Realm, node.ConditionId), out var folded).ShouldBeTrue(node.ConditionId);
|
||
(folded! with { Version = 0 }).ShouldBe(node with { Version = 0 }, node.ConditionId);
|
||
}
|
||
}
|
||
|
||
private async Task<(OpcUaApplicationHost Host, OtOpcUaNodeManager Nm, RecordingConditionSink Sink)> BootAsync(bool warm = false)
|
||
{
|
||
var applicationUri = $"urn:OtOpcUa.A1Test:{Guid.NewGuid():N}";
|
||
var started = await OpcUaHostStart.StartAsync(
|
||
port => new OpcUaApplicationHost(
|
||
new OpcUaApplicationHostOptions
|
||
{
|
||
ApplicationName = "OtOpcUa.A1Test",
|
||
ApplicationUri = applicationUri,
|
||
OpcUaPort = port,
|
||
PublicHostname = "localhost",
|
||
PkiStoreRoot = _pkiRoot,
|
||
Redundancy = new OpcUaRedundancyOptions { Mode = warm ? "Warm" : "Unset" },
|
||
PeerApplicationUris = warm ? ["urn:peer"] : [],
|
||
},
|
||
Microsoft.Extensions.Logging.Abstractions.NullLogger<OpcUaApplicationHost>.Instance),
|
||
() => new OtOpcUaSdkServer(), Ct);
|
||
var nm = started.Server.NodeManager!;
|
||
var sink = new RecordingConditionSink();
|
||
nm.ConditionStateSink = sink;
|
||
return (started.Host, nm, sink);
|
||
}
|
||
|
||
/// <summary>Cleans up the PKI root directory.</summary>
|
||
public void Dispose()
|
||
{
|
||
if (Directory.Exists(_pkiRoot))
|
||
{
|
||
try { Directory.Delete(_pkiRoot, recursive: true); }
|
||
catch { /* best-effort cleanup */ }
|
||
}
|
||
}
|
||
}
|
||
|
||
/// <summary>An in-memory <see cref="IConditionStateSink"/> that keeps every record with its assigned version.</summary>
|
||
internal sealed class RecordingConditionSink : IConditionStateSink
|
||
{
|
||
private long _version;
|
||
|
||
/// <summary>Every appended record, in order, with its version.</summary>
|
||
public List<ConditionStateRecord> Records { get; } = new();
|
||
|
||
/// <summary>The last apply state the node manager reported.</summary>
|
||
public bool? ApplyComplete { get; private set; }
|
||
|
||
/// <inheritdoc />
|
||
public long Watermark => _version;
|
||
|
||
/// <inheritdoc />
|
||
public long Append(ConditionStateRecord record)
|
||
{
|
||
var v = ++_version;
|
||
Records.Add(record with { Version = v });
|
||
return v;
|
||
}
|
||
|
||
/// <inheritdoc />
|
||
public void OnApplyStateChanged(bool complete) => ApplyComplete = complete;
|
||
}
|