Merge #938/#939/#940/#948: projected Read maxAge=0 serves a bounded async origin read; renewal carries refusal kind (PERMISSION_DENIED -> BadUserAccessDenied, cached 5 s); Write/CreateMonitoredItems renew a lapsed lease; no proof candidate for a re-delivered consumed acquisition
This commit is contained in:
@@ -208,11 +208,15 @@ public sealed class ProjectedDataAccess : IProjectedDataAccess, IDisposable
|
||||
// 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 readonly Dictionary<(DataRealm Realm, string LocalIdentifier, DataOperations Operation), Task<ProjectedRenewalResult>> _lapseRenewals = new();
|
||||
// #939: a failed renewal backs off briefly (Refused = false ⇒ retryable); a definitive ORIGIN refusal is held longer and
|
||||
// answered Denied (BadUserAccessDenied) without another origin call until it expires.
|
||||
private readonly Dictionary<(DataRealm Realm, string LocalIdentifier, DataOperations Operation), (long Until, bool Refused)> _lapseRenewalBackoff = new();
|
||||
private const int MaxLapseRenewalBackoffEntries = 4096;
|
||||
internal const int MaxQueuedLapseRenewals = 64;
|
||||
internal static readonly TimeSpan LapseRenewalBackoff = TimeSpan.FromMilliseconds(250);
|
||||
/// <summary>#939: how long a definitive origin refusal of a lapsed node's renewal is answered <c>BadUserAccessDenied</c> unsent.</summary>
|
||||
internal static readonly TimeSpan LapseRefusalHold = 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>
|
||||
@@ -221,11 +225,12 @@ public sealed class ProjectedDataAccess : IProjectedDataAccess, IDisposable
|
||||
private int _lapseRenewalsStarted;
|
||||
|
||||
/// <inheritdoc />
|
||||
public ProjectedLapseOutcome RenewLapsed(NodeId nodeId, RoleCarryingUserIdentity caller, DataOperations operation, out Task<bool>? renewal)
|
||||
public ProjectedLapseOutcome RenewLapsed(NodeId nodeId, RoleCarryingUserIdentity caller, DataOperations operation,
|
||||
out Task<ProjectedRenewalResult>? renewal)
|
||||
{
|
||||
renewal = null;
|
||||
if (caller is null || operation is not (DataOperations.Read or DataOperations.HistoryRead) || _renewalSink is not { } sink ||
|
||||
_catalog is not RemoteNamespaceResolver resolver) return ProjectedLapseOutcome.Denied;
|
||||
if (caller is null || operation is not (DataOperations.Read or DataOperations.HistoryRead or DataOperations.Write or DataOperations.Subscribe) ||
|
||||
_renewalSink is not { } sink || _catalog is not RemoteNamespaceResolver resolver) return ProjectedLapseOutcome.Denied;
|
||||
try
|
||||
{
|
||||
// The SDK node must still be live, and either it or its catalog proof must have lapsed — a refusal of a node whose
|
||||
@@ -235,9 +240,13 @@ public sealed class ProjectedDataAccess : IProjectedDataAccess, IDisposable
|
||||
definition.AuthorityIsCurrent() && _catalog.IsUsableProof(proof) ||
|
||||
proof.Generation != definition.ProjectionGeneration || !MetadataMatches(proof.Metadata, definition.Metadata) ||
|
||||
proof.Metadata.View.MappingId is not { } mapping || _connectionForMapping(mapping) is not { Length: > 0 } ||
|
||||
(operation == DataOperations.Read && proof.MaximumSampleAge <= TimeSpan.Zero) ||
|
||||
(operation is DataOperations.Read or DataOperations.Subscribe && proof.MaximumSampleAge <= TimeSpan.Zero) ||
|
||||
(operation == DataOperations.HistoryRead && (!definition.Historizing || !ProjectedHistoryAccess.Advertises(proof))))
|
||||
return ProjectedLapseOutcome.Denied;
|
||||
// #940: a write is also gated on this node's local write role — a node that may not write refuses whatever the lease
|
||||
// says, exactly as TryAcquire does.
|
||||
if (operation == DataOperations.Write && _localWriteRole() is not { Allowed: true, Generation: > 0 })
|
||||
return ProjectedLapseOutcome.Denied;
|
||||
var identity = new DataCallerIdentity(caller.Principal, caller.ApiKeyId, caller.CredentialVersion, caller.CredentialExpiresUtc);
|
||||
// The same grant the served operation needs, judged on everything but the lapsed lease: a caller without it is
|
||||
// refused exactly as before, and never causes an origin call.
|
||||
@@ -245,24 +254,25 @@ public sealed class ProjectedDataAccess : IProjectedDataAccess, IDisposable
|
||||
return ProjectedLapseOutcome.Denied;
|
||||
var key = (definition.Realm, definition.LocalIdentifier, operation);
|
||||
var budget = new DataBudget(LapseRenewalTimeout, 1, Math.Min(LapseRenewalBytes, _limits.MaxUnaryBytes));
|
||||
TaskCompletionSource<bool> started;
|
||||
TaskCompletionSource<ProjectedRenewalResult> started;
|
||||
lock (_sync)
|
||||
{
|
||||
if (_disposed) return ProjectedLapseOutcome.Unavailable;
|
||||
if (_lapseRenewals.TryGetValue(key, out var running)) { renewal = running; return ProjectedLapseOutcome.Renewing; }
|
||||
var now = Clock.GetTimestamp();
|
||||
if (_lapseRenewalBackoff.TryGetValue(key, out var until))
|
||||
if (_lapseRenewalBackoff.TryGetValue(key, out var held))
|
||||
{
|
||||
if (now < until) return ProjectedLapseOutcome.Unavailable;
|
||||
// #939: a recent definitive origin refusal is an access denial, answered without another origin call.
|
||||
if (now < held.Until) return held.Refused ? ProjectedLapseOutcome.Denied : ProjectedLapseOutcome.Unavailable;
|
||||
_lapseRenewalBackoff.Remove(key);
|
||||
}
|
||||
if (_lapseRenewals.Count >= MaxQueuedLapseRenewals) return ProjectedLapseOutcome.Unavailable;
|
||||
started = new TaskCompletionSource<bool>(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
started = new TaskCompletionSource<ProjectedRenewalResult>(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
_lapseRenewals.Add(key, started.Task);
|
||||
}
|
||||
Interlocked.Increment(ref _lapseRenewalsStarted);
|
||||
// Never on the caller's thread: the renewal awaits the origin and commits through the SDK sink (node-manager Lock).
|
||||
_ = Task.Run(() => RunLapseRenewalAsync(resolver, sink, key, proof, definition, nodeId, caller, identity, operation, budget, started));
|
||||
_ = Task.Run(() => RunLapseRenewalAsync(resolver, sink, key, proof, definition, nodeId, identity, operation, budget, started));
|
||||
renewal = started.Task;
|
||||
return ProjectedLapseOutcome.Renewing;
|
||||
}
|
||||
@@ -271,52 +281,42 @@ public sealed class ProjectedDataAccess : IProjectedDataAccess, IDisposable
|
||||
|
||||
private async Task RunLapseRenewalAsync(RemoteNamespaceResolver resolver, IProjectedNamespacePageSink sink,
|
||||
(DataRealm Realm, string LocalIdentifier, DataOperations Operation) key, ProjectedNodeProof proof, ProjectedVariableDefinition definition, NodeId nodeId,
|
||||
RoleCarryingUserIdentity caller, DataCallerIdentity identity, DataOperations operation, DataBudget budget, TaskCompletionSource<bool> completion)
|
||||
DataCallerIdentity identity, DataOperations operation, DataBudget budget, TaskCompletionSource<ProjectedRenewalResult> completion)
|
||||
{
|
||||
var renewed = false;
|
||||
var result = ProjectedRenewalResult.Failed;
|
||||
try
|
||||
{
|
||||
renewed = await resolver.RenewExactAsync(proof, definition, nodeId, identity, null, sink, budget,
|
||||
result = await resolver.RenewExactOutcomeAsync(proof, definition, nodeId, identity, null, sink, budget,
|
||||
() => { lock (_sync) return !_disposed; }, CancellationToken.None, overlap: false,
|
||||
authorizeAs: Operation(operation), required: operation, onDemand: true).ConfigureAwait(false);
|
||||
}
|
||||
catch (Exception ex) when (ex is not OutOfMemoryException) { renewed = false; }
|
||||
catch (Exception ex) when (ex is not OutOfMemoryException) { result = ProjectedRenewalResult.Failed; }
|
||||
finally
|
||||
{
|
||||
lock (_sync)
|
||||
{
|
||||
_lapseRenewals.Remove(key);
|
||||
if (!renewed && !_disposed)
|
||||
if (result != ProjectedRenewalResult.Renewed && !_disposed)
|
||||
{
|
||||
if (_lapseRenewalBackoff.Count >= MaxLapseRenewalBackoffEntries) EvictLapseBackoffLocked();
|
||||
var delay = (long)(LapseRenewalBackoff.TotalSeconds * Clock.TimestampFrequency);
|
||||
_lapseRenewalBackoff[key] = Clock.GetTimestamp() + Math.Max(1, delay);
|
||||
var refused = result == ProjectedRenewalResult.Refused;
|
||||
var delay = (long)((refused ? LapseRefusalHold : LapseRenewalBackoff).TotalSeconds * Clock.TimestampFrequency);
|
||||
_lapseRenewalBackoff[key] = (Clock.GetTimestamp() + Math.Max(1, delay), refused);
|
||||
}
|
||||
}
|
||||
}
|
||||
// A Read answered retryable while the lease renewed: fetch the value now, through the ordinary authorized path, so the
|
||||
// client's retry is served from the fresh sample instead of starting another cold read.
|
||||
if (renewed && operation == DataOperations.Read)
|
||||
{
|
||||
IProjectedDemandLease? demand = null;
|
||||
try
|
||||
{
|
||||
if (TryAcquire(nodeId, caller, DataOperations.Read, out demand) && demand is not null &&
|
||||
ScheduleRead(demand, new DataBudget(LapseRenewalTimeout, 1, ProjectedReadBytes), Clock.GetTimestamp())) demand = null;
|
||||
}
|
||||
catch (Exception ex) when (ex is not OutOfMemoryException) { }
|
||||
finally { demand?.Dispose(); }
|
||||
}
|
||||
completion.TrySetResult(renewed);
|
||||
// #938: the Read that started this renewal reads the origin itself, within its own request, once it commits — so the
|
||||
// renewal no longer schedules a separate cache-warming read.
|
||||
completion.TrySetResult(result);
|
||||
}
|
||||
// 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();
|
||||
var expired = _lapseRenewalBackoff.Where(entry => entry.Value.Until <= 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);
|
||||
if (expired.Length == 0) _lapseRenewalBackoff.Remove(_lapseRenewalBackoff.MinBy(entry => entry.Value.Until).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;
|
||||
@@ -860,21 +860,46 @@ public sealed class ProjectedDataAccess : IProjectedDataAccess, IDisposable
|
||||
}
|
||||
public bool ScheduleRead(IProjectedDemandLease demand, DataBudget budget, long requestStartedTimestamp)
|
||||
{
|
||||
if (demand is not Demand item || item.RequestedOperation != DataOperations.Read || !item.IsValid || budget is null) return false;
|
||||
if (!TryAdmitRead(demand, budget, requestStartedTimestamp, out var item, out var boundedBudget)) return false;
|
||||
_ = Task.Run(() => ReadCoreAsync(item!, boundedBudget!, requestStartedTimestamp, CancellationToken.None, ownsDemand: true)); return true;
|
||||
}
|
||||
/// <inheritdoc />
|
||||
public Task<ProjectedOriginRead> ReadNowAsync(IProjectedDemandLease demand, DataBudget budget, long requestStartedTimestamp,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
// #938: the same admission (unary count + bytes) and the same authenticated, freshness-checked, cache-publishing read as
|
||||
// ScheduleRead — but the caller awaits it and is served what it read. The caller keeps the demand. Admission is decided
|
||||
// here, synchronously, so NotAdmitted is an already-completed task.
|
||||
if (cancellationToken.IsCancellationRequested) return Task.FromResult(ProjectedOriginRead.NoValue);
|
||||
if (!TryAdmitRead(demand, budget, requestStartedTimestamp, out var item, out var boundedBudget))
|
||||
return Task.FromResult(demand is Demand { IsValid: true } ? ProjectedOriginRead.NotAdmitted : ProjectedOriginRead.NoValue);
|
||||
return Task.Run(async () =>
|
||||
{
|
||||
var value = await ReadCoreAsync(item!, boundedBudget!, requestStartedTimestamp, cancellationToken, ownsDemand: false).ConfigureAwait(false);
|
||||
return value is null ? ProjectedOriginRead.NoValue : new ProjectedOriginRead(ProjectedOriginReadStatus.Served, value);
|
||||
}, CancellationToken.None);
|
||||
}
|
||||
private bool TryAdmitRead(IProjectedDemandLease demand, DataBudget budget, long requestStartedTimestamp, out Demand? item, out DataBudget? boundedBudget)
|
||||
{
|
||||
item = null; boundedBudget = null;
|
||||
if (demand is not Demand candidate || candidate.RequestedOperation != DataOperations.Read || !candidate.IsValid || budget is null) return false;
|
||||
try { budget.Validate(); } catch (ArgumentException) { return false; }
|
||||
var elapsed = Clock.GetElapsedTime(requestStartedTimestamp, Clock.GetTimestamp());
|
||||
if (elapsed < TimeSpan.Zero || elapsed >= budget.Timeout) return false;
|
||||
// The request's byte budget is an upper bound. Narrow it to this adapter's
|
||||
// configured physical limit before admission and before remote dispatch.
|
||||
var boundedBudget = budget with { MaxBytes = Math.Min(budget.MaxBytes, _limits.MaxUnaryBytes) };
|
||||
var bounded = budget with { MaxBytes = Math.Min(budget.MaxBytes, _limits.MaxUnaryBytes) };
|
||||
lock (_sync)
|
||||
{
|
||||
if (_disposed || _unaryCount >= _limits.MaxUnaryOperations || boundedBudget.MaxBytes > _limits.MaxUnaryBytes - _unaryBytes || !item.TryHold()) return false;
|
||||
_unaryCount++; _unaryBytes += boundedBudget.MaxBytes;
|
||||
if (_disposed || _unaryCount >= _limits.MaxUnaryOperations || bounded.MaxBytes > _limits.MaxUnaryBytes - _unaryBytes || !candidate.TryHold()) return false;
|
||||
_unaryCount++; _unaryBytes += bounded.MaxBytes;
|
||||
}
|
||||
_ = Task.Run(() => ReadCoreAsync(item, boundedBudget, requestStartedTimestamp)); return true;
|
||||
item = candidate; boundedBudget = bounded;
|
||||
return true;
|
||||
}
|
||||
private async Task ReadCoreAsync(Demand demand, DataBudget budget, long started)
|
||||
// Returns the read sample when it is servable to the demand's caller: authenticated by the demand's current binding, fresh
|
||||
// within the mapping's stale timeout, and published to (or already superseded in) the projection cache. Null otherwise.
|
||||
private async Task<DataValueSnapshot?> ReadCoreAsync(Demand demand, DataBudget budget, long started, CancellationToken callerStop, bool ownsDemand)
|
||||
{
|
||||
IGrpcDataAdapterConnectionLease? connection = null;
|
||||
try
|
||||
@@ -882,14 +907,14 @@ public sealed class ProjectedDataAccess : IProjectedDataAccess, IDisposable
|
||||
var original = demand.CurrentBinding;
|
||||
var originalProof = original.Proof;
|
||||
var remaining = budget.Timeout - Clock.GetElapsedTime(started, Clock.GetTimestamp());
|
||||
if (remaining <= TimeSpan.Zero || !demand.IsValid || !ReferenceEquals(demand.CurrentBinding, original)) return;
|
||||
if (remaining <= TimeSpan.Zero || !demand.IsValid || !ReferenceEquals(demand.CurrentBinding, original)) return null;
|
||||
var connectionId = _connectionForMapping(originalProof.Metadata.View.MappingId!);
|
||||
if (string.IsNullOrWhiteSpace(connectionId)) return;
|
||||
if (string.IsNullOrWhiteSpace(connectionId)) return null;
|
||||
using var timeout = new CancellationTokenSource(remaining, Clock);
|
||||
using var linked = CancellationTokenSource.CreateLinkedTokenSource(timeout.Token, demand.CancellationToken);
|
||||
using var linked = CancellationTokenSource.CreateLinkedTokenSource(timeout.Token, demand.CancellationToken, callerStop);
|
||||
connection = await _connections.AcquireAsync(connectionId, linked.Token).ConfigureAwait(false);
|
||||
if (connection is null || !ReferenceEquals(connection.Connection.Clock, Clock) || connection.CancellationToken.IsCancellationRequested ||
|
||||
!demand.IsValid || !ReferenceEquals(demand.CurrentBinding, original)) return;
|
||||
!demand.IsValid || !ReferenceEquals(demand.CurrentBinding, original)) return null;
|
||||
using var route = CancellationTokenSource.CreateLinkedTokenSource(linked.Token, connection.CancellationToken);
|
||||
var readStarted = Clock.GetTimestamp();
|
||||
var result = await connection.Connection.ReadAsync(new DataReadRequest([new ReadItem("0", originalProof.OriginMetadata.View, null)], budget with { Timeout = remaining }), route.Token).ConfigureAwait(false);
|
||||
@@ -897,32 +922,36 @@ public sealed class ProjectedDataAccess : IProjectedDataAccess, IDisposable
|
||||
{
|
||||
if (result.Count != 1 || result[0].CorrelationId != "0" || result[0].Status != DataItemStatus.Good || result[0].Readiness != DataReadiness.Ready ||
|
||||
result[0].Sample is not { } sample || sample.Serving != originalProof.Lease.Serving || sample.Version <= 0 || !demand.IsValid ||
|
||||
!ReferenceEquals(demand.CurrentBinding, original) || route.IsCancellationRequested) return;
|
||||
!ReferenceEquals(demand.CurrentBinding, original) || route.IsCancellationRequested) return null;
|
||||
result[0].AgeBounds.Validate();
|
||||
// An unstamped implementation is conservatively anchored before the read call.
|
||||
var received = result[0].FreshnessObservedTimestamp ?? readStarted;
|
||||
if (!result[0].AgeBounds.Advance(Clock.GetElapsedTime(received, Clock.GetTimestamp())).IsFresh(originalProof.MaximumSampleAge)) return;
|
||||
if (sample.Value.EstimatedRetainedBytes > budget.MaxBytes) return;
|
||||
if (!result[0].AgeBounds.Advance(Clock.GetElapsedTime(received, Clock.GetTimestamp())).IsFresh(originalProof.MaximumSampleAge)) return null;
|
||||
if (sample.Value.EstimatedRetainedBytes > budget.MaxBytes) return null;
|
||||
var payload = DecodeValue(sample.Value, originalProof.OriginMetadata);
|
||||
var snapshot = new DataValueSnapshot(payload, sample.StatusCode, sample.SourceTimestampUtc?.UtcDateTime, sample.ServerTimestampUtc?.UtcDateTime);
|
||||
var source = GetSource(demand, connectionId);
|
||||
if (source is null) return;
|
||||
if (source is null) return null;
|
||||
lock (source.Gate)
|
||||
{
|
||||
if (!demand.IsValid || !ReferenceEquals(demand.CurrentBinding, original) || !source.IsValid || sample.Version <= source.LastVersion || route.IsCancellationRequested ||
|
||||
!result[0].AgeBounds.Advance(Clock.GetElapsedTime(received, Clock.GetTimestamp())).IsFresh(originalProof.MaximumSampleAge)) return;
|
||||
if (!demand.IsValid || !ReferenceEquals(demand.CurrentBinding, original) || !source.IsValid || route.IsCancellationRequested ||
|
||||
!result[0].AgeBounds.Advance(Clock.GetElapsedTime(received, Clock.GetTimestamp())).IsFresh(originalProof.MaximumSampleAge)) return null;
|
||||
// The cache already holds this acquisition or a newer one: nothing to publish, but what was read is still an
|
||||
// authenticated, fresh origin sample of this request (#938 serves it).
|
||||
if (sample.Version <= source.LastVersion) return snapshot;
|
||||
var update = new ProjectedValueUpdate(source.Route, snapshot, result[0].AgeBounds, received, source.CaptureReadProof(originalProof), true, originalProof.MaximumSampleAge, sample.Version);
|
||||
if (_publisher.TryPublish([update])) { source.LastVersion = sample.Version; source.CacheLocked(update, sample.Version); }
|
||||
else if (!ProjectedEvidenceRetirement.CanDrop(update.SourceProof)) source.Invalidate();
|
||||
if (_publisher.TryPublish([update])) { source.LastVersion = sample.Version; source.CacheLocked(update, sample.Version); return snapshot; }
|
||||
if (!ProjectedEvidenceRetirement.CanDrop(update.SourceProof)) source.Invalidate();
|
||||
return null;
|
||||
}
|
||||
}
|
||||
finally { foreach (var item in result) item.Dispose(); }
|
||||
}
|
||||
catch (Exception) { }
|
||||
catch (Exception) { return null; }
|
||||
finally
|
||||
{
|
||||
try { if (connection is not null) await connection.DisposeAsync().ConfigureAwait(false); }
|
||||
finally { demand.Dispose(); demand.ReleaseHold(); lock (_sync) { _unaryCount--; _unaryBytes -= budget.MaxBytes; } }
|
||||
finally { if (ownsDemand) demand.Dispose(); demand.ReleaseHold(); lock (_sync) { _unaryCount--; _unaryBytes -= budget.MaxBytes; } }
|
||||
}
|
||||
}
|
||||
public async Task<DataWriteOutcome> WriteAsync(IProjectedDemandLease demand, object? value, DataBudget budget,
|
||||
|
||||
@@ -312,21 +312,39 @@ public sealed class RemoteNamespaceResolver : IFederatedProjectionCatalog, IDisp
|
||||
// Refresh exactly one already-owned projected item. This deliberately creates no Browse
|
||||
// page, cursor or sibling visibility and does not create a physical subscription.
|
||||
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,
|
||||
bool onDemand = false) =>
|
||||
await RenewExactOutcomeAsync(previous, definition, nodeId, caller, configured, sink, budget, demandActive, cancellationToken,
|
||||
overlap, authorizeAs, required, onDemand).ConfigureAwait(false) == ProjectedRenewalResult.Renewed;
|
||||
|
||||
/// <summary>
|
||||
/// <see cref="RenewExactAsync"/> with the reason a renewal did not commit (#939): <see cref="ProjectedRenewalResult.Refused"/>
|
||||
/// ONLY for a definitive refusal BY THE ORIGIN — the call answered <c>PERMISSION_DENIED</c>, the item was answered
|
||||
/// <c>Denied</c>, the principal no longer holds Metadata, or the metadata no longer grants <paramref name="required"/>.
|
||||
/// Everything else (unreachable / unready / non-primary origin, capacity, timeout, a changed shape, a local fence) is
|
||||
/// <see cref="ProjectedRenewalResult.Failed"/>, i.e. retryable.
|
||||
/// </summary>
|
||||
internal async Task<ProjectedRenewalResult> RenewExactOutcomeAsync(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,
|
||||
bool onDemand = false)
|
||||
{
|
||||
const ProjectedRenewalResult Failed = ProjectedRenewalResult.Failed;
|
||||
const ProjectedRenewalResult Refused = ProjectedRenewalResult.Refused;
|
||||
// #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.
|
||||
if (authorizeAs is not (OpcUaOperation.CreateMonitoredItems or OpcUaOperation.Read or OpcUaOperation.HistoryRead) ||
|
||||
required is not (DataOperations.Subscribe or DataOperations.Read or DataOperations.HistoryRead)) return false;
|
||||
// renews for the operation the caller is performing (Read / HistoryRead / #940 Write / Subscribe) and requires exactly
|
||||
// that bit at the origin.
|
||||
if (authorizeAs is not (OpcUaOperation.CreateMonitoredItems or OpcUaOperation.Read or OpcUaOperation.HistoryRead or OpcUaOperation.WriteOperate) ||
|
||||
required is not (DataOperations.Subscribe or DataOperations.Read or DataOperations.HistoryRead or DataOperations.Write)) return Failed;
|
||||
var mapping = previous.Metadata.View.MappingId;
|
||||
if (mapping is null || previous.Subject.Scope.Segments.Count == 0) return false;
|
||||
if (mapping is null || previous.Subject.Scope.Segments.Count == 0) return Failed;
|
||||
ProjectedMappingBinding binding;
|
||||
lock (_sync)
|
||||
{
|
||||
if (_disposed || !_mappings.TryGetValue(mapping, out binding!)) return false;
|
||||
if (_disposed || !_mappings.TryGetValue(mapping, out binding!)) return Failed;
|
||||
}
|
||||
bool CallerAllowed() => demandActive() && (configured is not null
|
||||
? configured.Matches(mapping, previous.Metadata.View, binding.LocalAuthority)
|
||||
@@ -339,16 +357,16 @@ public sealed class RemoteNamespaceResolver : IFederatedProjectionCatalog, IDisp
|
||||
!string.Equals(previous.Subject.Scope.ClusterId, binding.LocalScope.ClusterId, StringComparison.OrdinalIgnoreCase) ||
|
||||
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;
|
||||
!previous.Subject.LocalAncestry.SequenceEqual(binding.LocalAncestry, StringComparer.OrdinalIgnoreCase)) return Failed;
|
||||
// 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 (!await slots.WaitAsync(onDemand ? budget.Timeout : TimeSpan.Zero, cancellationToken).ConfigureAwait(false)) return Failed;
|
||||
if (onDemand)
|
||||
{
|
||||
var left = budget.Timeout - System.Diagnostics.Stopwatch.GetElapsedTime(queued);
|
||||
if (left <= TimeSpan.Zero) { slots.Release(); return false; }
|
||||
if (left <= TimeSpan.Zero) { slots.Release(); return Failed; }
|
||||
budget = budget with { Timeout = left };
|
||||
}
|
||||
IGrpcDataAdapterConnectionLease? connection = null;
|
||||
@@ -359,22 +377,31 @@ public sealed class RemoteNamespaceResolver : IFederatedProjectionCatalog, IDisp
|
||||
using var linked = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, timeout.Token);
|
||||
connection = await _source.AcquireAsync(binding.Mapping.DataConnectionId, linked.Token).ConfigureAwait(false);
|
||||
if (connection is null || !ReferenceEquals(connection.Connection.Clock, Clock) ||
|
||||
!string.Equals(connection.Connection.Target.ExpectedClusterId, previous.OriginMetadata.View.Address.OriginClusterId, StringComparison.OrdinalIgnoreCase)) return false;
|
||||
!string.Equals(connection.Connection.Target.ExpectedClusterId, previous.OriginMetadata.View.Address.OriginClusterId, StringComparison.OrdinalIgnoreCase)) return Failed;
|
||||
using var route = CancellationTokenSource.CreateLinkedTokenSource(linked.Token, connection.CancellationToken);
|
||||
var capabilities = await connection.Connection.GetCapabilitiesAsync(budget, route.Token).ConfigureAwait(false);
|
||||
capabilities.Validate();
|
||||
var serving = capabilities.Serving;
|
||||
var target = connection.Connection.Target;
|
||||
if (!capabilities.MetadataItemLeases || capabilities.Readiness != DataReadiness.Ready ||
|
||||
(capabilities.Operations & DataOperations.Metadata) == 0 || serving.ServingGeneration <= 0 ||
|
||||
if (!capabilities.MetadataItemLeases || capabilities.Readiness != DataReadiness.Ready || serving.ServingGeneration <= 0 ||
|
||||
!(string.Equals(serving.Role, "Primary", StringComparison.OrdinalIgnoreCase) ||
|
||||
target.Mode == DataTargetMode.Node && target.Consistency == DataConsistency.ReadyReplica && string.Equals(serving.Role, "Secondary", StringComparison.OrdinalIgnoreCase))) return false;
|
||||
target.Mode == DataTargetMode.Node && target.Consistency == DataConsistency.ReadyReplica && string.Equals(serving.Role, "Secondary", StringComparison.OrdinalIgnoreCase))) return Failed;
|
||||
// #939: a ready, authenticated origin that no longer grants this principal Metadata at all has refused the renewal.
|
||||
if ((capabilities.Operations & DataOperations.Metadata) == 0) return Refused;
|
||||
var elapsed = Clock.GetElapsedTime(started, Clock.GetTimestamp());
|
||||
if (elapsed < TimeSpan.Zero || elapsed >= budget.Timeout) return false;
|
||||
if (elapsed < TimeSpan.Zero || elapsed >= budget.Timeout) return Failed;
|
||||
var results = await connection.Connection.GetMetadataAsync(new([previous.OriginMetadata.View],
|
||||
budget with { MaxItems = 1, Timeout = budget.Timeout - elapsed }), route.Token).ConfigureAwait(false);
|
||||
elapsed = Clock.GetElapsedTime(started, Clock.GetTimestamp());
|
||||
if (elapsed < TimeSpan.Zero || elapsed >= budget.Timeout || linked.IsCancellationRequested) return false;
|
||||
if (elapsed < TimeSpan.Zero || elapsed >= budget.Timeout || linked.IsCancellationRequested) return Failed;
|
||||
// #939: the origin's own verdict on this item — Denied, or a Good answer that no longer grants the operation — is a
|
||||
// definitive refusal (the consumer answers BadUserAccessDenied), not a lapse to retry.
|
||||
if (results.Count == 1 && results[0].CorrelationId == "0" &&
|
||||
(results[0].Status == DataItemStatus.Denied ||
|
||||
results[0].Status == DataItemStatus.Good && results[0].Value is { } granted && granted.View == previous.OriginMetadata.View &&
|
||||
(binding.Mapping.AllowedOperations & required) == required &&
|
||||
((granted.AllowedOperations & required) == 0 || required == DataOperations.Write && !granted.Writable)))
|
||||
return Refused;
|
||||
if (results.Count != 1 || results[0].CorrelationId != "0" || results[0].Status != DataItemStatus.Good ||
|
||||
results[0].Value is not { } metadata || results[0].Lease is not { } remoteLease ||
|
||||
metadata.View != previous.OriginMetadata.View || metadata.Serving != serving || metadata.CatalogRevision != serving.CatalogEpoch ||
|
||||
@@ -385,14 +412,14 @@ public sealed class RemoteNamespaceResolver : IFederatedProjectionCatalog, IDisp
|
||||
metadata.ArrayElementKind != previous.OriginMetadata.ArrayElementKind ||
|
||||
!metadata.Dimensions.SequenceEqual(previous.OriginMetadata.Dimensions) ||
|
||||
(metadata.AllowedOperations & binding.Mapping.AllowedOperations & required) == 0 ||
|
||||
!IsCurrent(binding) || !CallerAllowed() || connection.CancellationToken.IsCancellationRequested) return false;
|
||||
!IsCurrent(binding) || !CallerAllowed() || connection.CancellationToken.IsCancellationRequested) return Failed;
|
||||
metadata.Validate(); remoteLease.Validate();
|
||||
var generation = _cache.CaptureGeneration(mapping);
|
||||
var maximumLease = TimeSpan.FromMilliseconds(binding.Mapping.MetadataLeaseMilliseconds);
|
||||
if (caller?.CredentialExpiresUtc is { } expiry)
|
||||
{
|
||||
var remaining = expiry - Clock.GetUtcNow();
|
||||
if (remaining <= TimeSpan.Zero) return false;
|
||||
if (remaining <= TimeSpan.Zero) return Failed;
|
||||
if (remaining < maximumLease) maximumLease = remaining;
|
||||
}
|
||||
var lease = new BoundProjectionLease(new MetadataAuthorityLease(serving, remoteLease, started, maximumLease, TimeSpan.Zero, Clock),
|
||||
@@ -406,10 +433,10 @@ public sealed class RemoteNamespaceResolver : IFederatedProjectionCatalog, IDisp
|
||||
TimeSpan.FromMilliseconds(binding.Mapping.StaleTimeoutMilliseconds));
|
||||
var guard = new ExactAuthority(renewed);
|
||||
if (!guard.IsCurrent() || caller is not null && !_policy.AuthorizeMapped(caller, authorizeAs,
|
||||
mapped.View, serving, subject, resolver, lease)) return false;
|
||||
mapped.View, serving, subject, resolver, lease)) return Failed;
|
||||
var newDefinition = new ProjectedVariableDefinition(definition.Realm, definition.LocalIdentifier, definition.Parent,
|
||||
mapped, generation, guard.IsCurrent) { Lifetime = definition.Lifetime, Historizing = ProjectedHistoryAccess.Advertises(renewed) };
|
||||
return sink.TryRenewExact(nodeId, definition, newDefinition, () =>
|
||||
var committedRenewal = sink.TryRenewExact(nodeId, definition, newDefinition, () =>
|
||||
{
|
||||
var duration = Clock.GetElapsedTime(started, Clock.GetTimestamp());
|
||||
if (linked.IsCancellationRequested || cancellationToken.IsCancellationRequested || connection.CancellationToken.IsCancellationRequested ||
|
||||
@@ -422,8 +449,11 @@ public sealed class RemoteNamespaceResolver : IFederatedProjectionCatalog, IDisp
|
||||
guard.Adopt(actual);
|
||||
return guard.IsCurrent();
|
||||
});
|
||||
return committedRenewal ? ProjectedRenewalResult.Renewed : Failed;
|
||||
}
|
||||
catch (Exception ex) when (ex is not OutOfMemoryException) { return false; }
|
||||
// #939: the origin answered the call itself PERMISSION_DENIED (e.g. the operation is no longer granted to this
|
||||
// principal). The connection reports it as the cause of its "no ready endpoint" failure.
|
||||
catch (Exception ex) when (ex is not OutOfMemoryException) { return IsOriginPermissionDenied(ex) ? Refused : Failed; }
|
||||
finally
|
||||
{
|
||||
try { if (connection is not null) await connection.DisposeAsync().ConfigureAwait(false); }
|
||||
@@ -431,6 +461,12 @@ public sealed class RemoteNamespaceResolver : IFederatedProjectionCatalog, IDisp
|
||||
finally { slots.Release(); }
|
||||
}
|
||||
}
|
||||
internal static bool IsOriginPermissionDenied(Exception? ex)
|
||||
{
|
||||
for (var depth = 0; ex is not null && depth < 8; ex = ex.InnerException, depth++)
|
||||
if (ex is Grpc.Core.RpcException { StatusCode: Grpc.Core.StatusCode.PermissionDenied }) return true;
|
||||
return false;
|
||||
}
|
||||
public void Dispose()
|
||||
{
|
||||
ProjectedMappingBinding[] old;
|
||||
|
||||
Reference in New Issue
Block a user