Files
lmxopcua/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ProjectedHistoryAccess.cs
T
Joseph Doherty af06183412 fix(grpc-data): projected Processed values keep their aggregate's type
Found by the H3 live gate (H02): a Double Average of a UInt16 node was decoded
against the node's catalog kind and came back null + BadTypeMismatch per
interval (the result status stayed Good, which is why the wire test missed
it). Raw/AtTime values are still checked against the catalog kind; Processed
values accept any scalar kind. The wire test now asserts the interval's value.
Gate: re-browse the projected leaves after every deploy (a deploy retires cold
projected nodes; the same opaque ids come back).
2026-11-24 01:04:04 -05:00

459 lines
24 KiB
C#

using Opc.Ua;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections;
using ZB.MOM.WW.OtOpcUa.OpcUaServer;
using ZB.MOM.WW.OtOpcUa.OpcUaServer.Security;
namespace ZB.MOM.WW.OtOpcUa.Runtime.DataConnections;
/// <summary>What a projected HistoryRead demand is bound to (H3).</summary>
/// <param name="MappingId">The mapping.</param>
/// <param name="MappingRevision">The deployed mapping revision.</param>
/// <param name="ConnectionId">The deployed connection the mapping reads through.</param>
/// <param name="OriginMetadata">The origin's metadata (origin view, value kind).</param>
/// <param name="Serving">The origin serving identity the projection was built under.</param>
/// <param name="ProjectionGeneration">The projection generation.</param>
internal sealed record ProjectedHistoryTarget(string MappingId, long MappingRevision, string ConnectionId, DataMetadata OriginMetadata,
ServingIdentity Serving, long ProjectionGeneration);
/// <summary>
/// H3 — consumer OPC UA projection of remote history (gRPC data history plan §2.1, §3.2, §3.3). For each projected node:
/// resolve + authorize + pin it through <see cref="ProjectedDataAccess"/> (a <see cref="DataOperations.HistoryRead"/>
/// demand: the mapping's HistoryRead bit and a local HistoryRead grant on the mapping scope, ACLs on or off), group the
/// batch per deployed connection and per details, and forward through <see cref="IDataHistoryService"/>.
/// <list type="bullet">
/// <item>A fresh read may move endpoint within its deadline (the connection decides); a RESUMED read never moves —
/// its origin token pins the issuing endpoint and serving incarnation, and its cursor re-checks the caller, the
/// mapping revision, the projection generation, the serving identity and the connection lease (route) before any
/// call. Any mismatch ⇒ <c>BadContinuationPointInvalid</c> and the origin token is released.</item>
/// <item>A resume resends the ORIGINAL details verbatim (the origin binds their hash); local SDK resumes ignore details,
/// so the consumer does too.</item>
/// <item>The per-request assembly budget (min <c>MaxHistoryAssemblyBytesPerRequest</c> of the batch's mappings) is shared
/// across the batch; once spent, the remaining nodes are <c>BadTooManyOperations</c>.</item>
/// <item>Deadline per call = min(the consumer's remaining <c>HistoryReadDeadline</c>, the connection's
/// <c>HistoryTimeoutMilliseconds</c>) ⇒ <c>BadTimeout</c>; a cancelled read is never an origin fault.</item>
/// <item>Releases (<c>releaseContinuationPoints</c>, session close, eviction) are coalesced per connection into one
/// best-effort <c>ReleaseHistoryAsync</c>; the origin's idle expiry is the backstop.</item>
/// </list>
/// </summary>
public sealed class ProjectedHistoryAccess : IProjectedHistoryAccess, IDisposable
{
internal const uint Good = 0, BadContinuationPointInvalid = 0x804A0000u, BadTooManyOperations = 0x80100000u, BadTimeout = 0x800A0000u,
BadNoCommunication = 0x80310000u, BadTypeMismatch = 0x80740000u, BadHistoryOperationUnsupported = 0x80720000u;
internal const long DefaultAssemblyBudget = 16L * 1024 * 1024;
private readonly ProjectedDataAccess _access;
private readonly IGrpcDataAdapterConnectionSource _connections;
private readonly Func<string, long?> _assemblyBudget;
private readonly TimeProvider _clock;
private readonly object _releaseGate = new();
private readonly Dictionary<string, List<byte[]>> _pendingReleases = new(StringComparer.OrdinalIgnoreCase);
private readonly CancellationTokenSource _stop = new();
private Task _releaseFlush = Task.CompletedTask;
private int _disposed;
/// <summary>Creates the gateway.</summary>
/// <param name="access">The projected data access that resolves, authorizes and pins projected nodes.</param>
/// <param name="connections">The deployed connection registry.</param>
/// <param name="assemblyBudget">A mapping's <c>MaxHistoryAssemblyBytesPerRequest</c>; null = not deployed.</param>
/// <param name="clock">The clock.</param>
public ProjectedHistoryAccess(ProjectedDataAccess access, IGrpcDataAdapterConnectionSource connections,
Func<string, long?> assemblyBudget, TimeProvider clock)
{
_access = access ?? throw new ArgumentNullException(nameof(access));
_connections = connections ?? throw new ArgumentNullException(nameof(connections));
_assemblyBudget = assemblyBudget ?? throw new ArgumentNullException(nameof(assemblyBudget));
_clock = clock ?? throw new ArgumentNullException(nameof(clock));
}
/// <summary>How long a release waits to coalesce with others for the same connection (a session close disposes one by one).</summary>
internal TimeSpan ReleaseCoalesce { get; init; } = TimeSpan.FromMilliseconds(25);
/// <summary>Releases queued and not yet sent (tests).</summary>
internal int PendingReleasesForTests { get { lock (_releaseGate) return _pendingReleases.Values.Sum(x => x.Count); } }
/// <summary>Release calls sent (tests): one per connection per coalesced flush.</summary>
internal int ReleaseCallsForTests => Volatile.Read(ref _releaseCalls);
private int _releaseCalls;
/// <summary>Waits for the queued releases to be sent (tests).</summary>
internal async Task FlushReleasesForTestsAsync()
{
Task flush;
lock (_releaseGate) flush = _releaseFlush;
await flush.ConfigureAwait(false);
lock (_releaseGate) flush = _releaseFlush;
await flush.ConfigureAwait(false);
}
/// <summary>
/// Whether a projected node is advertised as historizing: the mapping (masked by the export) grants HistoryRead AND the
/// origin's negotiated metadata (<c>HistoryInfo</c>, bit 32) says historizing.
/// </summary>
public static bool Advertises(ProjectedNodeProof proof) =>
proof is not null && (proof.Subject.AllowedOperations & DataOperations.HistoryRead) != 0
&& (proof.OriginMetadata.AllowedOperations & DataOperations.HistoryRead) != 0
&& proof.OriginMetadata.History is { Historizing: true } && proof.OriginMetadata.NodeKind is "Variable" or "Tag";
/// <inheritdoc />
public async Task<IReadOnlyList<ProjectedHistoryOutcome>> ReadAsync(RoleCarryingUserIdentity caller, DataHistoryDetails details,
IReadOnlyList<ProjectedHistoryNode> nodes, TimeSpan deadline, CancellationToken cancellationToken)
{
ArgumentNullException.ThrowIfNull(caller); ArgumentNullException.ThrowIfNull(details); ArgumentNullException.ThrowIfNull(nodes);
var started = _clock.GetTimestamp();
var outcomes = new ProjectedHistoryOutcome?[nodes.Count];
var demands = new IProjectedDemandLease?[nodes.Count];
var targets = new ProjectedHistoryTarget?[nodes.Count];
var callerKey = CallerKey(caller);
long budget = DefaultAssemblyBudget;
try
{
// 1. Resolve, authorize and pin every node; check each resumed cursor against what it was issued under.
for (var i = 0; i < nodes.Count; i++)
{
var node = nodes[i];
var cursor = node.Resume as RemoteCursor;
if (node.Resume is not null && (cursor is null || !ReferenceEquals(cursor.Owner, this)))
{
node.Resume.Release();
outcomes[i] = Fail(BadContinuationPointInvalid);
continue;
}
if (!_access.TryAcquire(node.NodeId, caller, DataOperations.HistoryRead, out var demand) || demand is null
|| !_access.TryDescribeHistoryDemand(demand, out var target) || target is null)
{
demand?.Dispose();
cursor?.ReleaseOrigin();
// The node manager already authorized the node: a projection that cannot be pinned now is not servable.
outcomes[i] = Fail(cursor is null ? BadNoCommunication : BadContinuationPointInvalid);
continue;
}
demands[i] = demand;
targets[i] = target;
if (cursor is not null && !cursor.StillMatches(callerKey, target, demand))
{
// Mapping revision change, failover, projection rebuild, another caller: the cursor never resumes.
cursor.ReleaseOrigin();
outcomes[i] = Fail(BadContinuationPointInvalid);
}
}
// 2. The per-request assembly budget, shared across the batch: the tightest mapping's.
budget = long.MaxValue;
foreach (var target in targets)
if (target is not null) budget = Math.Min(budget, _assemblyBudget(target.MappingId) is { } b and > 0 ? b : DefaultAssemblyBudget);
if (budget == long.MaxValue) budget = DefaultAssemblyBudget;
// 3. One call per (connection, details, resumed endpoint): a resumed item pins its issuing endpoint, so cursors of
// different endpoints, and fresh items (which may move), never share a call.
var groups = Enumerable.Range(0, nodes.Count).Where(i => outcomes[i] is null)
.GroupBy(i => new GroupKey(targets[i]!.ConnectionId, DetailsOf(nodes[i], details), ResumeKey(nodes[i])))
.ToArray();
foreach (var group in groups)
{
var indices = group.ToArray();
if (cancellationToken.IsCancellationRequested) { FailAll(indices, BadTimeout); continue; }
TimeSpan remaining;
if (deadline > TimeSpan.Zero)
{
remaining = deadline - _clock.GetElapsedTime(started);
if (remaining <= TimeSpan.Zero) { FailAll(indices, BadTimeout); continue; }
}
else remaining = TimeSpan.FromHours(1); // unbounded locally: the connection's HistoryTimeout still caps each call
if (budget <= 0) { FailAll(indices, BadTooManyOperations); continue; }
await ReadGroupAsync(group.Key, indices, remaining, cancellationToken).ConfigureAwait(false);
}
return outcomes.Select(o => o ?? Fail(BadNoCommunication)).ToArray();
}
finally
{
foreach (var demand in demands) demand?.Dispose();
}
async Task ReadGroupAsync(GroupKey key, int[] indices, TimeSpan remaining, CancellationToken ct)
{
IGrpcDataAdapterConnectionLease? lease = null;
try
{
using var timeout = new CancellationTokenSource(remaining, _clock);
using var linked = CancellationTokenSource.CreateLinkedTokenSource(ct, timeout.Token);
lease = await _connections.AcquireAsync(key.ConnectionId, linked.Token).ConfigureAwait(false);
if (lease is null || lease.Connection is not IDataHistoryService history || lease.CancellationToken.IsCancellationRequested)
{
foreach (var i in indices)
{
if (nodes[i].Resume is RemoteCursor c) { c.ReleaseOrigin(); outcomes[i] = Fail(BadContinuationPointInvalid); }
else outcomes[i] = Fail(BadNoCommunication);
}
return;
}
var route = lease.RouteIdentity;
var items = new List<DataHistoryReadItem>(indices.Length);
var sent = new List<int>(indices.Length);
foreach (var i in indices)
{
if (nodes[i].Resume is RemoteCursor cursor)
{
// The connection lease moved (expiry, redeployment, credential change): its tokens are gone.
if (!Equals(cursor.RouteIdentity, route))
{
cursor.ReleaseOrigin();
outcomes[i] = Fail(BadContinuationPointInvalid);
continue;
}
items.Add(new DataHistoryReadItem(sent.Count.ToString(System.Globalization.CultureInfo.InvariantCulture),
targets[i]!.OriginMetadata.View, cursor.AggregateId, cursor.Token));
}
else
{
items.Add(new DataHistoryReadItem(sent.Count.ToString(System.Globalization.CultureInfo.InvariantCulture),
targets[i]!.OriginMetadata.View, nodes[i].AggregateId));
}
sent.Add(i);
}
if (items.Count == 0) return;
IReadOnlyList<DataHistoryReadResult> answers;
try
{
answers = await history.ReadAsync(new DataHistoryReadRequest(key.Details, items,
new DataBudget(remaining, items.Count, (int)Math.Min(int.MaxValue, budget))), linked.Token).ConfigureAwait(false);
}
catch (OperationCanceledException)
{
// Our deadline or the SDK request ending: a timeout, never an origin fault (the connection records none).
foreach (var i in sent) outcomes[i] = Fail(BadTimeout);
return;
}
try
{
if (answers.Count != items.Count)
{
foreach (var i in sent) outcomes[i] = Fail(BadNoCommunication);
return;
}
for (var k = 0; k < answers.Count; k++)
{
var i = sent[k];
var answer = answers[k];
if (answer.CorrelationId != items[k].CorrelationId)
{
outcomes[i] = Fail(BadNoCommunication);
continue;
}
// The per-request assembly budget, in request order across the whole batch: once a node does not fit,
// it and every later node is BadTooManyOperations (never a partial answer; its origin cursor released).
long nodeBytes = 0;
foreach (var sample in answer.Samples) nodeBytes += sample.Value.EstimatedRetainedBytes;
if (nodeBytes > budget)
{
budget = 0;
if (answer.Continuation is { } dropped) EnqueueRelease(key.ConnectionId, dropped);
outcomes[i] = Fail(BadTooManyOperations);
continue;
}
budget -= nodeBytes;
var target = targets[i]!;
RemoteCursor? next = null;
if (answer.Continuation is { } token)
{
next = new RemoteCursor(this, target.OriginMetadata.View.Realm, demands[i]!.LocalIdentifier, token, key.ConnectionId, route,
target, callerKey, key.Details, nodes[i].Resume is RemoteCursor prior ? prior.AggregateId : nodes[i].AggregateId);
}
outcomes[i] = new ProjectedHistoryOutcome(answer.StatusCode, Convert(answer.Samples, target.OriginMetadata, key.Details is DataHistoryProcessedDetails), next);
}
}
finally
{
foreach (var answer in answers) answer.Dispose();
}
}
catch (OperationCanceledException)
{
foreach (var i in indices)
{
if (outcomes[i] is not null) continue;
if (nodes[i].Resume is RemoteCursor c) c.ReleaseOrigin();
outcomes[i] = Fail(BadTimeout);
}
return;
}
catch (Exception ex) when (ex is InvalidOperationException or UnauthorizedAccessException or ArgumentException or ObjectDisposedException)
{
foreach (var i in indices) outcomes[i] ??= Fail(nodes[i].Resume is null ? BadNoCommunication : BadContinuationPointInvalid);
return;
}
finally
{
if (lease is not null) await lease.DisposeAsync().ConfigureAwait(false);
}
}
void FailAll(int[] indices, uint status)
{
foreach (var i in indices)
{
if (nodes[i].Resume is RemoteCursor c) c.ReleaseOrigin();
outcomes[i] = Fail(status);
}
}
}
private static ProjectedHistoryOutcome Fail(uint status) => new(status, []);
private static DataHistoryDetails DetailsOf(ProjectedHistoryNode node, DataHistoryDetails request) =>
node.Resume is RemoteCursor cursor ? cursor.Details : request;
private static string ResumeKey(ProjectedHistoryNode node)
{
if (node.Resume is not RemoteCursor cursor) return "fresh";
return GrpcDataConnection.TryUnwrap(cursor.Token, out var endpoint, out var serving, out _)
? FormattableString.Invariant($"{endpoint}|{serving}") : "resume";
}
private static string CallerKey(RoleCarryingUserIdentity caller) =>
string.Join('\0', caller.Principal ?? "", caller.ApiKeyId ?? "", caller.CredentialVersion ?? "");
/// <summary>
/// Values verbatim (status, absent timestamps). Raw and AtTime values are the node's own values: a kind that disagrees
/// with the catalog is <c>BadTypeMismatch</c> (plan §3.3), never coerced. A Processed value has its AGGREGATE's type (a
/// Double Average or an Int32 Count of a UInt16 node), so only its shape is checked: any scalar kind is accepted.
/// </summary>
private static OriginHistorySample[] Convert(IReadOnlyList<DataHistorySample> samples, DataMetadata metadata, bool processed)
{
var converted = new OriginHistorySample[samples.Count];
for (var i = 0; i < samples.Count; i++)
{
var sample = samples[i];
object? value;
var status = sample.StatusCode;
try
{
var expected = processed && sample.Value.Kind is not (DataValueKind.Null or DataValueKind.Array)
? metadata with { ValueKind = sample.Value.Kind, ValueRank = -1, Dimensions = [], ArrayElementKind = null }
: metadata;
value = ProjectedDataAccess.DecodeValue(sample.Value, expected);
}
catch (Exception ex) when (ex is ArgumentException or InvalidCastException or InvalidOperationException)
{
value = null;
status = BadTypeMismatch;
}
converted[i] = new OriginHistorySample(value, status, sample.SourceTimestampUtc?.UtcDateTime, sample.ServerTimestampUtc?.UtcDateTime);
}
return converted;
}
/// <summary>Queues an origin token for a coalesced best-effort release on its connection.</summary>
private void EnqueueRelease(string connectionId, byte[] token)
{
if (Volatile.Read(ref _disposed) != 0) return;
lock (_releaseGate)
{
if (!_pendingReleases.TryGetValue(connectionId, out var list)) _pendingReleases[connectionId] = list = [];
list.Add(token);
if (!_releaseFlush.IsCompleted) return;
_releaseFlush = Task.Run(FlushReleasesAsync);
}
}
private async Task FlushReleasesAsync()
{
try { await Task.Delay(ReleaseCoalesce, _stop.Token).ConfigureAwait(false); }
catch (OperationCanceledException) { return; }
Dictionary<string, List<byte[]>> batch;
lock (_releaseGate)
{
batch = new(_pendingReleases, StringComparer.OrdinalIgnoreCase);
_pendingReleases.Clear();
}
foreach (var (connectionId, tokens) in batch)
{
IGrpcDataAdapterConnectionLease? lease = null;
try
{
using var timeout = new CancellationTokenSource(TimeSpan.FromSeconds(30));
using var linked = CancellationTokenSource.CreateLinkedTokenSource(timeout.Token, _stop.Token);
lease = await _connections.AcquireAsync(connectionId, linked.Token).ConfigureAwait(false);
if (lease?.Connection is not IDataHistoryService history) continue;
Interlocked.Increment(ref _releaseCalls);
await history.ReleaseAsync(tokens, linked.Token).ConfigureAwait(false);
}
catch (Exception ex) when (ex is not OutOfMemoryException) { } // best effort; the origin's idle expiry is the backstop
finally
{
if (lease is not null) try { await lease.DisposeAsync().ConfigureAwait(false); } catch (Exception) { }
}
}
lock (_releaseGate)
if (_pendingReleases.Count > 0 && Volatile.Read(ref _disposed) == 0) _releaseFlush = Task.Run(FlushReleasesAsync);
}
/// <inheritdoc />
public void Dispose()
{
if (Interlocked.Exchange(ref _disposed, 1) != 0) return;
_stop.Cancel();
_stop.Dispose();
}
/// <summary>
/// Whether a cursor issued under <paramref name="issued"/> for <paramref name="issuedCaller"/> may resume now: same caller
/// (principal, key, credential version), mapping and revision, deployed connection, projection generation, origin view
/// and serving identity (node, incarnation, serving generation, role — a failover or restart changes it).
/// </summary>
internal static bool CursorMatches(ProjectedHistoryTarget issued, string issuedCaller, ProjectedHistoryTarget now, string caller) =>
string.Equals(caller, issuedCaller, StringComparison.Ordinal)
&& string.Equals(now.MappingId, issued.MappingId, StringComparison.Ordinal) && now.MappingRevision == issued.MappingRevision
&& string.Equals(now.ConnectionId, issued.ConnectionId, StringComparison.OrdinalIgnoreCase)
&& now.ProjectionGeneration == issued.ProjectionGeneration && now.OriginMetadata.View == issued.OriginMetadata.View
&& string.Equals(now.Serving.NodeId, issued.Serving.NodeId, StringComparison.Ordinal)
&& string.Equals(now.Serving.Incarnation, issued.Serving.Incarnation, StringComparison.Ordinal)
&& now.Serving.ServingGeneration == issued.Serving.ServingGeneration
&& string.Equals(now.Serving.Role, issued.Serving.Role, StringComparison.Ordinal);
private sealed record GroupKey(string ConnectionId, DataHistoryDetails Details, string Resume);
/// <summary>The remote cursor in the consumer's SDK session store (<see cref="HistoryCursorKind"/> <c>Remote</c>).</summary>
private sealed class RemoteCursor(ProjectedHistoryAccess owner, DataRealm realm, string localIdentifier, byte[] token, string connectionId,
object? routeIdentity, ProjectedHistoryTarget target, string callerKey, DataHistoryDetails details, uint? aggregateId)
: ProjectedHistoryContinuation(realm, localIdentifier)
{
private int _originReleased;
internal ProjectedHistoryAccess Owner => owner;
internal byte[] Token => token;
internal object? RouteIdentity => routeIdentity;
internal DataHistoryDetails Details => details;
internal uint? AggregateId => aggregateId;
/// <summary>The caller, mapping revision, projection generation, serving identity and connection still match.</summary>
internal bool StillMatches(string caller, ProjectedHistoryTarget now, IProjectedDemandLease demand) =>
demand.Realm == Realm && string.Equals(demand.LocalIdentifier, LocalIdentifier, StringComparison.Ordinal)
&& CursorMatches(target, callerKey, now, caller);
/// <summary>Releases the origin token (once), whether the cursor was claimed for a resume or not.</summary>
internal void ReleaseOrigin()
{
if (Interlocked.Exchange(ref _originReleased, 1) == 0) owner.EnqueueRelease(connectionId, token);
}
protected override void OnRelease() => ReleaseOrigin();
}
}