fix(grpc-data): #922 review r1 — own renewal pool + queue, bounded HistoryRead wait, two-authority denial, per-op keys
This commit is contained in:
@@ -8961,6 +8961,7 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage
|
||||
|
||||
var vetoes = new ServiceResult?[nodesToProcess.Count];
|
||||
var lapses = new ProjectedLapseOutcome?[nodesToProcess.Count];
|
||||
var renewalTasks = new Task<bool>?[nodesToProcess.Count];
|
||||
List<Task<bool>>? renewals = null;
|
||||
var access = ProjectedDataAccess;
|
||||
for (var i = 0; i < nodesToProcess.Count; i++)
|
||||
@@ -8973,13 +8974,29 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage
|
||||
Task<bool>? renewal = null;
|
||||
try { lapses[i] = access.RenewLapsed(handle.NodeId, identity, DataOperations.HistoryRead, out renewal); }
|
||||
catch (Exception) { lapses[i] = ProjectedLapseOutcome.Denied; renewal = null; }
|
||||
renewalTasks[i] = renewal;
|
||||
if (renewal is not null) (renewals ??= []).Add(renewal);
|
||||
}
|
||||
if (renewals is not null)
|
||||
{
|
||||
// Block-bridged once per batch, like the projected history read itself; the SDK released Lock before dispatching.
|
||||
try { Task.WhenAll(renewals).Wait(ProjectedLapseRenewalWait); }
|
||||
catch (AggregateException) { }
|
||||
// #922 review: the wait holds an SDK request thread, so it takes one of the SAME non-local history slots a projected
|
||||
// read takes (never waiting for one — none free ⇒ the lapsed nodes are simply retryable), honours the request's
|
||||
// cancellation, and is clearly longer than the renewal's own budget so a renewal that completes is never answered late.
|
||||
var slots = GetNonLocalHistoryLimiter();
|
||||
if (slots.Wait(0))
|
||||
{
|
||||
try
|
||||
{
|
||||
var wait = HistoryReadDeadline > TimeSpan.Zero && HistoryReadDeadline < ProjectedLapseRenewalWait
|
||||
? HistoryReadDeadline : ProjectedLapseRenewalWait;
|
||||
Task.WhenAll(renewals).Wait((int)wait.TotalMilliseconds,
|
||||
context.OperationContext?.CancellationToken ?? CancellationToken.None);
|
||||
}
|
||||
catch (AggregateException) { }
|
||||
catch (OperationCanceledException) { }
|
||||
finally { slots.Release(); }
|
||||
}
|
||||
for (var i = 0; i < nodesToProcess.Count; i++)
|
||||
if (lapses[i] is ProjectedLapseOutcome.Renewing) vetoes[i] = Veto(nodesToProcess[i]);
|
||||
}
|
||||
@@ -8995,6 +9012,10 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage
|
||||
continue;
|
||||
}
|
||||
|
||||
// #922 review: the lapse classification and the veto are two authorities (DataOperationPolicy / DataPlaneAuthorizer).
|
||||
// A renewal that SUCCEEDED and is still vetoed is a real refusal, never a retryable one.
|
||||
if (lapses[i] is ProjectedLapseOutcome.Renewing && renewalTasks[i] is { IsCompletedSuccessfully: true, Result: true })
|
||||
lapses[i] = ProjectedLapseOutcome.Denied;
|
||||
if (lapses[i] is ProjectedLapseOutcome.Renewing or ProjectedLapseOutcome.Unavailable)
|
||||
{
|
||||
// Granted, but the lease could not be renewed in time (origin unreachable, capacity): retryable.
|
||||
@@ -9013,8 +9034,11 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage
|
||||
return allowed;
|
||||
}
|
||||
|
||||
/// <summary>#922: the longest a HistoryRead waits for the on-demand renewal of lapsed projected leases (one wait per batch).</summary>
|
||||
internal static readonly TimeSpan ProjectedLapseRenewalWait = TimeSpan.FromSeconds(5);
|
||||
/// <summary>
|
||||
/// #922: the longest a HistoryRead waits for the on-demand renewal of lapsed projected leases (one wait per batch, capped by
|
||||
/// <see cref="HistoryReadDeadline"/>) — longer than the renewal's own budget (3 s), so a completed renewal is always seen.
|
||||
/// </summary>
|
||||
internal static readonly TimeSpan ProjectedLapseRenewalWait = TimeSpan.FromSeconds(4);
|
||||
|
||||
/// <summary>#922: classifies (and, when it is a lapse, starts renewing) a refused projected node; total — a fault is Denied.</summary>
|
||||
private static ProjectedLapseOutcome ClassifyProjectedLapse(IProjectedDataAccess access, NodeId nodeId,
|
||||
|
||||
@@ -13,6 +13,7 @@ internal sealed class BoundProjectionLease(MetadataAuthorityLease remote, Cancel
|
||||
internal DataTarget? Target => target;
|
||||
internal object? BindingIdentity => bindingIdentity;
|
||||
internal TimeSpan Remaining => remote.Remaining;
|
||||
internal MetadataAuthorityLease Remote => remote;
|
||||
internal TimeSpan UsableDuration => remote.UsableDuration;
|
||||
private bool RouteAlive => !route.IsCancellationRequested && (routeCurrent?.Invoke() ?? true);
|
||||
internal bool LiveContext => RouteAlive && local.IsActive && bindingCurrent() && cache.IsCurrentGeneration(mapping, generation);
|
||||
|
||||
@@ -22,6 +22,9 @@ public sealed class ProjectedBrowseAccess : IProjectedBrowseAccess, IDisposable
|
||||
private readonly object _anchorGate = new();
|
||||
private readonly ConcurrentDictionary<string, Installed> _installed = new(StringComparer.OrdinalIgnoreCase);
|
||||
private readonly ConcurrentDictionary<WorkKey, TaskCompletionSource> _inflight = new();
|
||||
// #922 review: background refreshes of cached pages, keyed by the parent NODE (not caller / MaxResults), so varying the
|
||||
// browse parameters cannot multiply origin browses of one parent.
|
||||
private readonly ConcurrentDictionary<NodeId, byte> _refreshing = new();
|
||||
private readonly record struct Failure(ProjectionPageStatus Status, long Until);
|
||||
private readonly object _resultGate = new();
|
||||
private readonly Dictionary<WorkKey, Failure> _failures = new();
|
||||
@@ -194,7 +197,8 @@ public sealed class ProjectedBrowseAccess : IProjectedBrowseAccess, IDisposable
|
||||
{
|
||||
var now = _catalog.Clock.GetTimestamp();
|
||||
foreach (var expired in _failures.Where(x => x.Value.Until <= now).Select(x => x.Key).ToArray()) _failures.Remove(expired);
|
||||
if (refresh && (_failures.ContainsKey(key) || _inflight.ContainsKey(key))) return Empty(ProjectedBrowseReadiness.Pending);
|
||||
if (refresh && (_failures.ContainsKey(key) || _inflight.ContainsKey(key) || !_refreshing.TryAdd(exactParent, 0)))
|
||||
return Empty(ProjectedBrowseReadiness.Pending);
|
||||
if (_failures.TryGetValue(key, out var failure))
|
||||
return Empty(failure.Status switch
|
||||
{
|
||||
@@ -203,8 +207,12 @@ public sealed class ProjectedBrowseAccess : IProjectedBrowseAccess, IDisposable
|
||||
_ => ProjectedBrowseReadiness.Unavailable
|
||||
});
|
||||
if (_inflight.ContainsKey(key)) return Empty(ProjectedBrowseReadiness.Pending);
|
||||
if (_failures.Count + _pending >= _maxPending) return Empty(ProjectedBrowseReadiness.Unavailable);
|
||||
if (!_inflight.TryAdd(key, new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously))) return Empty(ProjectedBrowseReadiness.Pending);
|
||||
if (_failures.Count + _pending >= _maxPending ||
|
||||
!_inflight.TryAdd(key, new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously)))
|
||||
{
|
||||
if (refresh) _refreshing.TryRemove(exactParent, out _);
|
||||
return Empty(_failures.Count + _pending >= _maxPending ? ProjectedBrowseReadiness.Unavailable : ProjectedBrowseReadiness.Pending);
|
||||
}
|
||||
_pending++;
|
||||
}
|
||||
_ = Task.Run(async () =>
|
||||
@@ -217,6 +225,7 @@ public sealed class ProjectedBrowseAccess : IProjectedBrowseAccess, IDisposable
|
||||
lock (_resultGate)
|
||||
{
|
||||
_inflight.TryRemove(key, out var completed);
|
||||
if (refresh) _refreshing.TryRemove(exactParent, out _);
|
||||
_pending--;
|
||||
if (result != ProjectionPageStatus.Ready && !_stop.IsCancellationRequested)
|
||||
{
|
||||
|
||||
@@ -201,13 +201,20 @@ public sealed class ProjectedDataAccess : IProjectedDataAccess, IDisposable
|
||||
}
|
||||
catch (Exception ex) when (ex is ArgumentException or InvalidOperationException) { ProjectedStreamDiagnostics.Count(ProjectedStreamDiagnostics.Event.AcquireException); return false; }
|
||||
}
|
||||
// #922: at most one on-demand renewal per projected node; a failed one is not retried for a short back-off so a client
|
||||
// polling a node whose origin is unreachable cannot turn every Read into a metadata call.
|
||||
private readonly Dictionary<(DataRealm Realm, string LocalIdentifier), Task<bool>> _lapseRenewals = new();
|
||||
private readonly Dictionary<(DataRealm Realm, string LocalIdentifier), long> _lapseRenewalBackoff = new();
|
||||
// #922: at most one on-demand renewal per projected node AND operation (each requests its own bit at the origin); a failed
|
||||
// one is not retried for a short back-off so a client polling a node whose origin is unreachable cannot turn every Read into
|
||||
// a metadata call. Renewals never use the unary budget (that would starve cold reads, writes and subscription renewals):
|
||||
// they queue — at most MaxQueuedLapseRenewals — for the resolver's own on-demand pool, so a batch of N lapsed nodes renews
|
||||
// them all, a few at a time.
|
||||
private readonly Dictionary<(DataRealm Realm, string LocalIdentifier, DataOperations Operation), Task<bool>> _lapseRenewals = new();
|
||||
private readonly Dictionary<(DataRealm Realm, string LocalIdentifier, DataOperations Operation), long> _lapseRenewalBackoff = new();
|
||||
private const int MaxLapseRenewalBackoffEntries = 4096;
|
||||
internal const int MaxQueuedLapseRenewals = 64;
|
||||
internal static readonly TimeSpan LapseRenewalBackoff = TimeSpan.FromMilliseconds(250);
|
||||
internal static readonly TimeSpan LapseRenewalTimeout = TimeSpan.FromSeconds(5);
|
||||
/// <summary>The whole on-demand renewal, pool wait included; clearly shorter than the longest a HistoryRead waits for it.</summary>
|
||||
internal static readonly TimeSpan LapseRenewalTimeout = TimeSpan.FromSeconds(3);
|
||||
/// <summary>One metadata item and its capability probe: never a multi-MiB unary reservation.</summary>
|
||||
internal const long LapseRenewalBytes = 256 * 1024;
|
||||
internal int LapseRenewalsStartedForTests => Volatile.Read(ref _lapseRenewalsStarted);
|
||||
private int _lapseRenewalsStarted;
|
||||
|
||||
@@ -234,8 +241,8 @@ public sealed class ProjectedDataAccess : IProjectedDataAccess, IDisposable
|
||||
// refused exactly as before, and never causes an origin call.
|
||||
if (!_policy.AuthorizeMappedSubject(identity, Operation(operation), proof.Metadata.View, proof.Lease.Serving, proof.Subject, proof.Resolver))
|
||||
return ProjectedLapseOutcome.Denied;
|
||||
var key = (definition.Realm, definition.LocalIdentifier);
|
||||
var budget = new DataBudget(LapseRenewalTimeout, 1, _limits.MaxUnaryBytes);
|
||||
var key = (definition.Realm, definition.LocalIdentifier, operation);
|
||||
var budget = new DataBudget(LapseRenewalTimeout, 1, Math.Min(LapseRenewalBytes, _limits.MaxUnaryBytes));
|
||||
TaskCompletionSource<bool> started;
|
||||
lock (_sync)
|
||||
{
|
||||
@@ -247,9 +254,7 @@ public sealed class ProjectedDataAccess : IProjectedDataAccess, IDisposable
|
||||
if (now < until) return ProjectedLapseOutcome.Unavailable;
|
||||
_lapseRenewalBackoff.Remove(key);
|
||||
}
|
||||
if (_unaryCount >= _limits.MaxUnaryOperations || budget.MaxBytes > _limits.MaxUnaryBytes - _unaryBytes)
|
||||
return ProjectedLapseOutcome.Unavailable;
|
||||
_unaryCount++; _unaryBytes += budget.MaxBytes;
|
||||
if (_lapseRenewals.Count >= MaxQueuedLapseRenewals) return ProjectedLapseOutcome.Unavailable;
|
||||
started = new TaskCompletionSource<bool>(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
_lapseRenewals.Add(key, started.Task);
|
||||
}
|
||||
@@ -263,7 +268,7 @@ public sealed class ProjectedDataAccess : IProjectedDataAccess, IDisposable
|
||||
}
|
||||
|
||||
private async Task RunLapseRenewalAsync(RemoteNamespaceResolver resolver, IProjectedNamespacePageSink sink,
|
||||
(DataRealm Realm, string LocalIdentifier) key, ProjectedNodeProof proof, ProjectedVariableDefinition definition, NodeId nodeId,
|
||||
(DataRealm Realm, string LocalIdentifier, DataOperations Operation) key, ProjectedNodeProof proof, ProjectedVariableDefinition definition, NodeId nodeId,
|
||||
RoleCarryingUserIdentity caller, DataCallerIdentity identity, DataOperations operation, DataBudget budget, TaskCompletionSource<bool> completion)
|
||||
{
|
||||
var renewed = false;
|
||||
@@ -271,18 +276,17 @@ public sealed class ProjectedDataAccess : IProjectedDataAccess, IDisposable
|
||||
{
|
||||
renewed = await resolver.RenewExactAsync(proof, definition, nodeId, identity, null, sink, budget,
|
||||
() => { lock (_sync) return !_disposed; }, CancellationToken.None, overlap: false,
|
||||
authorizeAs: Operation(operation), required: operation).ConfigureAwait(false);
|
||||
authorizeAs: Operation(operation), required: operation, onDemand: true).ConfigureAwait(false);
|
||||
}
|
||||
catch (Exception ex) when (ex is not OutOfMemoryException) { renewed = false; }
|
||||
finally
|
||||
{
|
||||
lock (_sync)
|
||||
{
|
||||
_unaryCount--; _unaryBytes -= budget.MaxBytes;
|
||||
_lapseRenewals.Remove(key);
|
||||
if (!renewed && !_disposed)
|
||||
{
|
||||
if (_lapseRenewalBackoff.Count >= MaxLapseRenewalBackoffEntries) _lapseRenewalBackoff.Clear();
|
||||
if (_lapseRenewalBackoff.Count >= MaxLapseRenewalBackoffEntries) EvictLapseBackoffLocked();
|
||||
var delay = (long)(LapseRenewalBackoff.TotalSeconds * Clock.TimestampFrequency);
|
||||
_lapseRenewalBackoff[key] = Clock.GetTimestamp() + Math.Max(1, delay);
|
||||
}
|
||||
@@ -303,6 +307,15 @@ public sealed class ProjectedDataAccess : IProjectedDataAccess, IDisposable
|
||||
}
|
||||
completion.TrySetResult(renewed);
|
||||
}
|
||||
// Full map (rare): drop the expired entries; if none expired, the one that expires first — never the whole map, which would
|
||||
// let every node's back-off lapse at once.
|
||||
private void EvictLapseBackoffLocked()
|
||||
{
|
||||
var now = Clock.GetTimestamp();
|
||||
var expired = _lapseRenewalBackoff.Where(entry => entry.Value <= now).Select(entry => entry.Key).ToArray();
|
||||
foreach (var key in expired) _lapseRenewalBackoff.Remove(key);
|
||||
if (expired.Length == 0) _lapseRenewalBackoff.Remove(_lapseRenewalBackoff.MinBy(entry => entry.Value).Key);
|
||||
}
|
||||
/// <summary>The per-read byte budget the SDK Read path schedules a cold projected read with.</summary>
|
||||
internal const long ProjectedReadBytes = 4 * 1024 * 1024;
|
||||
internal bool TryAcquireConfigured(NodeId nodeId, ConfiguredProjectionCapability capability, out IProjectedDemandLease? demand)
|
||||
|
||||
@@ -22,6 +22,10 @@ public sealed class RemoteNamespaceResolver : IFederatedProjectionCatalog, IDisp
|
||||
private readonly DataOperationPolicy _policy;
|
||||
private readonly int _maxMappings;
|
||||
private readonly SemaphoreSlim _fetchSlots;
|
||||
// #922 review: on-demand renewals of lapsed nodes (a Read / HistoryRead) run on their OWN small pool, never on _fetchSlots,
|
||||
// so a burst of them cannot crowd out browse pages or the subscription renewals that keep live items from lapsing.
|
||||
private readonly SemaphoreSlim _onDemandSlots;
|
||||
internal int OnDemandRenewalSlots { get; }
|
||||
private readonly int _maximumWaiters;
|
||||
private readonly Func<CancellationToken, Task>? _beforeFetch;
|
||||
private int _waiterCount;
|
||||
@@ -44,6 +48,8 @@ public sealed class RemoteNamespaceResolver : IFederatedProjectionCatalog, IDisp
|
||||
_source = source ?? throw new ArgumentNullException(nameof(source)); _policy = policy ?? throw new ArgumentNullException(nameof(policy));
|
||||
if (maxMappings <= 0 || maxConcurrentFetches <= 0) throw new ArgumentOutOfRangeException(nameof(maxMappings));
|
||||
_maxMappings = maxMappings; _fetchSlots = new(maxConcurrentFetches, maxConcurrentFetches);
|
||||
OnDemandRenewalSlots = Math.Max(1, maxConcurrentFetches / 2);
|
||||
_onDemandSlots = new(OnDemandRenewalSlots, OnDemandRenewalSlots);
|
||||
_maximumWaiters = checked(maxConcurrentFetches * 16);
|
||||
_cache.Invalidated += OnInvalidated;
|
||||
}
|
||||
@@ -304,7 +310,8 @@ public sealed class RemoteNamespaceResolver : IFederatedProjectionCatalog, IDisp
|
||||
internal async Task<bool> RenewExactAsync(ProjectedNodeProof previous, ProjectedVariableDefinition definition,
|
||||
NodeId nodeId, DataCallerIdentity? caller, ConfiguredProjectionCapability? configured,
|
||||
IProjectedNamespacePageSink sink, DataBudget budget, Func<bool> demandActive, CancellationToken cancellationToken, bool overlap = false,
|
||||
OpcUaOperation authorizeAs = OpcUaOperation.CreateMonitoredItems, DataOperations required = DataOperations.Subscribe)
|
||||
OpcUaOperation authorizeAs = OpcUaOperation.CreateMonitoredItems, DataOperations required = DataOperations.Subscribe,
|
||||
bool onDemand = false)
|
||||
{
|
||||
// #922: a subscription renews for CreateMonitoredItems/Subscribe (the default); an on-demand renewal of a lapsed node
|
||||
// renews for the operation the caller is performing (Read / HistoryRead) and requires exactly that bit at the origin.
|
||||
@@ -329,7 +336,17 @@ public sealed class RemoteNamespaceResolver : IFederatedProjectionCatalog, IDisp
|
||||
previous.Subject.Scope.Segments.Count < binding.LocalScope.Segments.Count ||
|
||||
!previous.Subject.Scope.Segments.Take(binding.LocalScope.Segments.Count).SequenceEqual(binding.LocalScope.Segments, StringComparer.Ordinal) ||
|
||||
!previous.Subject.LocalAncestry.SequenceEqual(binding.LocalAncestry, StringComparer.OrdinalIgnoreCase)) return false;
|
||||
if (!await _fetchSlots.WaitAsync(0, cancellationToken).ConfigureAwait(false)) return false;
|
||||
// A subscription renewal never queues (it retries on its own cadence); an on-demand renewal waits for its own pool within
|
||||
// its budget, and the wait is charged to that budget.
|
||||
var slots = onDemand ? _onDemandSlots : _fetchSlots;
|
||||
var queued = System.Diagnostics.Stopwatch.GetTimestamp();
|
||||
if (!await slots.WaitAsync(onDemand ? budget.Timeout : TimeSpan.Zero, cancellationToken).ConfigureAwait(false)) return false;
|
||||
if (onDemand)
|
||||
{
|
||||
var left = budget.Timeout - System.Diagnostics.Stopwatch.GetElapsedTime(queued);
|
||||
if (left <= TimeSpan.Zero) { slots.Release(); return false; }
|
||||
budget = budget with { Timeout = left };
|
||||
}
|
||||
IGrpcDataAdapterConnectionLease? connection = null;
|
||||
try
|
||||
{
|
||||
@@ -407,7 +424,7 @@ public sealed class RemoteNamespaceResolver : IFederatedProjectionCatalog, IDisp
|
||||
{
|
||||
try { if (connection is not null) await connection.DisposeAsync().ConfigureAwait(false); }
|
||||
catch (Exception) { }
|
||||
finally { _fetchSlots.Release(); }
|
||||
finally { slots.Release(); }
|
||||
}
|
||||
}
|
||||
public void Dispose()
|
||||
|
||||
Reference in New Issue
Block a user