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
|
||||
|
||||
+372
@@ -0,0 +1,372 @@
|
||||
using Microsoft.Extensions.Logging.Abstractions;
|
||||
using Opc.Ua;
|
||||
using Opc.Ua.Server;
|
||||
using Shouldly;
|
||||
using Xunit;
|
||||
using ZB.MOM.WW.OtOpcUa.Commons.OpcUa;
|
||||
using ZB.MOM.WW.OtOpcUa.Configuration.Entities;
|
||||
using ZB.MOM.WW.OtOpcUa.Configuration.Enums;
|
||||
using ZB.MOM.WW.OtOpcUa.Core.Abstractions;
|
||||
using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections;
|
||||
using ZB.MOM.WW.OtOpcUa.Core.Authorization;
|
||||
using ZB.MOM.WW.OtOpcUa.OpcUaServer.Security;
|
||||
using SdkHistoryReadResult = Opc.Ua.HistoryReadResult;
|
||||
using DataValue = Opc.Ua.DataValue;
|
||||
|
||||
namespace ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests.DataConnections;
|
||||
|
||||
/// <summary>
|
||||
/// H3 — the SDK side of projected history: the projected access level, the mapped HistoryRead gate with ACLs on and off,
|
||||
/// the local/projected split keeping per-index slots, the Remote cursor in the session store (resume, release, session
|
||||
/// close, wrong node), consumer-side aggregate refusal and the never-remote modified read.
|
||||
/// </summary>
|
||||
[Trait("Category", "Unit"), Trait("Feature", "GrpcData"), Trait("Phase", "H3")]
|
||||
public sealed class ProjectedHistoryReadTests : IAsyncDisposable
|
||||
{
|
||||
private static readonly DateTimeOffset Now = new(2026, 11, 15, 12, 0, 0, TimeSpan.Zero);
|
||||
private static readonly DateTime T0 = new(2026, 11, 15, 11, 0, 0, DateTimeKind.Utc);
|
||||
private readonly string _pki = Path.Combine(Path.GetTempPath(), $"otopcua-projected-history-{Guid.NewGuid():N}");
|
||||
private OpcUaApplicationHost? _host;
|
||||
|
||||
[Fact]
|
||||
public async Task Only_a_historizing_definition_gets_the_HistoryRead_bit_and_never_HistoryWrite()
|
||||
{
|
||||
var (nm, f) = await BootAsync(aclEnabled: false, NodePermissions.Browse | NodePermissions.Read | NodePermissions.HistoryRead);
|
||||
var plain = Project(nm, f, "Plain", historizing: false);
|
||||
var historized = Project(nm, f, "Hist", historizing: true);
|
||||
var plainNode = Variable(nm, plain);
|
||||
plainNode.AccessLevel.ShouldBe(AccessLevels.CurrentRead);
|
||||
plainNode.Historizing.ShouldBeFalse();
|
||||
var histNode = Variable(nm, historized);
|
||||
histNode.AccessLevel.ShouldBe((byte)(AccessLevels.CurrentRead | AccessLevels.HistoryRead));
|
||||
histNode.UserAccessLevel.ShouldBe((byte)(AccessLevels.CurrentRead | AccessLevels.HistoryRead));
|
||||
(histNode.AccessLevel & AccessLevels.HistoryWrite).ShouldBe((byte)0);
|
||||
histNode.Historizing.ShouldBeTrue();
|
||||
|
||||
var access = new FakeAccess();
|
||||
nm.ProjectedHistoryAccess = access;
|
||||
var (results, errors) = Raw(nm, f.Identity, [plain, historized]);
|
||||
errors[0].StatusCode.Code.ShouldBe(StatusCodes.BadHistoryOperationUnsupported.Code, "no bit ⇒ the SDK refuses before any history code");
|
||||
errors[1].StatusCode.Code.ShouldBe(StatusCodes.Good.Code);
|
||||
access.Calls.ShouldBe(1);
|
||||
access.LastNodes.Single().NodeId.ShouldBe(historized);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(false)]
|
||||
[InlineData(true)]
|
||||
public async Task Mapped_HistoryRead_needs_the_local_grant_and_the_mapping_bit_with_acls_on_and_off(bool aclEnabled)
|
||||
{
|
||||
// Granted: served through the projection, ACLs on or off.
|
||||
var (nm, f) = await BootAsync(aclEnabled, NodePermissions.Browse | NodePermissions.Read | NodePermissions.HistoryRead);
|
||||
var node = Project(nm, f, "Speed", historizing: true);
|
||||
var access = new FakeAccess();
|
||||
nm.ProjectedHistoryAccess = access;
|
||||
var (results, errors) = Raw(nm, f.Identity, [node]);
|
||||
errors[0].StatusCode.Code.ShouldBe(StatusCodes.Good.Code);
|
||||
Values(results[0]).Select(v => SdkValueBoundary.ToClr(v.WrappedValue)).ShouldBe([1.0, 2.0]);
|
||||
access.Calls.ShouldBe(1);
|
||||
|
||||
// No local HistoryRead grant on the mapping scope ⇒ BadUserAccessDenied, never sent — even with ACLs off.
|
||||
f.Grant(NodePermissions.Browse | NodePermissions.Read);
|
||||
(_, errors) = Raw(nm, f.Identity, [node]);
|
||||
errors[0].StatusCode.Code.ShouldBe(StatusCodes.BadUserAccessDenied.Code);
|
||||
access.Calls.ShouldBe(1);
|
||||
|
||||
// Local grant but the mapping (subject) lacks HistoryRead ⇒ denied too.
|
||||
f.Grant(NodePermissions.Browse | NodePermissions.Read | NodePermissions.HistoryRead);
|
||||
f.SubjectOperations = DataOperations.Browse | DataOperations.Read;
|
||||
(_, errors) = Raw(nm, f.Identity, [node]);
|
||||
errors[0].StatusCode.Code.ShouldBe(StatusCodes.BadUserAccessDenied.Code);
|
||||
access.Calls.ShouldBe(1);
|
||||
|
||||
// No identity at all ⇒ denied.
|
||||
(_, errors) = Raw(nm, null, [node]);
|
||||
errors[0].StatusCode.Code.ShouldBe(StatusCodes.BadUserAccessDenied.Code);
|
||||
access.Calls.ShouldBe(1);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task A_mixed_local_and_projected_batch_keeps_every_slot()
|
||||
{
|
||||
var (nm, f) = await BootAsync(aclEnabled: false, NodePermissions.Browse | NodePermissions.Read | NodePermissions.HistoryRead);
|
||||
nm.EnsureVariable("Plant/LocalA", "Plant", "LocalA", "Double", false, AddressSpaceRealm.Raw, historianTagname: "L.a");
|
||||
nm.EnsureVariable("Plant/LocalB", "Plant", "LocalB", "Double", false, AddressSpaceRealm.Raw, historianTagname: "L.b");
|
||||
var localA = nm.TryGetVariable("Plant/LocalA", AddressSpaceRealm.Raw)!.NodeId;
|
||||
var localB = nm.TryGetVariable("Plant/LocalB", AddressSpaceRealm.Raw)!.NodeId;
|
||||
var p1 = Project(nm, f, "One", historizing: true);
|
||||
var p2 = Project(nm, f, "Two", historizing: true);
|
||||
var access = new FakeAccess { Answer = node => node.NodeId == p1 ? [10.0] : [20.0, 21.0] };
|
||||
nm.ProjectedHistoryAccess = access;
|
||||
|
||||
var (results, errors) = Raw(nm, f.Identity, [p1, localA, p2, localB]);
|
||||
Values(results[0]).Select(v => SdkValueBoundary.ToClr(v.WrappedValue)).ShouldBe([10.0]);
|
||||
Values(results[2]).Select(v => SdkValueBoundary.ToClr(v.WrappedValue)).ShouldBe([20.0, 21.0]);
|
||||
// The local slots are the H1 port's answer (no historian ⇒ GoodNoData), untouched by the projected half.
|
||||
results[1].StatusCode.Code.ShouldBe(StatusCodes.GoodNoData.Code);
|
||||
results[3].StatusCode.Code.ShouldBe(StatusCodes.GoodNoData.Code);
|
||||
errors.ShouldAllBe(e => StatusCode.IsGood(e.StatusCode));
|
||||
access.Calls.ShouldBe(1, "one remote call for the batch's projected half");
|
||||
access.LastNodes.Select(n => n.NodeId).ShouldBe([p1, p2]);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task A_remote_cursor_resumes_once_and_is_released_by_releaseContinuationPoints_and_session_close()
|
||||
{
|
||||
var (nm, f) = await BootAsync(aclEnabled: true, NodePermissions.Browse | NodePermissions.Read | NodePermissions.HistoryRead);
|
||||
var store = new InMemoryHistoryContinuationStore();
|
||||
nm.HistoryContinuationStore = store;
|
||||
var node = Project(nm, f, "Paged", historizing: true);
|
||||
var other = Project(nm, f, "Other", historizing: true);
|
||||
var access = new FakeAccess { Paged = true };
|
||||
nm.ProjectedHistoryAccess = access;
|
||||
|
||||
var (results, _) = Raw(nm, f.Identity, [node]);
|
||||
var cp = results[0].ContinuationPoint;
|
||||
cp.IsEmpty.ShouldBeFalse();
|
||||
var first = access.Issued.Single();
|
||||
store.Count.ShouldBe(1);
|
||||
|
||||
// Resume: the SAME cursor comes back to the projection, claimed for the resume (not released).
|
||||
(results, _) = Raw(nm, f.Identity, [node], cp);
|
||||
access.LastNodes.Single().Resume.ShouldBeSameAs(first);
|
||||
first.Released.ShouldBe(0);
|
||||
var second = access.Issued[1];
|
||||
var cp2 = results[0].ContinuationPoint;
|
||||
|
||||
// The same point again ⇒ invalid (single-use), unsent.
|
||||
var calls = access.Calls;
|
||||
(results, var errors) = Raw(nm, f.Identity, [node], cp);
|
||||
errors[0].StatusCode.Code.ShouldBe(StatusCodes.BadContinuationPointInvalid.Code);
|
||||
access.Calls.ShouldBe(calls);
|
||||
|
||||
// A cursor resumed on ANOTHER node ⇒ invalid and released.
|
||||
(_, errors) = Raw(nm, f.Identity, [other], cp2);
|
||||
errors[0].StatusCode.Code.ShouldBe(StatusCodes.BadContinuationPointInvalid.Code);
|
||||
second.Released.ShouldBe(1);
|
||||
|
||||
// releaseContinuationPoints forwards one release.
|
||||
(results, _) = Raw(nm, f.Identity, [node]);
|
||||
var third = access.Issued[2];
|
||||
Release(nm, f.Identity, node, results[0].ContinuationPoint);
|
||||
third.Released.ShouldBe(1);
|
||||
store.Count.ShouldBe(0);
|
||||
|
||||
// Session close (the SDK disposes every point) releases what is still open.
|
||||
Raw(nm, f.Identity, [node]);
|
||||
Raw(nm, f.Identity, [other]);
|
||||
store.Count.ShouldBe(2);
|
||||
store.Clear();
|
||||
access.Issued.Skip(3).ShouldAllBe(c => c.Released == 1);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task A_bad_remote_answer_carries_no_cursor_and_unknown_aggregates_and_modified_reads_are_refused_unsent()
|
||||
{
|
||||
var (nm, f) = await BootAsync(aclEnabled: false, NodePermissions.Browse | NodePermissions.Read | NodePermissions.HistoryRead);
|
||||
nm.HistoryContinuationStore = new InMemoryHistoryContinuationStore();
|
||||
var node = Project(nm, f, "Speed", historizing: true);
|
||||
var access = new FakeAccess { Status = StatusCodes.BadAggregateNotSupported.Code, Paged = true };
|
||||
nm.ProjectedHistoryAccess = access;
|
||||
|
||||
// The origin refuses the aggregate: verbatim, no cursor kept (and the one it returned is released).
|
||||
var processed = new ReadProcessedDetails
|
||||
{
|
||||
StartTime = T0, EndTime = T0.AddHours(1), ProcessingInterval = 60_000,
|
||||
AggregateType = [ObjectIds.AggregateFunction_Average],
|
||||
};
|
||||
var (results, errors) = Read(nm, f.Identity, processed, [node]);
|
||||
errors[0].StatusCode.Code.ShouldBe(StatusCodes.BadAggregateNotSupported.Code);
|
||||
results[0].ContinuationPoint.IsEmpty.ShouldBeTrue();
|
||||
access.Issued.ShouldAllBe(c => c.Released == 1);
|
||||
access.LastNodes.Single().AggregateId.ShouldBe(Objects.AggregateFunction_Average);
|
||||
|
||||
// An aggregate the consumer cannot name ⇒ BadAggregateNotSupported without a call.
|
||||
var calls = access.Calls;
|
||||
processed.AggregateType = [new NodeId("not-an-aggregate", 2)];
|
||||
(_, errors) = Read(nm, f.Identity, processed, [node]);
|
||||
errors[0].StatusCode.Code.ShouldBe(StatusCodes.BadAggregateNotSupported.Code);
|
||||
access.Calls.ShouldBe(calls);
|
||||
|
||||
// A modified read is never served remotely.
|
||||
var modified = new ReadRawModifiedDetails { StartTime = T0, EndTime = T0.AddHours(1), NumValuesPerNode = 5, IsReadModified = true };
|
||||
(_, errors) = Read(nm, f.Identity, modified, [node]);
|
||||
errors[0].StatusCode.Code.ShouldBe(StatusCodes.BadHistoryOperationUnsupported.Code);
|
||||
access.Calls.ShouldBe(calls);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Unset_bounds_travel_absent_and_AtTime_carries_its_times()
|
||||
{
|
||||
OtOpcUaNodeManager.ToRemoteDetails(new ReadRawModifiedDetails { EndTime = T0, NumValuesPerNode = 3, ReturnBounds = true, IsReadModified = false })
|
||||
.ShouldBe(new DataHistoryRawDetails(null, new DateTimeOffset(T0), 3, true));
|
||||
var atTime = OtOpcUaNodeManager.ToRemoteDetails(new ReadAtTimeDetails { ReqTimes = [T0], UseSimpleBounds = true })
|
||||
.ShouldBeOfType<DataHistoryAtTimeDetails>();
|
||||
atTime.RequestedTimesUtc.ShouldBe([new DateTimeOffset(T0)]);
|
||||
atTime.UseSimpleBounds.ShouldBeTrue();
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------------------------------------------------------
|
||||
|
||||
private static (List<SdkHistoryReadResult> Results, List<ServiceResult> Errors) Raw(OtOpcUaNodeManager nm, IUserIdentity? identity,
|
||||
NodeId[] nodes, ByteString cp = default) =>
|
||||
Read(nm, identity, new ReadRawModifiedDetails
|
||||
{
|
||||
StartTime = T0, EndTime = T0.AddHours(1), NumValuesPerNode = 2, IsReadModified = false, ReturnBounds = false,
|
||||
}, nodes, cp);
|
||||
|
||||
private static (List<SdkHistoryReadResult> Results, List<ServiceResult> Errors) Read(OtOpcUaNodeManager nm, IUserIdentity? identity,
|
||||
HistoryReadDetails details, NodeId[] nodes, ByteString cp = default)
|
||||
{
|
||||
var context = new OperationContext(new RequestHeader(), null, RequestType.HistoryRead, RequestLifetime.None, identity);
|
||||
var results = nodes.Select(_ => (SdkHistoryReadResult)null!).ToList();
|
||||
var errors = nodes.Select(_ => (ServiceResult)null!).ToList();
|
||||
nm.HistoryRead(context, details, TimestampsToReturn.Both, false,
|
||||
nodes.Select(n => new HistoryReadValueId { NodeId = n, ContinuationPoint = cp }).ToList(), results, errors);
|
||||
return (results, errors);
|
||||
}
|
||||
|
||||
private static void Release(OtOpcUaNodeManager nm, IUserIdentity identity, NodeId node, ByteString cp)
|
||||
{
|
||||
var context = new OperationContext(new RequestHeader(), null, RequestType.HistoryRead, RequestLifetime.None, identity);
|
||||
var results = new List<SdkHistoryReadResult> { null! };
|
||||
var errors = new List<ServiceResult> { null! };
|
||||
nm.HistoryRead(context, new ReadRawModifiedDetails { IsReadModified = false, ReturnBounds = false }, TimestampsToReturn.Both, true,
|
||||
new List<HistoryReadValueId> { new() { NodeId = node, ContinuationPoint = cp } }, results, errors);
|
||||
StatusCode.IsGood(errors[0].StatusCode).ShouldBeTrue();
|
||||
}
|
||||
|
||||
private static IReadOnlyList<DataValue> Values(SdkHistoryReadResult result) =>
|
||||
ExtensionObject.ToEncodeable(result.HistoryData) is HistoryData data ? data.DataValues.ToArray() ?? [] : [];
|
||||
|
||||
private static BaseDataVariableState Variable(OtOpcUaNodeManager nm, NodeId id) =>
|
||||
((NodeHandle)nm.GetManagerHandle(id)!).Node.ShouldBeOfType<BaseDataVariableState>();
|
||||
|
||||
private static NodeId Project(OtOpcUaNodeManager nm, Fixture f, string name, bool historizing)
|
||||
{
|
||||
var parent = nm.TryGetFolder("Plant", AddressSpaceRealm.Raw)!.NodeId;
|
||||
var origin = new DataAddress("origin", "ns", "string", "Device/" + name);
|
||||
var view = new DataView(origin, DataRealm.Raw, "mapping-a", 1, "Plant/Mount/" + name);
|
||||
var metadata = new DataMetadata(view, name, "Tag", DataValueKind.Double, -1, [], false,
|
||||
DataOperations.Browse | DataOperations.Read | DataOperations.HistoryRead, 1, null, null, false, History: new DataHistoryInfo(historizing));
|
||||
var identifier = ProjectedDataIds.Identifier("mapping-a", origin);
|
||||
nm.TryEnsureProjectedVariable(new ProjectedVariableDefinition(DataRealm.Raw, identifier, parent, metadata, 1, () => true)
|
||||
{ Historizing = historizing }, out var node).ShouldBeTrue();
|
||||
f.Views[identifier] = view;
|
||||
return node!.Value;
|
||||
}
|
||||
|
||||
private async Task<(OtOpcUaNodeManager Nm, Fixture F)> BootAsync(bool aclEnabled, NodePermissions permissions)
|
||||
{
|
||||
var started = await OpcUaHostStart.StartAsync(port => new OpcUaApplicationHost(new OpcUaApplicationHostOptions
|
||||
{
|
||||
ApplicationName = "ProjectedHistory", ApplicationUri = $"urn:ProjectedHistory:{Guid.NewGuid():N}",
|
||||
OpcUaPort = port, PublicHostname = "localhost", PkiStoreRoot = _pki,
|
||||
}, NullLogger<OpcUaApplicationHost>.Instance), () => new OtOpcUaSdkServer(), TestContext.Current.CancellationToken);
|
||||
_host = started.Host;
|
||||
var nm = started.Server.NodeManager!;
|
||||
nm.EnsureFolder("Plant", null, "Plant", AddressSpaceRealm.Raw);
|
||||
var f = new Fixture(aclEnabled, permissions);
|
||||
nm.Authorizer = f.Gate;
|
||||
nm.MappedSubjectResolver = (realm, id) => f.Resolve(realm, id);
|
||||
return (nm, f);
|
||||
}
|
||||
|
||||
public async ValueTask DisposeAsync()
|
||||
{
|
||||
if (_host is not null) await _host.DisposeAsync();
|
||||
if (Directory.Exists(_pki))
|
||||
try { Directory.Delete(_pki, recursive: true); } catch (IOException) { }
|
||||
}
|
||||
|
||||
private sealed class Fixture
|
||||
{
|
||||
private readonly DataPlaneAuthorityState _state = new();
|
||||
private readonly TestLease _lease = new();
|
||||
internal readonly ApiKey Key = new() { ApiKeyId = "key-a", Name = "key-a", Principal = "reader", SecretHash = "hash", Enabled = true,
|
||||
ExpiresUtc = Now.AddHours(1).UtcDateTime };
|
||||
internal readonly DataPlaneAuthorizer Gate;
|
||||
internal readonly Dictionary<string, DataView> Views = new(StringComparer.Ordinal);
|
||||
internal DataOperations SubjectOperations { get; set; } =
|
||||
DataOperations.Browse | DataOperations.Read | DataOperations.HistoryRead;
|
||||
|
||||
internal Fixture(bool aclEnabled, NodePermissions permissions)
|
||||
{
|
||||
Grant(permissions);
|
||||
var clock = new TestClock();
|
||||
Gate = new DataPlaneAuthorizer(_state, new TriePermissionEvaluator(_state.Tries, clock), aclEnabled, NullLogger.Instance, clock);
|
||||
}
|
||||
|
||||
internal void Grant(NodePermissions permissions) =>
|
||||
_state.Apply("c1", "rev-" + (int)permissions, [Key],
|
||||
[new NodeAcl { NodeAclId = "acl", ClusterId = "c1", Principal = "reader", ScopeKind = NodeAclScopeKind.RawFolder,
|
||||
ScopeId = "folder", PermissionFlags = permissions }],
|
||||
new Dictionary<AclScopeRef, IReadOnlyList<NodeAclPath>> { [new(NodeAclScopeKind.RawFolder, "folder")] = [new(["raw", "Plant", "Mount"])] });
|
||||
|
||||
internal RoleCarryingUserIdentity Identity => new(new UserNameIdentityToken { UserName = "apikey" }, [], "reader", Key.ApiKeyId,
|
||||
DataCallerIdentity.CredentialVersionFor(Key), Now.AddMinutes(2));
|
||||
|
||||
internal MappedNodeResolution Resolve(AddressSpaceRealm realm, string identifier)
|
||||
{
|
||||
if (!Views.TryGetValue(identifier, out var view)) return MappedNodeResolution.Local;
|
||||
var subject = new MappedNamespaceSubject(view,
|
||||
new NodeScope { ClusterId = "c1", Kind = NodeHierarchyKind.Raw, Segments = view.Subject.Split('/') },
|
||||
["local-parent", "mapping-a"], _lease.Serving, SubjectOperations, WriteThrough: false);
|
||||
var resolver = new MappedSubjectResolver([subject], catalogEpoch: 7, new TestCatalogAuthority(_state));
|
||||
return MappedNodeResolution.Mapped(view, subject, resolver, _lease);
|
||||
}
|
||||
}
|
||||
|
||||
private sealed class FakeAccess : IProjectedHistoryAccess
|
||||
{
|
||||
public int Calls;
|
||||
public IReadOnlyList<ProjectedHistoryNode> LastNodes = [];
|
||||
public readonly List<FakeCursor> Issued = [];
|
||||
public bool Paged { get; init; }
|
||||
public uint Status { get; init; }
|
||||
public Func<ProjectedHistoryNode, double[]> Answer { get; init; } = _ => [1.0, 2.0];
|
||||
|
||||
public Task<IReadOnlyList<ProjectedHistoryOutcome>> ReadAsync(RoleCarryingUserIdentity caller, DataHistoryDetails details,
|
||||
IReadOnlyList<ProjectedHistoryNode> nodes, TimeSpan deadline, CancellationToken cancellationToken)
|
||||
{
|
||||
Calls++;
|
||||
LastNodes = nodes;
|
||||
return Task.FromResult<IReadOnlyList<ProjectedHistoryOutcome>>(nodes.Select(node =>
|
||||
{
|
||||
FakeCursor? next = null;
|
||||
if (Paged)
|
||||
{
|
||||
var key = node.NodeId.TryGetValue(out string id) ? id : "";
|
||||
next = new FakeCursor(key);
|
||||
Issued.Add(next);
|
||||
}
|
||||
var samples = Answer(node).Select((v, i) => new OriginHistorySample(v, 0, T0.AddSeconds(i), null)).ToArray();
|
||||
return new ProjectedHistoryOutcome(Status, Status == 0 ? samples : [], next);
|
||||
}).ToArray());
|
||||
}
|
||||
}
|
||||
|
||||
private sealed class FakeCursor(string identifier) : ProjectedHistoryContinuation(DataRealm.Raw, identifier)
|
||||
{
|
||||
public int Released;
|
||||
protected override void OnRelease() => Interlocked.Increment(ref Released);
|
||||
}
|
||||
|
||||
private sealed class TestCatalogAuthority(DataPlaneAuthorityState state) : IDataMappedCatalogAuthority
|
||||
{
|
||||
public long CatalogEpoch => 1;
|
||||
public long AuthorityEpoch => state.Current.GenerationId;
|
||||
public bool IsActive => true;
|
||||
}
|
||||
|
||||
private sealed class TestLease : IDataAuthorizationLease
|
||||
{
|
||||
public ServingIdentity Serving { get; } = new("node-a", "incarnation-a", "Primary", 7, 1);
|
||||
public bool IsValid => true;
|
||||
}
|
||||
|
||||
private sealed class TestClock : TimeProvider
|
||||
{
|
||||
public override DateTimeOffset GetUtcNow() => Now;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user