From e3f21cb86c5bbcedbc64cb3fd01f76b77db23199 Mon Sep 17 00:00:00 2001 From: Joseph Doherty Date: Tue, 24 Nov 2026 08:01:57 -0500 Subject: [PATCH] feat(grpc-data): H4 remote-history diagnostics and metrics MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Consumer and origin history evidence for data connections (plan §6): - DataConnectionHistoryDiagnostics: otopcua.dataconn.history.reads{variant,status_class,side} and otopcua.dataconn.history.continuations.active{side} on the exported OtOpcUa meter (the H2 origin counter sat on a private meter the host never exported); the plan's unknown-bits counter is the existing X0 otopcua.dataconnection.unknown_operations_dropped, reused - per-connection projected answers by status class and open consumer continuations (settled on resume claim or release); origin sessions, open continuations and answers by status class - negotiated features and advertised history variants/aggregates per connection - AdminUI data-connections page renders them plus the dropped unknown-operation bits (#919) - H4 unit-phase manifest key --- scripts/validation/grpc-data/unit-phases.json | 33 ++++ .../DataConnectionDiagnosticsSnapshot.cs | 22 ++- .../Interfaces/NodeDiagnosticsSnapshot.cs | 7 +- .../Clusters/ClusterDataConnections.razor | 30 +++- .../DataConnectionDiagnostics.cs | 37 +++++ .../DataConnectionRegistration.cs | 9 +- .../IProjectedHistoryAccess.cs | 10 +- .../DataConnectionDeploymentRuntime.cs | 17 +- .../DataConnectionHistoryDiagnostics.cs | 151 ++++++++++++++++++ .../GrpcDataConnection.Diagnostics.cs | 13 +- .../LocalDataRuntimeComposition.cs | 5 +- .../LocalDataServices.History.cs | 31 ++-- .../DataConnections/ProjectedHistoryAccess.cs | 51 +++++- .../Drivers/DriverHostActor.cs | 3 +- .../GrpcDataHistoryDiagnosticsDisplayTests.cs | 58 +++++++ .../GrpcDataDeploymentActivationTests.cs | 24 +++ .../GrpcDataHistoryDiagnosticsWireTests.cs | 85 ++++++++++ .../GrpcDataHistoryMetricsTests.cs | 127 +++++++++++++++ .../GrpcDataLocalConnectionTests.cs | 4 +- 19 files changed, 687 insertions(+), 30 deletions(-) create mode 100644 src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/DataConnectionHistoryDiagnostics.cs create mode 100644 tests/Server/ZB.MOM.WW.OtOpcUa.AdminUI.Tests/DataConnections/GrpcDataHistoryDiagnosticsDisplayTests.cs create mode 100644 tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataHistoryDiagnosticsWireTests.cs create mode 100644 tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataHistoryMetricsTests.cs diff --git a/scripts/validation/grpc-data/unit-phases.json b/scripts/validation/grpc-data/unit-phases.json index 9dc13d469..45f5d7b7b 100644 --- a/scripts/validation/grpc-data/unit-phases.json +++ b/scripts/validation/grpc-data/unit-phases.json @@ -919,5 +919,38 @@ "GrpcDataProjectedAccessTests" ] } + ], + "H4": [ + { + "project": "tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/ZB.MOM.WW.OtOpcUa.Runtime.Tests.csproj", + "filter": "(Feature=GrpcData&Phase=H4)|FullyQualifiedName~.GrpcDataProjectedHistoryCursorTests.|FullyQualifiedName~.GrpcDataOriginHistorySessionTests.", + "new_classes": [ + "GrpcDataHistoryMetricsTests" + ], + "existing_classes": [ + "GrpcDataConfiguredDiscoveryWireTests", + "GrpcDataDeploymentActivationTests", + "GrpcDataProjectedHistoryCursorTests", + "GrpcDataOriginHistorySessionTests" + ] + }, + { + "project": "tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests/ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests.csproj", + "filter": "FullyQualifiedName~.ProjectedHistoryReadTests.", + "new_classes": [], + "existing_classes": [ + "ProjectedHistoryReadTests" + ] + }, + { + "project": "tests/Server/ZB.MOM.WW.OtOpcUa.AdminUI.Tests/ZB.MOM.WW.OtOpcUa.AdminUI.Tests.csproj", + "filter": "(Feature=GrpcData&Phase=H4)|FullyQualifiedName~.GrpcDataDiagnosticsTests.", + "new_classes": [ + "GrpcDataHistoryDiagnosticsDisplayTests" + ], + "existing_classes": [ + "GrpcDataDiagnosticsTests" + ] + } ] } diff --git a/src/Core/ZB.MOM.WW.OtOpcUa.Commons/Interfaces/DataConnectionDiagnosticsSnapshot.cs b/src/Core/ZB.MOM.WW.OtOpcUa.Commons/Interfaces/DataConnectionDiagnosticsSnapshot.cs index 819a0d770..7dcc5f6c5 100644 --- a/src/Core/ZB.MOM.WW.OtOpcUa.Commons/Interfaces/DataConnectionDiagnosticsSnapshot.cs +++ b/src/Core/ZB.MOM.WW.OtOpcUa.Commons/Interfaces/DataConnectionDiagnosticsSnapshot.cs @@ -38,4 +38,24 @@ public sealed record DataConnectionDiagnosticsSnapshot( // X0 tolerant reader: operation bits this connection row was authored with that this node does not implement and // dropped (None = nothing dropped; null = from an older sender), and how many of its mappings had bits dropped. DataOperations? DroppedUnknownOperations = null, - int? MappingsWithDroppedOperations = null); + int? MappingsWithDroppedOperations = null, + // H4 consumer-side history evidence: the features the last capability handshake negotiated (None = v1 behaviour), the + // history variants and aggregate count the origin advertised to this caller, projected HistoryRead results by status + // class (per node, as answered to local OPC UA clients) and the remote continuations held in local sessions. + DataFeatures? NegotiatedFeatures = null, + IReadOnlyList? HistoryVariants = null, + int? HistoryAggregateCount = null, + long? HistoryReadsGood = null, + long? HistoryReadsUncertain = null, + long? HistoryReadsBad = null, + int? OpenRemoteContinuations = null); + +/// H4 origin-side remote-history evidence for one node (what it serves to peers over data connections). +/// The node has a historian backend and can serve remote history. +/// Live peer history sessions. +/// Origin continuations (page cursors and chunk remainders) held for peers. +/// Remote history items answered Good since process start. +/// Remote history items answered Uncertain since process start. +/// Remote history items answered Bad (including refusals) since process start. +public sealed record OriginHistoryDiagnostics(bool Available, int Sessions, int OpenContinuations, long ReadsGood, + long ReadsUncertain, long ReadsBad); diff --git a/src/Core/ZB.MOM.WW.OtOpcUa.Commons/Interfaces/NodeDiagnosticsSnapshot.cs b/src/Core/ZB.MOM.WW.OtOpcUa.Commons/Interfaces/NodeDiagnosticsSnapshot.cs index 019d3404f..1517e0ea1 100644 --- a/src/Core/ZB.MOM.WW.OtOpcUa.Commons/Interfaces/NodeDiagnosticsSnapshot.cs +++ b/src/Core/ZB.MOM.WW.OtOpcUa.Commons/Interfaces/NodeDiagnosticsSnapshot.cs @@ -47,6 +47,10 @@ public sealed record DriverInstanceDiagnostics( /// X0 tolerant reader: origin exports on this node whose operation bits this build does not implement, with the /// bits dropped (no grant). Empty when none; null from a sender built before X0 or when no catalog is staged. /// +/// +/// H4: remote history this node serves to data-connection peers. Null from a sender built before H4 or when the node +/// runs no data-connection services. +/// public sealed record NodeDiagnosticsSnapshot( NodeId NodeId, RevisionHash? CurrentRevision, @@ -54,4 +58,5 @@ public sealed record NodeDiagnosticsSnapshot( DateTime AsOfUtc, bool RunningFromCache = false, IReadOnlyList? DataConnections = null, - IReadOnlyDictionary? DroppedExportOperations = null); + IReadOnlyDictionary? DroppedExportOperations = null, + OriginHistoryDiagnostics? OriginHistory = null); diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/Components/Pages/Clusters/ClusterDataConnections.razor b/src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/Components/Pages/Clusters/ClusterDataConnections.razor index f6edf530f..e9cdb665f 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/Components/Pages/Clusters/ClusterDataConnections.razor +++ b/src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/Components/Pages/Clusters/ClusterDataConnections.razor @@ -35,7 +35,9 @@ else @if (live.Row.Serving is { } serving) { · serving @serving.NodeId · role @serving.Role · incarnation @serving.Incarnation }
Streams @live.Row.ActiveStreams · calls @live.Row.ActiveCalls · retained import views @Measure(live.Row.SourceCount) · registrations @Measure(live.Row.RegistrationCount) · resets @Measure(live.Row.ResetCount) · coalesced notices @Measure(live.Row.CoalescedCount) · overflows @Measure(live.Row.OverflowCount)
Writes succeeded @Measure(live.Row.WriteSucceededCount) · rejected @Measure(live.Row.WriteRejectedCount) · failed @Measure(live.Row.WriteFailedCount) · unconfirmed @Measure(live.Row.WriteUnconfirmedCount) · unknown @Measure(live.Row.WriteUnknownCount)
-
Last observed sample bound @Time(live.Row.LastSampleAtUtc) (age upper bound @DataConnectionDiagnostics.SampleAge(live.Row)) · metadata lease expires @Time(live.Row.MetadataLeaseExpiresAtUtc) · last handshake @Time(live.Row.LastVerifiedAtUtc) · observed @live.Row.AsOfUtc.ToString("u") · artifact @live.Row.ArtifactRevision · protocol @(live.Row.ProtocolMajor is { } major && live.Row.ProtocolMinor is { } minor ? $"{major}.{minor}" : "unavailable")
+
Last observed sample bound @Time(live.Row.LastSampleAtUtc) (age upper bound @DataConnectionDiagnostics.SampleAge(live.Row)) · metadata lease expires @Time(live.Row.MetadataLeaseExpiresAtUtc) · last handshake @Time(live.Row.LastVerifiedAtUtc) · observed @live.Row.AsOfUtc.ToString("u") · artifact @live.Row.ArtifactRevision · protocol @(live.Row.ProtocolMajor is { } major && live.Row.ProtocolMinor is { } minor ? $"{major}.{minor}" : "unavailable")
+
Negotiated features @DataConnectionDiagnostics.Features(live.Row.NegotiatedFeatures) · origin history @DataConnectionDiagnostics.HistoryServed(live.Row) · projected history reads @DataConnectionDiagnostics.HistoryCounts(live.Row.HistoryReadsGood, live.Row.HistoryReadsUncertain, live.Row.HistoryReadsBad) · open remote continuations (local sessions) @Measure(live.Row.OpenRemoteContinuations)
+
Dropped unknown operation bits: connection @DataConnectionDiagnostics.DroppedBits(live.Row.DroppedUnknownOperations) · mappings with dropped bits @Measure(live.Row.MappingsWithDroppedOperations)@if (DataConnectionDiagnostics.HasDrops(live.Row.DroppedUnknownOperations, live.Row.MappingsWithDroppedOperations)) { — this node's build is older than a feature authored here; the dropped bits grant nothing until the node is upgraded. }
} @foreach (var applied in _applied.Where(x => Same(x.ConnectionId, row.Id))) { @applied.NodeId: last applied revision @applied.Revision (@(applied.Enabled ? "enabled" : "disabled")) } @if (row.Draft is { } editable) { } @@ -43,6 +45,30 @@ else +
+

