133 lines
7.4 KiB
C#
133 lines
7.4 KiB
C#
using Opc.Ua;
|
|
using ZB.MOM.WW.OtOpcUa.Core.Authorization;
|
|
using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections;
|
|
using ZB.MOM.WW.OtOpcUa.OpcUaServer;
|
|
|
|
namespace ZB.MOM.WW.OtOpcUa.Runtime.DataConnections;
|
|
|
|
/// <summary>Prepares bounded remote pages and hands them to the local atomic publication boundary.</summary>
|
|
public sealed class ProjectedNamespaceApplier : IDisposable
|
|
{
|
|
private readonly IFederatedProjectionCatalog _catalog;
|
|
private readonly IProjectedNamespacePageSink _sink;
|
|
private readonly SemaphoreSlim _slots;
|
|
private readonly CancellationTokenSource _stop = new();
|
|
private int _disposed;
|
|
|
|
public ProjectedNamespaceApplier(IFederatedProjectionCatalog catalog, IProjectedNamespacePageSink sink, int maxConcurrent)
|
|
{
|
|
_catalog = catalog ?? throw new ArgumentNullException(nameof(catalog));
|
|
_sink = sink ?? throw new ArgumentNullException(nameof(sink));
|
|
if (maxConcurrent <= 0) throw new ArgumentOutOfRangeException(nameof(maxConcurrent));
|
|
_slots = new(maxConcurrent, maxConcurrent);
|
|
}
|
|
|
|
private sealed class CommitState(long generation, ServingIdentity serving)
|
|
{
|
|
private int _aborted;
|
|
internal long Generation => generation;
|
|
internal ServingIdentity Serving => serving;
|
|
internal bool Aborted => Volatile.Read(ref _aborted) != 0;
|
|
internal void Abort() => Interlocked.Exchange(ref _aborted, 1);
|
|
}
|
|
|
|
// This object deliberately owns one frozen item and small shared control only. A bound method
|
|
// must never capture the preparation frame, its siblings, request, linked CTS or cursor owner.
|
|
private sealed class ItemGuard : IProjectedRetainedAuthority
|
|
{
|
|
internal readonly ProjectedNodeProof Proof;
|
|
private readonly CommitState _state;
|
|
private readonly CancellationToken _stop;
|
|
internal ItemGuard(ProjectedNodeProof proof, CommitState state, CancellationToken stop)
|
|
{
|
|
Proof = proof with
|
|
{
|
|
Metadata = proof.Metadata with { Dimensions = Array.AsReadOnly(proof.Metadata.Dimensions.ToArray()) },
|
|
OriginMetadata = proof.OriginMetadata with { Dimensions = Array.AsReadOnly(proof.OriginMetadata.Dimensions.ToArray()) },
|
|
Subject = proof.Subject with
|
|
{
|
|
Scope = proof.Subject.Scope with { Segments = Array.AsReadOnly(proof.Subject.Scope.Segments.ToArray()) },
|
|
LocalAncestry = Array.AsReadOnly(proof.Subject.LocalAncestry.ToArray())
|
|
}
|
|
};
|
|
_state = state; _stop = stop;
|
|
RetainedBytes = checked(2048L + ProjectedProofSize.Estimate(Proof));
|
|
}
|
|
public long RetainedBytes { get; }
|
|
public bool IsCurrent()
|
|
{
|
|
try
|
|
{
|
|
return !_state.Aborted && !_stop.IsCancellationRequested && Proof.Generation == _state.Generation &&
|
|
Proof.Lease.Serving == _state.Serving && Proof.Resolver.LocalAuthority.IsActive &&
|
|
Proof.Resolver.Resolve(Proof.Metadata.View, Proof.Subject).Kind == MappedSubjectResolutionKind.Mapped && Proof.Lease.IsValid;
|
|
}
|
|
catch (Exception) { return false; }
|
|
}
|
|
|
|
}
|
|
|
|
public async Task<bool> ApplyPageAsync(ProjectedBrowseRequest request, NodeId exactParent, CancellationToken cancellationToken) =>
|
|
await ApplyPageResultAsync(request, exactParent, cancellationToken).ConfigureAwait(false) == ProjectionPageStatus.Ready;
|
|
|
|
public async Task<ProjectionPageStatus> ApplyPageResultAsync(ProjectedBrowseRequest request, NodeId exactParent, CancellationToken cancellationToken)
|
|
{
|
|
ArgumentNullException.ThrowIfNull(request);
|
|
if (Volatile.Read(ref _disposed) != 0 || !_slots.Wait(0)) return ProjectionPageStatus.Unavailable;
|
|
try
|
|
{
|
|
request.Budget.Validate();
|
|
var elapsed = _catalog.Clock.GetElapsedTime(request.RequestStartedTimestamp, _catalog.Clock.GetTimestamp());
|
|
var remaining = request.Budget.Timeout - elapsed;
|
|
if (elapsed < TimeSpan.Zero || remaining <= TimeSpan.Zero) return ProjectionPageStatus.Unavailable;
|
|
using var linked = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, _stop.Token);
|
|
linked.CancelAfter(remaining);
|
|
using var prepared = await _catalog.PreparePageAsync(request, linked.Token).ConfigureAwait(false);
|
|
var page = prepared.Snapshot;
|
|
if (page.Status != ProjectionPageStatus.Ready) return page.Status;
|
|
if (page.Generation <= 0 || page.Lease is not { IsValid: true } pageLease || page.LocalAuthority is not { IsActive: true } local ||
|
|
page.Items.Count > request.Budget.MaxItems) return ProjectionPageStatus.Unavailable;
|
|
var state = new CommitState(page.Generation, pageLease.Serving);
|
|
var guards = page.Items.Select(item => new ItemGuard(item, state, _stop.Token)).ToArray();
|
|
var root = page.ParentProof is { } parentProof ? new ItemGuard(parentProof, state, _stop.Token) : null;
|
|
bool PageCurrent() => Volatile.Read(ref _disposed) == 0 && !linked.IsCancellationRequested &&
|
|
!state.Aborted && local.IsActive && pageLease.IsValid;
|
|
if (!PageCurrent() || guards.Any(guard => !guard.IsCurrent()) || root is not null && !root.IsCurrent())
|
|
return ProjectionPageStatus.Unavailable;
|
|
var definitions = guards.Select(guard => new ProjectedVariableDefinition(guard.Proof.Metadata.View.Realm,
|
|
guard.Proof.LocalIdentifier, exactParent, guard.Proof.Metadata, guard.Proof.Generation, guard.IsCurrent)).ToArray();
|
|
var rootLeaf = root is not null && ProjectedCatalogCache.IsValueNode(root.Proof.Metadata);
|
|
if (rootLeaf && (definitions.Length != 0 || !page.Complete)) return ProjectionPageStatus.Unavailable;
|
|
var attempted = 0;
|
|
var committed = false;
|
|
var accepted = false;
|
|
bool Commit()
|
|
{
|
|
if (Interlocked.Exchange(ref attempted, 1) != 0 || !PageCurrent() ||
|
|
guards.Any(guard => !guard.IsCurrent()) || root is not null && !root.IsCurrent()) return false;
|
|
committed = prepared.TryCommit();
|
|
return committed && PageCurrent();
|
|
}
|
|
try
|
|
{
|
|
accepted = rootLeaf
|
|
? _sink.TryApplyRootLeaf(exactParent, new ProjectedVariableDefinition(root!.Proof.Metadata.View.Realm,
|
|
root.Proof.LocalIdentifier, exactParent, root.Proof.Metadata, root.Proof.Generation, root.IsCurrent), Commit)
|
|
: _sink.TryApply(exactParent, definitions, Commit);
|
|
return accepted && committed && PageCurrent() ? ProjectionPageStatus.Ready : ProjectionPageStatus.Unavailable;
|
|
}
|
|
// Successful SDK/cache acceptance publishes shared metadata. A later caller timeout
|
|
// does not revoke it; its independent lease/deployment guards still fence every use.
|
|
finally { if (!accepted || !committed) state.Abort(); }
|
|
}
|
|
catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested || _stop.IsCancellationRequested) { return ProjectionPageStatus.Unavailable; }
|
|
catch (OperationCanceledException) { return ProjectionPageStatus.Unavailable; }
|
|
finally { _slots.Release(); }
|
|
}
|
|
|
|
public void Dispose()
|
|
{
|
|
if (Interlocked.Exchange(ref _disposed, 1) == 0) _stop.Cancel();
|
|
}
|
|
}
|