270 lines
17 KiB
C#
270 lines
17 KiB
C#
using System.Collections.Concurrent;
|
|
using Opc.Ua;
|
|
using ZB.MOM.WW.OtOpcUa.Commons.OpcUa;
|
|
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;
|
|
|
|
/// <summary>Caller-bound projection browse scheduling and local anchor lifetime.</summary>
|
|
public sealed class ProjectedBrowseAccess : IProjectedBrowseAccess, IDisposable
|
|
{
|
|
private sealed record Installed(NodeId Node, ProjectedAnchorDefinition Definition, ProjectedMappingPlacement Placement);
|
|
private readonly record struct WorkKey(NodeId Parent, DataCallerIdentity Caller, string? Cursor, int MaxItems);
|
|
private readonly ProjectedMappingDeploymentRuntime _lifecycle;
|
|
private readonly IFederatedProjectionCatalog _catalog;
|
|
private readonly ProjectedNamespaceApplier _applier;
|
|
private readonly IProjectedAnchorSink _anchors;
|
|
private readonly Func<string, string, NodeId?> _resolveNode;
|
|
private readonly DataBudget _budget;
|
|
private readonly int _maxPending;
|
|
private readonly object _anchorGate = new();
|
|
private readonly ConcurrentDictionary<string, Installed> _installed = new(StringComparer.OrdinalIgnoreCase);
|
|
private readonly ConcurrentDictionary<WorkKey, TaskCompletionSource> _inflight = new();
|
|
private readonly record struct Failure(ProjectionPageStatus Status, long Until);
|
|
private readonly object _resultGate = new();
|
|
private readonly Dictionary<WorkKey, Failure> _failures = new();
|
|
private readonly CancellationTokenSource _stop = new();
|
|
private int _pending, _disposed;
|
|
|
|
public ProjectedBrowseAccess(ProjectedMappingDeploymentRuntime lifecycle, IFederatedProjectionCatalog catalog,
|
|
ProjectedNamespaceApplier applier, IProjectedAnchorSink anchors, Func<string, string, NodeId?> resolveNode,
|
|
DataBudget budget, int maxPending)
|
|
{
|
|
_lifecycle = lifecycle ?? throw new ArgumentNullException(nameof(lifecycle));
|
|
_catalog = catalog ?? throw new ArgumentNullException(nameof(catalog));
|
|
_applier = applier ?? throw new ArgumentNullException(nameof(applier));
|
|
_anchors = anchors ?? throw new ArgumentNullException(nameof(anchors));
|
|
_resolveNode = resolveNode ?? throw new ArgumentNullException(nameof(resolveNode));
|
|
_budget = budget ?? throw new ArgumentNullException(nameof(budget)); _budget.Validate();
|
|
if (maxPending <= 0) throw new ArgumentOutOfRangeException(nameof(maxPending));
|
|
_maxPending = maxPending;
|
|
_lifecycle.Changed += OnChanged;
|
|
RefreshAnchors();
|
|
}
|
|
|
|
private void OnChanged(IReadOnlyList<ProjectedMappingPlacement> _) => RefreshAnchors();
|
|
private bool Current(ProjectedMappingPlacement placement) => _lifecycle.IsCurrentPlacement(placement);
|
|
|
|
/// <summary>Reconciles against the live SDK binding; safe to call after the deferred sink binds.</summary>
|
|
public void RefreshAnchors()
|
|
{
|
|
lock (_lifecycle.TransitionGate)
|
|
lock (_anchorGate)
|
|
{
|
|
if (Volatile.Read(ref _disposed) != 0) return;
|
|
// During an unresolved deployment the old guard is already invalid. Retain its
|
|
// bounded SDK lifetime so an identical placement can be reauthorized later.
|
|
if (_lifecycle.Suspended) return;
|
|
var placements = _lifecycle.Active;
|
|
foreach (var entry in _installed.ToArray())
|
|
{
|
|
var old = entry.Value;
|
|
if (Current(old.Placement)) continue;
|
|
var next = placements.FirstOrDefault(candidate => CompatiblePlacement(old.Placement, candidate));
|
|
if (next is not null && Current(next))
|
|
{
|
|
var renewed = new ProjectedAnchorDefinition(next.Mapping.Realm, old.Definition.LocalIdentifier,
|
|
old.Definition.Parent, next.Mapping.BranchName, next.Anchor.Subject,
|
|
next.Mapping.RemoteNamespaceMappingId, next.Mapping.Revision, () => Current(next))
|
|
{ LocalScope = next.Scope, Lifetime = old.Definition.Lifetime };
|
|
if (_anchors.TryEnsureProjectedAnchor(renewed, out var node) && node == old.Node)
|
|
{
|
|
if (Current(next))
|
|
{
|
|
_installed[entry.Key] = new(old.Node, renewed, next);
|
|
continue;
|
|
}
|
|
_installed.TryRemove(entry.Key, out _);
|
|
_anchors.TryRemoveProjectedAnchor(old.Node, renewed);
|
|
continue;
|
|
}
|
|
}
|
|
_installed.TryRemove(entry.Key, out _);
|
|
_anchors.TryRemoveProjectedAnchor(old.Node, old.Definition);
|
|
}
|
|
foreach (var placement in placements)
|
|
{
|
|
var mappingId = placement.Mapping.RemoteNamespaceMappingId;
|
|
if (_installed.ContainsKey(mappingId) || !Current(placement)) continue;
|
|
// Transport realm roots deliberately use a disjoint identifier kind. Resolve only
|
|
// the exact trusted local root to the native SDK root, never a remote claimed ID.
|
|
var localRoot = LocalExportCatalog.RealmRoot(placement.Parent.Address.OriginClusterId, placement.Mapping.Realm);
|
|
var isRoot = placement.Parent == localRoot && string.Equals(placement.Parent.Address.OriginClusterId,
|
|
placement.Mapping.ClusterId, StringComparison.OrdinalIgnoreCase);
|
|
if (!isRoot && placement.Parent.Address.IdentifierKind != "string") continue;
|
|
var parent = _resolveNode(isRoot ? V3NodeIds.RawNamespaceUri : placement.Parent.Address.NamespaceUri,
|
|
isRoot ? V3NodeIds.SharedRootFolderId : placement.Parent.Address.Identifier);
|
|
if (parent is not { } parentNode) continue;
|
|
var id = ProjectedDataIds.Identifier(mappingId, placement.Anchor.Address);
|
|
var definition = new ProjectedAnchorDefinition(placement.Mapping.Realm, id, parentNode, placement.Mapping.BranchName,
|
|
placement.Anchor.Subject, mappingId, placement.Mapping.Revision, () => Current(placement))
|
|
{ LocalScope = placement.Scope };
|
|
if (_anchors.TryEnsureProjectedAnchor(definition, out var node) && node is { } anchorNode)
|
|
{
|
|
if (Current(placement)) _installed[mappingId] = new(anchorNode, definition, placement);
|
|
else _anchors.TryRemoveProjectedAnchor(anchorNode, definition);
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
private static bool CompatiblePlacement(ProjectedMappingPlacement previous, ProjectedMappingPlacement next) =>
|
|
previous.Parent == next.Parent && previous.Anchor == next.Anchor && previous.Mapping.Realm == next.Mapping.Realm &&
|
|
string.Equals(previous.Mapping.RemoteNamespaceMappingId, next.Mapping.RemoteNamespaceMappingId, StringComparison.OrdinalIgnoreCase) &&
|
|
previous.Mapping.Revision == next.Mapping.Revision &&
|
|
string.Equals(previous.Mapping.DataConnectionId, next.Mapping.DataConnectionId, StringComparison.OrdinalIgnoreCase) &&
|
|
previous.Mapping.LocalParentKind == next.Mapping.LocalParentKind &&
|
|
string.Equals(previous.Mapping.LocalParentId, next.Mapping.LocalParentId, StringComparison.OrdinalIgnoreCase) &&
|
|
previous.Mapping.RemoteRootEntityId == next.Mapping.RemoteRootEntityId &&
|
|
previous.Mapping.BranchName == next.Mapping.BranchName && previous.Scope.Kind == next.Scope.Kind &&
|
|
string.Equals(previous.Scope.ClusterId, next.Scope.ClusterId, StringComparison.OrdinalIgnoreCase) &&
|
|
previous.Scope.Segments.SequenceEqual(next.Scope.Segments, StringComparer.Ordinal) &&
|
|
previous.LocalAncestry.SequenceEqual(next.LocalAncestry, StringComparer.OrdinalIgnoreCase);
|
|
|
|
private sealed class PageGuard(ProjectedBrowseAccess owner, IProjectedPageGuard source)
|
|
{
|
|
public bool IsCurrent() => Volatile.Read(ref owner._disposed) == 0 && source.IsCurrent;
|
|
}
|
|
|
|
private static ProjectedBrowsePage Empty(ProjectedBrowseReadiness status) => new(status, [], null, false, static () => false);
|
|
|
|
public ProjectedBrowsePage GetOrSchedulePage(ProjectedBrowsePageRequest input)
|
|
{
|
|
ArgumentNullException.ThrowIfNull(input);
|
|
if (Volatile.Read(ref _disposed) != 0) return Empty(ProjectedBrowseReadiness.Unavailable);
|
|
var id = input.Parent.IdentifierAsString;
|
|
if (!ProjectedDataIds.TryDecodeIdentifier(id, out var mappingId, out _)) return Empty(ProjectedBrowseReadiness.Unavailable);
|
|
if (!_installed.TryGetValue(mappingId, out var anchor) || !Current(anchor.Placement)) return Empty(ProjectedBrowseReadiness.Unavailable);
|
|
DataView parent;
|
|
if (anchor.Node == input.Parent) parent = anchor.Placement.Anchor;
|
|
else
|
|
{
|
|
var realm = anchor.Placement.Mapping.Realm;
|
|
var expected = _resolveNode(ProjectedDataIds.NamespaceUri(realm), id);
|
|
if (expected != input.Parent || !_catalog.TryResolveProjected(realm, id, out var proof) || proof is null ||
|
|
proof.Subject.View.MappingId != mappingId || !proof.Lease.IsValid || !ReferenceEquals(proof.Resolver.LocalAuthority, anchor.Placement.Authority))
|
|
return Empty(ProjectedBrowseReadiness.Unavailable);
|
|
parent = proof.Metadata.View;
|
|
}
|
|
var caller = input.Caller;
|
|
if (caller is null || string.IsNullOrWhiteSpace(caller.Principal) || string.IsNullOrWhiteSpace(caller.ApiKeyId) ||
|
|
string.IsNullOrWhiteSpace(caller.CredentialVersion)) return Empty(ProjectedBrowseReadiness.Unavailable);
|
|
var identity = new DataCallerIdentity(caller.Principal, caller.ApiKeyId, caller.CredentialVersion, caller.CredentialExpiresUtc);
|
|
var maximum = input.MaximumResults == 0 ? _budget.MaxItems : (int)Math.Min((long)input.MaximumResults, _budget.MaxItems);
|
|
var budget = _budget with { MaxItems = maximum };
|
|
var request = new ProjectedBrowseRequest(mappingId, parent, null, input.Cursor, identity, budget, input.RequestStartedTimestamp);
|
|
var snapshot = _catalog.TryGetParent(request);
|
|
if (snapshot.Status == ProjectionPageStatus.Ready)
|
|
{
|
|
if (snapshot.Lease is not { IsValid: true } lease || snapshot.LocalAuthority is not { IsActive: true } local ||
|
|
!ReferenceEquals(local, anchor.Placement.Authority) || snapshot.Generation <= 0)
|
|
return Empty(ProjectedBrowseReadiness.Unavailable);
|
|
var nodes = new List<NodeId>(snapshot.Items.Count);
|
|
foreach (var item in snapshot.Items)
|
|
{
|
|
if (item.Generation != snapshot.Generation || !ReferenceEquals(item.Resolver.LocalAuthority, local) || !item.Lease.IsValid ||
|
|
item.Subject.View.MappingId != mappingId || _resolveNode(ProjectedDataIds.NamespaceUri(item.Metadata.View.Realm), item.LocalIdentifier) is not { } node)
|
|
return Empty(ProjectedBrowseReadiness.Unavailable);
|
|
nodes.Add(node);
|
|
}
|
|
var expectedIds = nodes.ToArray();
|
|
var sourceGuard = _catalog.CaptureParentGuard(request, snapshot);
|
|
if (sourceGuard is null) return Empty(ProjectedBrowseReadiness.Unavailable);
|
|
var guard = new PageGuard(this, sourceGuard);
|
|
if (!guard.IsCurrent()) return Empty(ProjectedBrowseReadiness.Unavailable);
|
|
var retainedBytes = checked(sourceGuard.RetainedBytes + 2048L + 2L * (snapshot.Continuation?.Length ?? 0) +
|
|
expectedIds.Sum(node => 128L + 2L * node.IdentifierAsString.Length));
|
|
return new(ProjectedBrowseReadiness.Ready, Array.AsReadOnly(expectedIds), snapshot.Continuation, snapshot.Complete,
|
|
guard.IsCurrent, retainedBytes);
|
|
}
|
|
if (snapshot.Status == ProjectionPageStatus.InvalidContinuation) return Empty(ProjectedBrowseReadiness.InvalidContinuation);
|
|
var key = new WorkKey(input.Parent, identity, input.Cursor, maximum);
|
|
lock (_resultGate)
|
|
{
|
|
var now = _catalog.Clock.GetTimestamp();
|
|
foreach (var expired in _failures.Where(x => x.Value.Until <= now).Select(x => x.Key).ToArray()) _failures.Remove(expired);
|
|
if (_failures.TryGetValue(key, out var failure))
|
|
return Empty(failure.Status switch
|
|
{
|
|
ProjectionPageStatus.InvalidContinuation => ProjectedBrowseReadiness.InvalidContinuation,
|
|
ProjectionPageStatus.Pending => ProjectedBrowseReadiness.Pending,
|
|
_ => ProjectedBrowseReadiness.Unavailable
|
|
});
|
|
if (_inflight.ContainsKey(key)) return Empty(ProjectedBrowseReadiness.Pending);
|
|
if (_failures.Count + _pending >= _maxPending) return Empty(ProjectedBrowseReadiness.Unavailable);
|
|
if (!_inflight.TryAdd(key, new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously))) return Empty(ProjectedBrowseReadiness.Pending);
|
|
_pending++;
|
|
}
|
|
var exactParent = input.Parent;
|
|
_ = Task.Run(async () =>
|
|
{
|
|
var result = ProjectionPageStatus.Unavailable;
|
|
try { if (Current(anchor.Placement)) result = await _applier.ApplyPageResultAsync(request, exactParent, _stop.Token).ConfigureAwait(false); }
|
|
catch (Exception) { }
|
|
finally
|
|
{
|
|
lock (_resultGate)
|
|
{
|
|
_inflight.TryRemove(key, out var completed);
|
|
_pending--;
|
|
if (result != ProjectionPageStatus.Ready && !_stop.IsCancellationRequested)
|
|
{
|
|
var now = _catalog.Clock.GetTimestamp();
|
|
var seconds = result == ProjectionPageStatus.InvalidContinuation ? 60L : 0L;
|
|
var delay = seconds == 0 ? Math.Max(1, _catalog.Clock.TimestampFrequency / 4) :
|
|
_catalog.Clock.TimestampFrequency > long.MaxValue / seconds ? long.MaxValue : _catalog.Clock.TimestampFrequency * seconds;
|
|
_failures[key] = new(result, now > long.MaxValue - delay ? long.MaxValue : now + delay);
|
|
}
|
|
completed?.TrySetResult();
|
|
}
|
|
}
|
|
});
|
|
return Empty(ProjectedBrowseReadiness.Pending);
|
|
}
|
|
|
|
public async Task<ProjectedBrowsePage> WaitForPageAsync(ProjectedBrowsePageRequest request, CancellationToken cancellationToken)
|
|
{
|
|
ArgumentNullException.ThrowIfNull(request);
|
|
for (var retry = 0; retry < 3; retry++)
|
|
{
|
|
var page = GetOrSchedulePage(request);
|
|
if (page.Status != ProjectedBrowseReadiness.Pending) return page;
|
|
var caller = request.Caller;
|
|
var identity = new DataCallerIdentity(caller.Principal, caller.ApiKeyId, caller.CredentialVersion, caller.CredentialExpiresUtc);
|
|
var max = request.MaximumResults == 0 ? _budget.MaxItems : (int)Math.Min((long)request.MaximumResults, _budget.MaxItems);
|
|
var key = new WorkKey(request.Parent, identity, request.Cursor, max);
|
|
if (!_inflight.TryGetValue(key, out var pending)) continue;
|
|
var elapsed = _catalog.Clock.GetElapsedTime(request.RequestStartedTimestamp, _catalog.Clock.GetTimestamp());
|
|
var remaining = _budget.Timeout - elapsed;
|
|
if (elapsed < TimeSpan.Zero || remaining <= TimeSpan.Zero) return Empty(ProjectedBrowseReadiness.Unavailable);
|
|
try { await pending.Task.WaitAsync(remaining, _catalog.Clock, cancellationToken).ConfigureAwait(false); }
|
|
catch (TimeoutException) { return Empty(ProjectedBrowseReadiness.Unavailable); }
|
|
}
|
|
return Empty(ProjectedBrowseReadiness.Unavailable);
|
|
}
|
|
|
|
public ProjectedBrowseReadiness GetOrSchedule(ProjectedBrowseContext context)
|
|
{
|
|
ArgumentNullException.ThrowIfNull(context);
|
|
if (!ProjectedDataIds.TryDecodeIdentifier(context.Parent.IdentifierAsString, out _, out _)) return ProjectedBrowseReadiness.Ready;
|
|
if (context.Caller is null) return ProjectedBrowseReadiness.Unavailable;
|
|
var page = GetOrSchedulePage(new(context.Parent, context.Caller, null, context.Continuation.MaxResultsToReturn, context.RequestStartedTimestamp));
|
|
return page.Status == ProjectedBrowseReadiness.Ready && !page.Complete ? ProjectedBrowseReadiness.Unavailable : page.Status;
|
|
}
|
|
|
|
public void Dispose()
|
|
{
|
|
if (Interlocked.Exchange(ref _disposed, 1) != 0) return;
|
|
_lifecycle.Changed -= OnChanged;
|
|
_stop.Cancel();
|
|
lock (_resultGate) _failures.Clear();
|
|
lock (_anchorGate)
|
|
{
|
|
foreach (var item in _installed.Values) _anchors.TryRemoveProjectedAnchor(item.Node, item.Definition);
|
|
_installed.Clear();
|
|
}
|
|
}
|
|
}
|