feat(grpc-data): H3 SDK side of projected history
Projected variables advertise Historizing + the HistoryRead access bit (never HistoryWrite) only when the definition says so. The Raw/Processed/AtTime overrides split authorized handles: local ones go to the H1 port unchanged, projected ones to IProjectedHistoryAccess, each written back to its own slot; nothing waits under Lock. HistoryCursorKind.Remote stores the projection's cursor in the SDK session store; disposing the point (session close, eviction, releaseContinuationPoints, faulted request) releases it at the origin. Mapped HistoryRead is opened deliberately in DataPlaneAuthorizer; other mapped operations outside the allowlist stay closed.
This commit is contained in:
@@ -87,7 +87,10 @@ internal sealed class SessionHistoryContinuationStore : IHistoryContinuationStor
|
||||
// RestoreHistoryContinuationPoint REMOVES the slot (single-use) and returns null for an unknown /
|
||||
// malformed (non-16-byte) point — exactly the "miss ⇒ BadContinuationPointInvalid" contract.
|
||||
using var point = session.ContinuationPoints.RestoreHistory(ByteString.From(continuationPoint));
|
||||
return (point as SessionHistoryPoint)?.State;
|
||||
if (point is not SessionHistoryPoint taken) return null;
|
||||
// A take hands the state (and an H3 remote cursor) back to the caller: disposing the slot must not release it.
|
||||
taken.Taken = true;
|
||||
return taken.State;
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
@@ -98,8 +101,15 @@ internal sealed class SessionHistoryContinuationStore : IHistoryContinuationStor
|
||||
{
|
||||
public Guid Id { get; } = id;
|
||||
public HistoryContinuationState State { get; } = state;
|
||||
// The immutable resume state contains managed value data only. No handles or owned resources.
|
||||
public void Dispose() { }
|
||||
public bool Taken { get; set; }
|
||||
|
||||
// Local resume state is managed values only. An H3 remote cursor holds an origin continuation: the SDK disposes the
|
||||
// point on session close, oldest-eviction, releaseContinuationPoints and a faulted request — each of those (never a
|
||||
// take) releases it at the origin, best effort (the origin's idle expiry is the backstop).
|
||||
public void Dispose()
|
||||
{
|
||||
if (!Taken) State.Remote?.Release();
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -132,7 +142,7 @@ internal sealed class InMemoryHistoryContinuationStore(int capacity = 100) : IHi
|
||||
while (_states.Count >= _capacity && _order.Count > 0)
|
||||
{
|
||||
var oldest = _order.Dequeue();
|
||||
_states.Remove(oldest);
|
||||
if (_states.Remove(oldest, out var evicted)) evicted.Remote?.Release();
|
||||
}
|
||||
|
||||
_states[id] = state;
|
||||
@@ -160,9 +170,29 @@ internal sealed class InMemoryHistoryContinuationStore(int capacity = 100) : IHi
|
||||
{
|
||||
if (continuationPoint is null || continuationPoint.Length != 16) return;
|
||||
var id = new Guid(continuationPoint);
|
||||
HistoryContinuationState? released;
|
||||
lock (_gate)
|
||||
{
|
||||
_states.Remove(id);
|
||||
_states.Remove(id, out released);
|
||||
}
|
||||
|
||||
released?.Remote?.Release();
|
||||
}
|
||||
|
||||
/// <summary>Live entries (tests).</summary>
|
||||
public int Count { get { lock (_gate) return _states.Count; } }
|
||||
|
||||
/// <summary>Drops every entry as an SDK session close does — releasing remote cursors (tests).</summary>
|
||||
public void Clear()
|
||||
{
|
||||
HistoryContinuationState[] all;
|
||||
lock (_gate)
|
||||
{
|
||||
all = _states.Values.ToArray();
|
||||
_states.Clear();
|
||||
_order.Clear();
|
||||
}
|
||||
|
||||
foreach (var state in all) state.Remote?.Release();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -98,7 +98,8 @@ internal sealed record HistoryContinuationState(
|
||||
AddressSpaceRealm BoundRealm = default,
|
||||
string? BoundIdentifier = null,
|
||||
string? BoundTag = null,
|
||||
long AddressSpaceEpoch = -1)
|
||||
long AddressSpaceEpoch = -1,
|
||||
ProjectedHistoryContinuation? Remote = null)
|
||||
{
|
||||
/// <summary>The walk-back hint this cursor carries.</summary>
|
||||
public ReverseWalkHint WalkHint => new(SegmentWidthTicks, EmptyFromTicks, EmptyToTicks);
|
||||
@@ -115,6 +116,12 @@ internal enum HistoryCursorKind
|
||||
|
||||
/// <summary>HistoryReadRaw with <c>IsReadModified = true</c> — the Part 11 modification trail.</summary>
|
||||
Modified,
|
||||
|
||||
/// <summary>
|
||||
/// H3: a projected node's remote cursor (<see cref="HistoryContinuationState.Remote"/>) — an origin token plus what the
|
||||
/// projection bound it to. Disposing the stored point (session close, eviction, release) releases it at the origin.
|
||||
/// </summary>
|
||||
Remote,
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
|
||||
@@ -0,0 +1,86 @@
|
||||
using Opc.Ua;
|
||||
using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections;
|
||||
using ZB.MOM.WW.OtOpcUa.OpcUaServer.Security;
|
||||
|
||||
namespace ZB.MOM.WW.OtOpcUa.OpcUaServer;
|
||||
|
||||
/// <summary>
|
||||
/// H3 — the remote cursor behind a <see cref="HistoryCursorKind.Remote"/> continuation point in the consumer's SDK session
|
||||
/// store (gRPC data history plan §3.2). Opaque to the node manager: the projection side (Runtime) owns what it binds —
|
||||
/// the origin token, mapping id/revision, serving incarnation, projection generation, caller key and the ORIGINAL request
|
||||
/// details — and re-checks all of it on resume. The node manager only binds it to the projected node it was issued for.
|
||||
/// </summary>
|
||||
public abstract class ProjectedHistoryContinuation
|
||||
{
|
||||
private int _released;
|
||||
|
||||
/// <summary>Creates a cursor bound to one projected node.</summary>
|
||||
/// <param name="realm">The projected node's realm.</param>
|
||||
/// <param name="localIdentifier">The projected node's opaque local identifier.</param>
|
||||
protected ProjectedHistoryContinuation(DataRealm realm, string localIdentifier)
|
||||
{
|
||||
ArgumentException.ThrowIfNullOrWhiteSpace(localIdentifier);
|
||||
Realm = realm;
|
||||
LocalIdentifier = localIdentifier;
|
||||
}
|
||||
|
||||
/// <summary>The projected node's realm.</summary>
|
||||
public DataRealm Realm { get; }
|
||||
|
||||
/// <summary>The projected node's local identifier.</summary>
|
||||
public string LocalIdentifier { get; }
|
||||
|
||||
/// <summary>True once the cursor was released or handed back for a resume (it is single-use either way).</summary>
|
||||
public bool IsSpent => Volatile.Read(ref _released) != 0;
|
||||
|
||||
/// <summary>
|
||||
/// Best-effort, idempotent, non-blocking release of the origin continuation (<c>releaseContinuationPoints</c>, session
|
||||
/// close, eviction, a store refusal). The origin's idle expiry is the backstop.
|
||||
/// </summary>
|
||||
public void Release()
|
||||
{
|
||||
if (Interlocked.Exchange(ref _released, 1) == 0) OnRelease();
|
||||
}
|
||||
|
||||
/// <summary>Marks the cursor as handed back for a resume: the resume read owns the origin token from here on.</summary>
|
||||
/// <returns><c>false</c> when it was already released or resumed.</returns>
|
||||
public bool TryClaimForResume() => Interlocked.Exchange(ref _released, 1) == 0;
|
||||
|
||||
/// <summary>Forwards the release to the origin (called at most once).</summary>
|
||||
protected abstract void OnRelease();
|
||||
}
|
||||
|
||||
/// <summary>One projected node of a consumer HistoryRead (H3).</summary>
|
||||
/// <param name="NodeId">The projected node.</param>
|
||||
/// <param name="AggregateId">Processed only: the requested aggregate's ns=0 numeric id.</param>
|
||||
/// <param name="Resume">The claimed remote cursor of a resumed read; null = a fresh read.</param>
|
||||
public sealed record ProjectedHistoryNode(NodeId NodeId, uint? AggregateId = null, ProjectedHistoryContinuation? Resume = null);
|
||||
|
||||
/// <summary>One projected node's outcome: the origin's Part 11 status verbatim, its values, and the next cursor.</summary>
|
||||
/// <param name="StatusCode">The full OPC UA status.</param>
|
||||
/// <param name="Samples">The values (CLR values, verbatim status and timestamps).</param>
|
||||
/// <param name="Continuation">The next remote cursor; null when the read is complete.</param>
|
||||
public sealed record ProjectedHistoryOutcome(uint StatusCode, IReadOnlyList<OriginHistorySample> Samples, ProjectedHistoryContinuation? Continuation = null);
|
||||
|
||||
/// <summary>
|
||||
/// H3 — HistoryRead on projected variables (plan §2.1, §3.2): resolves each projected node to its mapping, deployed
|
||||
/// connection lease and origin view, authorizes it (the mapping's HistoryRead bit and a local
|
||||
/// <c>NodePermissions.HistoryRead</c> grant on the mapping scope, ACLs on or off), and forwards through
|
||||
/// <see cref="IDataHistoryService"/>. A fresh read may move endpoint within its deadline; a resumed read never moves.
|
||||
/// </summary>
|
||||
public interface IProjectedHistoryAccess
|
||||
{
|
||||
/// <summary>
|
||||
/// Reads one batch of projected nodes for <paramref name="caller"/>. Never called under the node-manager <c>Lock</c>.
|
||||
/// Results are in <paramref name="nodes"/> order. Every <see cref="ProjectedHistoryNode.Resume"/> cursor is owned by
|
||||
/// the call (resumed or released), whatever the outcome.
|
||||
/// </summary>
|
||||
/// <param name="caller">The session identity.</param>
|
||||
/// <param name="details">The request details (fresh nodes; a resumed node resends its ORIGINAL details).</param>
|
||||
/// <param name="nodes">The projected nodes.</param>
|
||||
/// <param name="deadline">The consumer request's remaining <c>HistoryReadDeadline</c>; non-positive = unbounded.</param>
|
||||
/// <param name="cancellationToken">The SDK request lifetime.</param>
|
||||
/// <returns>One outcome per node.</returns>
|
||||
Task<IReadOnlyList<ProjectedHistoryOutcome>> ReadAsync(RoleCarryingUserIdentity caller, DataHistoryDetails details,
|
||||
IReadOnlyList<ProjectedHistoryNode> nodes, TimeSpan deadline, CancellationToken cancellationToken);
|
||||
}
|
||||
@@ -39,6 +39,12 @@ public sealed record ProjectedVariableDefinition(DataRealm Realm, string LocalId
|
||||
{
|
||||
/// <summary>Stable across same-node metadata renewal, replaced on node retirement.</summary>
|
||||
public ProjectedNodeLifetime Lifetime { get; init; } = new();
|
||||
|
||||
/// <summary>
|
||||
/// H3: the node is <c>Historizing</c> with the HistoryRead access bit — only when the mapping grants HistoryRead AND the
|
||||
/// origin's negotiated metadata says the node is historizing (plan §2.1). Never the HistoryWrite bit.
|
||||
/// </summary>
|
||||
public bool Historizing { get; init; }
|
||||
}
|
||||
|
||||
/// <summary>Locally authorized placement for a configured mapping anchor.</summary>
|
||||
@@ -4677,6 +4683,7 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage
|
||||
!commit() || !renewed.AuthorityIsCurrent() || !old.Lifetime.IsActive) return false;
|
||||
_projectedVariables[nodeId] = (existing.Parent, renewed.ProjectionGeneration, renewed.Metadata, existing.Node, renewed.AuthorityIsCurrent);
|
||||
_projectedDefinitions[nodeId] = renewed;
|
||||
ApplyProjectedHistorizing(existing.Node, renewed.Historizing);
|
||||
_projectedNodeBytes += delta; _projectedNodeCharges[nodeId] = charge;
|
||||
CommitProjectedDefinition(nodeId, renewed);
|
||||
return true;
|
||||
@@ -4740,6 +4747,7 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage
|
||||
_projectedVariables[renewal.Id] = (previous.Parent, renewal.Definition.ProjectionGeneration, renewal.Definition.Metadata,
|
||||
previous.Node, renewal.Definition.AuthorityIsCurrent);
|
||||
_projectedDefinitions[renewal.Id] = renewal.Definition;
|
||||
ApplyProjectedHistorizing(previous.Node, renewal.Definition.Historizing);
|
||||
_projectedNodeBytes += renewal.Charge - _projectedNodeCharges[renewal.Id];
|
||||
_projectedNodeCharges[renewal.Id] = renewal.Charge;
|
||||
}
|
||||
@@ -4796,6 +4804,7 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage
|
||||
!installed.AuthorityIsCurrent() || !commit() || !installed.AuthorityIsCurrent()) return false;
|
||||
_projectedVariables[anchorId] = (existing.Parent, existing.Generation, installed.Metadata, existingNode, installed.AuthorityIsCurrent);
|
||||
_projectedDefinitions[anchorId] = installed;
|
||||
ApplyProjectedHistorizing(existingNode, installed.Historizing);
|
||||
_projectedNodeCharges[anchorId] = renewedCharge;
|
||||
_projectedNodeBytes += delta;
|
||||
CommitProjectedDefinition(anchorId, installed);
|
||||
@@ -4833,6 +4842,7 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage
|
||||
var charged = false;
|
||||
try
|
||||
{
|
||||
ApplyProjectedHistorizing(variable, installed.Historizing);
|
||||
parent.RemoveChild(folder); PredefinedNodes?.Remove(anchorId);
|
||||
parent.AddChild(variable); AddPredefinedNode(SystemContext, variable);
|
||||
_projectedAnchors[anchorId] = (anchor.Definition, variable);
|
||||
@@ -4925,6 +4935,7 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage
|
||||
AccessLevel = AccessLevels.CurrentRead, UserAccessLevel = AccessLevels.CurrentRead,
|
||||
Value = Variant.Null, StatusCode = StatusCodes.BadWaitingForInitialData, Timestamp = DateTime.MinValue };
|
||||
if (!definition.AuthorityIsCurrent()) return false;
|
||||
ApplyProjectedHistorizing(node, definition.Historizing);
|
||||
parent.AddChild(node); AddPredefinedNode(SystemContext, node);
|
||||
_projectedVariables.Add(candidate, (definition.Parent, definition.ProjectionGeneration, definition.Metadata, node, definition.AuthorityIsCurrent));
|
||||
_projectedDefinitions.Add(candidate, definition);
|
||||
@@ -8798,7 +8809,7 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
/// <remarks>A thin adapter over the history port (<see cref="ReadHistory"/>): authorize, then serve.</remarks>
|
||||
/// <remarks>A thin adapter over the history port (<see cref="ReadHistory"/>): authorize, then serve (H3: projected handles go remote).</remarks>
|
||||
protected override void HistoryReadRawModified(
|
||||
ServerSystemContext context,
|
||||
ReadRawModifiedDetails details,
|
||||
@@ -8810,11 +8821,11 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage
|
||||
IDictionary<NodeId, NodeState> cache)
|
||||
{
|
||||
nodesToProcess = AuthorizeHistoryRead(context, nodesToProcess, results, errors);
|
||||
ServeHistoryReadAdapter(context, details, nodesToRead, nodesToProcess, results, errors);
|
||||
ServeHistoryReadSplit(context, details, nodesToRead, nodesToProcess, results, errors);
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
/// <remarks>A thin adapter over the history port (<see cref="ReadHistory"/>): authorize, then serve.</remarks>
|
||||
/// <remarks>A thin adapter over the history port (<see cref="ReadHistory"/>): authorize, then serve (H3: projected handles go remote).</remarks>
|
||||
protected override void HistoryReadProcessed(
|
||||
ServerSystemContext context,
|
||||
ReadProcessedDetails details,
|
||||
@@ -8826,11 +8837,11 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage
|
||||
IDictionary<NodeId, NodeState> cache)
|
||||
{
|
||||
nodesToProcess = AuthorizeHistoryRead(context, nodesToProcess, results, errors);
|
||||
ServeHistoryReadAdapter(context, details, nodesToRead, nodesToProcess, results, errors);
|
||||
ServeHistoryReadSplit(context, details, nodesToRead, nodesToProcess, results, errors);
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
/// <remarks>A thin adapter over the history port (<see cref="ReadHistory"/>): authorize, then serve.</remarks>
|
||||
/// <remarks>A thin adapter over the history port (<see cref="ReadHistory"/>): authorize, then serve (H3: projected handles go remote).</remarks>
|
||||
protected override void HistoryReadAtTime(
|
||||
ServerSystemContext context,
|
||||
ReadAtTimeDetails details,
|
||||
@@ -8842,7 +8853,7 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage
|
||||
IDictionary<NodeId, NodeState> cache)
|
||||
{
|
||||
nodesToProcess = AuthorizeHistoryRead(context, nodesToProcess, results, errors);
|
||||
ServeHistoryReadAdapter(context, details, nodesToRead, nodesToProcess, results, errors);
|
||||
ServeHistoryReadSplit(context, details, nodesToRead, nodesToProcess, results, errors);
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
|
||||
@@ -0,0 +1,264 @@
|
||||
using System.Diagnostics;
|
||||
using Opc.Ua;
|
||||
using Opc.Ua.Server;
|
||||
using ZB.MOM.WW.OtOpcUa.Commons.OpcUa;
|
||||
using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections;
|
||||
using SdkHistoryReadResult = Opc.Ua.HistoryReadResult;
|
||||
using DataValue = Opc.Ua.DataValue;
|
||||
|
||||
namespace ZB.MOM.WW.OtOpcUa.OpcUaServer;
|
||||
|
||||
/// <summary>
|
||||
/// H3 — consumer OPC UA projection of remote history (gRPC data history plan §3.2). The Raw / Processed / AtTime overrides
|
||||
/// split one request's authorized handles: local handles go to the H1 port exactly as before, projected handles (the
|
||||
/// mapped/raw and mapped/uns namespaces) to <see cref="ProjectedHistoryAccess"/>. Every result is written back to its own
|
||||
/// handle's slot, so a mixed batch keeps request order. Nothing here runs under, or takes, <c>Lock</c>: the SDK releases it
|
||||
/// before it dispatches the overrides, and the remote read is block-bridged once per batch, like the port.
|
||||
/// </summary>
|
||||
public sealed partial class OtOpcUaNodeManager
|
||||
{
|
||||
private IProjectedHistoryAccess? _projectedHistoryAccess;
|
||||
|
||||
/// <summary>The remote history gateway for projected variables (H3); null = projected nodes answer unsupported.</summary>
|
||||
public IProjectedHistoryAccess? ProjectedHistoryAccess
|
||||
{
|
||||
get => Volatile.Read(ref _projectedHistoryAccess);
|
||||
set => Volatile.Write(ref _projectedHistoryAccess, value);
|
||||
}
|
||||
|
||||
/// <summary>Serves local handles through the port (unchanged) and projected handles remotely, each into its own slot.</summary>
|
||||
private void ServeHistoryReadSplit(
|
||||
ServerSystemContext context,
|
||||
HistoryReadDetails details,
|
||||
ArrayOf<HistoryReadValueId> nodesToRead,
|
||||
List<NodeHandle> nodesToProcess,
|
||||
IList<SdkHistoryReadResult> results,
|
||||
IList<ServiceResult> errors)
|
||||
{
|
||||
List<NodeHandle>? projected = null;
|
||||
foreach (var handle in nodesToProcess)
|
||||
if (IsProjectedDescendant(handle.NodeId)) (projected ??= []).Add(handle);
|
||||
if (projected is null)
|
||||
{
|
||||
ServeHistoryReadAdapter(context, details, nodesToRead, nodesToProcess, results, errors);
|
||||
return;
|
||||
}
|
||||
|
||||
var started = Stopwatch.GetTimestamp();
|
||||
var local = nodesToProcess.Where(h => !IsProjectedDescendant(h.NodeId)).ToList();
|
||||
if (local.Count > 0) ServeHistoryReadAdapter(context, details, nodesToRead, local, results, errors);
|
||||
ServeProjectedHistory(context, details, nodesToRead, projected, results, errors, started);
|
||||
}
|
||||
|
||||
/// <summary>The projected half of a variable-history request.</summary>
|
||||
private void ServeProjectedHistory(
|
||||
ServerSystemContext context,
|
||||
HistoryReadDetails details,
|
||||
ArrayOf<HistoryReadValueId> nodesToRead,
|
||||
List<NodeHandle> handles,
|
||||
IList<SdkHistoryReadResult> results,
|
||||
IList<ServiceResult> errors,
|
||||
long started)
|
||||
{
|
||||
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;
|
||||
|
||||
var pending = new List<(NodeHandle Handle, ProjectedHistoryNode Node)>(handles.Count);
|
||||
foreach (var handle in handles)
|
||||
{
|
||||
var key = MapKey(handle.NodeId);
|
||||
var tag = HistoryBindingTag(handle.NodeId);
|
||||
var cp = nodesToRead[handle.Index].ContinuationPoint;
|
||||
ProjectedHistoryContinuation? resume = null;
|
||||
if (cp.Length > 0)
|
||||
{
|
||||
// Single-use: the take removes the SDK slot. A cursor of another node / kind / epoch is refused AND released.
|
||||
var state = store.TryTake(session, cp.ToArray());
|
||||
if (state is not { Kind: HistoryCursorKind.Remote, Remote: { } cursor }
|
||||
|| !HistoryContinuationMatches(state, key.Realm, key.Id, tag, epoch)
|
||||
|| !cursor.TryClaimForResume())
|
||||
{
|
||||
state?.Remote?.Release();
|
||||
SetProjectedStatus(handle, results, errors, StatusCodes.BadContinuationPointInvalid);
|
||||
continue;
|
||||
}
|
||||
|
||||
resume = cursor;
|
||||
}
|
||||
|
||||
if (access is null || identity is null || remote is null)
|
||||
{
|
||||
// No projection gateway, no session identity, or a variant a remote read never serves (a modified read).
|
||||
resume?.Release();
|
||||
SetProjectedStatus(handle, results, errors, StatusCodes.BadHistoryOperationUnsupported);
|
||||
continue;
|
||||
}
|
||||
|
||||
uint? aggregateId = null;
|
||||
if (remote is DataHistoryProcessedDetails && resume is null)
|
||||
{
|
||||
// Consumer-side unknown aggregate: refused up front, unsent (the origin refuses what IT cannot serve).
|
||||
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);
|
||||
continue;
|
||||
}
|
||||
|
||||
aggregateId = numeric;
|
||||
}
|
||||
|
||||
pending.Add((handle, new ProjectedHistoryNode(handle.NodeId, aggregateId, resume)));
|
||||
}
|
||||
|
||||
if (pending.Count == 0) return;
|
||||
var nodes = pending.Select(p => p.Node).ToArray();
|
||||
IReadOnlyList<ProjectedHistoryOutcome>? outcomes = null;
|
||||
// The same process-wide batch limiter as local reads: a remote read also holds an SDK request thread.
|
||||
WithHistoryBatchLimiter(pending, () =>
|
||||
{
|
||||
TimeSpan remaining;
|
||||
if (HistoryReadDeadline > TimeSpan.Zero)
|
||||
{
|
||||
remaining = HistoryReadDeadline - Stopwatch.GetElapsedTime(started);
|
||||
if (remaining <= TimeSpan.Zero)
|
||||
{
|
||||
outcomes = nodes.Select(_ => new ProjectedHistoryOutcome(StatusCodes.BadTimeout.Code, [])).ToArray();
|
||||
foreach (var node in nodes) node.Resume?.Release();
|
||||
return;
|
||||
}
|
||||
}
|
||||
else remaining = TimeSpan.Zero;
|
||||
|
||||
try
|
||||
{
|
||||
outcomes = access!.ReadAsync(identity!, remote!, nodes, remaining,
|
||||
context.OperationContext?.CancellationToken ?? CancellationToken.None).GetAwaiter().GetResult();
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
// The SDK request ended: a timeout for this caller, never an origin fault (the access owns the resumes).
|
||||
outcomes = nodes.Select(_ => new ProjectedHistoryOutcome(StatusCodes.BadTimeout.Code, [])).ToArray();
|
||||
}
|
||||
catch (Exception ex) when (ex is InvalidOperationException or ArgumentException or ObjectDisposedException)
|
||||
{
|
||||
outcomes = nodes.Select(_ => new ProjectedHistoryOutcome(StatusCodes.BadNoCommunication.Code, [])).ToArray();
|
||||
}
|
||||
}, p =>
|
||||
{
|
||||
p.Node.Resume?.Release();
|
||||
SetProjectedStatus(p.Handle, results, errors, StatusCodes.BadTooManyOperations);
|
||||
});
|
||||
|
||||
if (outcomes is null) return; // the limiter rejected the batch
|
||||
if (outcomes.Count != pending.Count)
|
||||
{
|
||||
foreach (var o in outcomes) o.Continuation?.Release();
|
||||
foreach (var p in pending) SetProjectedStatus(p.Handle, results, errors, StatusCodes.BadInternalError);
|
||||
return;
|
||||
}
|
||||
|
||||
for (var i = 0; i < pending.Count; i++)
|
||||
{
|
||||
var handle = pending[i].Handle;
|
||||
var outcome = outcomes[i];
|
||||
var status = new StatusCode(outcome.StatusCode);
|
||||
if (StatusCode.IsBad(status))
|
||||
{
|
||||
outcome.Continuation?.Release();
|
||||
SetProjectedStatus(handle, results, errors, status);
|
||||
continue;
|
||||
}
|
||||
|
||||
byte[]? cp = null;
|
||||
if (outcome.Continuation is { } next)
|
||||
{
|
||||
var key = MapKey(handle.NodeId);
|
||||
cp = SaveRemoteContinuation(session, store, key.Realm, key.Id, HistoryBindingTag(handle.NodeId), epoch, next);
|
||||
}
|
||||
|
||||
var values = new List<DataValue>(outcome.Samples.Count);
|
||||
foreach (var sample in outcome.Samples)
|
||||
values.Add(new DataValue(SdkValueBoundary.FromClr(sample.Value), new StatusCode(sample.StatusCode),
|
||||
sample.SourceTimestampUtc ?? DateTime.MinValue, sample.ServerTimestampUtc ?? DateTime.MinValue));
|
||||
errors[handle.Index] = ServiceResult.Good;
|
||||
results[handle.Index] = new SdkHistoryReadResult
|
||||
{
|
||||
StatusCode = status,
|
||||
HistoryData = new ExtensionObject(new HistoryData { DataValues = values }),
|
||||
ContinuationPoint = cp is null ? default : ByteString.From(cp),
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Stores a remote cursor in the session store, bound to its node and the current epoch. When it cannot be stored (no
|
||||
/// session, the epoch moved, the session refused it) the page is returned without a continuation point — as a local
|
||||
/// read degrades — and the origin cursor is released.
|
||||
/// </summary>
|
||||
private byte[]? SaveRemoteContinuation(ISession? session, IHistoryContinuationStore store, AddressSpaceRealm realm, string identifier,
|
||||
string tag, long epoch, ProjectedHistoryContinuation cursor)
|
||||
{
|
||||
if (epoch != Volatile.Read(ref _historyContinuationEpoch)) { cursor.Release(); return null; }
|
||||
byte[]? cp;
|
||||
try
|
||||
{
|
||||
cp = store.Save(session, new HistoryContinuationState(string.Empty, default, default, 0, 0, HistoryCursorKind.Remote,
|
||||
BoundRealm: realm, BoundIdentifier: identifier, BoundTag: tag, AddressSpaceEpoch: epoch, Remote: cursor));
|
||||
}
|
||||
catch (ServiceResultException) { cp = null; } // the SDK disposed (released) it
|
||||
if (cp is null) cursor.Release();
|
||||
return cp;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// H3: the projected node's history advertisement — the HistoryRead access bit (CurrentRead | HistoryRead) and
|
||||
/// <c>Historizing</c> when the definition says so, plain CurrentRead otherwise. Never HistoryWrite. Under <c>Lock</c>.
|
||||
/// </summary>
|
||||
private void ApplyProjectedHistorizing(BaseInstanceState node, bool historizing)
|
||||
{
|
||||
if (node is not BaseDataVariableState variable) return;
|
||||
var access = historizing ? (byte)(AccessLevels.CurrentRead | AccessLevels.HistoryRead) : AccessLevels.CurrentRead;
|
||||
if (variable.AccessLevel == access && variable.UserAccessLevel == access && variable.Historizing == historizing) return;
|
||||
variable.AccessLevel = access;
|
||||
variable.UserAccessLevel = access;
|
||||
variable.Historizing = historizing;
|
||||
variable.ClearChangeMasks(SystemContext, includeChildren: false);
|
||||
}
|
||||
|
||||
private static void SetProjectedStatus(NodeHandle handle, IList<SdkHistoryReadResult> results, IList<ServiceResult> errors, StatusCode status)
|
||||
{
|
||||
errors[handle.Index] = new ServiceResult(status);
|
||||
results[handle.Index] = new SdkHistoryReadResult { StatusCode = status };
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The SDK details as the SDK-free remote shape. An unset Part 11 bound travels ABSENT, never MinValue (plan §3.3). A
|
||||
/// modified read is never served remotely (null).
|
||||
/// </summary>
|
||||
internal static DataHistoryDetails? ToRemoteDetails(HistoryReadDetails details) => details switch
|
||||
{
|
||||
ReadRawModifiedDetails { IsReadModified: true } => null,
|
||||
ReadRawModifiedDetails raw => new DataHistoryRawDetails(Bound(raw.StartTime), Bound(raw.EndTime), raw.NumValuesPerNode, raw.ReturnBounds),
|
||||
ReadProcessedDetails processed => new DataHistoryProcessedDetails(Bound(processed.StartTime), Bound(processed.EndTime),
|
||||
TimeSpan.FromMilliseconds(processed.ProcessingInterval), processed.AggregateConfiguration is { } c
|
||||
? new DataAggregateConfiguration(c.UseServerCapabilitiesDefaults, c.TreatUncertainAsBad, c.PercentDataBad, c.PercentDataGood,
|
||||
c.UseSlopedExtrapolation)
|
||||
: null),
|
||||
ReadAtTimeDetails atTime => new DataHistoryAtTimeDetails(
|
||||
(atTime.ReqTimes.ToArray() ?? []).Select(t => new DateTimeOffset(DateTime.SpecifyKind(t.ToDateTime(), DateTimeKind.Utc))).ToArray(),
|
||||
atTime.UseSimpleBounds),
|
||||
_ => null,
|
||||
};
|
||||
|
||||
private static DateTimeOffset? Bound(DateTimeUtc value)
|
||||
{
|
||||
var clr = SdkValueBoundary.ToClrTimestamp(value);
|
||||
return clr == DateTime.MinValue ? null : new DateTimeOffset(DateTime.SpecifyKind(clr, DateTimeKind.Utc));
|
||||
}
|
||||
}
|
||||
@@ -185,6 +185,12 @@ public sealed class DataPlaneAuthorizer
|
||||
// lease expires, so a periodic detach is not a final-send gate. Until P08 installs a verified publish-time
|
||||
// gate, do not admit mapped data or event subscriptions at all.
|
||||
if (operation == OpcUaOperation.CreateMonitoredItems) { veto = DeniedResult; return true; }
|
||||
// H3: HistoryRead on a mapped node is opened DELIBERATELY — it needs the mapping's own HistoryRead bit (masked by the
|
||||
// export's) AND a local NodePermissions.HistoryRead grant on the mapping scope, with ACLs on or off (plan §6). Every
|
||||
// other mapped operation outside this allowlist (HistoryUpdate, alarm methods…) stays closed.
|
||||
if (operation is not (OpcUaOperation.Browse or OpcUaOperation.Read or OpcUaOperation.WriteOperate or OpcUaOperation.WriteTune
|
||||
or OpcUaOperation.WriteConfigure or OpcUaOperation.TransferSubscriptions or OpcUaOperation.HistoryRead))
|
||||
{ veto = DeniedResult; return true; }
|
||||
var caller = new DataCallerIdentity(identity.Principal, identity.ApiKeyId,
|
||||
identity.CredentialVersion, identity.CredentialExpiresUtc);
|
||||
try
|
||||
|
||||
Reference in New Issue
Block a user