From 4e6b1eb127d50d321bfcc20911717ad35ac8e4bc Mon Sep 17 00:00:00 2001 From: Joseph Doherty Date: Mon, 23 Nov 2026 19:36:21 -0500 Subject: [PATCH] feat(grpc-data): H1 override-level history port; SDK HistoryRead overrides become adapters Raw/modified, Processed and AtTime serving (aggregate refusals incl. #897 and SupportsAggregateFor, non-default AggregateConfiguration, modified+bounds BadInvalidArgument, batch limiter, deadline, continuation binding, value normalisation) now runs through OtOpcUaNodeManager.ReadHistory, addressed by (realm, identifier) instead of SDK node handles. Continuation cursors are re-keyed from the NodeId string to (realm, identifier). Adds the production PeerHistoryContinuationStore (per principal + incarnation, random 16-byte single-use tokens, 60 s idle expiry, oldest-idle eviction) for H2. --- .../HistoryPaging.cs | 8 +- .../HistoryReadPort.cs | 429 ++++++++++++++++++ .../OtOpcUaNodeManager.cs | 409 ++++++----------- .../PeerHistoryContinuationStore.cs | 205 +++++++++ 4 files changed, 773 insertions(+), 278 deletions(-) create mode 100644 src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/HistoryReadPort.cs create mode 100644 src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/PeerHistoryContinuationStore.cs diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/HistoryPaging.cs b/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/HistoryPaging.cs index 9bbaf8641..b07a79641 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/HistoryPaging.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/HistoryPaging.cs @@ -1,5 +1,6 @@ using Opc.Ua; using Opc.Ua.Server; +using ZB.MOM.WW.OtOpcUa.Commons.OpcUa; using ZB.MOM.WW.OtOpcUa.Core.Abstractions; namespace ZB.MOM.WW.OtOpcUa.OpcUaServer; @@ -73,7 +74,9 @@ namespace ZB.MOM.WW.OtOpcUa.OpcUaServer; /// that still has un-emitted ties — the next page over-fetches the cluster directly /// instead of first re-reading N + skip + 1 rows that are known to be ties. /// -/// The exact namespace-qualified node identity; required on every production cursor. +/// With , the node the cursor was issued for — re-keyed by the H1 history +/// port from the SDK NodeId string to (realm, identifier), so a cursor never depends on an SDK handle. +/// The node's identifier in ; required on every production cursor. /// The topology generation. A removal conservatively invalidates all cursors. internal sealed record HistoryContinuationState( string Tagname, @@ -90,7 +93,8 @@ internal sealed record HistoryContinuationState( long EmptyToTicks = 0, HistoryEndBound? PendingEndBound = null, bool WithinTieCluster = false, - string? BoundNodeKey = null, + AddressSpaceRealm BoundRealm = default, + string? BoundIdentifier = null, long AddressSpaceEpoch = -1) { /// The walk-back hint this cursor carries. diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/HistoryReadPort.cs b/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/HistoryReadPort.cs new file mode 100644 index 000000000..5037a76b6 --- /dev/null +++ b/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/HistoryReadPort.cs @@ -0,0 +1,429 @@ +using System.Security.Cryptography; +using System.Text; +using Opc.Ua; +using Opc.Ua.Server; +using ZB.MOM.WW.OtOpcUa.Commons.OpcUa; +using ZB.MOM.WW.OtOpcUa.Core.Abstractions; +using SdkHistoryReadResult = Opc.Ua.HistoryReadResult; + +namespace ZB.MOM.WW.OtOpcUa.OpcUaServer; + +/// +/// The variable-history request a call serves — Raw (incl. modified), +/// Processed or AtTime. Never HistoryUpdate and never events: those stay on their SDK overrides (plan §2.1.1, §3.1). +/// Timestamps are CLR UTC; an unset Part 11 bound is , exactly as the SDK overrides +/// handed it to the node manager before the port existed (the end-only / open-end rules depend on it). +/// +internal abstract record HistoryReadVariant +{ + /// Maps the SDK's onto the port variant the overrides serve. + /// Raw/modified, Processed or AtTime details. + /// The equivalent variant. + /// Event details (the port serves variable history only). + public static HistoryReadVariant From(HistoryReadDetails details) => details switch + { + ReadRawModifiedDetails raw => new HistoryReadRawVariant( + SdkValueBoundary.ToClrTimestamp(raw.StartTime), SdkValueBoundary.ToClrTimestamp(raw.EndTime), + raw.NumValuesPerNode, raw.ReturnBounds, raw.IsReadModified), + // OPC UA ProcessingInterval is a Duration in milliseconds — converted once per batch, as the override did. + ReadProcessedDetails processed => new HistoryReadProcessedVariant( + SdkValueBoundary.ToClrTimestamp(processed.StartTime), SdkValueBoundary.ToClrTimestamp(processed.EndTime), + TimeSpan.FromMilliseconds(processed.ProcessingInterval), processed.AggregateConfiguration), + // Snapshot the requested timestamps once — the same list is read for every node. + ReadAtTimeDetails atTime => new HistoryReadAtTimeVariant( + (atTime.ReqTimes.ToArray() ?? []).Select(t => t.ToDateTime()).ToList()), + _ => throw new ArgumentException($"The history port serves Raw, Processed and AtTime details, not {details.GetType().Name}.", nameof(details)), + }; + + /// + /// A stable SHA-256 (hex) of the request shape — what a peer continuation binds so a resume under different + /// details is refused (). Local SDK continuation points never use it. + /// + /// The lowercase hex digest. + public string ComputeDetailsHash() => + Convert.ToHexStringLower(SHA256.HashData(Encoding.UTF8.GetBytes(CanonicalForm()))); + + /// The canonical text digests. + /// An invariant, field-ordered rendering. + protected abstract string CanonicalForm(); +} + +/// HistoryRead-Raw (or, with , the Part 11 modification trail). +/// StartTime (MinValue = unset). +/// EndTime (MinValue = unset). +/// Per-page cap; 0 = all values. +/// Part 11 bounding values requested. +/// A modified-value read. +internal sealed record HistoryReadRawVariant(DateTime StartUtc, DateTime EndUtc, uint NumValuesPerNode, bool ReturnBounds, bool IsReadModified = false) + : HistoryReadVariant +{ + /// + protected override string CanonicalForm() => + $"raw|{StartUtc.Ticks}|{EndUtc.Ticks}|{NumValuesPerNode}|{ReturnBounds}|{IsReadModified}"; +} + +/// HistoryRead-Processed. The aggregate is per node (). +/// StartTime. +/// EndTime. +/// The interval. +/// The client's configuration; null = server defaults. +internal sealed record HistoryReadProcessedVariant(DateTime StartUtc, DateTime EndUtc, TimeSpan ProcessingInterval, AggregateConfiguration? AggregateConfiguration) + : HistoryReadVariant +{ + /// + protected override string CanonicalForm() + { + var c = AggregateConfiguration; + var config = c is null ? "null" : $"{c.UseServerCapabilitiesDefaults}|{c.TreatUncertainAsBad}|{c.PercentDataBad}|{c.PercentDataGood}|{c.UseSlopedExtrapolation}"; + return $"processed|{StartUtc.Ticks}|{EndUtc.Ticks}|{ProcessingInterval.Ticks}|{config}"; + } +} + +/// HistoryRead-AtTime. +/// The requested times, in request order. +internal sealed record HistoryReadAtTimeVariant(IReadOnlyList TimestampsUtc) : HistoryReadVariant +{ + /// + protected override string CanonicalForm() => "attime|" + string.Join(",", TimestampsUtc.Select(t => t.Ticks)); +} + +/// One node of a port request, addressed SDK-handle-free by (realm, identifier). +/// The address-space realm. +/// The node's s= identifier in that realm. +/// The inbound continuation point; null/empty = a fresh read. +/// Processed only: the requested aggregate function's NodeId. +internal readonly record struct HistoryReadPortItem( + AddressSpaceRealm Realm, string Identifier, byte[]? ContinuationPoint = null, NodeId AggregateType = default) +{ + /// The node, for log lines (Realm:Identifier). + public override string ToString() => $"{Realm}:{Identifier}"; +} + +/// +/// One node's outcome from the port, in the SDK's two-slot shape: is the service-level operation +/// status (the override's errors[i]) and the per-node result (results[i]). A slot left +/// null is one the pre-port override never wrote either — the SDK's own pre-seeded value stands (for the operation +/// status that is BadHistoryOperationUnsupported). +/// +internal sealed class HistoryReadNodeOutcome +{ + /// The operation status, or null when untouched. + public ServiceResult? Error { get; set; } + + /// The per-node result, or null when untouched. + public SdkHistoryReadResult? Result { get; set; } + + /// The effective operation status a non-SDK caller (H2) reports. + public StatusCode Status => Error?.StatusCode ?? StatusCodes.BadHistoryOperationUnsupported; + + /// The returned samples (HistoryData or HistoryModifiedData values), empty when none. + public IReadOnlyList Values => + Result?.HistoryData is { IsNull: false } body && ExtensionObject.ToEncodeable(body) is HistoryData data + ? data.DataValues.ToArray() ?? [] + : []; + + /// The outbound continuation point, or null when the read is complete. + public byte[]? ContinuationPoint => + Result is { } r && !r.ContinuationPoint.IsEmpty ? r.ContinuationPoint.ToArray() : null; +} + +/// What a continuation is bound to, handed to the scope on save and take. +/// The node's realm. +/// The node's identifier. +/// The history (address-space) epoch the cursor was issued under. +/// The request details (a peer binds their hash; the SDK session store ignores them). +internal readonly record struct HistoryContinuationBinding( + AddressSpaceRealm Realm, string Identifier, long Epoch, HistoryReadVariant? Details); + +/// +/// Where the port stores and takes resume state for one caller. The local SDK path binds it to the OPC UA session +/// (); a remote peer binds it to its authenticated +/// principal and connection incarnation (). The port itself always re-checks +/// the node, realm, epoch, cursor kind and tagname after a take, whatever the scope. +/// +internal interface IHistoryContinuationScope +{ + /// Stores ; returns the opaque token, or null when nothing can be stored (single-shot). + byte[]? Save(HistoryContinuationState state, HistoryContinuationBinding binding); + + /// Takes (removes) the state behind ; null when unknown/expired/mismatched. + HistoryContinuationState? TryTake(byte[] continuationPoint, HistoryContinuationBinding binding); +} + +/// +/// H1 — the override-level history port (gRPC data history plan §3.1). Everything the Raw / Processed / AtTime SDK +/// overrides did after authorization now lives here, addressed by (realm, identifier) instead of SDK node +/// handles, so H2 can serve a remote peer's HistoryRead through the exact same pipeline. The overrides are thin +/// adapters (): authorize, map handles to items, call the port, map back. +/// +public sealed partial class OtOpcUaNodeManager +{ + /// + /// Serves one variable-history batch: aggregate refusals (unknown / not served, the #897 Part 13 data-type rule, + /// the backend's SupportsAggregateFor, a non-default AggregateConfiguration), the modified+bounds + /// Bad_InvalidArgument rule, the process-wide batch limiter, the per-request deadline, continuation binding + /// and value normalisation. Authorization is the caller's (the SDK adapter's ACL gate; H2's ingress). + /// + /// The request variant. + /// The nodes, in request order. + /// Where this caller's continuation points live. + /// + /// The request lifetime. It is linked with ; a node still in flight when either + /// fires is BadTimeout. + /// + /// One outcome per item, in item order. + /// + /// Never called under Lock and never takes it for the read itself (the tagname and value-type lookups are + /// lock-free dictionary reads): HistoryRead runs outside the node-manager lock, and must stay there. Synchronous — + /// it block-bridges once at the batch boundary, exactly as the SDK overrides always did. + /// + internal IReadOnlyList ReadHistory( + HistoryReadVariant details, + IReadOnlyList items, + IHistoryContinuationScope continuations, + CancellationToken requestCancellation) + { + ArgumentNullException.ThrowIfNull(details); + ArgumentNullException.ThrowIfNull(items); + ArgumentNullException.ThrowIfNull(continuations); + var outcomes = new HistoryReadNodeOutcome[items.Count]; + for (var i = 0; i < outcomes.Length; i++) outcomes[i] = new HistoryReadNodeOutcome(); + var indices = Enumerable.Range(0, items.Count).ToList(); + + switch (details) + { + case HistoryReadRawVariant raw: + WithHistoryBatchLimiter(indices, () => + { + using var deadline = CreateDeadline(requestCancellation); + var ct = deadline?.Token ?? CancellationToken.None; + var work = new List>(items.Count); + foreach (var i in indices) + { + var item = items[i]; + var outcome = outcomes[i]; + if (raw.IsReadModified && raw.ReturnBounds && HonorReturnBounds) + { + // Part 11 §6.5.3.3: returnBounds "shall be set to FALSE" for a modified read, "otherwise the Server + // returns a Bad_InvalidArgument". Off with the ServerHistorian:HonorReturnBounds kill switch. + outcome.Error = StatusCodes.BadInvalidArgument; + outcome.Result = new SdkHistoryReadResult { StatusCode = StatusCodes.BadInvalidArgument }; + continue; + } + + if (raw.IsReadModified) + { + // Part 11 modified-value history: the prior values every HistoryUpdate recorded. Gated by the same + // HistoryRead authorization as a raw read; a backend with no trail ⇒ unsupported. + work.Add(() => ServeModifiedPagedAsync( + item, outcome, continuations, raw, raw.StartUtc, raw.EndUtc, raw.NumValuesPerNode, ct)); + continue; + } + + work.Add(() => ServeRawPagedAsync( + item, outcome, continuations, raw, raw.StartUtc, raw.EndUtc, raw.NumValuesPerNode, + ct, raw.ReturnBounds && HonorReturnBounds)); + } + + RunBounded(work, HistoryReadBatchParallelism); + }, i => RejectBatch(outcomes[i])); + NormalizeHistoryValues(items, outcomes); + break; + + case HistoryReadProcessedVariant processed: + { + // A client AggregateConfiguration other than the server defaults is refused per node, never silently ignored. + var configurationServable = ServerAggregateConfiguration.IsServable(processed.AggregateConfiguration); + var served = AdvertisedAggregateFunctions.ServedBy(HistorianDataSource); + WithHistoryBatchLimiter(indices, () => + { + using var deadline = CreateDeadline(requestCancellation); + var ct = deadline?.Token ?? CancellationToken.None; + var work = new List>(items.Count); + foreach (var i in indices) + { + var item = items[i]; + var outcome = outcomes[i]; + // One authority — the source's SupportedAggregates (also what HistoryServerCapabilities/ + // AggregateFunctions advertises; null ⇒ all, the same rule). An aggregate the server cannot name, or the + // backend does not serve, is refused up front without a backend call. + var aggregate = AggregateFunctionMap.Map(item.AggregateType); + if (aggregate is null || !served.Contains(aggregate.Value)) + { + outcome.Error = StatusCodes.BadAggregateNotSupported; + continue; + } + + // An aggregate not valid for THIS node's DataType (lmxopcua#897) — Part 11 §6.5.4: "If the Aggregate is + // not valid for the Node then the StatusCode shall be Bad_AggregateNotSupported". The shared Part 13 + // Table 50 rule (no numeric aggregate on a String / DateTime node, every backend), then the backend's own + // per-type limit (the Gateway's native TimeAverage / Total on a Boolean node). Unsent, so never a + // backend failure. + var nodeValueType = AtTimeValueType(item.Realm, item.Identifier); + if (!HistoryAggregateDataTypes.AppliesTo(aggregate.Value, nodeValueType) + || !HistorianDataSource.SupportsAggregateFor(aggregate.Value, nodeValueType)) + { + outcome.Error = StatusCodes.BadAggregateNotSupported; + continue; + } + + if (!configurationServable) + { + outcome.Error = StatusCodes.BadAggregateConfigurationRejected; + continue; + } + + // Processed is SINGLE-SHOT (no continuation point). Unlike Raw, ReadProcessedDetails carries NO client + // count cap (NumValuesPerNode) — the bucket count is deterministic (window / interval) and the + // single-shot backend returns every bucket in one read, so there is no "full page ⇒ maybe more" signal + // to page on. Returning the complete aggregate result with a null CP is spec-conformant (OPC UA Part 11 + // lets a server return all available data in one response). + var agg = aggregate.Value; + work.Add(() => ServeNodeAsync(item, outcome, (source, tagname, token) => source.ReadProcessedAsync( + tagname, processed.StartUtc, processed.EndUtc, processed.ProcessingInterval, agg, token), ct)); + } + + RunBounded(work, HistoryReadBatchParallelism); + }, i => RejectBatch(outcomes[i])); + break; + } + + case HistoryReadAtTimeVariant atTime: + WithHistoryBatchLimiter(indices, () => + { + using var deadline = CreateDeadline(requestCancellation); + var ct = deadline?.Token ?? CancellationToken.None; + var work = new List>(items.Count); + foreach (var i in indices) + { + var item = items[i]; + var outcome = outcomes[i]; + // The node's scalar value type, for a backend whose stored values carry none (the Gateway). + var valueType = AtTimeValueType(item.Realm, item.Identifier); + work.Add(() => ServeNodeAsync(item, outcome, (source, tagname, token) => source.ReadAtTimeAsync( + tagname, atTime.TimestampsUtc, valueType, token), ct)); + } + + RunBounded(work, HistoryReadBatchParallelism); + }, i => RejectBatch(outcomes[i])); + NormalizeHistoryValues(items, outcomes); + break; + + default: + throw new ArgumentException($"Unsupported history variant {details.GetType().Name}.", nameof(details)); + } + + return outcomes; + } + + /// The batch limiter's saturation answer for one node: BadTooManyOperations in both slots. + private static void RejectBatch(HistoryReadNodeOutcome outcome) + { + outcome.Error = StatusCodes.BadTooManyOperations; + outcome.Result = new SdkHistoryReadResult { StatusCode = StatusCodes.BadTooManyOperations }; + } + + /// + /// The SDK-override side of the port: maps the authorized handles to (realm, identifier) items — the same + /// realm-qualified key every node map uses () — serves them through + /// under the session's continuation scope, and writes each outcome back to the handle's + /// slots. A slot the port left unset keeps the SDK's pre-seeded value, as before. + /// + private void ServeHistoryReadAdapter( + ServerSystemContext context, + HistoryReadDetails details, + ArrayOf nodesToRead, + List nodesToProcess, + IList results, + IList errors) + { + var variant = HistoryReadVariant.From(details); + var aggregates = details is ReadProcessedDetails processed ? processed.AggregateType : default; + var items = new HistoryReadPortItem[nodesToProcess.Count]; + for (var i = 0; i < items.Length; i++) + { + var handle = nodesToProcess[i]; + var key = MapKey(handle.NodeId); + var cp = nodesToRead[handle.Index].ContinuationPoint; + // AggregateType is a per-node parallel collection (same length as nodesToRead, enforced by the base + // dispatcher); handle.Index is the node's position in it. + items[i] = new HistoryReadPortItem(key.Realm, key.Id, cp.Length > 0 ? cp.ToArray() : null, + variant is HistoryReadProcessedVariant ? aggregates[handle.Index] : default); + } + + var outcomes = ReadHistory(variant, items, SessionHistoryContinuationScope(context.OperationContext?.Session), + context.OperationContext?.CancellationToken ?? CancellationToken.None); + for (var i = 0; i < items.Length; i++) + { + var index = nodesToProcess[i].Index; + if (outcomes[i].Error is { } error) errors[index] = error; + if (outcomes[i].Result is { } result) results[index] = result; + } + } + + /// The continuation scope of a local OPC UA session — the SDK session store, as before the port. + /// The request's session; null on the session-less in-process path. + /// A scope reading at each call. + internal IHistoryContinuationScope SessionHistoryContinuationScope(ISession? session) => new SessionScope(this, session); + + /// Normalize stored and AtTime history to each scalar node's declared DataType. + private void NormalizeHistoryValues(IReadOnlyList items, IReadOnlyList outcomes) + { + for (var n = 0; n < items.Count; n++) + { + if (AtTimeValueType(items[n].Realm, items[n].Identifier) is not { } type || outcomes[n].Result?.HistoryData is not { } body) continue; + if (body.IsNull || ExtensionObject.ToEncodeable(body) is not HistoryData data) continue; + var values = data.DataValues.ToArray() ?? []; + for (var i = 0; i < values.Length; i++) + { + var value = values[i]; + var payload = SdkValueBoundary.ToClr(value.WrappedValue); + if (payload is null) continue; + try + { + // A gateway number cannot reconstruct a DateTime or a String which was never stored. + if ((type == TypeCode.DateTime && payload is not DateTime) + || (type == TypeCode.String && payload is not string)) throw new InvalidCastException(); + var converted = Convert.ChangeType(payload, type, System.Globalization.CultureInfo.InvariantCulture); + if (converted is float f && float.IsInfinity(f) && payload is double d && double.IsFinite(d)) + throw new OverflowException(); + values[i] = value.WithWrappedValue(SdkValueBoundary.FromClr(converted)); + } + catch (Exception ex) when (ex is InvalidCastException or OverflowException or FormatException) + { + values[i] = value.WithWrappedValue(Variant.Null).WithStatus(StatusCodes.BadTypeMismatch); + } + } + data.DataValues = values; + } + } + + /// + /// Saves a cursor bound to its node ((realm, identifier), re-keyed from the SDK NodeId string) and the current + /// history epoch. A cursor issued under an epoch that has since moved is not stored — the read degrades to + /// single-shot for that node, as before. + /// + private byte[]? SaveHistoryContinuation( + IHistoryContinuationScope scope, AddressSpaceRealm realm, string identifier, long epoch, + HistoryReadVariant? details, HistoryContinuationState state) + { + if (epoch != Volatile.Read(ref _historyContinuationEpoch)) return null; + return scope.Save(state with { BoundRealm = realm, BoundIdentifier = identifier, AddressSpaceEpoch = epoch }, + new HistoryContinuationBinding(realm, identifier, epoch, details)); + } + + /// Whether a taken cursor was issued for this node, in this realm, under this epoch. + private static bool HistoryContinuationMatches(HistoryContinuationState state, AddressSpaceRealm realm, string identifier, long epoch) => + state.BoundIdentifier is not null && state.BoundRealm == realm + && string.Equals(state.BoundIdentifier, identifier, StringComparison.Ordinal) && state.AddressSpaceEpoch == epoch; + + /// The SDK session store behind a scope (read per call, so a test's store swap applies to the next call). + private sealed class SessionScope(OtOpcUaNodeManager nm, ISession? session) : IHistoryContinuationScope + { + public byte[]? Save(HistoryContinuationState state, HistoryContinuationBinding binding) => + nm._historyContinuationStore.Save(session, state); + + public HistoryContinuationState? TryTake(byte[] continuationPoint, HistoryContinuationBinding binding) => + nm._historyContinuationStore.TryTake(session, continuationPoint); + } +} diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/OtOpcUaNodeManager.cs b/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/OtOpcUaNodeManager.cs index a7afb38b5..69633e2f0 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/OtOpcUaNodeManager.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/OtOpcUaNodeManager.cs @@ -85,7 +85,7 @@ public sealed record ProjectedAnchorDefinition(DataRealm Realm, string LocalIden // re-implementing the interface is the only way to put an ACL decision on that path. Since #855 condition events no // longer take it, and since #878 the decision there is a flat deny under enforcement (the SDK memoizes it, so it must // not depend on grants). Every other member maps to the inherited implementation exactly as before. -public sealed class OtOpcUaNodeManager : CustomNodeManager2, INodeManager3, IProjectedValueSink, IProjectedNamespacePageSink, IProjectedNodeLookup, IProjectedAnchorSink +public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManager3, IProjectedValueSink, IProjectedNamespacePageSink, IProjectedNodeLookup, IProjectedAnchorSink { /// Nonblocking lookup of the current projected parent readiness. public Func? ProjectedBrowseReadiness { get; set; } @@ -5491,7 +5491,17 @@ public sealed class OtOpcUaNodeManager : CustomNodeManager2, INodeManager3, IPro /// The hint, or null. internal TypeCode? AtTimeValueType(NodeId nodeId) { - if (!_variables.TryGetValue(MapKey(nodeId), out var variable) || variable.ValueRank != ValueRanks.Scalar) return null; + var key = MapKey(nodeId); + return AtTimeValueType(key.Realm, key.Id); + } + + /// The hint of a node addressed by (realm, identifier) (the history port). + /// The node's realm. + /// The node's identifier. + /// The hint, or null. + internal TypeCode? AtTimeValueType(AddressSpaceRealm realm, string identifier) + { + if (!_variables.TryGetValue(MapKey(realm, identifier), out var variable) || variable.ValueRank != ValueRanks.Scalar) return null; return TypeInfo.GetBuiltInType(variable.DataType) switch { BuiltInType.Boolean => TypeCode.Boolean, @@ -8788,6 +8798,7 @@ public sealed class OtOpcUaNodeManager : CustomNodeManager2, INodeManager3, IPro } /// + /// A thin adapter over the history port (): authorize, then serve. protected override void HistoryReadRawModified( ServerSystemContext context, ReadRawModifiedDetails details, @@ -8798,47 +8809,12 @@ public sealed class OtOpcUaNodeManager : CustomNodeManager2, INodeManager3, IPro List nodesToProcess, IDictionary cache) { - var session = context.OperationContext?.Session; nodesToProcess = AuthorizeHistoryRead(context, nodesToProcess, results, errors); - WithHistoryReadBatchLimiter(nodesToProcess, results, errors, () => - { - using var deadline = CreateDeadline(context); - var ct = deadline?.Token ?? CancellationToken.None; - var work = new List>(nodesToProcess.Count); - foreach (var handle in nodesToProcess) - { - if (details.IsReadModified && details.ReturnBounds && HonorReturnBounds) - { - // Part 11 §6.5.3.3: returnBounds "shall be set to FALSE" for a modified read, "otherwise the Server returns - // a Bad_InvalidArgument". Off with the ServerHistorian:HonorReturnBounds kill switch. - errors[handle.Index] = StatusCodes.BadInvalidArgument; - results[handle.Index] = new SdkHistoryReadResult { StatusCode = StatusCodes.BadInvalidArgument }; - continue; - } - - if (details.IsReadModified) - { - // Part 11 modified-value history: the prior values every HistoryUpdate recorded. Gated by the - // same HistoryRead authorization as a raw read (above); a backend with no trail ⇒ unsupported. - work.Add(() => ServeModifiedPagedAsync( - handle, session, nodesToRead, results, errors, - SdkValueBoundary.ToClrTimestamp(details.StartTime), SdkValueBoundary.ToClrTimestamp(details.EndTime), details.NumValuesPerNode, - ct)); - continue; - } - - work.Add(() => ServeRawPagedAsync( - handle, session, nodesToRead, results, errors, - SdkValueBoundary.ToClrTimestamp(details.StartTime), SdkValueBoundary.ToClrTimestamp(details.EndTime), details.NumValuesPerNode, - ct, details.ReturnBounds && HonorReturnBounds)); - } - - RunBounded(work, HistoryReadBatchParallelism); - }); - NormalizeHistoryValues(nodesToProcess, results); + ServeHistoryReadAdapter(context, details, nodesToRead, nodesToProcess, results, errors); } /// + /// A thin adapter over the history port (): authorize, then serve. protected override void HistoryReadProcessed( ServerSystemContext context, ReadProcessedDetails details, @@ -8849,70 +8825,12 @@ public sealed class OtOpcUaNodeManager : CustomNodeManager2, INodeManager3, IPro List nodesToProcess, IDictionary cache) { - // OPC UA ProcessingInterval is a Duration in milliseconds — convert once per batch. - var interval = TimeSpan.FromMilliseconds(details.ProcessingInterval); - // A client AggregateConfiguration other than the server defaults is refused per node, never silently ignored. - var configurationServable = ServerAggregateConfiguration.IsServable(details.AggregateConfiguration); nodesToProcess = AuthorizeHistoryRead(context, nodesToProcess, results, errors); - var served = AdvertisedAggregateFunctions.ServedBy(HistorianDataSource); - WithHistoryReadBatchLimiter(nodesToProcess, results, errors, () => - { - using var deadline = CreateDeadline(context); - var ct = deadline?.Token ?? CancellationToken.None; - var work = new List>(nodesToProcess.Count); - foreach (var handle in nodesToProcess) - { - // AggregateType is a per-node parallel collection (same length as nodesToRead, enforced by - // the base dispatcher). handle.Index is the node's position in that collection. - var aggregateNodeId = details.AggregateType[handle.Index]; - // One authority — the source's SupportedAggregates (also what HistoryServerCapabilities/ - // AggregateFunctions advertises; null ⇒ all, the same rule). An aggregate the server cannot name, or the - // backend does not serve, is refused up front without a backend call. - var aggregate = AggregateFunctionMap.Map(aggregateNodeId); - if (aggregate is null || !served.Contains(aggregate.Value)) - { - errors[handle.Index] = StatusCodes.BadAggregateNotSupported; - continue; - } - - // An aggregate not valid for THIS node's DataType (lmxopcua#897) — Part 11 §6.5.4: "If the Aggregate is not - // valid for the Node then the StatusCode shall be Bad_AggregateNotSupported". The shared Part 13 Table 50 - // rule (no numeric aggregate on a String / DateTime node, every backend), then the backend's own per-type - // limit (the Gateway's native TimeAverage / Total on a Boolean node). Unsent, so never a backend failure. - var nodeValueType = AtTimeValueType(handle.NodeId); - if (!HistoryAggregateDataTypes.AppliesTo(aggregate.Value, nodeValueType) - || !HistorianDataSource.SupportsAggregateFor(aggregate.Value, nodeValueType)) - { - errors[handle.Index] = StatusCodes.BadAggregateNotSupported; - continue; - } - - if (!configurationServable) - { - errors[handle.Index] = StatusCodes.BadAggregateConfigurationRejected; - continue; - } - - // Processed is SINGLE-SHOT (no continuation point). Unlike Raw, ReadProcessedDetails carries - // NO client count cap (NumValuesPerNode) — the bucket count is deterministic (window / interval) - // and the single-shot backend returns every bucket in one read, so there is no "full page ⇒ - // maybe more" signal to page on. Returning the complete aggregate result with a null CP is - // spec-conformant (OPC UA Part 11 lets a server return all available data in one response). - var agg = aggregate.Value; - work.Add(() => ServeNodeAsync(handle, results, errors, (source, tagname, token) => source.ReadProcessedAsync( - tagname, - SdkValueBoundary.ToClrTimestamp(details.StartTime), - SdkValueBoundary.ToClrTimestamp(details.EndTime), - interval, - agg, - token), ct)); - } - - RunBounded(work, HistoryReadBatchParallelism); - }); + ServeHistoryReadAdapter(context, details, nodesToRead, nodesToProcess, results, errors); } /// + /// A thin adapter over the history port (): authorize, then serve. protected override void HistoryReadAtTime( ServerSystemContext context, ReadAtTimeDetails details, @@ -8923,28 +8841,8 @@ public sealed class OtOpcUaNodeManager : CustomNodeManager2, INodeManager3, IPro List nodesToProcess, IDictionary cache) { - // Snapshot the requested timestamps once — the same list is read for every node. - var timestamps = (details.ReqTimes.ToArray() ?? []).Select(t => t.ToDateTime()).ToList(); nodesToProcess = AuthorizeHistoryRead(context, nodesToProcess, results, errors); - WithHistoryReadBatchLimiter(nodesToProcess, results, errors, () => - { - using var deadline = CreateDeadline(context); - var ct = deadline?.Token ?? CancellationToken.None; - var work = new List>(nodesToProcess.Count); - foreach (var handle in nodesToProcess) - { - // The node's scalar value type, for a backend whose stored values carry none (the Gateway). - var valueType = AtTimeValueType(handle.NodeId); - work.Add(() => ServeNodeAsync(handle, results, errors, (source, tagname, token) => source.ReadAtTimeAsync( - tagname, - timestamps, - valueType, - token), ct)); - } - - RunBounded(work, HistoryReadBatchParallelism); - }); - NormalizeHistoryValues(nodesToProcess, results); + ServeHistoryReadAdapter(context, details, nodesToRead, nodesToProcess, results, errors); } /// @@ -9137,7 +9035,8 @@ public sealed class OtOpcUaNodeManager : CustomNodeManager2, INodeManager3, IPro // for THIS node only. var state = _historyContinuationStore.TryTake(session, inboundCp.ToArray()); // A point is bound to the node that issued it: another node's source name is a miss too. - if (state is null || !HistoryContinuationMatches(state, handle.NodeId, historyEpoch) || state.Kind != HistoryCursorKind.Events || state.Tagname != sourceName) + var boundKey = MapKey(handle.NodeId); + if (state is null || !HistoryContinuationMatches(state, boundKey.Realm, boundKey.Id, historyEpoch) || state.Kind != HistoryCursorKind.Events || state.Tagname != sourceName) { errors[handle.Index] = StatusCodes.BadContinuationPointInvalid; results[handle.Index] = new SdkHistoryReadResult { StatusCode = StatusCodes.BadContinuationPointInvalid }; @@ -9313,7 +9212,9 @@ public sealed class OtOpcUaNodeManager : CustomNodeManager2, INodeManager3, IPro // ConditionName, as the live event does. Rewritten after paging: EventId and time are untouched. events = scope.ResolveConditions(events); var historyEvent = ProjectEvents(events, selectClauses, where, filterContext); - var outboundCp = pendingCursor is null ? null : SaveHistoryContinuation(session, handle.NodeId, historyEpoch, pendingCursor); + var eventsKey = MapKey(handle.NodeId); + var outboundCp = pendingCursor is null ? null : SaveHistoryContinuation( + SessionHistoryContinuationScope(session), eventsKey.Realm, eventsKey.Id, historyEpoch, details: null, pendingCursor); results[handle.Index] = new SdkHistoryReadResult { // No events ⇒ GoodNoData (the notifier is historized, the window just held no events — or none matched). @@ -9923,9 +9824,8 @@ public sealed class OtOpcUaNodeManager : CustomNodeManager2, INodeManager3, IPro /// tagname and is wrapped in try/catch so a backend throw / timeout becomes a Bad status for /// THIS node without throwing out of the batch. /// - /// The pre-filtered node handle to serve; handle.Index indexes results/errors. - /// The service-level results list to fill at handle.Index. - /// The service-level errors list to fill at handle.Index. + /// The history-port item to serve, addressed by (realm, identifier). + /// The item's outcome to fill (operation status + result). /// Invokes the resolved data-source read with the resolved tagname; only called /// once the tagname is confirmed present. /// @@ -9976,8 +9876,11 @@ public sealed class OtOpcUaNodeManager : CustomNodeManager2, INodeManager3, IPro IList results, IList errors, Action serve) => - WithHistoryBatchLimiter(nodesToProcess, errors, serve, handle => - results[handle.Index] = new SdkHistoryReadResult { StatusCode = StatusCodes.BadTooManyOperations }); + WithHistoryBatchLimiter(nodesToProcess, serve, handle => + { + errors[handle.Index] = StatusCodes.BadTooManyOperations; + results[handle.Index] = new SdkHistoryReadResult { StatusCode = StatusCodes.BadTooManyOperations }; + }); /// /// HistoryUpdate counterpart of : @@ -9993,19 +9896,20 @@ public sealed class OtOpcUaNodeManager : CustomNodeManager2, INodeManager3, IPro IList results, IList errors, Action serve) => - WithHistoryBatchLimiter(nodesToProcess, errors, serve, handle => - results[handle.Index] = new HistoryUpdateResult { StatusCode = StatusCodes.BadTooManyOperations }); + WithHistoryBatchLimiter(nodesToProcess, serve, handle => + { + errors[handle.Index] = StatusCodes.BadTooManyOperations; + results[handle.Index] = new HistoryUpdateResult { StatusCode = StatusCodes.BadTooManyOperations }; + }); - /// Shared body of the HistoryRead / HistoryUpdate batch limiter. - /// The batch's handles. - /// The service-level errors list. + /// Shared body of the HistoryRead / HistoryUpdate batch limiter (SDK handles, or the port's item indices). + /// The batch's nodes. /// The arm body. - /// Fills the per-node result slot when the batch is rejected. - private void WithHistoryBatchLimiter( - List nodesToProcess, - IList errors, + /// Fills the node's operation and result slots when the batch is rejected. + private void WithHistoryBatchLimiter( + IReadOnlyList nodesToProcess, Action serve, - Action rejectResult) + Action rejectResult) { var gate = GetHistoryReadBatchLimiter(); @@ -10017,10 +9921,7 @@ public sealed class OtOpcUaNodeManager : CustomNodeManager2, INodeManager3, IPro if (!gate.Wait(TimeSpan.FromMilliseconds(waitMs))) { foreach (var handle in nodesToProcess) - { - errors[handle.Index] = StatusCodes.BadTooManyOperations; rejectResult(handle); - } return; } @@ -10053,9 +9954,14 @@ public sealed class OtOpcUaNodeManager : CustomNodeManager2, INodeManager3, IPro /// Link the SDK request lifetime to the application's per-batch history deadline. /// The request's server context. /// The linked deadline source, or null when neither request nor application can cancel. - private CancellationTokenSource? CreateDeadline(ServerSystemContext context) + private CancellationTokenSource? CreateDeadline(ServerSystemContext context) => + CreateDeadline(context.OperationContext?.CancellationToken ?? CancellationToken.None); + + /// Link a request lifetime to the application's per-batch history deadline. + /// The request lifetime (the SDK request, or a peer's call). + /// The linked deadline source, or null when neither request nor application can cancel. + private CancellationTokenSource? CreateDeadline(CancellationToken request) { - var request = context.OperationContext?.CancellationToken ?? CancellationToken.None; if (!request.CanBeCanceled && HistoryReadDeadline <= TimeSpan.Zero) return null; var deadline = request.CanBeCanceled ? CancellationTokenSource.CreateLinkedTokenSource(request) @@ -10081,17 +9987,16 @@ public sealed class OtOpcUaNodeManager : CustomNodeManager2, INodeManager3, IPro } private async Task ServeNodeAsync( - NodeHandle handle, - IList results, - IList errors, + HistoryReadPortItem handle, + HistoryReadNodeOutcome outcome, Func> read, CancellationToken ct) { - if (!TryGetHistorizedTagname(handle.NodeId, out var tagname)) + if (!TryGetHistorizedTagname(handle.Identifier, out var tagname, handle.Realm)) { // Not a historized node we own a tagname for — unsupported. (The base pre-seeds this same // status, but set it explicitly so the contract is local + obvious.) - errors[handle.Index] = StatusCodes.BadHistoryOperationUnsupported; + outcome.Error = StatusCodes.BadHistoryOperationUnsupported; return; } @@ -10102,7 +10007,7 @@ public sealed class OtOpcUaNodeManager : CustomNodeManager2, INodeManager3, IPro var sourceResult = await read(HistorianDataSource, tagname!, ct).ConfigureAwait(false); var historyData = ToHistoryData(sourceResult); - results[handle.Index] = new SdkHistoryReadResult + outcome.Result = new SdkHistoryReadResult { // No source samples ⇒ GoodNoData (the node is historized, the window just held no data). StatusCode = historyData.DataValues.Count == 0 ? StatusCodes.GoodNoData : StatusCodes.Good, @@ -10112,39 +10017,39 @@ public sealed class OtOpcUaNodeManager : CustomNodeManager2, INodeManager3, IPro // continuation point. Raw pages via ServeRawPaged, not this helper. ContinuationPoint = default, }; - errors[handle.Index] = ServiceResult.Good; + outcome.Error = ServiceResult.Good; } catch (OperationCanceledException) { // The per-request deadline elapsed while this node was in flight — surface BadTimeout for // THIS node only (a spec-conformant history-read status), ahead of the generic catch. - errors[handle.Index] = StatusCodes.BadTimeout; - results[handle.Index] = new SdkHistoryReadResult { StatusCode = StatusCodes.BadTimeout }; + outcome.Error = StatusCodes.BadTimeout; + outcome.Result = new SdkHistoryReadResult { StatusCode = StatusCodes.BadTimeout }; } catch (HistoryAggregateNotSupportedException ex) { // The backend cannot serve this Part 13 aggregate — the spec status for THIS node, // not a logged server fault. - _logger.LogDebug(ex, "OtOpcUaNodeManager: backend does not support aggregate for node {NodeId}", handle.NodeId); - errors[handle.Index] = StatusCodes.BadAggregateNotSupported; - results[handle.Index] = new SdkHistoryReadResult { StatusCode = StatusCodes.BadAggregateNotSupported }; + _logger.LogDebug(ex, "OtOpcUaNodeManager: backend does not support aggregate for node {NodeId}", handle); + outcome.Error = StatusCodes.BadAggregateNotSupported; + outcome.Result = new SdkHistoryReadResult { StatusCode = StatusCodes.BadAggregateNotSupported }; } catch (HistoryReadLimitExceededException ex) { // The read would exceed a backend size limit (the time-weighted raw-row cap) — refuse THIS node // explicitly instead of a generic fault or a deadline-elapsed BadTimeout. - _logger.LogWarning("OtOpcUaNodeManager: HistoryRead limit exceeded for node {NodeId}: {Message}", handle.NodeId, ex.Message); - errors[handle.Index] = StatusCodes.BadTooManyOperations; - results[handle.Index] = new SdkHistoryReadResult { StatusCode = StatusCodes.BadTooManyOperations }; + _logger.LogWarning("OtOpcUaNodeManager: HistoryRead limit exceeded for node {NodeId}: {Message}", handle, ex.Message); + outcome.Error = StatusCodes.BadTooManyOperations; + outcome.Result = new SdkHistoryReadResult { StatusCode = StatusCodes.BadTooManyOperations }; } catch (Exception ex) { // One node's backend failure (throw / timeout) must not throw out of the batch — surface a // Bad status for THIS node only. Logged through the injected ILogger // rather than swallowed silently. - _logger.LogError(ex, "OtOpcUaNodeManager: HistoryRead failed for node {NodeId}", handle.NodeId); - errors[handle.Index] = HistoryReadFailureStatus(ex); - results[handle.Index] = new SdkHistoryReadResult { StatusCode = HistoryReadFailureStatus(ex) }; + _logger.LogError(ex, "OtOpcUaNodeManager: HistoryRead failed for node {NodeId}", handle); + outcome.Error = HistoryReadFailureStatus(ex); + outcome.Result = new SdkHistoryReadResult { StatusCode = HistoryReadFailureStatus(ex) }; } } @@ -10174,12 +10079,11 @@ public sealed class OtOpcUaNodeManager : CustomNodeManager2, INodeManager3, IPro /// isolation matches : a backend throw / an unknown continuation point /// becomes a Bad status for THIS node only and never throws out of the batch. /// - /// The pre-filtered node handle; handle.Index indexes results/errors. - /// The session the read runs under (null on the session-less in-process path). - /// The per-node read list; nodesToRead[handle.Index].ContinuationPoint - /// carries the inbound continuation point (non-null ⇒ a resume read). - /// The service-level results list to fill at handle.Index. - /// The service-level errors list to fill at handle.Index. + /// The history-port item, addressed by (realm, identifier); its + /// (non-empty ⇒ a resume read) is the inbound point. + /// The item's outcome to fill (operation status + result). + /// The caller's continuation scope (the SDK session, or a remote peer's store). + /// The request details, bound into a peer continuation. /// The request window's (inclusive) lower bound, used for a fresh read. /// The (inclusive) upper bound of the read window; unchanged across pages. /// The client's per-page cap; 0 means "all values, no paging". @@ -10189,11 +10093,10 @@ public sealed class OtOpcUaNodeManager : CustomNodeManager2, INodeManager3, IPro /// ends the last, and both count toward . A resumed read takes it from the cursor. /// private async Task ServeRawPagedAsync( - NodeHandle handle, - ISession? session, - ArrayOf nodesToRead, - IList results, - IList errors, + HistoryReadPortItem handle, + HistoryReadNodeOutcome outcome, + IHistoryContinuationScope continuations, + HistoryReadVariant details, DateTime startTimeUtc, DateTime endUtc, uint numValuesPerNode, @@ -10201,7 +10104,7 @@ public sealed class OtOpcUaNodeManager : CustomNodeManager2, INodeManager3, IPro bool returnBounds = false) { var historyEpoch = Volatile.Read(ref _historyContinuationEpoch); - var inboundCp = nodesToRead[handle.Index].ContinuationPoint; + var inboundCp = handle.ContinuationPoint; try { @@ -10216,12 +10119,12 @@ public sealed class OtOpcUaNodeManager : CustomNodeManager2, INodeManager3, IPro { // Resume read: take the stored cursor. A miss (unknown / evicted / malformed point) ⇒ // BadContinuationPointInvalid for THIS node. - var state = _historyContinuationStore.TryTake(session, inboundCp.ToArray()); - if (state is null || !HistoryContinuationMatches(state, handle.NodeId, historyEpoch) || state.Kind != HistoryCursorKind.Raw - || !TryGetHistorizedTagname(handle.NodeId, out var boundTag) || boundTag != state.Tagname) + var state = continuations.TryTake(inboundCp, new HistoryContinuationBinding(handle.Realm, handle.Identifier, historyEpoch, details)); + if (state is null || !HistoryContinuationMatches(state, handle.Realm, handle.Identifier, historyEpoch) || state.Kind != HistoryCursorKind.Raw + || !TryGetHistorizedTagname(handle.Identifier, out var boundTag, handle.Realm) || boundTag != state.Tagname) { - errors[handle.Index] = StatusCodes.BadContinuationPointInvalid; - results[handle.Index] = new SdkHistoryReadResult { StatusCode = StatusCodes.BadContinuationPointInvalid }; + outcome.Error = StatusCodes.BadContinuationPointInvalid; + outcome.Result = new SdkHistoryReadResult { StatusCode = StatusCodes.BadContinuationPointInvalid }; return; } @@ -10237,9 +10140,9 @@ public sealed class OtOpcUaNodeManager : CustomNodeManager2, INodeManager3, IPro else { // Fresh read: resolve the node's historian tagname (as ServeNode does). - if (!TryGetHistorizedTagname(handle.NodeId, out var resolved) || resolved is null) + if (!TryGetHistorizedTagname(handle.Identifier, out var resolved, handle.Realm) || resolved is null) { - errors[handle.Index] = StatusCodes.BadHistoryOperationUnsupported; + outcome.Error = StatusCodes.BadHistoryOperationUnsupported; return; } @@ -10284,7 +10187,7 @@ public sealed class OtOpcUaNodeManager : CustomNodeManager2, INodeManager3, IPro return null; } - return SaveHistoryContinuation(session, handle.NodeId, historyEpoch, new HistoryContinuationState( + return SaveHistoryContinuation(continuations, handle.Realm, handle.Identifier, historyEpoch, details, new HistoryContinuationState( tagname, previous, endUtc, 0, numValuesPerNode, SegmentWidthTicks: walkHint.WidthTicks, EmptyFromTicks: walkHint.EmptyFromTicks, EmptyToTicks: walkHint.EmptyToTicks, PendingEndBound: HistoryBounds.Carry(endBound!, page)! with { DataExhausted = true })); @@ -10323,13 +10226,13 @@ public sealed class OtOpcUaNodeManager : CustomNodeManager2, INodeManager3, IPro { var onlyBound = new List(1); var afterCp = await AppendEndBoundAsync(onlyBound, startUtc, numValuesPerNode).ConfigureAwait(false); - results[handle.Index] = new SdkHistoryReadResult + outcome.Result = new SdkHistoryReadResult { StatusCode = StatusCodes.Good, HistoryData = new ExtensionObject(ToHistoryDataFromSamples(onlyBound)), ContinuationPoint = afterCp is null ? default : ByteString.From(afterCp), }; - errors[handle.Index] = ServiceResult.Good; + outcome.Error = ServiceResult.Good; return; } @@ -10350,30 +10253,30 @@ public sealed class OtOpcUaNodeManager : CustomNodeManager2, INodeManager3, IPro if (startBound is not null && numValuesPerNode == 1 && anything) { // The page is the start bound alone; the data starts at StartTime on the next page. - var boundOnlyCp = SaveHistoryContinuation(session, handle.NodeId, historyEpoch, new HistoryContinuationState( + var boundOnlyCp = SaveHistoryContinuation(continuations, handle.Realm, handle.Identifier, historyEpoch, details, new HistoryContinuationState( tagname, startUtc, endUtc, 0, numValuesPerNode, SegmentWidthTicks: walkHint.WidthTicks, EmptyFromTicks: walkHint.EmptyFromTicks, EmptyToTicks: walkHint.EmptyToTicks, PendingEndBound: HistoryBounds.Carry(pending, [startBound]))); - results[handle.Index] = new SdkHistoryReadResult + outcome.Result = new SdkHistoryReadResult { StatusCode = StatusCodes.Good, HistoryData = new ExtensionObject(ToHistoryDataFromSamples([startBound])), ContinuationPoint = boundOnlyCp is null ? default : ByteString.From(boundOnlyCp), }; - errors[handle.Index] = ServiceResult.Good; + outcome.Error = ServiceResult.Good; return; } if (startBound is not null && numValuesPerNode == 1) { // Nothing at all — no data and no bound found: the pre-bounds GoodNoData answer. - results[handle.Index] = new SdkHistoryReadResult + outcome.Result = new SdkHistoryReadResult { StatusCode = StatusCodes.GoodNoData, HistoryData = new ExtensionObject(ToHistoryDataFromSamples([])), ContinuationPoint = default, }; - errors[handle.Index] = ServiceResult.Good; + outcome.Error = ServiceResult.Good; return; } @@ -10504,8 +10407,8 @@ public sealed class OtOpcUaNodeManager : CustomNodeManager2, INodeManager3, IPro "exceeding {Max} (MaxTieClusterOverfetch, or the backend's row ceiling less one); cannot page within it. " + "Increase MaxTieClusterOverfetch (or the HistorianGateway MaxValuesCeiling).", startUtc, tagname, cluster.Count, overfetchBound); - errors[handle.Index] = StatusCodes.BadTooManyOperations; - results[handle.Index] = new SdkHistoryReadResult { StatusCode = StatusCodes.BadTooManyOperations }; + outcome.Error = StatusCodes.BadTooManyOperations; + outcome.Result = new SdkHistoryReadResult { StatusCode = StatusCodes.BadTooManyOperations }; return; } @@ -10537,7 +10440,7 @@ public sealed class OtOpcUaNodeManager : CustomNodeManager2, INodeManager3, IPro EmptyFromTicks: walkHint.EmptyFromTicks, EmptyToTicks: walkHint.EmptyToTicks, PendingEndBound: HistoryBounds.Carry(endBound, slice), WithinTieCluster: resumeAt == startUtc); - clusterCp = SaveHistoryContinuation(session, handle.NodeId, historyEpoch, clusterState); + clusterCp = SaveHistoryContinuation(continuations, handle.Realm, handle.Identifier, historyEpoch, details, clusterState); } else if (endBound is not null) { @@ -10549,13 +10452,13 @@ public sealed class OtOpcUaNodeManager : CustomNodeManager2, INodeManager3, IPro clusterCp = await AppendEndBoundAsync(slice, startUtc, clusterAllowance).ConfigureAwait(false); } - results[handle.Index] = new SdkHistoryReadResult + outcome.Result = new SdkHistoryReadResult { StatusCode = slice.Count == 0 ? StatusCodes.GoodNoData : StatusCodes.Good, HistoryData = new ExtensionObject(ToHistoryDataFromSamples(slice)), ContinuationPoint = clusterCp is null ? default : ByteString.From(clusterCp), }; - errors[handle.Index] = ServiceResult.Good; + outcome.Error = ServiceResult.Good; return; } @@ -10592,7 +10495,7 @@ public sealed class OtOpcUaNodeManager : CustomNodeManager2, INodeManager3, IPro { // Save may return null (no session on this request) ⇒ degrade to single-shot for this node. // Built AFTER historyData so a failure projecting samples can never orphan a stored cursor. - outboundCp = SaveHistoryContinuation(session, handle.NodeId, historyEpoch, nextState); + outboundCp = SaveHistoryContinuation(continuations, handle.Realm, handle.Identifier, historyEpoch, details, nextState); } else if (endBound is not null) { @@ -10615,7 +10518,7 @@ public sealed class OtOpcUaNodeManager : CustomNodeManager2, INodeManager3, IPro historyData = ToHistoryDataFromSamples(samples); } - results[handle.Index] = new SdkHistoryReadResult + outcome.Result = new SdkHistoryReadResult { // No samples ⇒ GoodNoData (the node is historized, the window just held no data). With the // degenerate-cluster guard above, a resumed empty page now only means the window/cluster is @@ -10624,28 +10527,28 @@ public sealed class OtOpcUaNodeManager : CustomNodeManager2, INodeManager3, IPro HistoryData = new ExtensionObject(historyData), ContinuationPoint = outboundCp is null ? default : ByteString.From(outboundCp), }; - errors[handle.Index] = ServiceResult.Good; + outcome.Error = ServiceResult.Good; } catch (OperationCanceledException) { // The per-request deadline elapsed while paging this node — BadTimeout for THIS node only. - errors[handle.Index] = StatusCodes.BadTimeout; - results[handle.Index] = new SdkHistoryReadResult { StatusCode = StatusCodes.BadTimeout }; + outcome.Error = StatusCodes.BadTimeout; + outcome.Result = new SdkHistoryReadResult { StatusCode = StatusCodes.BadTimeout }; } catch (HistoryReadLimitExceededException ex) { // A request limit (a reverse read walked back from forward reads met a tie cluster over the row // budget) — BadTooManyOperations for THIS node, as on the processed path; not a backend fault. - _logger.LogWarning("OtOpcUaNodeManager: HistoryReadRaw limit exceeded for node {NodeId}: {Message}", handle.NodeId, ex.Message); - errors[handle.Index] = StatusCodes.BadTooManyOperations; - results[handle.Index] = new SdkHistoryReadResult { StatusCode = StatusCodes.BadTooManyOperations }; + _logger.LogWarning("OtOpcUaNodeManager: HistoryReadRaw limit exceeded for node {NodeId}: {Message}", handle, ex.Message); + outcome.Error = StatusCodes.BadTooManyOperations; + outcome.Result = new SdkHistoryReadResult { StatusCode = StatusCodes.BadTooManyOperations }; } catch (Exception ex) { // One node's backend failure must not throw out of the batch — Bad for THIS node only. - _logger.LogError(ex, "OtOpcUaNodeManager: HistoryReadRaw (paged) failed for node {NodeId}", handle.NodeId); - errors[handle.Index] = HistoryReadFailureStatus(ex); - results[handle.Index] = new SdkHistoryReadResult { StatusCode = HistoryReadFailureStatus(ex) }; + _logger.LogError(ex, "OtOpcUaNodeManager: HistoryReadRaw (paged) failed for node {NodeId}", handle); + outcome.Error = HistoryReadFailureStatus(ex); + outcome.Result = new SdkHistoryReadResult { StatusCode = HistoryReadFailureStatus(ex) }; } } @@ -10659,34 +10562,32 @@ public sealed class OtOpcUaNodeManager : CustomNodeManager2, INodeManager3, IPro /// point is BadContinuationPointInvalid. A backend that keeps no trail (Gateway, Null) throws /// ⇒ BadHistoryOperationUnsupported for this node. /// - /// The node handle; handle.Index indexes results/errors. - /// The session (null on the session-less in-process path ⇒ single-shot). - /// The per-node read list (inbound continuation points). - /// The service-level results list. - /// The service-level errors list. + /// The history-port item (inbound continuation point included). + /// The item's outcome to fill. + /// The caller's continuation scope (a session-less scope ⇒ single-shot). + /// The request details, bound into a peer continuation. /// Request StartTime. /// Request EndTime. /// Per-page cap; 0 = all. /// Request deadline. private async Task ServeModifiedPagedAsync( - NodeHandle handle, - ISession? session, - ArrayOf nodesToRead, - IList results, - IList errors, + HistoryReadPortItem handle, + HistoryReadNodeOutcome outcome, + IHistoryContinuationScope continuations, + HistoryReadVariant details, DateTime startTimeUtc, DateTime endUtc, uint numValuesPerNode, CancellationToken ct) { var historyEpoch = Volatile.Read(ref _historyContinuationEpoch); - var inboundCp = nodesToRead[handle.Index].ContinuationPoint; + var inboundCp = handle.ContinuationPoint; try { - if (!TryGetHistorizedTagname(handle.NodeId, out var tagname) || tagname is null) + if (!TryGetHistorizedTagname(handle.Identifier, out var tagname, handle.Realm) || tagname is null) { - errors[handle.Index] = StatusCodes.BadHistoryOperationUnsupported; - results[handle.Index] = new SdkHistoryReadResult { StatusCode = StatusCodes.BadHistoryOperationUnsupported }; + outcome.Error = StatusCodes.BadHistoryOperationUnsupported; + outcome.Result = new SdkHistoryReadResult { StatusCode = StatusCodes.BadHistoryOperationUnsupported }; return; } @@ -10694,11 +10595,11 @@ public sealed class OtOpcUaNodeManager : CustomNodeManager2, INodeManager3, IPro HistoryModifiedCursor? resumeAfter = null; if (inboundCp is { Length: > 0 }) { - var state = _historyContinuationStore.TryTake(session, inboundCp.ToArray()); - if (state is null || !HistoryContinuationMatches(state, handle.NodeId, historyEpoch) || state.Kind != HistoryCursorKind.Modified || state.Tagname != tagname) + var state = continuations.TryTake(inboundCp, new HistoryContinuationBinding(handle.Realm, handle.Identifier, historyEpoch, details)); + if (state is null || !HistoryContinuationMatches(state, handle.Realm, handle.Identifier, historyEpoch) || state.Kind != HistoryCursorKind.Modified || state.Tagname != tagname) { - errors[handle.Index] = StatusCodes.BadContinuationPointInvalid; - results[handle.Index] = new SdkHistoryReadResult { StatusCode = StatusCodes.BadContinuationPointInvalid }; + outcome.Error = StatusCodes.BadContinuationPointInvalid; + outcome.Result = new SdkHistoryReadResult { StatusCode = StatusCodes.BadContinuationPointInvalid }; return; } @@ -10725,36 +10626,36 @@ public sealed class OtOpcUaNodeManager : CustomNodeManager2, INodeManager3, IPro if (page.HasMore && numValuesPerNode > 0 && page.Values.Count > 0) { var last = page.Values[^1]; - outboundCp = SaveHistoryContinuation(session, handle.NodeId, historyEpoch, new HistoryContinuationState( + outboundCp = SaveHistoryContinuation(continuations, handle.Realm, handle.Identifier, historyEpoch, details, new HistoryContinuationState( tagname, last.SourceTimeUtc, endUtc, 0, numValuesPerNode, HistoryCursorKind.Modified, last.ModifiedId, startUtc)); } - results[handle.Index] = new SdkHistoryReadResult + outcome.Result = new SdkHistoryReadResult { StatusCode = page.Values.Count == 0 ? StatusCodes.GoodNoData : StatusCodes.Good, HistoryData = new ExtensionObject(data), ContinuationPoint = outboundCp is null ? default : ByteString.From(outboundCp), }; - errors[handle.Index] = ServiceResult.Good; + outcome.Error = ServiceResult.Good; } catch (OperationCanceledException) { - errors[handle.Index] = StatusCodes.BadTimeout; - results[handle.Index] = new SdkHistoryReadResult { StatusCode = StatusCodes.BadTimeout }; + outcome.Error = StatusCodes.BadTimeout; + outcome.Result = new SdkHistoryReadResult { StatusCode = StatusCodes.BadTimeout }; } catch (NotSupportedException ex) { // The backend keeps no modification trail (Gateway / Null) — the spec status, not a server fault. - _logger.LogDebug(ex, "OtOpcUaNodeManager: backend serves no modified-value history for node {NodeId}", handle.NodeId); - errors[handle.Index] = StatusCodes.BadHistoryOperationUnsupported; - results[handle.Index] = new SdkHistoryReadResult { StatusCode = StatusCodes.BadHistoryOperationUnsupported }; + _logger.LogDebug(ex, "OtOpcUaNodeManager: backend serves no modified-value history for node {NodeId}", handle); + outcome.Error = StatusCodes.BadHistoryOperationUnsupported; + outcome.Result = new SdkHistoryReadResult { StatusCode = StatusCodes.BadHistoryOperationUnsupported }; } catch (Exception ex) { - _logger.LogError(ex, "OtOpcUaNodeManager: HistoryRead (modified) failed for node {NodeId}", handle.NodeId); - errors[handle.Index] = HistoryReadFailureStatus(ex); - results[handle.Index] = new SdkHistoryReadResult { StatusCode = HistoryReadFailureStatus(ex) }; + _logger.LogError(ex, "OtOpcUaNodeManager: HistoryRead (modified) failed for node {NodeId}", handle); + outcome.Error = HistoryReadFailureStatus(ex); + outcome.Result = new SdkHistoryReadResult { StatusCode = HistoryReadFailureStatus(ex) }; } } @@ -10803,18 +10704,6 @@ public sealed class OtOpcUaNodeManager : CustomNodeManager2, INodeManager3, IPro } } - private byte[]? SaveHistoryContinuation(ISession? session, NodeId nodeId, long epoch, HistoryContinuationState state) - { - if (epoch != Volatile.Read(ref _historyContinuationEpoch)) return null; - return _historyContinuationStore.Save(session, state with - { - BoundNodeKey = nodeId.ToString(), AddressSpaceEpoch = epoch, - }); - } - - private static bool HistoryContinuationMatches(HistoryContinuationState state, NodeId nodeId, long epoch) => - state.BoundNodeKey == nodeId.ToString() && state.AddressSpaceEpoch == epoch; - /// Transport failures are retryable; unsupported operations retain their distinct status. private static StatusCode HistoryReadFailureStatus(Exception error) { @@ -10824,38 +10713,6 @@ public sealed class OtOpcUaNodeManager : CustomNodeManager2, INodeManager3, IPro return StatusCodes.BadHistoryOperationUnsupported; } - /// Normalize stored and AtTime history to each scalar node's declared DataType. - private void NormalizeHistoryValues(List handles, IList results) - { - foreach (var handle in handles) - { - if (AtTimeValueType(handle.NodeId) is not { } type || results[handle.Index]?.HistoryData is not { } body) continue; - if (body.IsNull || ExtensionObject.ToEncodeable(body) is not HistoryData data) continue; - var values = data.DataValues.ToArray() ?? []; - for (var i = 0; i < values.Length; i++) - { - var value = values[i]; - var payload = SdkValueBoundary.ToClr(value.WrappedValue); - if (payload is null) continue; - try - { - // A gateway number cannot reconstruct a DateTime or a String which was never stored. - if ((type == TypeCode.DateTime && payload is not DateTime) - || (type == TypeCode.String && payload is not string)) throw new InvalidCastException(); - var converted = Convert.ChangeType(payload, type, System.Globalization.CultureInfo.InvariantCulture); - if (converted is float f && float.IsInfinity(f) && payload is double d && double.IsFinite(d)) - throw new OverflowException(); - values[i] = value.WithWrappedValue(SdkValueBoundary.FromClr(converted)); - } - catch (Exception ex) when (ex is InvalidCastException or OverflowException or FormatException) - { - values[i] = value.WithWrappedValue(Variant.Null).WithStatus(StatusCodes.BadTypeMismatch); - } - } - data.DataValues = values; - } - } - /// Project a plain sample list into an SDK (the paged Raw path /// works on a trimmed rather than a whole ). /// The samples to project (already trimmed of boundary duplicates). diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/PeerHistoryContinuationStore.cs b/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/PeerHistoryContinuationStore.cs new file mode 100644 index 000000000..6187d641a --- /dev/null +++ b/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/PeerHistoryContinuationStore.cs @@ -0,0 +1,205 @@ +using System.Security.Cryptography; +using ZB.MOM.WW.OtOpcUa.Commons.OpcUa; + +namespace ZB.MOM.WW.OtOpcUa.OpcUaServer; + +/// +/// Everything a peer continuation is bound to (plan §3.2): the authenticated principal, the serving incarnation +/// (an origin restart or failover changes it), the history epoch (a rebuild/removal bumps it), the view +/// (realm, identifier) and the hash of the request details. +/// +/// The authenticated principal of the connection. +/// The serving incarnation the cursor was issued under. +/// The history (address-space) epoch. +/// The view's realm. +/// The view's identifier. +/// The of the request. +internal readonly record struct PeerHistoryContinuationKey( + string Principal, string ServingIncarnation, long Epoch, AddressSpaceRealm Realm, string Identifier, string DetailsHash); + +/// +/// The ORIGIN-side store for remote peers' HistoryRead continuation points (gRPC data history plan §3.2, phase H1; +/// wired to the RPC by H2). One instance per (authenticated principal, connection incarnation), so no peer can ever +/// reach another's cursors; unlike the SDK session store () there is no +/// session to own the points, so this store owns lifetime itself. +/// +/// Token: a fresh random 16-byte id (). Unguessable, so no MAC is needed; it +/// carries nothing — the state stays here. +/// Binding: each record binds the principal, serving incarnation, history epoch, view and details hash; a +/// take whose expected differs in ANY of them is a miss +/// (BadContinuationPointInvalid at the port). +/// Single-use: a take removes the record whether or not it matches, so a page lost in transit makes the +/// client's resume fail rather than silently skipping a page, and a token can never be replayed. +/// Idle expiry: a record not taken within (default 60 s, matching v1 browse +/// continuations) is gone — the backstop for a consumer that never resumes or releases. +/// Capacity: at most live records (the export limit). Saving past it evicts the +/// oldest-idle record — the one saved longest ago, since a record is never touched between its save and its +/// (single-use) take — after expired ones are swept. Eviction is silent; the evicted token's resume is a miss. +/// +/// Thread-safe; every operation is O(1) amortised under one short lock, and no I/O ever runs under it. +/// +internal sealed class PeerHistoryContinuationStore +{ + /// The default idle expiry (60 s, as v1 browse continuations). + public static readonly TimeSpan DefaultIdleExpiry = TimeSpan.FromSeconds(60); + + /// The token length in bytes. + public const int TokenLength = 16; + + private readonly Lock _gate = new(); + private readonly Dictionary> _entries = new(); + private readonly LinkedList _byAge = new(); // oldest save first == oldest idle first + private readonly TimeProvider _clock; + + /// Creates the store of one (principal, connection incarnation). + /// The authenticated principal. + /// This server's serving incarnation at connection time. + /// The export limit on concurrent continuations (≥ 1). + /// Idle expiry; null = . Must be positive. + /// Clock (tests inject a fake); null = system. + public PeerHistoryContinuationStore( + string principal, string servingIncarnation, int capacity, TimeSpan? idleExpiry = null, TimeProvider? clock = null) + { + ArgumentException.ThrowIfNullOrWhiteSpace(principal); + ArgumentException.ThrowIfNullOrWhiteSpace(servingIncarnation); + ArgumentOutOfRangeException.ThrowIfLessThan(capacity, 1); + var idle = idleExpiry ?? DefaultIdleExpiry; + ArgumentOutOfRangeException.ThrowIfLessThanOrEqual(idle, TimeSpan.Zero, nameof(idleExpiry)); + Principal = principal; + ServingIncarnation = servingIncarnation; + Capacity = capacity; + IdleExpiry = idle; + _clock = clock ?? TimeProvider.System; + } + + /// The principal this instance serves. + public string Principal { get; } + + /// The connection's serving incarnation. + public string ServingIncarnation { get; } + + /// The most live records. + public int Capacity { get; } + + /// How long an untaken record lives. + public TimeSpan IdleExpiry { get; } + + /// Live (unexpired) records — H3's "origin store count returns to 0" check reads it. + public int Count + { + get + { + lock (_gate) + { + Sweep(_clock.GetTimestamp()); + return _entries.Count; + } + } + } + + /// + /// Stores under a fresh token, bound to this instance's principal and incarnation, the + /// state's own epoch and view ( / + /// , set by the port) and . + /// + /// The bound resume state. + /// The request's details hash. + /// The 16-byte token. + public byte[] Save(HistoryContinuationState state, string detailsHash) + { + ArgumentNullException.ThrowIfNull(state); + ArgumentNullException.ThrowIfNull(detailsHash); + if (state.BoundIdentifier is null) + throw new ArgumentException("A peer continuation must be bound to its view.", nameof(state)); + + var token = RandomNumberGenerator.GetBytes(TokenLength); + var key = new PeerHistoryContinuationKey( + Principal, ServingIncarnation, state.AddressSpaceEpoch, state.BoundRealm, state.BoundIdentifier, detailsHash); + lock (_gate) + { + var now = _clock.GetTimestamp(); + Sweep(now); + while (_entries.Count >= Capacity && _byAge.First is { } oldest) Remove(oldest); + var id = new Guid(token); + _entries[id] = _byAge.AddLast(new Entry(id, key, state, now)); + } + + return token; + } + + /// + /// Takes (removes) the record behind and returns its state when it is live and every bound + /// field equals ; otherwise null. The record is consumed either way. + /// + /// The token the peer handed back. + /// What the resume must match. + /// The state, or null (unknown, expired, evicted, malformed or mismatched). + public HistoryContinuationState? TryTake(byte[]? token, PeerHistoryContinuationKey expected) + { + if (token is not { Length: TokenLength }) return null; + lock (_gate) + { + var now = _clock.GetTimestamp(); + Sweep(now); + if (!_entries.TryGetValue(new Guid(token), out var node)) return null; + Remove(node); + return node.Value.Key == expected ? node.Value.State : null; + } + } + + /// Drops a record without reading it (release_continuations). Idempotent. + /// The token to release. + /// Whether a live record was dropped. + public bool Release(byte[]? token) + { + if (token is not { Length: TokenLength }) return false; + lock (_gate) + { + if (!_entries.TryGetValue(new Guid(token), out var node)) return false; + Remove(node); + return true; + } + } + + /// Drops every record (the connection closed). + public void Clear() + { + lock (_gate) + { + _entries.Clear(); + _byAge.Clear(); + } + } + + private void Sweep(long now) + { + while (_byAge.First is { } oldest && _clock.GetElapsedTime(oldest.Value.SavedAt, now) >= IdleExpiry) Remove(oldest); + } + + private void Remove(LinkedListNode node) + { + _entries.Remove(node.Value.Id); + _byAge.Remove(node); + } + + private sealed record Entry(Guid Id, PeerHistoryContinuationKey Key, HistoryContinuationState State, long SavedAt); +} + +/// +/// The port's continuation scope for one remote peer: saves and takes through that peer's +/// , binding the request's details hash and this instance's principal and +/// incarnation on top of the view and epoch the port itself re-checks. +/// +/// The (principal, incarnation) store. +internal sealed class PeerHistoryContinuationScope(PeerHistoryContinuationStore store) : IHistoryContinuationScope +{ + /// + public byte[]? Save(HistoryContinuationState state, HistoryContinuationBinding binding) => + store.Save(state, binding.Details?.ComputeDetailsHash() ?? string.Empty); + + /// + public HistoryContinuationState? TryTake(byte[] continuationPoint, HistoryContinuationBinding binding) => + store.TryTake(continuationPoint, new PeerHistoryContinuationKey( + store.Principal, store.ServingIncarnation, binding.Epoch, binding.Realm, binding.Identifier, + binding.Details?.ComputeDetailsHash() ?? string.Empty)); +}