using System.Collections.ObjectModel;
using NodeId = Opc.Ua.NodeId;
using ZB.MOM.WW.OtOpcUa.Configuration.Entities;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections;
using ZB.MOM.WW.OtOpcUa.Core.Authorization;
using ZB.MOM.WW.OtOpcUa.OpcUaServer;
namespace ZB.MOM.WW.OtOpcUa.Runtime.DataConnections;
/// Trusted placement compiled from an applied mapping and its local catalog authority.
public sealed record ProjectedMappingBinding(RemoteNamespaceMapping Mapping, DataView LocalAnchor, NodeScope LocalScope,
IReadOnlyList LocalAncestry, IDataMappedCatalogAuthority LocalAuthority, Func LocalNameOccupied);
/// Resolves direct peer browse pages without routing origin-owned exports through a projection.
public sealed class RemoteNamespaceResolver : IFederatedProjectionCatalog, IDisposable
{
private readonly object _sync = new();
private readonly ProjectedCatalogCache _cache;
private readonly BrowseContinuationRegistry _cursors;
private readonly IGrpcDataAdapterConnectionSource _source;
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? _beforeFetch;
private int _waiterCount;
private sealed record FetchKey(ProjectedBrowseRequest Request, ProjectedMappingBinding Binding);
private sealed class SharedFetch(CancellationTokenSource stop)
{
internal readonly CancellationTokenSource Stop = stop;
internal Task Task = null!;
internal int Waiters;
internal readonly TaskCompletionSource Finished = new(TaskCreationOptions.RunContinuationsAsynchronously);
}
private readonly Dictionary _fetches = new();
private readonly HashSet _physicalJobs = new();
private Dictionary _mappings = new(StringComparer.OrdinalIgnoreCase);
private bool _disposed;
public RemoteNamespaceResolver(ProjectedCatalogCache cache, BrowseContinuationRegistry cursors,
IGrpcDataAdapterConnectionSource source, DataOperationPolicy policy, int maxMappings, int maxConcurrentFetches)
{
_cache = cache ?? throw new ArgumentNullException(nameof(cache)); _cursors = cursors ?? throw new ArgumentNullException(nameof(cursors));
_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;
}
internal RemoteNamespaceResolver(ProjectedCatalogCache cache, BrowseContinuationRegistry cursors,
IGrpcDataAdapterConnectionSource source, DataOperationPolicy policy, int maxMappings, int maxConcurrentFetches,
Func? beforeFetch) : this(cache, cursors, source, policy, maxMappings, maxConcurrentFetches)
{ _beforeFetch = beforeFetch; }
internal int OutstandingPhysicalJobs { get { lock (_sync) return _physicalJobs.Count; } }
internal Task WaitForPhysicalJobsAsync()
{
lock (_sync) return Task.WhenAll(_physicalJobs.Select(x => x.Finished.Task));
}
public TimeProvider Clock => _cache.Clock;
public event Action? Invalidated;
private void OnInvalidated(string mappingId, long generation) { _cursors.InvalidateMapping(mappingId); Invalidated?.Invoke(mappingId, generation); }
/// Installs only an already validated local mapping snapshot.
public void ApplyMappings(IReadOnlyList bindings)
{
ArgumentNullException.ThrowIfNull(bindings);
if (bindings.Count > _maxMappings) throw new InvalidOperationException("Mapping capacity exceeded.");
var next = new Dictionary(StringComparer.OrdinalIgnoreCase);
foreach (var binding in bindings)
{
ArgumentNullException.ThrowIfNull(binding);
var mapping = binding.Mapping;
if (!mapping.Enabled || mapping.Revision <= 0 || string.IsNullOrWhiteSpace(mapping.RemoteNamespaceMappingId) ||
string.IsNullOrWhiteSpace(mapping.DataConnectionId) || mapping.Realm != mapping.RemoteRealm || mapping.Realm == DataRealm.Unspecified ||
mapping.MaxProjectionNodes <= 0 || mapping.MaxProjectionDepth <= 0 || mapping.MetadataLeaseMilliseconds <= 0 || mapping.StaleTimeoutMilliseconds <= 0 ||
binding.LocalAnchor.MappingId != mapping.RemoteNamespaceMappingId || binding.LocalAnchor.MappingRevision != mapping.Revision ||
binding.LocalAnchor.Realm != mapping.Realm || binding.LocalAuthority is not { IsActive: true } || binding.LocalNameOccupied is null)
throw new ArgumentException("Invalid projection binding.", nameof(bindings));
var copy = System.Text.Json.JsonSerializer.Deserialize(System.Text.Json.JsonSerializer.SerializeToUtf8Bytes(mapping))!;
var frozen = binding with { Mapping = copy, LocalScope = binding.LocalScope with { Segments = Array.AsReadOnly(binding.LocalScope.Segments.ToArray()) },
LocalAncestry = Array.AsReadOnly(binding.LocalAncestry.ToArray()) };
if (!next.TryAdd(copy.RemoteNamespaceMappingId, frozen)) throw new ArgumentException("Duplicate mapping identity.", nameof(bindings));
}
ProjectedMappingBinding[] oldBindings;
lock (_sync)
{
ObjectDisposedException.ThrowIf(_disposed, this);
oldBindings = _mappings.Values.ToArray(); _mappings = next;
}
foreach (var old in oldBindings)
{
_cache.MarkUnavailable(old.Mapping.RemoteNamespaceMappingId, old.LocalAnchor);
if (!next.ContainsKey(old.Mapping.RemoteNamespaceMappingId)) _cache.ForgetMapping(old.Mapping.RemoteNamespaceMappingId);
}
foreach (var item in next.Values) _cache.CaptureGeneration(item.Mapping.RemoteNamespaceMappingId);
}
public ProjectedParentSnapshot TryGetParent(ProjectedBrowseRequest request) => _cache.TryGetParent(request);
public IProjectedPageGuard? CaptureParentGuard(ProjectedBrowseRequest request, ProjectedParentSnapshot expected) => _cache.CaptureParentGuard(request, expected);
public bool TryResolveProjected(DataRealm realm, string localId, out ProjectedNodeProof? proof) => _cache.TryResolveProjected(realm, localId, out proof);
public bool IsUsableProof(ProjectedNodeProof proof) => _cache.IsUsableProof(proof);
public bool TryPinProjected(DataRealm realm, string localId, out IDisposable? pin) => _cache.TryPinProjected(realm, localId, out pin);
internal bool TryResolveForRenewal(DataRealm realm, string localId, out ProjectedNodeProof? proof) =>
_cache.TryResolveForRenewal(realm, localId, out proof);
internal bool TryPinExpiredRecoveryPair(ProjectedNodeProof previous, ProjectedNodeProof successor, out IDisposable? pin) =>
_cache.TryPinExpiredRecoveryPair(previous, successor, out pin);
public async Task PreparePageAsync(ProjectedBrowseRequest request, CancellationToken cancellationToken)
{
ArgumentNullException.ThrowIfNull(request); request.Budget.Validate(); request.Parent.Validate();
// Continuations remain exclusive reservations; initial requests can share one physical fetch.
if (request.Continuation is not null) return await PrepareCoreAsync(request, cancellationToken).ConfigureAwait(false);
var elapsed = Clock.GetElapsedTime(request.RequestStartedTimestamp, Clock.GetTimestamp());
var remaining = request.Budget.Timeout - elapsed;
if (elapsed < TimeSpan.Zero || remaining <= TimeSpan.Zero) return PreparedPage.Failed(ProjectionPageStatus.Unavailable);
SharedFetch work; FetchKey key;
lock (_sync)
{
ObjectDisposedException.ThrowIf(_disposed, this);
if (!_mappings.TryGetValue(request.MappingId, out var binding) || _waiterCount >= _maximumWaiters)
return PreparedPage.Failed(ProjectionPageStatus.Unavailable);
key = new FetchKey(request with { RequestStartedTimestamp = 0 }, binding);
if (!_fetches.TryGetValue(key, out work!))
{
if (_physicalJobs.Count >= _maximumWaiters) return PreparedPage.Failed(ProjectionPageStatus.Unavailable);
work = new SharedFetch(new CancellationTokenSource());
_fetches.Add(key, work); _physicalJobs.Add(work);
var current = work;
current.Task = Task.Run(async () =>
{
if (_beforeFetch is not null) await _beforeFetch(current.Stop.Token).ConfigureAwait(false);
return await PrepareCoreAsync(request, current.Stop.Token).ConfigureAwait(false);
});
}
work.Waiters++; _waiterCount++;
}
try
{
using var timeout = new CancellationTokenSource(remaining, Clock);
using var linked = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, timeout.Token);
var prepared = await work.Task.WaitAsync(linked.Token).ConfigureAwait(false);
return prepared.CloneForWaiter(request);
}
catch (OperationCanceledException) when (!cancellationToken.IsCancellationRequested)
{ return PreparedPage.Failed(ProjectionPageStatus.Unavailable); }
finally
{
lock (_sync)
{
_waiterCount--; work.Waiters--;
if (work.Waiters == 0)
{
if (_fetches.TryGetValue(key, out var active) && ReferenceEquals(active, work)) _fetches.Remove(key);
if (!work.Task.IsCompleted) _ = work.Stop.CancelAsync();
_ = FinishSharedFetchAsync(work);
}
}
}
}
private async Task FinishSharedFetchAsync(SharedFetch work)
{
try { var page = await work.Task.ConfigureAwait(false); await page.DisposeAndWaitAsync().ConfigureAwait(false); }
catch (Exception) { }
finally
{
work.Stop.Dispose();
lock (_sync) _physicalJobs.Remove(work);
work.Finished.TrySetResult();
}
}
private async Task PrepareCoreAsync(ProjectedBrowseRequest request, CancellationToken cancellationToken)
{
ArgumentNullException.ThrowIfNull(request); request.Budget.Validate(); request.Parent.Validate();
ProjectedMappingBinding binding;
lock (_sync)
{
ObjectDisposedException.ThrowIf(_disposed, this);
if (!_mappings.TryGetValue(request.MappingId, out binding!)) return PreparedPage.Failed(ProjectionPageStatus.Unavailable);
}
if ((request.ConfiguredCapability is { } capability
? !capability.Matches(request.MappingId, request.Parent, binding.LocalAuthority)
: request.Caller is null || !_policy.IsCallerUsable(request.Caller) || !_policy.AuthorizeLocal(request.Caller, OpcUaOperation.Browse, binding.LocalScope)) ||
!binding.LocalAuthority.IsActive || request.Parent.MappingId != binding.Mapping.RemoteNamespaceMappingId ||
request.Parent.MappingRevision != binding.Mapping.Revision || request.Parent.Realm != binding.Mapping.Realm)
return PreparedPage.Failed(ProjectionPageStatus.Unavailable);
var elapsed = Clock.GetElapsedTime(request.RequestStartedTimestamp, Clock.GetTimestamp());
var remaining = request.Budget.Timeout - elapsed;
if (elapsed < TimeSpan.Zero || remaining <= TimeSpan.Zero) return PreparedPage.Failed(ProjectionPageStatus.Unavailable);
if (!await _fetchSlots.WaitAsync(0, cancellationToken).ConfigureAwait(false)) return PreparedPage.Failed(ProjectionPageStatus.Unavailable);
IGrpcDataAdapterConnectionLease? connection = null; PreparedBrowseContinuation? cursor = null; var transferred = false;
try
{
using var timeout = new CancellationTokenSource(remaining, Clock);
using var linked = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, timeout.Token);
connection = await _source.AcquireAsync(binding.Mapping.DataConnectionId, linked.Token).ConfigureAwait(false);
if (connection is null) return PreparedPage.Failed(ProjectionPageStatus.Unavailable);
if (!ReferenceEquals(connection.Connection.Clock, Clock) || !string.Equals(connection.Connection.Target.ExpectedClusterId,
request.Parent.Address.OriginClusterId, StringComparison.OrdinalIgnoreCase)) return PreparedPage.Failed(ProjectionPageStatus.Unavailable);
using var route = CancellationTokenSource.CreateLinkedTokenSource(linked.Token, connection.CancellationToken);
var generation = _cache.CaptureGeneration(request.MappingId);
DataMetadata originParent;
ProjectedNodeProof? previousParent = null;
if (request.Parent == binding.LocalAnchor)
{
var originView = new DataView(request.Parent.Address, request.Parent.Realm, null, 0, binding.Mapping.RemoteRootEntityId);
var metadata = await connection.Connection.GetMetadataAsync(new([originView], request.Budget with { Timeout = remaining }), route.Token).ConfigureAwait(false);
if (metadata.Count != 1 || metadata[0].Status != DataItemStatus.Good || metadata[0].Value is not { } root || root.View.Address != originView.Address || root.View.MappingId is not null || root.Serving is null)
return PreparedPage.Failed(ProjectionPageStatus.Unavailable);
originParent = root;
}
else
{
var localId = ProjectedDataIds.Identifier(request.MappingId, request.Parent.Address);
if (!_cache.TryResolveProjected(request.Parent.Realm, localId, out previousParent) || previousParent!.Metadata.View != request.Parent)
return PreparedPage.Failed(ProjectionPageStatus.Unavailable);
originParent = previousParent.OriginMetadata;
}
var serving = originParent.Serving!;
var target = connection.Connection.Target;
if (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 PreparedPage.Failed(ProjectionPageStatus.Unavailable);
var continuationBinding = new BrowseContinuationBinding(request.ConfiguredCapability?.Nonce ?? request.Caller.Principal,
request.ConfiguredCapability is null ? request.Caller.ApiKeyId ?? "" : "configured",
request.ConfiguredCapability is null ? request.Caller.CredentialVersion ?? "" : "configured",
binding.Mapping.RemoteNamespaceMappingId, binding.Mapping.Revision, request.Parent, request.Filter, binding.LocalAuthority.CatalogEpoch,
serving, request.ConfiguredCapability is null ? request.Caller.CredentialExpiresUtc : null);
if (request.Continuation is not null && !_cursors.TryPrepare(request.Continuation, continuationBinding, out cursor))
return PreparedPage.Failed(ProjectionPageStatus.InvalidContinuation);
elapsed = Clock.GetElapsedTime(request.RequestStartedTimestamp, Clock.GetTimestamp()); remaining = request.Budget.Timeout - elapsed;
if (remaining <= TimeSpan.Zero) return PreparedPage.Failed(ProjectionPageStatus.Unavailable);
var branch = await connection.Connection.BrowseAsync(new BrowseRequest(originParent.View, request.Filter, cursor?.RemoteCursor,
request.Budget with { Timeout = remaining }), route.Token).ConfigureAwait(false);
if (branch.Status != DataItemStatus.Good || branch.Parent != originParent.View || branch.Serving is null || branch.Serving != serving || branch.Lease is null ||
branch.Lease.CatalogEpoch != serving.CatalogEpoch || branch.Lease.AuthorityEpoch != serving.AuthorityEpoch ||
branch.Items.Count > Math.Min(request.Budget.MaxItems, binding.Mapping.MaxProjectionNodes) ||
branch.Complete != (branch.Continuation is null) || connection.CancellationToken.IsCancellationRequested)
return PreparedPage.Failed(ProjectionPageStatus.Unavailable);
var maxLease = TimeSpan.FromMilliseconds(binding.Mapping.MetadataLeaseMilliseconds);
var lease = new BoundProjectionLease(new MetadataAuthorityLease(serving, branch.Lease, request.RequestStartedTimestamp, maxLease, TimeSpan.Zero, Clock),
connection.CancellationToken, binding.LocalAuthority, _cache, request.MappingId, generation, () => IsCurrent(binding), connection.RouteCurrent,
connection.RouteIdentity, connection.Connection.Target, binding);
if (!lease.IsValid) return PreparedPage.Failed(ProjectionPageStatus.Unavailable);
var parentScope = previousParent?.Subject.Scope ?? binding.LocalScope;
var ancestry = previousParent?.Subject.LocalAncestry ?? binding.LocalAncestry;
var mappedParent = originParent with { View = request.Parent, Serving = serving };
var parentSubject = new MappedNamespaceSubject(request.Parent, parentScope, ancestry, serving,
binding.Mapping.AllowedOperations & originParent.AllowedOperations, binding.Mapping.WriteThrough && originParent.Writable);
var parentResolver = new MappedSubjectResolver([parentSubject], serving.CatalogEpoch, binding.LocalAuthority);
var parentProof = new ProjectedNodeProof(ProjectedDataIds.Identifier(request.MappingId, originParent.View.Address), mappedParent, parentSubject, parentResolver, lease, generation, originParent, TimeSpan.FromMilliseconds(binding.Mapping.StaleTimeoutMilliseconds));
var results = new List(); var seenNames = new HashSet(StringComparer.Ordinal);
foreach (var item in branch.Items)
{
// #941: an item this build cannot materialise is skipped, not a reason to fail the whole page (the applier and
// the node manager apply a page all-or-nothing). It never enters the snapshot, the cache or the address space,
// and its browse name does not count against the page's duplicate check.
if (!ProjectedCatalogCache.IsMaterialisable(item)) continue;
item.Validate();
if (item.Serving != serving || item.View.MappingId is not null || item.View.Realm != request.Parent.Realm ||
item.CatalogRevision != serving.CatalogEpoch || !string.Equals(item.View.Address.OriginClusterId, originParent.View.Address.OriginClusterId, StringComparison.OrdinalIgnoreCase) ||
string.IsNullOrWhiteSpace(item.BrowseName) || item.BrowseName.Contains('/') || !seenNames.Add(item.BrowseName) ||
binding.LocalNameOccupied(request.Parent, item.BrowseName)) return PreparedPage.Failed(ProjectionPageStatus.Unavailable);
var segments = parentScope.Segments.Concat([item.BrowseName]).ToArray();
if (segments.Length - binding.LocalScope.Segments.Count > binding.Mapping.MaxProjectionDepth) return PreparedPage.Failed(ProjectionPageStatus.Unavailable);
var localView = item.View with { MappingId = binding.Mapping.RemoteNamespaceMappingId, MappingRevision = binding.Mapping.Revision, Subject = string.Join('/', segments) };
var scope = parentScope with { Segments = Array.AsReadOnly(segments) };
var subject = new MappedNamespaceSubject(localView, scope, ancestry, serving, binding.Mapping.AllowedOperations & item.AllowedOperations, binding.Mapping.WriteThrough && item.Writable);
var resolver = new MappedSubjectResolver([subject], serving.CatalogEpoch, binding.LocalAuthority);
results.Add(new ProjectedNodeProof(ProjectedDataIds.Identifier(request.MappingId, item.View.Address), item with { View = localView }, subject, resolver, lease, generation, item, TimeSpan.FromMilliseconds(binding.Mapping.StaleTimeoutMilliseconds)));
}
var snapshot = new ProjectedParentSnapshot(ProjectionPageStatus.Ready, Array.AsReadOnly(results.ToArray()), branch.Complete, null, generation, lease, binding.LocalAuthority, parentProof);
var prepared = new PreparedPage(_cache, _cursors, request, snapshot, continuationBinding, cursor, branch.Continuation, connection, _fetchSlots, Clock, branch.Lease.Duration < maxLease ? branch.Lease.Duration : maxLease, binding.Mapping.MaxProjectionNodes);
cursor = null; connection = null; transferred = true; return prepared;
}
catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested) { throw; }
catch (Exception) { return PreparedPage.Failed(ProjectionPageStatus.Unavailable); }
finally
{
cursor?.Dispose();
if (!transferred)
{
try { if (connection is not null) await connection.DisposeAsync().ConfigureAwait(false); }
finally { _fetchSlots.Release(); }
}
}
}
private bool IsCurrent(ProjectedMappingBinding binding)
{
lock (_sync) return !_disposed && _mappings.TryGetValue(binding.Mapping.RemoteNamespaceMappingId, out var current) && ReferenceEquals(current, binding);
}
private sealed class ExactAuthority(ProjectedNodeProof proof) : IProjectedRetainedAuthority
{
private ProjectedNodeProof _proof = proof;
public long RetainedBytes { get; } = checked(2048L + ProjectedProofSize.Estimate(proof));
internal void Adopt(ProjectedNodeProof committed) => Volatile.Write(ref _proof, committed);
internal bool IsFor(ProjectedNodeProof committed) => ReferenceEquals(Volatile.Read(ref _proof), committed);
public bool IsCurrent()
{
var proof = Volatile.Read(ref _proof);
try { return proof.Lease.IsValid && proof.Resolver.LocalAuthority.IsActive &&
proof.Resolver.Resolve(proof.Metadata.View, proof.Subject).Kind == MappedSubjectResolutionKind.Mapped; }
catch (Exception ex) when (ex is ArgumentException or InvalidOperationException) { return false; }
}
}
internal static bool DefinitionOwnsProof(ProjectedVariableDefinition definition, ProjectedNodeProof proof) =>
definition.AuthorityIsCurrent.Target is ExactAuthority authority && authority.IsFor(proof) && authority.IsCurrent();
// 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 RenewExactAsync(ProjectedNodeProof previous, ProjectedVariableDefinition definition,
NodeId nodeId, DataCallerIdentity? caller, ConfiguredProjectionCapability? configured,
IProjectedNamespacePageSink sink, DataBudget budget, Func demandActive, CancellationToken cancellationToken, bool overlap = false,
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.
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;
var mapping = previous.Metadata.View.MappingId;
if (mapping is null || previous.Subject.Scope.Segments.Count == 0) return false;
ProjectedMappingBinding binding;
lock (_sync)
{
if (_disposed || !_mappings.TryGetValue(mapping, out binding!)) return false;
}
bool CallerAllowed() => demandActive() && (configured is not null
? configured.Matches(mapping, previous.Metadata.View, binding.LocalAuthority)
: caller is not null && _policy.IsCallerUsable(caller) &&
_policy.AuthorizeLocal(caller, authorizeAs, previous.Subject.Scope));
if (!IsCurrent(binding) || !binding.LocalAuthority.IsActive || !CallerAllowed() ||
previous.Metadata.View.MappingRevision != binding.Mapping.Revision || previous.Metadata.View.Realm != binding.Mapping.Realm ||
previous.OriginMetadata.View.MappingId is not null ||
previous.Subject.Scope.Kind != binding.LocalScope.Kind ||
!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;
// 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
{
var started = Clock.GetTimestamp();
using var timeout = new CancellationTokenSource(budget.Timeout, Clock);
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;
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 ||
!(string.Equals(serving.Role, "Primary", StringComparison.OrdinalIgnoreCase) ||
target.Mode == DataTargetMode.Node && target.Consistency == DataConsistency.ReadyReplica && string.Equals(serving.Role, "Secondary", StringComparison.OrdinalIgnoreCase))) return false;
var elapsed = Clock.GetElapsedTime(started, Clock.GetTimestamp());
if (elapsed < TimeSpan.Zero || elapsed >= budget.Timeout) return false;
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 (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 ||
remoteLease.CatalogEpoch != serving.CatalogEpoch || remoteLease.AuthorityEpoch != serving.AuthorityEpoch ||
remoteLease.Duration <= TimeSpan.Zero || remoteLease.Duration > capabilities.Limits.MaxMetadataLease ||
metadata.BrowseName != previous.OriginMetadata.BrowseName || metadata.NodeKind != previous.OriginMetadata.NodeKind ||
metadata.ValueKind != previous.OriginMetadata.ValueKind || metadata.ValueRank != previous.OriginMetadata.ValueRank ||
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;
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 < maximumLease) maximumLease = remaining;
}
var lease = new BoundProjectionLease(new MetadataAuthorityLease(serving, remoteLease, started, maximumLease, TimeSpan.Zero, Clock),
connection.CancellationToken, binding.LocalAuthority, _cache, mapping, generation, () => IsCurrent(binding), connection.RouteCurrent,
connection.RouteIdentity, connection.Connection.Target, binding);
var subject = previous.Subject with { Serving = serving, AllowedOperations = binding.Mapping.AllowedOperations & metadata.AllowedOperations,
WriteThrough = binding.Mapping.WriteThrough && metadata.Writable };
var mapped = metadata with { View = previous.Metadata.View };
var resolver = new MappedSubjectResolver([subject], serving.CatalogEpoch, binding.LocalAuthority);
var renewed = new ProjectedNodeProof(previous.LocalIdentifier, mapped, subject, resolver, lease, generation, metadata,
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;
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 duration = Clock.GetElapsedTime(started, Clock.GetTimestamp());
if (linked.IsCancellationRequested || cancellationToken.IsCancellationRequested || connection.CancellationToken.IsCancellationRequested ||
duration < TimeSpan.Zero || duration >= budget.Timeout ||
!IsCurrent(binding) || !CallerAllowed() || !guard.IsCurrent()) return false;
ProjectedNodeProof? actual;
var committed = overlap ? _cache.TryRenewOverlap(previous, renewed, binding.Mapping.MaxProjectionNodes, out actual) :
_cache.TryRenewExact(previous, renewed, binding.Mapping.MaxProjectionNodes, out actual);
if (!committed || actual is null) return false;
guard.Adopt(actual);
return guard.IsCurrent();
});
}
catch (Exception ex) when (ex is not OutOfMemoryException) { return false; }
finally
{
try { if (connection is not null) await connection.DisposeAsync().ConfigureAwait(false); }
catch (Exception) { }
finally { slots.Release(); }
}
}
public void Dispose()
{
ProjectedMappingBinding[] old;
lock (_sync)
{
if (_disposed) return; _disposed = true; old = _mappings.Values.ToArray(); _mappings.Clear();
foreach (var work in _fetches.Values) _ = work.Stop.CancelAsync();
}
foreach (var item in old) _cache.MarkUnavailable(item.Mapping.RemoteNamespaceMappingId, item.LocalAnchor);
_cache.Invalidated -= OnInvalidated;
}
}