feat: expose mapped raw and uns data through grpc adapters
This commit is contained in:
@@ -0,0 +1,287 @@
|
||||
using System.Collections.ObjectModel;
|
||||
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;
|
||||
|
||||
namespace ZB.MOM.WW.OtOpcUa.Runtime.DataConnections;
|
||||
|
||||
/// <summary>Trusted placement compiled from an applied mapping and its local catalog authority.</summary>
|
||||
public sealed record ProjectedMappingBinding(RemoteNamespaceMapping Mapping, DataView LocalAnchor, NodeScope LocalScope,
|
||||
IReadOnlyList<string> LocalAncestry, IDataMappedCatalogAuthority LocalAuthority, Func<DataView, string, bool> LocalNameOccupied);
|
||||
|
||||
/// <summary>Resolves direct peer browse pages without routing origin-owned exports through a projection.</summary>
|
||||
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;
|
||||
private readonly int _maximumWaiters;
|
||||
private readonly Func<CancellationToken, Task>? _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<PreparedPage> Task = null!;
|
||||
internal int Waiters;
|
||||
internal readonly TaskCompletionSource Finished = new(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
}
|
||||
private readonly Dictionary<FetchKey, SharedFetch> _fetches = new();
|
||||
private readonly HashSet<SharedFetch> _physicalJobs = new();
|
||||
private Dictionary<string, ProjectedMappingBinding> _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);
|
||||
_maximumWaiters = checked(maxConcurrentFetches * 16);
|
||||
_cache.Invalidated += OnInvalidated;
|
||||
}
|
||||
internal RemoteNamespaceResolver(ProjectedCatalogCache cache, BrowseContinuationRegistry cursors,
|
||||
IGrpcDataAdapterConnectionSource source, DataOperationPolicy policy, int maxMappings, int maxConcurrentFetches,
|
||||
Func<CancellationToken, Task>? 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<string, long>? Invalidated;
|
||||
private void OnInvalidated(string mappingId, long generation) { _cursors.InvalidateMapping(mappingId); Invalidated?.Invoke(mappingId, generation); }
|
||||
/// <summary>Installs only an already validated local mapping snapshot.</summary>
|
||||
public void ApplyMappings(IReadOnlyList<ProjectedMappingBinding> bindings)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(bindings);
|
||||
if (bindings.Count > _maxMappings) throw new InvalidOperationException("Mapping capacity exceeded.");
|
||||
var next = new Dictionary<string, ProjectedMappingBinding>(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<RemoteNamespaceMapping>(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 TryPinProjected(DataRealm realm, string localId, out IDisposable? pin) => _cache.TryPinProjected(realm, localId, out pin);
|
||||
public async Task<IProjectedPreparedPage> 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<PreparedPage> 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));
|
||||
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<ProjectedNodeProof>(); var seenNames = new HashSet<string>(StringComparer.Ordinal);
|
||||
foreach (var item in branch.Items)
|
||||
{
|
||||
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);
|
||||
}
|
||||
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;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user