diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/IProjectedHistoryAccess.cs b/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/IProjectedHistoryAccess.cs index 2ed760691..3f3e17ecb 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/IProjectedHistoryAccess.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/IProjectedHistoryAccess.cs @@ -105,4 +105,13 @@ public interface IProjectedHistoryAccess /// One outcome per node. Task> ReadAsync(RoleCarryingUserIdentity caller, DataHistoryDetails details, IReadOnlyList nodes, TimeSpan deadline, CancellationToken cancellationToken); + + /// + /// H4 diagnostics: the projected answers of one request exactly as the client sees them — every projected node once, with + /// its final status (refusals before or instead of a remote call included; a request that faults counts every projected + /// node Bad). Called by the node manager after the request, outside Lock. Default: nothing is counted. + /// + /// raw | processed | attime | modified. + /// Each projected node and the status the client got for it. + void RecordAnswered(string variant, IReadOnlyList<(NodeId NodeId, uint StatusCode)> answers) { } } diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/OtOpcUaNodeManager.cs b/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/OtOpcUaNodeManager.cs index 749fe7248..fa936fd0e 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/OtOpcUaNodeManager.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/OtOpcUaNodeManager.cs @@ -9955,7 +9955,7 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage /// respected (the same benign wiring race as ). /// /// The shared batch limiter semaphore. - private SemaphoreSlim GetHistoryReadBatchLimiter() + internal SemaphoreSlim GetHistoryReadBatchLimiter() { var gate = _historyReadBatchLimiter; if (gate is not null) return gate; diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/ProjectedHistoryRead.cs b/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/ProjectedHistoryRead.cs index 53ffdb3be..6d379355b 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/ProjectedHistoryRead.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/ProjectedHistoryRead.cs @@ -50,7 +50,11 @@ public sealed partial class OtOpcUaNodeManager ServeProjectedHistory(context, details, nodesToRead, projected, results, errors, started); } - /// The projected half of a variable-history request. + /// + /// The projected half of a variable-history request. H4: every projected answer is counted once, with the status the client + /// sees, at the point that status is set; a fault that escapes to the SDK (the service then fails) counts every projected + /// node of the request Bad instead. + /// private void ServeProjectedHistory( ServerSystemContext context, HistoryReadDetails details, @@ -59,15 +63,67 @@ public sealed partial class OtOpcUaNodeManager IList results, IList errors, long started) + { + var answered = new List<(NodeId NodeId, uint StatusCode)>(handles.Count); + var access = ProjectedHistoryAccess; + try + { + ServeProjectedHistoryCore(context, details, nodesToRead, handles, results, errors, started, access, answered); + } + catch + { + answered.Clear(); + foreach (var handle in handles) answered.Add((handle.NodeId, StatusCodes.BadInternalError.Code)); + throw; + } + finally + { + RecordProjectedAnswers(access, details, answered); + } + } + + /// The variant label of a HistoryRead's details. + internal static string HistoryVariant(HistoryReadDetails details) => details switch + { + ReadRawModifiedDetails { IsReadModified: true } => "modified", + ReadRawModifiedDetails => "raw", + ReadProcessedDetails => "processed", + ReadAtTimeDetails => "attime", + _ => "unknown", + }; + + private static void RecordProjectedAnswers(IProjectedHistoryAccess? access, HistoryReadDetails details, + List<(NodeId NodeId, uint StatusCode)> answered) + { + if (access is null || answered.Count == 0) return; + try { access.RecordAnswered(HistoryVariant(details), answered); } + catch (Exception ex) when (ex is not OutOfMemoryException) { } // diagnostics never fail a read + } + + private void ServeProjectedHistoryCore( + ServerSystemContext context, + HistoryReadDetails details, + ArrayOf nodesToRead, + List handles, + IList results, + IList errors, + long started, + IProjectedHistoryAccess? access, + List<(NodeId NodeId, uint StatusCode)> answered) { var session = context.OperationContext?.Session; var store = _historyContinuationStore; var epoch = Volatile.Read(ref _historyContinuationEpoch); - var access = ProjectedHistoryAccess; var identity = IdentityOf(context); var remote = ToRemoteDetails(details); var aggregates = details is ReadProcessedDetails processed ? processed.AggregateType : default; + void Refuse(NodeHandle handle, StatusCode status) + { + SetProjectedStatus(handle, results, errors, status); + answered.Add((handle.NodeId, status.Code)); + } + var pending = new List<(NodeHandle Handle, ProjectedHistoryNode Node)>(handles.Count); ProjectedHistoryContinuation? claimed = null; try @@ -87,7 +143,7 @@ public sealed partial class OtOpcUaNodeManager || !cursor.TryClaimForResume()) { state?.Remote?.Release(); - SetProjectedStatus(handle, results, errors, StatusCodes.BadContinuationPointInvalid); + Refuse(handle, StatusCodes.BadContinuationPointInvalid); continue; } @@ -99,7 +155,7 @@ public sealed partial class OtOpcUaNodeManager { // No projection gateway, no session identity, or a variant a remote read never serves (a modified read). resume?.ReleaseEvenIfClaimed(); - SetProjectedStatus(handle, results, errors, StatusCodes.BadHistoryOperationUnsupported); + Refuse(handle, StatusCodes.BadHistoryOperationUnsupported); continue; } @@ -110,7 +166,7 @@ public sealed partial class OtOpcUaNodeManager var aggregate = aggregates[handle.Index]; if (AggregateFunctionMap.Map(aggregate) is null || aggregate.NamespaceIndex != 0 || !aggregate.TryGetValue(out uint numeric)) { - SetProjectedStatus(handle, results, errors, StatusCodes.BadAggregateNotSupported); + Refuse(handle, StatusCodes.BadAggregateNotSupported); continue; } @@ -143,7 +199,7 @@ public sealed partial class OtOpcUaNodeManager if (!projectedSlots.Wait(0)) { ReleaseResumes(); - foreach (var p in pending) SetProjectedStatus(p.Handle, results, errors, StatusCodes.BadTooManyOperations); + foreach (var p in pending) Refuse(p.Handle, StatusCodes.BadTooManyOperations); return; } @@ -181,7 +237,7 @@ public sealed partial class OtOpcUaNodeManager }, p => { p.Node.Resume?.ReleaseEvenIfClaimed(); - SetProjectedStatus(p.Handle, results, errors, StatusCodes.BadTooManyOperations); + Refuse(p.Handle, StatusCodes.BadTooManyOperations); }); } finally @@ -194,7 +250,7 @@ public sealed partial class OtOpcUaNodeManager { foreach (var o in outcomes) o.Continuation?.Release(); ReleaseResumes(); - foreach (var p in pending) SetProjectedStatus(p.Handle, results, errors, StatusCodes.BadInternalError); + foreach (var p in pending) Refuse(p.Handle, StatusCodes.BadInternalError); return; } @@ -224,7 +280,7 @@ public sealed partial class OtOpcUaNodeManager if (StatusCode.IsBad(status)) { outcome.Continuation?.Release(); - SetProjectedStatus(handle, results, errors, status); + Refuse(handle, status); return; } @@ -247,6 +303,7 @@ public sealed partial class OtOpcUaNodeManager HistoryData = new ExtensionObject(new HistoryData { DataValues = values }), ContinuationPoint = cp is null ? default : ByteString.From(cp), }; + answered.Add((handle.NodeId, status.Code)); } } diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ProjectedDataAccess.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ProjectedDataAccess.cs index aeae8532b..000d35ff8 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ProjectedDataAccess.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ProjectedDataAccess.cs @@ -151,6 +151,22 @@ public sealed class ProjectedDataAccess : IProjectedDataAccess, IDisposable DataValueKind.Guid => items.Cast().ToArray(), _ => throw new ArgumentException("Unsupported array element kind.") }; } + /// + /// H4 diagnostics: the deployed connection a projected node's mapping uses, without authorizing or pinning anything; null + /// when the node no longer resolves. Never an access decision. + /// + internal string? ConnectionOf(NodeId nodeId) + { + try + { + return _nodes.TryResolve(nodeId, out var definition) && definition is not null + && _catalog.TryResolveProjected(definition.Realm, definition.LocalIdentifier, out var proof) && proof is not null + && proof.Metadata.View.MappingId is { } mapping && _connectionForMapping(mapping) is { Length: > 0 } connectionId + ? connectionId : null; + } + catch (Exception ex) when (ex is ArgumentException or InvalidOperationException) { return null; } + } + public bool TryAcquire(NodeId nodeId, RoleCarryingUserIdentity caller, DataOperations operation, out IProjectedDemandLease? demand) { demand = null; 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 2f90f37c5..dcaadce18 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ProjectedHistoryAccess.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ProjectedHistoryAccess.cs @@ -97,6 +97,18 @@ public sealed class ProjectedHistoryAccess : IProjectedHistoryAccess, IDisposabl await flush.ConfigureAwait(false); } + /// + /// + /// H4 review: counted by the node manager at the point each status is set (limiter refusals, a spent deadline, a count + /// mismatch and a serve-time fault included), not here from the gateway's outcomes. Each node is attributed to the + /// connection its mapping is deployed on, best effort (none when the node no longer resolves: metric only). + /// + public void RecordAnswered(string variant, IReadOnlyList<(NodeId NodeId, uint StatusCode)> answers) + { + ArgumentNullException.ThrowIfNull(answers); + foreach (var (node, status) in answers) Diagnostics.RecordConsumerRead(_access.ConnectionOf(node), variant, status); + } + /// /// Whether a projected node is advertised as historizing: the mapping (masked by the export) grants HistoryRead AND the /// origin's negotiated metadata (HistoryInfo, bit 32) says historizing. @@ -200,7 +212,7 @@ public sealed class ProjectedHistoryAccess : IProjectedHistoryAccess, IDisposabl left -= assembled[i]; } - return Recorded(outcomes.Select(o => o ?? Fail(BadNoCommunication)).ToArray()); + return outcomes.Select(o => o ?? Fail(BadNoCommunication)).ToArray(); } catch (Exception ex) when (ex is not OutOfMemoryException) { @@ -216,21 +228,13 @@ public sealed class ProjectedHistoryAccess : IProjectedHistoryAccess, IDisposabl outcomes[i] = Fail(timedOut ? BadTimeout : ex is OperationCanceledException && resumed ? BadContinuationPointInvalid : BadNoCommunication); } - return Recorded(outcomes.Select(o => o!).ToArray()); + return 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 diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests/DataConnections/ProjectedHistoryReadTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests/DataConnections/ProjectedHistoryReadTests.cs index ac9afe89f..52c8c20c8 100644 --- a/tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests/DataConnections/ProjectedHistoryReadTests.cs +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests/DataConnections/ProjectedHistoryReadTests.cs @@ -214,6 +214,76 @@ public sealed class ProjectedHistoryReadTests : IAsyncDisposable access.Issued[0].Released.ShouldBe(0, "the store owns the saved cursor"); } + [Fact] + [Trait("Phase", "H4")] + public async Task Every_projected_answer_is_recorded_once_with_the_status_the_client_sees() + { + // H4 review item 1: counted where the status is set — limiter refusals, a spent deadline, a count mismatch and a + // serve-time fault included — never from the gateway's outcomes alone. + var (nm, f) = await BootAsync(aclEnabled: false, NodePermissions.Browse | NodePermissions.Read | NodePermissions.HistoryRead); + nm.HistoryContinuationStore = new InMemoryHistoryContinuationStore(); + var a = Project(nm, f, "Speed", historizing: true); + var b = Project(nm, f, "Flow", historizing: true); + var access = new FakeAccess(); + nm.ProjectedHistoryAccess = access; + + (string Variant, uint[] Statuses) Delta(Action act) + { + var before = access.Answered.Count; + act(); + var added = access.Answered.Skip(before).ToArray(); + added.Select(x => x.Variant).Distinct().Count().ShouldBe(1); + return (added[0].Variant, added.Select(x => x.Status).ToArray()); + } + + // Served: Good, once per node. + var served = Delta(() => Raw(nm, f.Identity, [a, b])); + served.Variant.ShouldBe("raw"); + served.Statuses.ShouldBe([StatusCodes.Good.Code, StatusCodes.Good.Code]); + + // Refused unsent by the consumer: an unknown aggregate, a modified read. + var processed = new ReadProcessedDetails { StartTime = T0, EndTime = T0.AddHours(1), ProcessingInterval = 60_000, + AggregateType = [new NodeId("not-an-aggregate", 2)] }; + var unknown = Delta(() => Read(nm, f.Identity, processed, [a])); + unknown.Variant.ShouldBe("processed"); + unknown.Statuses.ShouldBe([StatusCodes.BadAggregateNotSupported.Code]); + var modified = new ReadRawModifiedDetails { StartTime = T0, EndTime = T0.AddHours(1), NumValuesPerNode = 5, IsReadModified = true }; + var refused = Delta(() => Read(nm, f.Identity, modified, [a])); + refused.Variant.ShouldBe("modified"); + refused.Statuses.ShouldBe([StatusCodes.BadHistoryOperationUnsupported.Code]); + + // The non-local (projected) slot limiter saturated. + var nonLocal = nm.GetNonLocalHistoryLimiter(); + var taken = 0; + while (nonLocal.Wait(0, TestContext.Current.CancellationToken)) taken++; + try { Delta(() => Raw(nm, f.Identity, [a, b])).Statuses.ShouldBe([StatusCodes.BadTooManyOperations.Code, StatusCodes.BadTooManyOperations.Code]); } + finally { nonLocal.Release(taken); } + + // The shared batch limiter saturated (its admission wait is capped by the request deadline). + var batch = nm.GetHistoryReadBatchLimiter(); + nm.HistoryReadDeadline = TimeSpan.FromMilliseconds(100); + taken = 0; + while (batch.Wait(0, TestContext.Current.CancellationToken)) taken++; + try { Delta(() => Raw(nm, f.Identity, [a])).Statuses.ShouldBe([StatusCodes.BadTooManyOperations.Code]); } + finally { batch.Release(taken); nm.HistoryReadDeadline = TimeSpan.FromSeconds(60); } + + // The request deadline spent before the remote call. + nm.HistoryReadDeadline = TimeSpan.FromTicks(1); + try { Delta(() => Raw(nm, f.Identity, [a])).Statuses.ShouldBe([StatusCodes.BadTimeout.Code]); } + finally { nm.HistoryReadDeadline = TimeSpan.FromSeconds(60); } + + // The gateway answered the wrong number of outcomes. + access.DropLast = true; + Delta(() => Raw(nm, f.Identity, [a, b])).Statuses.ShouldBe([StatusCodes.BadInternalError.Code, StatusCodes.BadInternalError.Code]); + access.DropLast = false; + + // A serve-time fault after the gateway returned: the service fails, so every projected node counts Bad — never Good. + var poisoned = new FakeAccess { FirstValue = new object() }; + nm.ProjectedHistoryAccess = poisoned; + Should.Throw(() => Raw(nm, f.Identity, [a, b])); + poisoned.Answered.Select(x => x.Status).ShouldBe([StatusCodes.BadInternalError.Code, StatusCodes.BadInternalError.Code]); + } + [Fact] public void Unset_bounds_travel_absent_and_AtTime_carries_its_times() { @@ -470,6 +540,15 @@ public sealed class ProjectedHistoryReadTests : IAsyncDisposable /// When set, every call throws it (after claiming nothing — the cursors are the caller's to release). public Exception? Throw { get; set; } public int Entries; + /// When set, the answer omits the last node (an outcome count mismatch). + public bool DropLast { get; set; } + /// H4: what the node manager reported as answered, in order. + public readonly List<(string Variant, NodeId Node, uint Status)> Answered = []; + + public void RecordAnswered(string variant, IReadOnlyList<(NodeId NodeId, uint StatusCode)> answers) + { + lock (Answered) foreach (var (node, status) in answers) Answered.Add((variant, node, status)); + } public async Task> ReadAsync(RoleCarryingUserIdentity caller, DataHistoryDetails details, IReadOnlyList nodes, TimeSpan deadline, CancellationToken cancellationToken) @@ -479,7 +558,7 @@ public sealed class ProjectedHistoryReadTests : IAsyncDisposable if (Interlocked.Increment(ref Entries) > 0) Entered.TrySetResult(); if (Hold is { } hold) await hold.Task.ConfigureAwait(false); if (Throw is { } error) throw error; - return (nodes.Select(node => + return (nodes.Take(DropLast ? nodes.Count - 1 : nodes.Count).Select(node => { FakeCursor? next = null; if (Paged)