Origin evidence by node

+ @if (!_nodeSnapshots.Any()) {

No node has reported.

} + @foreach (var (nodeId, node) in _nodeSnapshots) + { +
@nodeId + @if (node.OriginHistory is { } origin) + { + · remote history @(origin.Available ? "served" : "no historian backend") · peer history sessions @origin.Sessions · open origin continuations @origin.OpenContinuations · history items answered @DataConnectionDiagnostics.HistoryCounts(origin.ReadsGood, origin.ReadsUncertain, origin.ReadsBad) + } + else { · remote history evidence unavailable } + @if (node.DroppedExportOperations is { } dropped) + { + @if (dropped.Count == 0) { · dropped unknown export bits: none } + else + { +
Exports with dropped unknown operation bits: @string.Join("; ", dropped.OrderBy(x => x.Key, StringComparer.OrdinalIgnoreCase).Select(x => $"{x.Key}: {DataConnectionDiagnostics.DroppedBits(x.Value)}")) — this node's build is older than a feature authored here; the dropped bits grant nothing until the node is upgraded.
+ } + } + else { · dropped unknown export bits unavailable } +
+ } +
+

Exports

@if (!Exports.Any()) {

No export grants have been authored.

} @@ -125,6 +151,7 @@ else private object? _deleteCandidate; private IReadOnlyList _applied = []; private List<(string NodeId, DataConnectionDiagnosticsSnapshot Row)> _live = []; + private List<(string NodeId, NodeDiagnosticsSnapshot Snapshot)> _nodeSnapshots = []; private IReadOnlyList ConnectionRows => DataConnectionDiagnostics.Rows(Connections, _applied.Select(x => x.ConnectionId), _live.Select(x => x.Row.ConnectionId)); private IEnumerable Connections => _snapshot!.DataConnections.Where(x => Same(x.ClusterId, ClusterId)); private IEnumerable Exports => _snapshot!.DataExports.Where(x => Same(x.ClusterId, ClusterId)); @@ -139,6 +166,7 @@ else try { return (node.NodeId, Snapshot: (NodeDiagnosticsSnapshot?)await Diagnostics.GetDiagnosticsAsync(NodeId.Parse($"{node.Host}:{node.AkkaPort}"), CancellationToken.None)); } catch (Exception) { return (node.NodeId, Snapshot: (NodeDiagnosticsSnapshot?)null); } })); + _nodeSnapshots = observations.Where(x => x.Snapshot is not null).Select(x => (x.NodeId, x.Snapshot!)).ToList(); _live = observations.Where(x => x.Snapshot?.DataConnections is not null) .SelectMany(x => x.Snapshot!.DataConnections!.Select(row => (x.NodeId, row))).ToList(); } diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/DataConnections/DataConnectionDiagnostics.cs b/src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/DataConnections/DataConnectionDiagnostics.cs index 63d07dcb5..9badce08a 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/DataConnections/DataConnectionDiagnostics.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/DataConnections/DataConnectionDiagnostics.cs @@ -1,4 +1,6 @@ +using ZB.MOM.WW.OtOpcUa.Commons.Interfaces; using ZB.MOM.WW.OtOpcUa.Configuration.Entities; +using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections; namespace ZB.MOM.WW.OtOpcUa.AdminUI.DataConnections; @@ -23,6 +25,41 @@ public static class DataConnectionDiagnostics "disabled" => "Disabled", "connecting" => "Connecting", "ready" => "Ready", "degraded" => "Degraded", "auth-failed" => "Authentication failed", "backoff" => "Backoff", _ => "Unavailable" }; + /// H4: the features the last handshake negotiated; "none (v1)" when the peer negotiated nothing optional. + public static string Features(DataFeatures? features) => features switch + { + null => "unavailable", + DataFeatures.None => "none (v1 behaviour)", + { } f => string.Join(", ", Enum.GetValues().Where(x => x != DataFeatures.None && f.HasFlag(x)).Select(x => x.ToString()) + .DefaultIfEmpty($"0x{(int)f:X}")), + }; + + /// H4: the history variants and aggregate count the origin advertised to this caller. + public static string HistoryServed(DataConnectionDiagnosticsSnapshot row) => + row.HistoryVariants is not { } variants ? "not advertised" + : variants.Count == 0 ? "advertised, no variant granted" + : string.Join(", ", variants) + (row.HistoryAggregateCount is { } n ? $" ({n} aggregates)" : ""); + + /// H4: history results by status class, "unavailable" from a node built before H4. + public static string HistoryCounts(long? good, long? uncertain, long? bad) => + good is null && uncertain is null && bad is null ? "unavailable" + : $"good {good ?? 0} · uncertain {uncertain ?? 0} · bad {bad ?? 0}"; + + /// + /// #919: operation bits a node dropped because its build does not implement them. Named when this AdminUI knows the + /// bit, hex otherwise; "unavailable" from a node built before X0. + /// + public static string DroppedBits(DataOperations? bits) => bits switch + { + null => "unavailable", + DataOperations.None => "none", + { } b => string.Join(", ", Enumerable.Range(0, 31).Select(i => (DataOperations)(1 << i)).Where(x => b.HasFlag(x)) + .Select(x => Enum.IsDefined(x) ? DataOperationAuthoring.Label(x) : $"0x{(int)x:X}")), + }; + + /// #919: true when the drop deserves the "node build is older than the authored feature" hint. + public static bool HasDrops(DataOperations? bits, int? mappings = null) => bits is { } b && b != DataOperations.None || mappings is > 0; + public static string Endpoint(string? value) => Uri.TryCreate(value, UriKind.Absolute, out var uri) && uri.Scheme == Uri.UriSchemeHttps ? (uri.HostNameType == UriHostNameType.IPv6 ? $"https://[{uri.Host}]{(uri.IsDefaultPort ? "" : $":{uri.Port}")}" : $"https://{uri.IdnHost}{(uri.IsDefaultPort ? "" : $":{uri.Port}")}") : "Unavailable"; } diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Host/Configuration/DataConnectionRegistration.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Host/Configuration/DataConnectionRegistration.cs index ff33ad910..2f574c943 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Host/Configuration/DataConnectionRegistration.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Host/Configuration/DataConnectionRegistration.cs @@ -118,12 +118,15 @@ public static class DataConnectionRegistration (!settings.IsWarm || state.WarmRole == WarmRole.Active), state.Generation); }, renewalSink: sp.GetRequiredService())); services.AddSingleton(sp => sp.GetRequiredService()); + // H4: one dependency-free history diagnostics instance shared by the origin services, the consumer gateway and the + // diagnostics readers (it also backs the otopcua.dataconn.history.* metrics). + services.AddSingleton(); // H3: OPC UA HistoryRead on projected variables, forwarded over the mapping's deployed connection. services.AddSingleton(sp => new ProjectedHistoryAccess(sp.GetRequiredService(), sp.GetRequiredService(), mappingId => sp.GetRequiredService().TryGetHistoryAssemblyBudget(mappingId, out var bytes) ? bytes : null, - sp.GetRequiredService())); + sp.GetRequiredService(), sp.GetRequiredService())); services.AddSingleton(sp => sp.GetRequiredService()); services.AddSingleton(sp => new ConfiguredProjectionDiscovery( sp.GetRequiredService(), sp.GetRequiredService(), @@ -161,7 +164,8 @@ public static class DataConnectionRegistration options.MaxStreams, Math.Min(options.MaxStreams, options.MaxStreamsPerPrincipal), options.MaxTransportBytes, 128, 64, options.MaxPendingBytes, options.MaxSessionLifetime, TimeSpan.FromSeconds(5)), // H2: remote history over the node manager's history port, resolved once the SDK server is up. - new DeferredOriginHistoryPort(sp.GetRequiredService()), LoggerFor(sp)); + new DeferredOriginHistoryPort(sp.GetRequiredService()), LoggerFor(sp), + sp.GetRequiredService()); }); services.AddSingleton(sp => new DeferredFactory(() => sp.GetRequiredService().Services)); services.AddSingleton(); @@ -227,6 +231,7 @@ public static class DataConnectionRegistration }) { Logger = LoggerFor(sp), + HistoryDiagnostics = sp.GetRequiredService(), }; return runtime; }); diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/IProjectedHistoryAccess.cs b/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/IProjectedHistoryAccess.cs index dc050e9ef..2ed760691 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/IProjectedHistoryAccess.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/IProjectedHistoryAccess.cs @@ -53,7 +53,15 @@ public abstract class ProjectedHistoryContinuation /// Marks the cursor as handed back for a resume: the resume read owns the origin token from here on. /// false when it was already released or resumed. - public bool TryClaimForResume() => Volatile.Read(ref _released) == 0 && Interlocked.Exchange(ref _claimed, 1) == 0; + public bool TryClaimForResume() + { + if (Volatile.Read(ref _released) != 0 || Interlocked.Exchange(ref _claimed, 1) != 0) return false; + OnClaimed(); + return true; + } + + /// Called once when the cursor is claimed for a resume (its origin token is about to be sent back). + protected virtual void OnClaimed() { } private void ReleaseOnce() { diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/DataConnectionDeploymentRuntime.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/DataConnectionDeploymentRuntime.cs index 96cce8cf0..307f0e3b0 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/DataConnectionDeploymentRuntime.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/DataConnectionDeploymentRuntime.cs @@ -46,6 +46,8 @@ public sealed class DataConnectionDeploymentRuntime : IAsyncDisposable private readonly object _sync = new(); /// Diagnostics sink for the X0 dropped-operation warning; optional (an init property keeps the constructor shape). public ILogger Logger { private get; init; } = NullLogger.Instance; + /// H4: consumer/origin remote-history evidence merged into the diagnostics; optional (init keeps the constructor shape). + public DataConnectionHistoryDiagnostics? HistoryDiagnostics { get; init; } private IReadOnlyDictionary _droppedOperations = new Dictionary(); private long _unknownOperationRows; private readonly string _node, _owner; @@ -118,7 +120,18 @@ public sealed class DataConnectionDeploymentRuntime : IAsyncDisposable DataOperations? Dropped(string id) => dropped.TryGetValue(id, out var bits) ? bits : DataOperations.None; int? MappingDrops(string id) => mappingsWithDroppedOperations is null ? null : mappingsWithDroppedOperations.TryGetValue(id, out var count) ? count : 0; - return desired.Specs.Values.Select(spec => + var history = HistoryDiagnostics; + ZB.MOM.WW.OtOpcUa.Commons.Interfaces.DataConnectionDiagnosticsSnapshot WithHistory( + ZB.MOM.WW.OtOpcUa.Commons.Interfaces.DataConnectionDiagnosticsSnapshot row) + { + if (history is null) return row; + var counts = history.CaptureConsumer(row.ConnectionId); + return row with { HistoryReadsGood = counts.Good, HistoryReadsUncertain = counts.Uncertain, HistoryReadsBad = counts.Bad, + OpenRemoteContinuations = counts.OpenContinuations }; + } + return desired.Specs.Values.Select(spec => WithHistory(Capture(spec))).ToArray(); + + ZB.MOM.WW.OtOpcUa.Commons.Interfaces.DataConnectionDiagnosticsSnapshot Capture(Spec spec) { if (!_attemptPending && _scopeReady && _entries.TryGetValue(spec.Id, out var entry) && entry.Ready) return entry.Connection.CaptureDiagnostics(spec.Revision, desired.ScopeVersion, desired.ArtifactRevision) with @@ -128,7 +141,7 @@ public sealed class DataConnectionDeploymentRuntime : IAsyncDisposable _attemptPending ? "connecting" : _retryNotBefore > _clock.GetTimestamp() ? "backoff" : "connecting", null, null, 0, 0, desired.ScopeVersion, desired.ArtifactRevision, _clock.GetUtcNow().UtcDateTime) { DroppedUnknownOperations = Dropped(spec.Id), MappingsWithDroppedOperations = MappingDrops(spec.Id) }; - }).ToArray(); + } } } diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/DataConnectionHistoryDiagnostics.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/DataConnectionHistoryDiagnostics.cs new file mode 100644 index 000000000..4fb7b961f --- /dev/null +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/DataConnectionHistoryDiagnostics.cs @@ -0,0 +1,151 @@ +using System.Collections.Concurrent; +using System.Diagnostics.Metrics; +using System.Runtime.CompilerServices; +using ZB.MOM.WW.OtOpcUa.Commons.Interfaces; +using ZB.MOM.WW.OtOpcUa.Commons.Observability; +using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections; + +namespace ZB.MOM.WW.OtOpcUa.Runtime.DataConnections; + +/// Consumer-side remote-history evidence for one deployed connection (H4 diagnostics). +public sealed record ConsumerHistoryCounts(long Good, long Uncertain, long Bad, int OpenContinuations); + +/// +/// H4 remote-history diagnostics and metrics for one process (plan §6 "Metrics"). It has no dependencies, so the origin +/// services (), the consumer gateway () and the +/// diagnostics readers (, the driver host) share one instance without a cycle. +/// +/// +/// Metrics, on , never carry an id in a label: +/// +/// — one per history item answered, tagged variant (raw | processed | attime), +/// status_class (good | uncertain | bad) and side (origin = served to a peer; consumer = a projected node's +/// answer to a local OPC UA client). A node can be both, so side keeps the two from being summed. +/// — open remote continuations, tagged side: origin cursors held for +/// peers, and consumer cursors held in local OPC UA sessions (created, neither resumed nor released). +/// +/// +/// The plan's …operations.unknown_bits_dropped is the X0 counter +/// (otopcua.dataconnection.unknown_operations_dropped, tag kind); it is reused, not duplicated. +/// +/// +public sealed class DataConnectionHistoryDiagnostics +{ + public const string ReadsCounterName = "otopcua.dataconn.history.reads"; + public const string ContinuationsGaugeName = "otopcua.dataconn.history.continuations.active"; + public const string OriginSide = "origin"; + public const string ConsumerSide = "consumer"; + + private static readonly Counter Reads = OtOpcUaTelemetry.Meter.CreateCounter(ReadsCounterName, unit: "{item}", + description: "Remote history items answered over data connections (tags: variant = raw|processed|attime; " + + "status_class = good|uncertain|bad; side = origin|consumer)."); + + // Weak: a process normally holds one instance, tests many; none needs disposing to leave the gauge. + private static readonly ConditionalWeakTable Live = new(); + + static DataConnectionHistoryDiagnostics() + { + OtOpcUaTelemetry.Meter.CreateObservableGauge(ContinuationsGaugeName, static () => Observe(), unit: "{continuation}", + description: "Open remote-history continuations (tag side = origin: cursors held for peers; consumer: cursors held " + + "in local OPC UA sessions)."); + } + + private static IEnumerable> Observe() + { + int origin = 0, consumer = 0; + foreach (var (instance, _) in Live) + { + origin += instance.CaptureOrigin()?.OpenContinuations ?? 0; + consumer += instance.OpenConsumerContinuations; + } + + return + [ + new Measurement(origin, new KeyValuePair("side", OriginSide)), + new Measurement(consumer, new KeyValuePair("side", ConsumerSide)), + ]; + } + + private sealed class Counts + { + public long Good, Uncertain, Bad; + public int Open; + } + + private readonly ConcurrentDictionary _consumer = new(StringComparer.OrdinalIgnoreCase); + private readonly Counts _origin = new(); + private Func<(bool Available, int Sessions, int Open)>? _originState; + + public DataConnectionHistoryDiagnostics() => Live.AddOrUpdate(this, new object()); + + /// The variant label of a request's details. + internal static string Variant(DataHistoryDetails details) => details switch + { + DataHistoryRawDetails => "raw", DataHistoryProcessedDetails => "processed", DataHistoryAtTimeDetails => "attime", _ => "unknown", + }; + + /// The status_class label of an OPC UA status code (its top two bits). + internal static string StatusClass(uint status) => (status >> 30) switch { 0 => "good", 1 => "uncertain", _ => "bad" }; + + private static void Add(Counts counts, uint status) + { + switch (status >> 30) + { + case 0: Interlocked.Increment(ref counts.Good); break; + case 1: Interlocked.Increment(ref counts.Uncertain); break; + default: Interlocked.Increment(ref counts.Bad); break; + } + } + + /// Counts one answer on the metric only (an origin or gateway built without a diagnostics instance). + internal static void Count(string side, string variant, uint status) => + Reads.Add(1, new KeyValuePair("variant", variant), + new KeyValuePair("status_class", StatusClass(status)), new KeyValuePair("side", side)); + + /// One origin answer to a peer's history item. + internal void RecordOriginRead(string variant, uint status) + { + Add(_origin, status); + Count(OriginSide, variant, status); + } + + /// One projected node's answer to a local OPC UA client; null when unresolved. + internal void RecordConsumerRead(string? connectionId, string variant, uint status) + { + if (connectionId is not null) Add(_consumer.GetOrAdd(connectionId, static _ => new Counts()), status); + Count(ConsumerSide, variant, status); + } + + /// A consumer continuation was handed to a local session. + internal void ConsumerContinuationOpened(string connectionId) => + Interlocked.Increment(ref _consumer.GetOrAdd(connectionId, static _ => new Counts()).Open); + + /// A consumer continuation was resumed (its token sent back) or released. + internal void ConsumerContinuationSettled(string connectionId) + { + if (_consumer.TryGetValue(connectionId, out var counts)) Interlocked.Decrement(ref counts.Open); + } + + /// Connects the origin services whose live state (backend, sessions, open cursors) this reports. + internal void AttachOrigin(Func<(bool Available, int Sessions, int Open)> state) => _originState = state; + + /// The consumer evidence for one connection; zeros when it has seen no history traffic. + public ConsumerHistoryCounts CaptureConsumer(string connectionId) => + _consumer.TryGetValue(connectionId, out var c) + ? new(Interlocked.Read(ref c.Good), Interlocked.Read(ref c.Uncertain), Interlocked.Read(ref c.Bad), Math.Max(0, Volatile.Read(ref c.Open))) + : new(0, 0, 0, 0); + + /// Consumer continuations open across every connection. + public int OpenConsumerContinuations => _consumer.Values.Sum(x => Math.Max(0, Volatile.Read(ref x.Open))); + + /// The origin evidence; null until origin services are attached (no data-connection origin on this node yet). + public OriginHistoryDiagnostics? CaptureOrigin() + { + if (_originState is not { } state) return null; + (bool Available, int Sessions, int Open) now; + try { now = state(); } + catch (Exception) { return null; } + return new(now.Available, now.Sessions, now.Open, Interlocked.Read(ref _origin.Good), Interlocked.Read(ref _origin.Uncertain), + Interlocked.Read(ref _origin.Bad)); + } +} diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/GrpcDataConnection.Diagnostics.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/GrpcDataConnection.Diagnostics.cs index 794beae6c..93e533561 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/GrpcDataConnection.Diagnostics.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/GrpcDataConnection.Diagnostics.cs @@ -9,6 +9,9 @@ public sealed partial class GrpcDataConnection private string? _diagnosticEndpoint; private ServingIdentity? _diagnosticServing; private int? _diagnosticMajor, _diagnosticMinor; + private DataFeatures? _negotiatedFeatures; + private IReadOnlyList? _historyVariants; + private int? _historyAggregateCount; private string _diagnosticState = "connecting"; private DateTime? _lastSampleAtUtc, _metadataLeaseExpiresAtUtc, _lastVerifiedAtUtc; private TimeSpan? _sampleAgeUpper; @@ -32,7 +35,8 @@ public sealed partial class GrpcDataConnection SampleAgeUpperBound: ObservedUpperAge(), CoalescedCount: Interlocked.Read(ref _coalescedCount), CompactFrameCount: Interlocked.Read(ref _compactFrameCount), FallbackFrameCount: Interlocked.Read(ref _fallbackFrameCount), - SerializedValueFrameBytes: Interlocked.Read(ref _serializedValueFrameBytes), AccountingInstanceId: _accountingInstanceId); + SerializedValueFrameBytes: Interlocked.Read(ref _serializedValueFrameBytes), AccountingInstanceId: _accountingInstanceId, + NegotiatedFeatures: _negotiatedFeatures, HistoryVariants: _historyVariants, HistoryAggregateCount: _historyAggregateCount); } private TimeSpan? ObservedUpperAge() @@ -50,6 +54,13 @@ public sealed partial class GrpcDataConnection _diagnosticEndpoint = new UriBuilder(endpoint.Scheme, endpoint.Host, endpoint.Port).Uri.GetLeftPart(UriPartial.Authority); _diagnosticServing = capabilities.Serving; _lastVerifiedAtUtc = Clock.GetUtcNow().UtcDateTime; _diagnosticMajor = capabilities.ProtocolMajor; _diagnosticMinor = capabilities.ProtocolMinor; + // H4: what the data calls of this handshake negotiate, and the history the origin advertised to this caller. + _negotiatedFeatures = RequestedFeatures(capabilities); + _historyVariants = capabilities.History is { } history + ? new[] { history.Raw ? "raw" : null, history.Processed ? "processed" : null, history.AtTime ? "attime" : null } + .OfType().ToArray() + : null; + _historyAggregateCount = capabilities.History?.Aggregates.Count; _diagnosticState = capabilities.Readiness == DataReadiness.Ready ? "ready" : "degraded"; } } diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/LocalDataRuntimeComposition.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/LocalDataRuntimeComposition.cs index e3b37b9b1..3236f8848 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/LocalDataRuntimeComposition.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/LocalDataRuntimeComposition.cs @@ -18,7 +18,8 @@ public sealed class LocalDataRuntimeComposition : IDisposable public LocalDataRuntimeComposition(LocalCatalogCoordinator catalog, PartitionedSampleHub hub, DataOperationPolicy policy, DataCapabilitiesProvider capabilities, TimeProvider clock, DataWriteRuntime writes, IActorRef host, SubscriptionAcquisitionCapacity acquisitionCapacity, LocalDataRuntimeLimits limits, - ZB.MOM.WW.OtOpcUa.OpcUaServer.IOriginHistoryPort? history = null, Microsoft.Extensions.Logging.ILogger? logger = null) + ZB.MOM.WW.OtOpcUa.OpcUaServer.IOriginHistoryPort? history = null, Microsoft.Extensions.Logging.ILogger? logger = null, + DataConnectionHistoryDiagnostics? historyDiagnostics = null) { ArgumentNullException.ThrowIfNull(catalog); ArgumentNullException.ThrowIfNull(hub); ArgumentNullException.ThrowIfNull(policy); ArgumentNullException.ThrowIfNull(capabilities); @@ -38,7 +39,7 @@ public sealed class LocalDataRuntimeComposition : IDisposable writes: context => writes.ForCaller(context, () => host), targetSubscriptions: (context, target) => new LocalSubscriptionService(services!, context, target, _demand, sessionLimits, capacity), subscriptionFreshnessChallenges: true, history: history) - { Logger = logger ?? Microsoft.Extensions.Logging.Abstractions.NullLogger.Instance }; + { Logger = logger ?? Microsoft.Extensions.Logging.Abstractions.NullLogger.Instance, HistoryDiagnostics = historyDiagnostics }; Services = services; } public LocalDataServices Services { get; } diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/LocalDataServices.History.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/LocalDataServices.History.cs index b4c47d698..0400b110b 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/LocalDataServices.History.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/LocalDataServices.History.cs @@ -1,4 +1,3 @@ -using System.Diagnostics.Metrics; using System.Globalization; using System.Text; using ZB.MOM.WW.OtOpcUa.Commons.DataConnections; @@ -24,8 +23,21 @@ public sealed partial class LocalDataServices internal const uint BadContinuationPointInvalid = 0x804A0000u; private const int ResponseMarginBytes = 64 * 1024; - private static readonly Meter HistoryMeter = new("ZB.MOM.WW.OtOpcUa.DataConnections.History"); - private static readonly Counter HistoryReads = HistoryMeter.CreateCounter("otopcua.dataconn.history.reads"); + private DataConnectionHistoryDiagnostics? _historyDiagnostics; + + /// + /// H4: where origin history answers are counted and this origin's live history state is reported (diagnostics and the + /// otopcua.dataconn.history.* metrics). Before H4 the counter sat on a private meter the host never exported. + /// + public DataConnectionHistoryDiagnostics? HistoryDiagnostics + { + get => _historyDiagnostics; + init + { + _historyDiagnostics = value; + value?.AttachOrigin(() => (HistoryServing is not null, HistorySessionCount, HistoryOpenContinuations)); + } + } private readonly IOriginHistoryPort? _history; private readonly OriginHistorySessions _historySessions; @@ -442,15 +454,14 @@ public sealed partial class LocalDataServices private static long SampleBytes(DataHistorySample sample, DataMetadata? catalog) => DataHistoryProtoMapper.EncodeSample(sample, catalog).CalculateSize() + 6L; - private static DataHistoryReadResult[] Record(DataHistoryReadRequest request, DataHistoryReadResult[] results) + private DataHistoryReadResult[] Record(DataHistoryReadRequest request, DataHistoryReadResult[] results) { - var variant = request.Details switch - { - DataHistoryRawDetails => "raw", DataHistoryProcessedDetails => "processed", DataHistoryAtTimeDetails => "attime", _ => "unknown", - }; + var variant = DataConnectionHistoryDiagnostics.Variant(request.Details); foreach (var result in results) - HistoryReads.Add(1, new KeyValuePair("variant", variant), - new KeyValuePair("status_class", (result.StatusCode >> 30) switch { 0 => "good", 1 => "uncertain", _ => "bad" })); + { + if (_historyDiagnostics is { } diagnostics) diagnostics.RecordOriginRead(variant, result.StatusCode); + else DataConnectionHistoryDiagnostics.Count(DataConnectionHistoryDiagnostics.OriginSide, variant, result.StatusCode); + } return results; } } diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ProjectedHistoryAccess.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ProjectedHistoryAccess.cs index e2ca73cb9..2f90f37c5 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ProjectedHistoryAccess.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ProjectedHistoryAccess.cs @@ -63,15 +63,20 @@ public sealed class ProjectedHistoryAccess : IProjectedHistoryAccess, IDisposabl /// The deployed connection registry. /// A mapping's MaxHistoryAssemblyBytesPerRequest; null = not deployed. /// The clock. + /// H4 per-connection counts and metrics; a private instance when not shared. public ProjectedHistoryAccess(ProjectedDataAccess access, IGrpcDataAdapterConnectionSource connections, - Func assemblyBudget, TimeProvider clock) + Func assemblyBudget, TimeProvider clock, DataConnectionHistoryDiagnostics? diagnostics = null) { + Diagnostics = diagnostics ?? new DataConnectionHistoryDiagnostics(); _access = access ?? throw new ArgumentNullException(nameof(access)); _connections = connections ?? throw new ArgumentNullException(nameof(connections)); _assemblyBudget = assemblyBudget ?? throw new ArgumentNullException(nameof(assemblyBudget)); _clock = clock ?? throw new ArgumentNullException(nameof(clock)); } + /// H4: projected answers by status class and the consumer continuations held in local sessions, per connection. + public DataConnectionHistoryDiagnostics Diagnostics { get; } + /// How long a release waits to coalesce with others for the same connection (a session close disposes one by one). internal TimeSpan ReleaseCoalesce { get; init; } = TimeSpan.FromMilliseconds(25); @@ -195,7 +200,7 @@ public sealed class ProjectedHistoryAccess : IProjectedHistoryAccess, IDisposabl left -= assembled[i]; } - return outcomes.Select(o => o ?? Fail(BadNoCommunication)).ToArray(); + return Recorded(outcomes.Select(o => o ?? Fail(BadNoCommunication)).ToArray()); } catch (Exception ex) when (ex is not OutOfMemoryException) { @@ -211,13 +216,21 @@ public sealed class ProjectedHistoryAccess : IProjectedHistoryAccess, IDisposabl outcomes[i] = Fail(timedOut ? BadTimeout : ex is OperationCanceledException && resumed ? BadContinuationPointInvalid : BadNoCommunication); } - return outcomes.Select(o => o!).ToArray(); + return Recorded(outcomes.Select(o => o!).ToArray()); } finally { foreach (var demand in demands) demand?.Dispose(); } + // H4: one count per node as answered to the local client, attributed to its connection when it resolved to one. + ProjectedHistoryOutcome[] Recorded(ProjectedHistoryOutcome[] answered) + { + var variant = DataConnectionHistoryDiagnostics.Variant(details); + for (var i = 0; i < answered.Length; i++) Diagnostics.RecordConsumerRead(targets[i]?.ConnectionId, variant, answered[i].StatusCode); + return answered; + } + TimeSpan Remaining() => deadline > TimeSpan.Zero ? deadline - _clock.GetElapsedTime(started) : TimeSpan.FromHours(1); // unbounded locally: the connection's HistoryTimeout still caps each call @@ -527,11 +540,34 @@ public sealed class ProjectedHistoryAccess : IProjectedHistoryAccess, IDisposabl private sealed record GroupKey(string ConnectionId, DataHistoryDetails Details, string Resume); /// The remote cursor in the consumer's SDK session store ( Remote). - private sealed class RemoteCursor(ProjectedHistoryAccess owner, DataRealm realm, string localIdentifier, byte[] token, string connectionId, - object? routeIdentity, ProjectedHistoryTarget target, string callerKey, DataHistoryDetails details, uint? aggregateId) - : ProjectedHistoryContinuation(realm, localIdentifier) + private sealed class RemoteCursor : ProjectedHistoryContinuation { - private int _originReleased; + private readonly ProjectedHistoryAccess owner; + private readonly byte[] token; + private readonly string connectionId; + private readonly object? routeIdentity; + private readonly ProjectedHistoryTarget target; + private readonly string callerKey; + private readonly DataHistoryDetails details; + private readonly uint? aggregateId; + private int _originReleased, _settled; + + internal RemoteCursor(ProjectedHistoryAccess owner, DataRealm realm, string localIdentifier, byte[] token, string connectionId, + object? routeIdentity, ProjectedHistoryTarget target, string callerKey, DataHistoryDetails details, uint? aggregateId) + : base(realm, localIdentifier) + { + this.owner = owner; this.token = token; this.connectionId = connectionId; this.routeIdentity = routeIdentity; + this.target = target; this.callerKey = callerKey; this.details = details; this.aggregateId = aggregateId; + owner.Diagnostics.ConsumerContinuationOpened(connectionId); + } + + /// H4: open until resumed (the origin consumes the token) or released, whichever comes first. + private void Settle() + { + if (Interlocked.Exchange(ref _settled, 1) == 0) owner.Diagnostics.ConsumerContinuationSettled(connectionId); + } + + protected override void OnClaimed() => Settle(); internal ProjectedHistoryAccess Owner => owner; internal byte[] Token => token; internal object? RouteIdentity => routeIdentity; @@ -546,6 +582,7 @@ public sealed class ProjectedHistoryAccess : IProjectedHistoryAccess, IDisposabl /// Releases the origin token (once), whether the cursor was claimed for a resume or not. internal void ReleaseOrigin() { + Settle(); if (Interlocked.Exchange(ref _originReleased, 1) == 0) owner.EnqueueRelease(connectionId, token); } diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/Drivers/DriverHostActor.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/Drivers/DriverHostActor.cs index eeef8df2b..c301388c6 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/Drivers/DriverHostActor.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/Drivers/DriverHostActor.cs @@ -2983,7 +2983,8 @@ public sealed class DriverHostActor : ReceiveActor, IWithTimers, IWithUnboundedS RunningFromCache: _isRunningFromCache, DataConnections: _dataConnections?.CaptureDiagnostics(_projectedPublisher?.CaptureSourceCounts(), _catalogCoordinator?.ProjectedMappings?.CaptureDroppedByConnection()), - DroppedExportOperations: _catalogCoordinator?.Current?.DroppedUnknownOperations); + DroppedExportOperations: _catalogCoordinator?.Current?.DroppedUnknownOperations, + OriginHistory: _dataConnections?.HistoryDiagnostics?.CaptureOrigin()); Sender.Tell(snapshot); } diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.AdminUI.Tests/DataConnections/GrpcDataHistoryDiagnosticsDisplayTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.AdminUI.Tests/DataConnections/GrpcDataHistoryDiagnosticsDisplayTests.cs new file mode 100644 index 000000000..61d92a9f7 --- /dev/null +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.AdminUI.Tests/DataConnections/GrpcDataHistoryDiagnosticsDisplayTests.cs @@ -0,0 +1,58 @@ +using Shouldly; +using Xunit; +using ZB.MOM.WW.OtOpcUa.AdminUI.DataConnections; +using ZB.MOM.WW.OtOpcUa.Commons.Interfaces; +using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections; + +namespace ZB.MOM.WW.OtOpcUa.AdminUI.Tests.DataConnections; + +/// H4 diagnostics display (plan §6) and the X0 dropped-bit rendering (#919) on the data-connections page. +[Trait("Category", "Unit"), Trait("Feature", "GrpcData"), Trait("Phase", "H4")] +public sealed class GrpcDataHistoryDiagnosticsDisplayTests +{ + private static DataConnectionDiagnosticsSnapshot Row() => + new("link", 1, "ready", null, null, 0, 0, 1, "artifact", DateTime.UtcNow); + + [Fact] + public void Negotiated_features_distinguish_unavailable_v1_and_history() + { + DataConnectionDiagnostics.Features(null).ShouldBe("unavailable"); + DataConnectionDiagnostics.Features(DataFeatures.None).ShouldBe("none (v1 behaviour)"); + DataConnectionDiagnostics.Features(DataFeatures.History).ShouldBe("History"); + DataConnectionDiagnostics.Features(DataFeatures.History | DataFeatures.Conditions).ShouldBe("History, Conditions"); + } + + [Fact] + public void Origin_history_shows_the_advertised_variants_and_aggregate_count() + { + DataConnectionDiagnostics.HistoryServed(Row()).ShouldBe("not advertised"); + DataConnectionDiagnostics.HistoryServed(Row() with { HistoryVariants = [] }).ShouldBe("advertised, no variant granted"); + DataConnectionDiagnostics.HistoryServed(Row() with { HistoryVariants = ["raw", "processed", "attime"], HistoryAggregateCount = 12 }) + .ShouldBe("raw, processed, attime (12 aggregates)"); + } + + [Fact] + public void History_counts_by_status_class_are_unavailable_from_an_older_node_not_zero() + { + DataConnectionDiagnostics.HistoryCounts(null, null, null).ShouldBe("unavailable"); + DataConnectionDiagnostics.HistoryCounts(5, 0, 2).ShouldBe("good 5 · uncertain 0 · bad 2"); + } + + [Fact] + public void Dropped_bits_are_named_when_known_and_hex_when_not() + { + DataConnectionDiagnostics.DroppedBits(null).ShouldBe("unavailable"); + DataConnectionDiagnostics.DroppedBits(DataOperations.None).ShouldBe("none"); + DataConnectionDiagnostics.DroppedBits(DataOperations.HistoryRead | DataOperations.AlarmSubscribe).ShouldBe("HistoryRead, AlarmSubscribe"); + DataConnectionDiagnostics.DroppedBits((DataOperations)(1 << 20)).ShouldBe("0x100000"); + } + + [Fact] + public void The_older_build_hint_shows_only_when_something_was_dropped() + { + DataConnectionDiagnostics.HasDrops(null).ShouldBeFalse(); + DataConnectionDiagnostics.HasDrops(DataOperations.None, 0).ShouldBeFalse(); + DataConnectionDiagnostics.HasDrops(DataOperations.HistoryRead).ShouldBeTrue(); + DataConnectionDiagnostics.HasDrops(DataOperations.None, 2).ShouldBeTrue("a mapping's drop counts even when the connection dropped none"); + } +} diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataDeploymentActivationTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataDeploymentActivationTests.cs index be2c92882..f979a6bee 100644 --- a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataDeploymentActivationTests.cs +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataDeploymentActivationTests.cs @@ -51,6 +51,30 @@ public sealed class GrpcDataDeploymentActivationTests runtime.CaptureDiagnostics().ShouldHaveSingleItem().State.ShouldBe("connecting"); } + [Fact, Trait("Phase", "H4")] + public async Task Diagnostics_carry_the_consumer_history_counts_and_open_continuations_per_connection() + { + var activator = new PausedActivator(); + var history = new DataConnectionHistoryDiagnostics(); + await using var runtime = new DataConnectionDeploymentRuntime("node-a", "owner", new Security(), activator, 4) { HistoryDiagnostics = history }; + runtime.Apply(Snapshot(1, Definition("link", "secret-reference"), Definition("other", "secret-reference"))); + await activator.Entered.Task.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken); + history.RecordConsumerRead("LINK", "raw", 0); + history.RecordConsumerRead("link", "processed", 0x40000000u); + history.RecordConsumerRead("link", "attime", 0x80720000u); + history.ConsumerContinuationOpened("link"); + var rows = runtime.CaptureDiagnostics(); + var link = rows.Single(x => x.ConnectionId == "link"); + (link.HistoryReadsGood, link.HistoryReadsUncertain, link.HistoryReadsBad, link.OpenRemoteContinuations).ShouldBe((1L, 1L, 1L, 1)); + var other = rows.Single(x => x.ConnectionId == "other"); + (other.HistoryReadsGood, other.HistoryReadsBad, other.OpenRemoteContinuations).ShouldBe((0L, 0L, 0), "zeros, not unavailable: no traffic yet"); + activator.Release.TrySetResult(); + await using var plain = new DataConnectionDeploymentRuntime("node-a", "owner", new Security(), new PausedActivator { PauseFirst = false }, 4); + plain.Apply(Snapshot(1, Definition("link", "secret-reference"))); + await EventuallyAsync(() => plain.CaptureDiagnostics().Count == 1); + plain.CaptureDiagnostics().ShouldHaveSingleItem().HistoryReadsGood.ShouldBeNull("no history diagnostics wired = unavailable"); + } + [Fact] public async Task Transient_security_resolution_exception_retries_without_a_change_event() { diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataHistoryDiagnosticsWireTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataHistoryDiagnosticsWireTests.cs new file mode 100644 index 000000000..1f856ca01 --- /dev/null +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataHistoryDiagnosticsWireTests.cs @@ -0,0 +1,85 @@ +using Opc.Ua; +using Shouldly; +using Xunit; +using ZB.MOM.WW.OtOpcUa.Core.Abstractions; +using ZB.MOM.WW.OtOpcUa.Runtime.DataConnections; + +namespace ZB.MOM.WW.OtOpcUa.Runtime.Tests.DataConnections; + +/// +/// H4 — the remote-history diagnostics follow real traffic: a real consumer OPC UA session reads a projected node through +/// the real projection stack and a real in-process origin; both sides' counts by status class and open continuations +/// move with each page, resume and release. +/// +public sealed partial class GrpcDataConfiguredDiscoveryWireTests +{ + [Fact(Timeout = 90000)] + [Trait("Phase", "H4")] + public async Task History_diagnostics_count_answers_by_status_class_and_track_open_continuations_on_both_sides() + { + await using var originServer = await HistoryOrigin.StartAsync(7); + originServer.Source.Aggregates = new HashSet { HistoryAggregateType.Average }; + using var origin = new LocalDataFixture(servingGeneration: 1, history: originServer.Port); + ProjectedHistoryAccess? history = null; + await WithComposedServer(origin, origin.Raw, async (session, _, _, _, _, _, anchor) => + { + var client = (SessionClient)session; + await BrowseAll(client, anchor, 1); + var consumer = history!.Diagnostics; + + // Before any history traffic: nothing counted, nothing open; the origin reports its backend. + consumer.CaptureConsumer("link").ShouldBe(new ConsumerHistoryCounts(0, 0, 0, 0)); + var idle = origin.HistoryDiagnostics.CaptureOrigin().ShouldNotBeNull(); + idle.Available.ShouldBeTrue(); + (idle.ReadsGood, idle.ReadsBad, idle.OpenContinuations).ShouldBe((0L, 0L, 0)); + + // Page 1 of 7 at 2 per page: one Good answer on each side, one continuation open on each side. + var page = await RawHistory(client, anchor, 2, default); + page.ContinuationPoint.IsEmpty.ShouldBeFalse(); + consumer.CaptureConsumer("link").ShouldBe(new ConsumerHistoryCounts(1, 0, 0, 1)); + consumer.CaptureConsumer("LINK").Good.ShouldBe(1, "connection ids are case-insensitive"); + origin.HistoryDiagnostics.CaptureOrigin()!.OpenContinuations.ShouldBe(1); + origin.HistoryDiagnostics.CaptureOrigin()!.ReadsGood.ShouldBe(1); + + // Resume: the claimed cursor settles, its successor opens — still one open, two Good answers. + var next = await RawHistory(client, anchor, 2, page.ContinuationPoint); + next.ContinuationPoint.IsEmpty.ShouldBeFalse(); + consumer.CaptureConsumer("link").ShouldBe(new ConsumerHistoryCounts(2, 0, 0, 1)); + consumer.OpenConsumerContinuations.ShouldBe(1); + + // releaseContinuationPoints: the consumer cursor settles at once, the origin's after the coalesced release. + await client.HistoryReadAsync(new RequestHeader(), new ExtensionObject(RawDetails(2)), TimestampsToReturn.Both, true, + [new HistoryReadValueId { NodeId = anchor, ContinuationPoint = next.ContinuationPoint }], TestContext.Current.CancellationToken); + consumer.CaptureConsumer("link").OpenContinuations.ShouldBe(0); + await AwaitReleases(history, () => origin.Services.HistoryOpenContinuations == 0); + origin.HistoryDiagnostics.CaptureOrigin()!.OpenContinuations.ShouldBe(0); + + // An aggregate the origin refuses: one Bad answer on each side. + var refused = await ProcessedHistory(client, anchor, ObjectIds.AggregateFunction_Count); + refused.StatusCode.Code.ShouldBe(StatusCodes.BadAggregateNotSupported.Code); + consumer.CaptureConsumer("link").ShouldBe(new ConsumerHistoryCounts(2, 0, 1, 0)); + var after = origin.HistoryDiagnostics.CaptureOrigin()!; + (after.ReadsGood, after.ReadsUncertain, after.ReadsBad).ShouldBe((2L, 0L, 1L)); + }, localPermissions: 15, allowHistory: true, connectionSource: new PersistentConnections(origin), onHistory: (h, _) => history = h); + } + + [Fact(Timeout = 90000)] + [Trait("Phase", "H4")] + public async Task Consumer_session_close_settles_its_open_consumer_continuations() + { + await using var originServer = await HistoryOrigin.StartAsync(7); + using var origin = new LocalDataFixture(servingGeneration: 1, history: originServer.Port); + ProjectedHistoryAccess? history = null; + await WithComposedServer(origin, origin.Raw, async (session, _, _, _, _, _, anchor) => + { + var client = (SessionClient)session; + await BrowseAll(client, anchor, 1); + (await RawHistory(client, anchor, 2, default)).ContinuationPoint.IsEmpty.ShouldBeFalse(); + history!.Diagnostics.OpenConsumerContinuations.ShouldBe(1); + await session.CloseAsync(TestContext.Current.CancellationToken); + await AwaitReleases(history, () => origin.Services.HistoryOpenContinuations == 0); + history.Diagnostics.OpenConsumerContinuations.ShouldBe(0, "the SDK disposed the Remote point on session close"); + origin.HistoryDiagnostics.CaptureOrigin()!.OpenContinuations.ShouldBe(0); + }, localPermissions: 15, allowHistory: true, connectionSource: new PersistentConnections(origin), onHistory: (h, _) => history = h); + } +} diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataHistoryMetricsTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataHistoryMetricsTests.cs new file mode 100644 index 000000000..3ffc620ac --- /dev/null +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataHistoryMetricsTests.cs @@ -0,0 +1,127 @@ +using System.Diagnostics.Metrics; +using Shouldly; +using Xunit; +using ZB.MOM.WW.OtOpcUa.Commons.Observability; +using ZB.MOM.WW.OtOpcUa.Runtime.DataConnections; + +namespace ZB.MOM.WW.OtOpcUa.Runtime.Tests.DataConnections; + +/// +/// H4 metrics (plan §6): otopcua.dataconn.history.reads{variant,status_class,side} and +/// otopcua.dataconn.history.continuations.active{side} on the exported OtOpcUa meter, no ids in labels; the plan's +/// unknown-bit counter is the existing X0 instrument (reused, not duplicated). +/// +[Trait("Category", "Unit"), Trait("Feature", "GrpcData"), Trait("Phase", "H4")] +public sealed class GrpcDataHistoryMetricsTests +{ + private static readonly string[] AllowedLabels = ["variant", "status_class", "side"]; + + [Fact] + public void History_reads_are_counted_on_the_exported_meter_with_variant_status_class_and_side_only() + { + var seen = new List<(long Value, Dictionary Tags)>(); + using var listener = new MeterListener(); + listener.InstrumentPublished = (instrument, l) => + { + if (instrument.Meter.Name == OtOpcUaTelemetry.MeterName && instrument.Name == DataConnectionHistoryDiagnostics.ReadsCounterName) + l.EnableMeasurementEvents(instrument); + }; + listener.SetMeasurementEventCallback((_, value, tags, _) => + { + var map = new Dictionary(); + foreach (var tag in tags) map[tag.Key] = tag.Value; + lock (seen) seen.Add((value, map)); + }); + listener.Start(); + + var diagnostics = new DataConnectionHistoryDiagnostics(); + diagnostics.RecordConsumerRead("connection-with-an-id", "processed", 0x40000000u); + diagnostics.RecordOriginRead("attime", 0x80720000u); + listener.Dispose(); + + List<(long Value, Dictionary Tags)> snapshot; + lock (seen) snapshot = seen.ToList(); + // Other tests may count in parallel on the same static counter: assert presence of ours and the label set of all. + snapshot.ShouldContain(x => Equals(x.Tags["side"], "consumer") && Equals(x.Tags["variant"], "processed") + && Equals(x.Tags["status_class"], "uncertain")); + snapshot.ShouldContain(x => Equals(x.Tags["side"], "origin") && Equals(x.Tags["variant"], "attime") + && Equals(x.Tags["status_class"], "bad")); + foreach (var (value, tags) in snapshot) + { + value.ShouldBe(1); + tags.Keys.OrderBy(x => x).ShouldBe(AllowedLabels.OrderBy(x => x), "no connection, node or principal id in labels"); + tags.Values.ShouldNotContain("connection-with-an-id"); + } + } + + [Fact] + public void Open_continuations_gauge_reports_origin_and_consumer_sides() + { + var diagnostics = new DataConnectionHistoryDiagnostics(); + diagnostics.AttachOrigin(() => (true, 1, 3)); + diagnostics.ConsumerContinuationOpened("link"); + diagnostics.ConsumerContinuationOpened("link"); + + var observed = new Dictionary(); + using var listener = new MeterListener(); + listener.InstrumentPublished = (instrument, l) => + { + if (instrument.Meter.Name == OtOpcUaTelemetry.MeterName && instrument.Name == DataConnectionHistoryDiagnostics.ContinuationsGaugeName) + l.EnableMeasurementEvents(instrument); + }; + listener.SetMeasurementEventCallback((_, value, tags, _) => + { + foreach (var tag in tags) if (tag.Key == "side") observed[(string)tag.Value!] = value; + }); + listener.Start(); + listener.RecordObservableInstruments(); + + // Sums across live instances (other tests' instances may add), so at least ours. + observed.Keys.OrderBy(x => x).ShouldBe(["consumer", "origin"]); + observed["origin"].ShouldBeGreaterThanOrEqualTo(3); + observed["consumer"].ShouldBeGreaterThanOrEqualTo(2); + GC.KeepAlive(diagnostics); + } + + [Fact] + public void Consumer_counts_are_per_connection_case_insensitive_and_settle_never_goes_negative() + { + var diagnostics = new DataConnectionHistoryDiagnostics(); + diagnostics.RecordConsumerRead("Link", "raw", 0); + diagnostics.RecordConsumerRead(null, "raw", 0x80000000u); // unresolved node: metric only + diagnostics.ConsumerContinuationOpened("link"); + diagnostics.ConsumerContinuationSettled("LINK"); + diagnostics.ConsumerContinuationSettled("never-opened"); + diagnostics.CaptureConsumer("LINK").ShouldBe(new ConsumerHistoryCounts(1, 0, 0, 0)); + diagnostics.CaptureConsumer("never-opened").ShouldBe(new ConsumerHistoryCounts(0, 0, 0, 0)); + diagnostics.OpenConsumerContinuations.ShouldBe(0); + } + + [Fact] + public void Origin_evidence_is_unavailable_until_attached_and_when_the_state_probe_fails() + { + var diagnostics = new DataConnectionHistoryDiagnostics(); + diagnostics.CaptureOrigin().ShouldBeNull(); + diagnostics.RecordOriginRead("raw", 0); + diagnostics.AttachOrigin(() => (false, 0, 0)); + diagnostics.CaptureOrigin().ShouldBe(new ZB.MOM.WW.OtOpcUa.Commons.Interfaces.OriginHistoryDiagnostics(false, 0, 0, 1, 0, 0)); + diagnostics.AttachOrigin(() => throw new InvalidOperationException("history port not ready")); + diagnostics.CaptureOrigin().ShouldBeNull(); + } + + [Fact] + public void The_plan_unknown_bit_counter_is_the_existing_X0_instrument_not_a_second_one() + { + // Plan §6 names "…operations.unknown_bits_dropped"; X0 already counts exactly that (one per row per accepted change). + UnknownOperationDrops.CounterName.ShouldBe("otopcua.dataconnection.unknown_operations_dropped"); + var names = new List(); + using var listener = new MeterListener(); + listener.InstrumentPublished = (instrument, _) => + { + if (instrument.Meter.Name == OtOpcUaTelemetry.MeterName) lock (names) names.Add(instrument.Name); + }; + listener.Start(); + _ = new DataConnectionHistoryDiagnostics(); + lock (names) names.ShouldNotContain(x => x.Contains("unknown_bits", StringComparison.Ordinal)); + } +} diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataLocalConnectionTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataLocalConnectionTests.cs index 5b89a1f11..d7338e99f 100644 --- a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataLocalConnectionTests.cs +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataLocalConnectionTests.cs @@ -125,6 +125,8 @@ internal sealed class LocalDataFixture : IDisposable internal readonly DataView Raw = new(new("cluster", "https://zb.com/otopcua/raw", "string", "Plant/Driver/Device/Speed"), DataRealm.Raw, null, 0, "Plant/Driver/Device/Speed"); internal readonly DataView Uns = new(new("cluster", "https://zb.com/otopcua/uns", "string", "Area/Line/Equipment/Speed"), DataRealm.Uns, null, 0, "Area/Line/Equipment/Speed"); internal readonly LocalDataServices Services; + /// H4: the origin's history diagnostics (counts by status class, live sessions and continuations). + internal readonly DataConnectionHistoryDiagnostics HistoryDiagnostics = new(); internal readonly LocalExportCatalog Catalog; internal readonly DataAuthenticatedContext Context; @@ -196,7 +198,7 @@ internal sealed class LocalDataFixture : IDisposable var capabilities = new DataCapabilitiesProvider("cluster", () => Serving, () => Catalog.IsActive, limits); Services = new LocalDataServices(() => Catalog, Hub, new DataOperationPolicy(Authority, new TriePermissionEvaluator(Authority.Tries, Clock), Clock), capabilities, Clock, writes: writes, subscriptions: subscriptions, - targetSubscriptions: targetSubscriptions, history: history); + targetSubscriptions: targetSubscriptions, history: history) { HistoryDiagnostics = HistoryDiagnostics }; } internal IDataConnection Connection() => Services.Create(Context, new(DataTargetMode.Node, "cluster", Serving.NodeId));