diff --git a/src/Core/ZB.MOM.WW.OtOpcUa.Commons/Observability/OtOpcUaTelemetry.cs b/src/Core/ZB.MOM.WW.OtOpcUa.Commons/Observability/OtOpcUaTelemetry.cs index 54f5d5316..34cbb7c61 100644 --- a/src/Core/ZB.MOM.WW.OtOpcUa.Commons/Observability/OtOpcUaTelemetry.cs +++ b/src/Core/ZB.MOM.WW.OtOpcUa.Commons/Observability/OtOpcUaTelemetry.cs @@ -228,6 +228,22 @@ public static class OtOpcUaTelemetry Meter.CreateCounter("otopcua.opcua.standby.suppressed_alarm_events", unit: "{event}", description: "New alarm condition events suppressed on a Warm standby."); + /// A1: driver instances whose initial alarm state was not signalled within their + /// DataConnections:ConditionKnownSignalTimeout (their conditions stay unknown, never known-inactive). + public static readonly Counter DataConnConditionsUnsignalled = + Meter.CreateCounter("otopcua.dataconn.conditions.unsignalled", unit: "{condition}", + description: "Native conditions whose initial alarm state was not signalled within the signal timeout."); + + /// A1: condition-state hub partitions whose bounded buffer overflowed (epoch invalidated ⇒ subscribers resnapshot). + public static readonly Counter DataConnConditionPartitionOverflows = + Meter.CreateCounter("otopcua.dataconn.conditions.partition_overflows", unit: "{overflow}", + description: "Condition-state hub partition overflows (epoch invalidated)."); + + /// A1 (G3): deferred MarkConditionsKnown discarded because an alarm projection of the same source did not land. + public static readonly Counter DataConnConditionMarksDiscarded = + Meter.CreateCounter("otopcua.dataconn.conditions.marks_discarded", unit: "{mark}", + description: "Deferred condition-known marks discarded after a deferred alarm projection was dropped or skipped."); + // ---------------- Convenience helpers ---------------- /// diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Host/OpcUa/OtOpcUaServerHostedService.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Host/OpcUa/OtOpcUaServerHostedService.cs index 7f4b03407..3809da6b7 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Host/OpcUa/OtOpcUaServerHostedService.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Host/OpcUa/OtOpcUaServerHostedService.cs @@ -61,6 +61,8 @@ public sealed class OtOpcUaServerHostedService : IHostedService, IAsyncDisposabl private readonly IProjectedBrowseAccess? _projectedBrowseAccess; private readonly IProjectedDataAccess? _projectedDataAccess; private readonly IProjectedHistoryAccess? _projectedHistoryAccess; + // A1 (plan §5.1): the condition-state hub the node manager's delta callback feeds. Invisible until A2. + private readonly IConditionStateSink? _conditionStateSink; private readonly IFederatedProjectionCatalog? _projectedCatalog; private readonly DataConnectionOptions _dataConnectionOptions; @@ -167,9 +169,11 @@ public sealed class OtOpcUaServerHostedService : IHostedService, IAsyncDisposabl IProjectedBrowseAccess? projectedBrowseAccess = null, IProjectedDataAccess? projectedDataAccess = null, IFederatedProjectionCatalog? projectedCatalog = null, - IProjectedHistoryAccess? projectedHistoryAccess = null) + IProjectedHistoryAccess? projectedHistoryAccess = null, + IConditionStateSink? conditionStateSink = null) { _projectedHistoryAccess = projectedHistoryAccess; + _conditionStateSink = conditionStateSink; _dataConnectionOptions = configuration.GetSection(DataConnectionOptions.SectionName).Get() ?? new(); _projectedBrowseAccess = projectedBrowseAccess; _projectedDataAccess = projectedDataAccess; @@ -269,6 +273,7 @@ public sealed class OtOpcUaServerHostedService : IHostedService, IAsyncDisposabl _server.NodeManager.ProjectedBrowseClock = _time; _server.NodeManager.ProjectedDataAccess = _projectedDataAccess; _server.NodeManager.ProjectedHistoryAccess = _projectedHistoryAccess; + _server.NodeManager.ConditionStateSink = _conditionStateSink; if (_projectedCatalog is { } projectedCatalog) _server.NodeManager.MappedSubjectResolver = (realm, identifier) => projectedCatalog.TryResolveProjected(realm == AddressSpaceRealm.Raw ? DataRealm.Raw : DataRealm.Uns, diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ConditionStateHub.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ConditionStateHub.cs new file mode 100644 index 000000000..11bbc7ddc --- /dev/null +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ConditionStateHub.cs @@ -0,0 +1,203 @@ +using System.Collections.Concurrent; +using ZB.MOM.WW.OtOpcUa.Commons.Observability; +using ZB.MOM.WW.OtOpcUa.Commons.OpcUa; +using ZB.MOM.WW.OtOpcUa.Core.Abstractions; +using ZB.MOM.WW.OtOpcUa.OpcUaServer; + +namespace ZB.MOM.WW.OtOpcUa.Runtime.DataConnections; + +/// +/// The origin's condition-state hub (plan §5.1, A1): the node manager's SDK-free delta callback lands here, in +/// bounded per-partition buffers, and A2's condition streams read from it. Header-gated and invisible until A2. +/// +/// +/// +/// Never blocks the node manager. and run under the node +/// manager's Lock: they take one partition's tiny lock, enqueue and return — no I/O, no wait. A full +/// partition evicts its oldest record and raises that partition's floor; a reader whose cursor sits below +/// the floor has lost a record and must reset to a fresh snapshot (). +/// That is the plan's "partition epoch invalidated", made per reader so a caught-up reader is never reset. +/// +/// +/// Versions are global. One monotonically increasing version across partitions, so a snapshot slice's +/// watermark (taken under the same Lock) orders every delta for every condition in that slice. +/// +/// +/// snapshot_complete readiness = the node manager's current apply has completed +/// () AND this node holds its Primary verdict +/// (). Until both hold, A2 sends a Control NotReady. +/// +/// +/// Unsignalled-state diagnostic (F5). records "initial alarm state not +/// signalled" per driver instance (elapsed time, condition count) and counts +/// otopcua.dataconn.conditions.unsignalled; a later signal clears it (). +/// +/// +public sealed class ConditionStateHub : IConditionStateSink +{ + /// Default partition count. + public const int DefaultPartitionCount = 16; + + /// Default per-partition buffer capacity (records). + public const int DefaultPartitionCapacity = 8192; + + private sealed class Partition + { + public readonly object Gate = new(); + public readonly Queue Buffer = new(); + public long Floor; + } + + private readonly Partition[] _partitions; + private readonly int _capacity; + private readonly IDriverPrimaryRoleSource? _primary; + private readonly ConcurrentDictionary _unsignalled = new(StringComparer.Ordinal); + private long _version; + private volatile bool _applyComplete; + + /// Creates the hub. + /// The node's Primary verdict, or null (never Primary ⇒ never snapshot-complete). + /// Partition count (≥ 1). + /// Records each partition retains (≥ 1). + public ConditionStateHub(IDriverPrimaryRoleSource? primary = null, int partitionCount = DefaultPartitionCount, + int partitionCapacity = DefaultPartitionCapacity) + { + ArgumentOutOfRangeException.ThrowIfLessThan(partitionCount, 1); + ArgumentOutOfRangeException.ThrowIfLessThan(partitionCapacity, 1); + _primary = primary; + _capacity = partitionCapacity; + _partitions = new Partition[partitionCount]; + for (var i = 0; i < partitionCount; i++) _partitions[i] = new Partition(); + } + + /// The partition count. + public int PartitionCount => _partitions.Length; + + /// + public long Watermark => Interlocked.Read(ref _version); + + /// Whether the current address-space apply has completed. + public bool IsApplyComplete => _applyComplete; + + /// snapshot_complete may be sent: apply complete AND this node is Primary. + public bool IsSnapshotComplete => _applyComplete && _primary?.ShouldActAsPrimary == true; + + /// + public long Append(ConditionStateRecord record) + { + ArgumentNullException.ThrowIfNull(record); + var p = _partitions[PartitionOf(record.Realm, record.ConditionId, _partitions.Length)]; + lock (p.Gate) + { + // The version is taken inside the partition gate so each partition's buffer is in version order. + var version = Interlocked.Increment(ref _version); + if (p.Buffer.Count >= _capacity) + { + p.Floor = p.Buffer.Dequeue().Version; + OtOpcUaTelemetry.DataConnConditionPartitionOverflows.Add(1); + } + + p.Buffer.Enqueue(record with { Version = version }); + return version; + } + } + + /// + public void OnApplyStateChanged(bool complete) => _applyComplete = complete; + + /// The stable partition of a condition (FNV-1a over realm + id). + /// The condition's realm. + /// The condition id. + /// The partition count. + /// The partition index. + public static int PartitionOf(AddressSpaceRealm realm, string conditionId, int partitionCount) + { + unchecked + { + var h = 2166136261u ^ (uint)realm; + h *= 16777619u; + foreach (var c in conditionId) + { + h = (h ^ c) * 16777619u; + } + + return (int)(h % (uint)partitionCount); + } + } + + /// + /// Read a partition's records with a version above , at most + /// . when a record above the cursor was + /// already evicted — the reader must take a fresh snapshot of that partition. + /// + /// The partition index. + /// The reader's cursor (the slice watermark or the last version it applied). + /// The most records to return. + /// The read. + public ConditionDeltaRead Read(int partition, long afterVersion, int max = int.MaxValue) + { + var p = _partitions[partition]; + lock (p.Gate) + { + if (afterVersion < p.Floor) return new ConditionDeltaRead(true, p.Floor, []); + var records = new List(); + foreach (var r in p.Buffer) + { + if (r.Version <= afterVersion) continue; + if (records.Count >= max) break; + records.Add(r); + } + + return new ConditionDeltaRead(false, p.Floor, records); + } + } + + /// Read every partition after one cursor (tests and diagnostics), in version order. + /// The cursor. + /// The records, or null when any partition requires a reset. + public IReadOnlyList? ReadAll(long afterVersion) + { + var all = new List(); + for (var i = 0; i < _partitions.Length; i++) + { + var read = Read(i, afterVersion); + if (read.ResetRequired) return null; + all.AddRange(read.Records); + } + + all.Sort((a, b) => a.Version.CompareTo(b.Version)); + return all; + } + + /// F5: a driver's initial alarm state was not signalled in time — its conditions stay unknown. + /// The driver instance. + /// Time since its quality went Good. + /// How many of its conditions are still unsignalled. + public void ReportUnsignalled(string driverInstanceId, TimeSpan elapsed, int conditions) + { + ArgumentException.ThrowIfNullOrEmpty(driverInstanceId); + _unsignalled[driverInstanceId] = new UnsignalledConditionState(driverInstanceId, elapsed, conditions); + OtOpcUaTelemetry.DataConnConditionsUnsignalled.Add(conditions, + new KeyValuePair("driver", driverInstanceId)); + } + + /// A later signal (or the driver's removal) clears the diagnostic. + /// The driver instance. + /// Whether a diagnostic was cleared. + public bool ClearUnsignalled(string driverInstanceId) => _unsignalled.TryRemove(driverInstanceId, out _); + + /// The current "initial alarm state not signalled" diagnostics, by driver instance. + public IReadOnlyDictionary Unsignalled => _unsignalled; +} + +/// One partition read. +/// A record above the cursor was evicted; resnapshot the partition. +/// The version of the last evicted record. +/// The records above the cursor, in version order. +public sealed record ConditionDeltaRead(bool ResetRequired, long Floor, IReadOnlyList Records); + +/// The F5 data-connection diagnostic "initial alarm state not signalled". +/// The driver instance. +/// Time since its quality went Good when the timeout fired. +/// How many of its conditions were still unsignalled. +public sealed record UnsignalledConditionState(string DriverInstanceId, TimeSpan Elapsed, int Conditions); diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/ServiceCollectionExtensions.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/ServiceCollectionExtensions.cs index 179471ad2..734ce3276 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/ServiceCollectionExtensions.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/ServiceCollectionExtensions.cs @@ -95,6 +95,12 @@ public static class ServiceCollectionExtensions // publishes two verdicts into the same object rather than into two that disagree. services.TryAddSingleton(); services.TryAddSingleton(sp => sp.GetRequiredService()); + // A1 (grpc-data plan §5.1): the origin condition-state hub. The node manager's SDK-free delta callback feeds it; + // its snapshot_complete readiness reads the same Primary verdict. Header-gated and unread until A2. + services.TryAddSingleton(sp => new ZB.MOM.WW.OtOpcUa.Runtime.DataConnections.ConditionStateHub( + sp.GetRequiredService())); + services.TryAddSingleton( + sp => sp.GetRequiredService()); // the continuous-historization capture verdict, registered here — unconditionally on // every driver-role node — for the same reason as the line above, and NOT alongside the alarm diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/ConditionStateHubTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/ConditionStateHubTests.cs new file mode 100644 index 000000000..86323d87c --- /dev/null +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/ConditionStateHubTests.cs @@ -0,0 +1,137 @@ +using Shouldly; +using Xunit; +using ZB.MOM.WW.OtOpcUa.Commons.OpcUa; +using ZB.MOM.WW.OtOpcUa.Core.Abstractions; +using ZB.MOM.WW.OtOpcUa.OpcUaServer; +using ZB.MOM.WW.OtOpcUa.Runtime.DataConnections; + +namespace ZB.MOM.WW.OtOpcUa.Runtime.Tests.DataConnections; + +/// A1 : bounded partitions, per-reader reset, readiness, F5 diagnostic. +[Trait("Feature", "GrpcData")] +[Trait("Phase", "A1")] +[Trait("Category", "Unit")] +public sealed class ConditionStateHubTests : IDisposable +{ + private static CancellationToken Ct => TestContext.Current.CancellationToken; + private readonly string _pkiRoot = Path.Combine(Path.GetTempPath(), $"otopcua-a1hub-{Guid.NewGuid():N}"); + + private static ConditionStateRecord Rec(string id, bool active = false, bool known = true) => new( + AddressSpaceRealm.Raw, id, true, 0, false, known, active, true, true, true, AlarmShelvingKind.Unshelved, 500, "m", + 0, null, DateTime.UtcNow, active, new ConditionActivationMarker("i", 0)); + + private sealed class Primary(bool value) : IDriverPrimaryRoleSource + { + public bool ShouldActAsPrimary { get; set; } = value; + public void PublishPrimaryRole(bool shouldActAsPrimary) => ShouldActAsPrimary = shouldActAsPrimary; + } + + [Fact] + public void Versions_are_global_and_reads_return_records_after_the_cursor() + { + var hub = new ConditionStateHub(partitionCount: 4); + var v1 = hub.Append(Rec("a")); + var v2 = hub.Append(Rec("b")); + v2.ShouldBe(v1 + 1); + hub.Watermark.ShouldBe(v2); + hub.ReadAll(0)!.Select(r => r.ConditionId).ShouldBe(["a", "b"]); + hub.ReadAll(v1)!.Single().ConditionId.ShouldBe("b"); + } + + [Fact] + public void An_overflow_resets_only_a_reader_that_fell_behind_the_evicted_record() + { + var hub = new ConditionStateHub(partitionCount: 1, partitionCapacity: 3); + for (var i = 0; i < 3; i++) hub.Append(Rec($"c{i}")); + var caughtUp = hub.Watermark; + hub.Append(Rec("c3")); // evicts version 1 + + hub.Read(0, afterVersion: 0).ResetRequired.ShouldBeTrue(); // lost record 1 + hub.Read(0, afterVersion: 1).ResetRequired.ShouldBeFalse(); // record 1 already applied + hub.Read(0, caughtUp).Records.Single().ConditionId.ShouldBe("c3"); + } + + [Fact] + public void Snapshot_complete_needs_apply_complete_and_the_Primary_verdict() + { + var primary = new Primary(false); + var hub = new ConditionStateHub(primary); + hub.IsSnapshotComplete.ShouldBeFalse(); + hub.OnApplyStateChanged(true); + hub.IsSnapshotComplete.ShouldBeFalse(); // not Primary + primary.ShouldActAsPrimary = true; + hub.IsSnapshotComplete.ShouldBeTrue(); + hub.OnApplyStateChanged(false); // a rebuild began + hub.IsSnapshotComplete.ShouldBeFalse(); + } + + [Fact] + public void The_unsignalled_diagnostic_is_raised_and_cleared() + { + var hub = new ConditionStateHub(); + hub.ReportUnsignalled("drv", TimeSpan.FromSeconds(120), 3); + hub.Unsignalled["drv"].Conditions.ShouldBe(3); + hub.ClearUnsignalled("drv").ShouldBeTrue(); + hub.Unsignalled.ShouldBeEmpty(); + } + + /// + /// The falsely-empty negative test (A1): an origin restart with standing alarms. Until the apply completes the + /// hub is not snapshot-complete, and no record claims a condition known-inactive before its source projected. + /// + [Fact] + public async Task An_origin_restart_is_never_a_falsely_empty_or_falsely_normal_snapshot() + { + var primary = new Primary(true); + var hub = new ConditionStateHub(primary); + var (host, nm) = await BootAsync(); + nm.ConditionStateSink = hub; + hub.IsSnapshotComplete.ShouldBeFalse(); // nothing applied yet: the cold node manager is not complete + + nm.EnsureFolder("Plant/dev", null, "dev", AddressSpaceRealm.Raw); + nm.MaterialiseAlarmCondition("Plant/dev/A", "Plant/dev", "A", "OffNormalAlarm", 700, AddressSpaceRealm.Raw, isNative: true); + nm.MaterialiseAlarmCondition("Plant/dev/B", "Plant/dev", "B", "OffNormalAlarm", 700, AddressSpaceRealm.Raw, isNative: true); + hub.IsSnapshotComplete.ShouldBeFalse(); // mid-apply: the set may still be incomplete + nm.CompleteAddressSpaceApply(); + hub.IsSnapshotComplete.ShouldBeTrue(); + + // A is a standing alarm whose replay has not arrived yet; nothing may say "known, inactive" about it. + hub.ReadAll(0)!.ShouldNotContain(r => r.StateKnown && !r.Active); + + nm.WriteAlarmCondition("Plant/dev/A", new AlarmConditionSnapshot(true, false, true, true, AlarmShelvingKind.Unshelved, 700, "A"), + DateTime.UtcNow, AddressSpaceRealm.Raw); + nm.MarkConditionsKnown("drv", ["Plant/dev/A", "Plant/dev/B"], AddressSpaceRealm.Raw); + + var records = hub.ReadAll(0)!; + records.Where(r => r.ConditionId == "Plant/dev/A" && r.StateKnown).ShouldAllBe(r => r.Active); + records.Last(r => r.ConditionId == "Plant/dev/B").StateKnown.ShouldBeTrue(); + await host.DisposeAsync(); + } + + private async Task<(OpcUaApplicationHost Host, OtOpcUaNodeManager Nm)> BootAsync() + { + var started = await OpcUaHostStart.StartAsync( + port => new OpcUaApplicationHost( + new OpcUaApplicationHostOptions + { + ApplicationName = "OtOpcUa.A1HubTest", + ApplicationUri = $"urn:OtOpcUa.A1HubTest:{Guid.NewGuid():N}", + OpcUaPort = port, + PublicHostname = "localhost", + PkiStoreRoot = _pkiRoot, + }, + Microsoft.Extensions.Logging.Abstractions.NullLogger.Instance), + () => new OtOpcUaSdkServer(), Ct); + return (started.Host, started.Server.NodeManager!); + } + + /// Cleans up the PKI root directory. + public void Dispose() + { + if (Directory.Exists(_pkiRoot)) + { + try { Directory.Delete(_pkiRoot, recursive: true); } + catch { /* best-effort cleanup */ } + } + } +}