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:
Joseph Doherty
2026-12-01 19:56:38 -05:00
16 changed files with 1241 additions and 135 deletions
@@ -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;