feat(grpc-data): H3 ProjectedHistoryAccess over deployed connections
Resolves, authorizes (HistoryRead demand: mapping bit + local grant on the mapping scope, ACLs on or off) and pins each projected node, groups the batch per connection / details / issuing endpoint and forwards through IDataHistoryService. Remote cursors bind caller, mapping id+revision, connection route, projection generation, origin view and serving identity, and resend the ORIGINAL details; any change => BadContinuationPointInvalid with the origin token released. Shared per-request assembly budget (min mapping MaxHistoryAssemblyBytesPerRequest) => BadTooManyOperations for the remaining nodes. Releases coalesce per connection. Replaces the H2 refusal pin with the intended behaviour (granted => served, no grant => BadUserAccessDenied).
This commit is contained in:
@@ -118,6 +118,13 @@ public static class DataConnectionRegistration
|
||||
(!settings.IsWarm || state.WarmRole == WarmRole.Active), state.Generation);
|
||||
}, renewalSink: sp.GetRequiredService<IProjectedNamespacePageSink>()));
|
||||
services.AddSingleton<IProjectedDataAccess>(sp => sp.GetRequiredService<ProjectedDataAccess>());
|
||||
// H3: OPC UA HistoryRead on projected variables, forwarded over the mapping's deployed connection.
|
||||
services.AddSingleton(sp => new ProjectedHistoryAccess(sp.GetRequiredService<ProjectedDataAccess>(),
|
||||
sp.GetRequiredService<IGrpcDataAdapterConnectionSource>(),
|
||||
mappingId => sp.GetRequiredService<ProjectedMappingDeploymentRuntime>().TryGetHistoryAssemblyBudget(mappingId, out var bytes)
|
||||
? bytes : null,
|
||||
sp.GetRequiredService<TimeProvider>()));
|
||||
services.AddSingleton<IProjectedHistoryAccess>(sp => sp.GetRequiredService<ProjectedHistoryAccess>());
|
||||
services.AddSingleton<IConfiguredProjectionDiscovery>(sp => new ConfiguredProjectionDiscovery(
|
||||
sp.GetRequiredService<ProjectedMappingDeploymentRuntime>(), sp.GetRequiredService<IFederatedProjectionCatalog>(),
|
||||
sp.GetRequiredService<ProjectedNamespaceApplier>(), sp.GetRequiredService<IProjectedNodeLookup>(),
|
||||
|
||||
@@ -60,6 +60,7 @@ public sealed class OtOpcUaServerHostedService : IHostedService, IAsyncDisposabl
|
||||
private readonly DriverWriteBounds _writeBounds;
|
||||
private readonly IProjectedBrowseAccess? _projectedBrowseAccess;
|
||||
private readonly IProjectedDataAccess? _projectedDataAccess;
|
||||
private readonly IProjectedHistoryAccess? _projectedHistoryAccess;
|
||||
private readonly IFederatedProjectionCatalog? _projectedCatalog;
|
||||
private readonly DataConnectionOptions _dataConnectionOptions;
|
||||
|
||||
@@ -140,6 +141,7 @@ public sealed class OtOpcUaServerHostedService : IHostedService, IAsyncDisposabl
|
||||
/// <param name="projectedBrowseAccess">Optional caller-bound mapped browse scheduler.</param>
|
||||
/// <param name="projectedDataAccess">Optional bounded mapped read, write and subscription gateway.</param>
|
||||
/// <param name="projectedCatalog">Optional live projection catalog used for mapped authorization.</param>
|
||||
/// <param name="projectedHistoryAccess">Optional HistoryRead gateway for projected variables (H3).</param>
|
||||
public OtOpcUaServerHostedService(
|
||||
IOptions<OpcUaApplicationHostOptions> options,
|
||||
DeferredAddressSpaceSink deferredSink,
|
||||
@@ -164,8 +166,10 @@ public sealed class OtOpcUaServerHostedService : IHostedService, IAsyncDisposabl
|
||||
DeferredStandbyProjection? deferredStandby = null,
|
||||
IProjectedBrowseAccess? projectedBrowseAccess = null,
|
||||
IProjectedDataAccess? projectedDataAccess = null,
|
||||
IFederatedProjectionCatalog? projectedCatalog = null)
|
||||
IFederatedProjectionCatalog? projectedCatalog = null,
|
||||
IProjectedHistoryAccess? projectedHistoryAccess = null)
|
||||
{
|
||||
_projectedHistoryAccess = projectedHistoryAccess;
|
||||
_dataConnectionOptions = configuration.GetSection(DataConnectionOptions.SectionName).Get<DataConnectionOptions>() ?? new();
|
||||
_projectedBrowseAccess = projectedBrowseAccess;
|
||||
_projectedDataAccess = projectedDataAccess;
|
||||
@@ -264,6 +268,7 @@ public sealed class OtOpcUaServerHostedService : IHostedService, IAsyncDisposabl
|
||||
_server.NodeManager.ProjectedBrowseAccess = _projectedBrowseAccess;
|
||||
_server.NodeManager.ProjectedBrowseClock = _time;
|
||||
_server.NodeManager.ProjectedDataAccess = _projectedDataAccess;
|
||||
_server.NodeManager.ProjectedHistoryAccess = _projectedHistoryAccess;
|
||||
if (_projectedCatalog is { } projectedCatalog)
|
||||
_server.NodeManager.MappedSubjectResolver = (realm, identifier) =>
|
||||
projectedCatalog.TryResolveProjected(realm == AddressSpaceRealm.Raw ? DataRealm.Raw : DataRealm.Uns,
|
||||
|
||||
@@ -43,6 +43,9 @@ public sealed partial class LocalDataServices
|
||||
/// <summary>Live history sessions (diagnostics/tests).</summary>
|
||||
internal int HistorySessionCount => _historySessions.Count;
|
||||
|
||||
/// <summary>Open origin continuations (page cursors + chunk remainders) across every session (diagnostics/tests).</summary>
|
||||
internal int HistoryOpenContinuations => _historySessions.OpenContinuations;
|
||||
|
||||
/// <summary>Remainder bytes retained for a principal across its sessions (diagnostics/tests).</summary>
|
||||
internal long HistoryRetainedBytes(string principal) => _historySessions.RetainedBytes(principal);
|
||||
|
||||
|
||||
@@ -194,6 +194,17 @@ internal sealed class OriginHistorySessions(TimeProvider clock, int maxSessions
|
||||
/// <summary>Live sessions (diagnostics/tests).</summary>
|
||||
public int Count { get { lock (_gate) return _sessions.Count; } }
|
||||
|
||||
/// <summary>Open page cursors plus chunk remainders across every session (diagnostics/tests).</summary>
|
||||
public int OpenContinuations
|
||||
{
|
||||
get
|
||||
{
|
||||
OriginHistorySession[] sessions;
|
||||
lock (_gate) sessions = _sessions.Values.Select(x => x.Session).ToArray();
|
||||
return sessions.Sum(x => x.Cursors.Count + x.ChunkCount);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Remainder bytes retained for <paramref name="principal"/> across its sessions.</summary>
|
||||
public long RetainedBytes(string principal) { lock (_gate) return _retained.GetValueOrDefault(principal); }
|
||||
|
||||
|
||||
@@ -130,7 +130,7 @@ public sealed class ProjectedDataAccess : IProjectedDataAccess, IDisposable
|
||||
if (metadata.ValueKind == DataValueKind.Timestamp && value is DateTime timestamp) value = new DateTimeOffset(timestamp.ToUniversalTime());
|
||||
return ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections.DataValue.FromScalar(metadata.ValueKind, value);
|
||||
}
|
||||
private static object? DecodeValue(ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections.DataValue value, DataMetadata metadata)
|
||||
internal static object? DecodeValue(ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections.DataValue value, DataMetadata metadata)
|
||||
{
|
||||
if (value.Kind == DataValueKind.Null) return null;
|
||||
if (value.Kind != metadata.ValueKind) throw new ArgumentException("Value kind does not match metadata.");
|
||||
@@ -154,13 +154,15 @@ public sealed class ProjectedDataAccess : IProjectedDataAccess, IDisposable
|
||||
public bool TryAcquire(NodeId nodeId, RoleCarryingUserIdentity caller, DataOperations operation, out IProjectedDemandLease? demand)
|
||||
{
|
||||
demand = null;
|
||||
if (caller is null || operation is not (DataOperations.Browse or DataOperations.Read or DataOperations.Write or DataOperations.Subscribe)) { ProjectedStreamDiagnostics.Count(ProjectedStreamDiagnostics.Event.AcquireInvalid); return false; }
|
||||
if (caller is null || operation is not (DataOperations.Browse or DataOperations.Read or DataOperations.Write or DataOperations.Subscribe or DataOperations.HistoryRead)) { ProjectedStreamDiagnostics.Count(ProjectedStreamDiagnostics.Event.AcquireInvalid); return false; }
|
||||
try
|
||||
{
|
||||
if (!_nodes.TryResolve(nodeId, out var definition) || definition is null || !definition.AuthorityIsCurrent() ||
|
||||
!_catalog.TryResolveProjected(definition.Realm, definition.LocalIdentifier, out var proof) || proof is null ||
|
||||
proof.Generation != definition.ProjectionGeneration || !MetadataMatches(proof.Metadata, definition.Metadata) ||
|
||||
((operation is DataOperations.Read or DataOperations.Subscribe) && proof.MaximumSampleAge <= TimeSpan.Zero) ||
|
||||
// H3: history only on a node projected Historizing (mapping bit AND origin HistoryInfo), whatever the caller holds.
|
||||
(operation == DataOperations.HistoryRead && (!definition.Historizing || !ProjectedHistoryAccess.Advertises(proof))) ||
|
||||
proof.Metadata.View.MappingId is not { } mapping || proof.Lease.Serving.ServingGeneration <= 0 ||
|
||||
_connectionForMapping(mapping) is not { Length: > 0 } connectionId) { ProjectedStreamDiagnostics.Count(ProjectedStreamDiagnostics.Event.AcquireDefinition); return false; }
|
||||
var identity = new DataCallerIdentity(caller.Principal, caller.ApiKeyId, caller.CredentialVersion, caller.CredentialExpiresUtc);
|
||||
@@ -213,12 +215,24 @@ public sealed class ProjectedDataAccess : IProjectedDataAccess, IDisposable
|
||||
if (lease is Demand demand) await demand.Completion.ConfigureAwait(false);
|
||||
}
|
||||
public bool HasLiveDemand(DataRealm realm, string localIdentifier) { lock (_sync) return _demandCounts.ContainsKey((realm, localIdentifier)); }
|
||||
/// <summary>H3: what a HistoryRead demand is bound to — its mapping, revision, deployed connection and the origin's metadata.</summary>
|
||||
internal bool TryDescribeHistoryDemand(IProjectedDemandLease lease, out ProjectedHistoryTarget? target)
|
||||
{
|
||||
target = null;
|
||||
if (lease is not Demand { RequestedOperation: DataOperations.HistoryRead } demand || !demand.IsValid) return false;
|
||||
var binding = demand.CurrentBinding;
|
||||
if (binding.Proof.Metadata.View.MappingId is not { } mapping) return false;
|
||||
target = new ProjectedHistoryTarget(mapping, binding.Proof.Metadata.View.MappingRevision, binding.ConnectionId,
|
||||
binding.Proof.OriginMetadata, binding.Proof.Lease.Serving, binding.Proof.Generation);
|
||||
return true;
|
||||
}
|
||||
private static OpcUaOperation Operation(DataOperations operation) => operation switch
|
||||
{
|
||||
DataOperations.Browse => OpcUaOperation.Browse,
|
||||
DataOperations.Read => OpcUaOperation.Read,
|
||||
DataOperations.Write => OpcUaOperation.WriteOperate,
|
||||
DataOperations.Subscribe => OpcUaOperation.CreateMonitoredItems,
|
||||
DataOperations.HistoryRead => OpcUaOperation.HistoryRead,
|
||||
_ => throw new ArgumentOutOfRangeException(nameof(operation))
|
||||
};
|
||||
private sealed class Demand(ProjectedDataAccess owner, NodeId nodeId, ProjectedVariableDefinition definition,
|
||||
|
||||
@@ -0,0 +1,448 @@
|
||||
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), 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); a value kind that disagrees with the catalog is <c>BadTypeMismatch</c>.</summary>
|
||||
private static OriginHistorySample[] Convert(IReadOnlyList<DataHistorySample> samples, DataMetadata metadata)
|
||||
{
|
||||
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 { value = ProjectedDataAccess.DecodeValue(sample.Value, metadata); }
|
||||
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();
|
||||
}
|
||||
}
|
||||
+13
@@ -122,6 +122,19 @@ public sealed class ProjectedMappingDeploymentRuntime : IDisposable
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>H3: the mapping's per-request history assembly budget, while its activated authority is current.</summary>
|
||||
public bool TryGetHistoryAssemblyBudget(string mappingId, out long bytes)
|
||||
{
|
||||
bytes = 0;
|
||||
if (!TryGetConnectionId(mappingId, out _)) return false;
|
||||
lock (_gate)
|
||||
{
|
||||
if (!_byMapping.TryGetValue(mappingId, out var placement)) return false;
|
||||
bytes = placement.Mapping.MaxHistoryAssemblyBytesPerRequest;
|
||||
return bytes > 0;
|
||||
}
|
||||
}
|
||||
|
||||
public void Stage(CatalogAttempt attempt, IReadOnlyList<RemoteNamespaceMapping> mappings, IReadOnlyList<DataConnection> connections)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(attempt);
|
||||
|
||||
@@ -95,7 +95,8 @@ public sealed class ProjectedNamespaceApplier : IDisposable
|
||||
if (!PageCurrent() || guards.Any(guard => !guard.IsCurrent()) || root is not null && !root.IsCurrent())
|
||||
return ProjectionPageStatus.Unavailable;
|
||||
var definitions = guards.Select(guard => new ProjectedVariableDefinition(guard.Proof.Metadata.View.Realm,
|
||||
guard.Proof.LocalIdentifier, exactParent, guard.Proof.Metadata, guard.Proof.Generation, guard.IsCurrent)).ToArray();
|
||||
guard.Proof.LocalIdentifier, exactParent, guard.Proof.Metadata, guard.Proof.Generation, guard.IsCurrent)
|
||||
{ Historizing = ProjectedHistoryAccess.Advertises(guard.Proof) }).ToArray();
|
||||
var rootLeaf = root is not null && ProjectedCatalogCache.IsValueNode(root.Proof.Metadata);
|
||||
if (rootLeaf && (definitions.Length != 0 || !page.Complete)) return ProjectionPageStatus.Unavailable;
|
||||
var attempted = 0;
|
||||
@@ -112,7 +113,8 @@ public sealed class ProjectedNamespaceApplier : IDisposable
|
||||
{
|
||||
accepted = rootLeaf
|
||||
? _sink.TryApplyRootLeaf(exactParent, new ProjectedVariableDefinition(root!.Proof.Metadata.View.Realm,
|
||||
root.Proof.LocalIdentifier, exactParent, root.Proof.Metadata, root.Proof.Generation, root.IsCurrent), Commit)
|
||||
root.Proof.LocalIdentifier, exactParent, root.Proof.Metadata, root.Proof.Generation, root.IsCurrent)
|
||||
{ Historizing = ProjectedHistoryAccess.Advertises(root.Proof) }, Commit)
|
||||
: _sink.TryApply(exactParent, definitions, Commit);
|
||||
return accepted && committed && PageCurrent() ? ProjectionPageStatus.Ready : ProjectionPageStatus.Unavailable;
|
||||
}
|
||||
|
||||
@@ -380,7 +380,7 @@ public sealed class RemoteNamespaceResolver : IFederatedProjectionCatalog, IDisp
|
||||
if (!guard.IsCurrent() || caller is not null && !_policy.AuthorizeMapped(caller, OpcUaOperation.CreateMonitoredItems,
|
||||
mapped.View, serving, subject, resolver, lease)) return false;
|
||||
var newDefinition = new ProjectedVariableDefinition(definition.Realm, definition.LocalIdentifier, definition.Parent,
|
||||
mapped, generation, guard.IsCurrent) { Lifetime = definition.Lifetime };
|
||||
mapped, generation, guard.IsCurrent) { Lifetime = definition.Lifetime, Historizing = ProjectedHistoryAccess.Advertises(renewed) };
|
||||
return sink.TryRenewExact(nodeId, definition, newDefinition, () =>
|
||||
{
|
||||
var duration = Clock.GetElapsedTime(started, Clock.GetTimestamp());
|
||||
|
||||
Reference in New Issue
Block a user