121 lines
6.9 KiB
C#
121 lines
6.9 KiB
C#
using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections;
|
|
using ZB.MOM.WW.OtOpcUa.Core.Authorization;
|
|
|
|
namespace ZB.MOM.WW.OtOpcUa.Runtime.DataConnections;
|
|
|
|
/// <summary>Combines the remote metadata lease with local catalog and connection retirement fences.</summary>
|
|
internal sealed class BoundProjectionLease(MetadataAuthorityLease remote, CancellationToken route,
|
|
IDataMappedCatalogAuthority local, ProjectedCatalogCache cache, string mapping, long generation, Func<bool> bindingCurrent,
|
|
Func<bool>? routeCurrent = null, object? routeIdentity = null, DataTarget? target = null, object? bindingIdentity = null) : IDataAuthorizationLease
|
|
{
|
|
public ServingIdentity Serving => remote.Serving;
|
|
internal object? RouteIdentity => routeIdentity;
|
|
internal DataTarget? Target => target;
|
|
internal object? BindingIdentity => bindingIdentity;
|
|
internal TimeSpan Remaining => remote.Remaining;
|
|
internal TimeSpan UsableDuration => remote.UsableDuration;
|
|
private bool RouteAlive => !route.IsCancellationRequested && (routeCurrent?.Invoke() ?? true);
|
|
internal bool LiveContext => RouteAlive && local.IsActive && bindingCurrent() && cache.IsCurrentGeneration(mapping, generation);
|
|
internal bool ExpiredNaturally => remote.ExpiredNaturally && LiveContext;
|
|
public bool IsValid => LiveContext && remote.IsValid;
|
|
internal ProjectionLeaseDiagnostics CaptureDiagnostics() => new(RouteAlive, local.IsActive,
|
|
remote.IsValid, bindingCurrent(), cache.IsCurrentGeneration(mapping, generation));
|
|
}
|
|
|
|
// Read-only observations, not an authorization decision. The five fences can change
|
|
// between reads, and callers must continue to use IsValid for authority.
|
|
internal sealed record ProjectionLeaseDiagnostics(bool RouteAlive, bool LocalAuthorityActive, bool RemoteLeaseValid,
|
|
bool MappingBindingCurrent, bool CacheGenerationCurrent);
|
|
|
|
/// <summary>A page holds its physical connection lease until the caller commits or aborts it.</summary>
|
|
internal sealed class PreparedPage : IProjectedPreparedPage
|
|
{
|
|
private readonly ProjectedCatalogCache? _cache;
|
|
private readonly BrowseContinuationRegistry? _cursors;
|
|
private readonly ProjectedBrowseRequest? _request;
|
|
private readonly BrowseContinuationBinding? _binding;
|
|
private readonly PreparedBrowseContinuation? _cursor;
|
|
private readonly string? _nextPeerCursor;
|
|
private readonly SharedPageConnection? _connection;
|
|
private readonly TimeProvider? _clock;
|
|
private readonly TimeSpan _cursorLifetime;
|
|
private readonly long _cursorStart;
|
|
private readonly int _maximumMappingNodes;
|
|
private int _finished;
|
|
private ProjectedParentSnapshot _snapshot;
|
|
private PreparedPage(ProjectionPageStatus status) => _snapshot = new(status, [], false, null, 0);
|
|
internal PreparedPage(ProjectedCatalogCache cache, BrowseContinuationRegistry cursors, ProjectedBrowseRequest request,
|
|
ProjectedParentSnapshot snapshot, BrowseContinuationBinding binding, PreparedBrowseContinuation? cursor, string? nextPeerCursor,
|
|
IGrpcDataAdapterConnectionLease connection, SemaphoreSlim slots, TimeProvider clock, TimeSpan cursorLifetime, int maximumMappingNodes)
|
|
{
|
|
_cache = cache; _cursors = cursors; _request = request; _snapshot = snapshot; _binding = binding;
|
|
_cursor = cursor; _nextPeerCursor = nextPeerCursor; _connection = new SharedPageConnection(connection, slots); _clock = clock;
|
|
_cursorLifetime = cursorLifetime; _cursorStart = request.RequestStartedTimestamp; _maximumMappingNodes = maximumMappingNodes;
|
|
}
|
|
private PreparedPage(PreparedPage original, ProjectedBrowseRequest request)
|
|
{
|
|
_cache = original._cache; _cursors = original._cursors; _request = request; _snapshot = original._snapshot; _binding = original._binding;
|
|
_nextPeerCursor = original._nextPeerCursor; _connection = original._connection; _connection!.AddReference();
|
|
_clock = original._clock; _cursorLifetime = original._cursorLifetime; _cursorStart = original._cursorStart; _maximumMappingNodes = original._maximumMappingNodes;
|
|
}
|
|
internal static PreparedPage Failed(ProjectionPageStatus status) => new(status);
|
|
internal PreparedPage CloneForWaiter(ProjectedBrowseRequest request) => _connection is null
|
|
? Failed(_snapshot.Status) : new PreparedPage(this, request);
|
|
public ProjectedParentSnapshot Snapshot => _snapshot;
|
|
public bool TryCommit()
|
|
{
|
|
if (Interlocked.Exchange(ref _finished, 1) != 0 || _cache is null || _request is null || _binding is null || _cursors is null || _clock is null) return false;
|
|
try
|
|
{
|
|
if (_connection!.CancellationToken.IsCancellationRequested || _snapshot.Lease is not { IsValid: true } ||
|
|
_clock.GetElapsedTime(_request.RequestStartedTimestamp, _clock.GetTimestamp()) >= _request.Budget.Timeout) return false;
|
|
var ok = _cache.TryPublish(_request, _snapshot, () =>
|
|
{
|
|
if (_cursor is not null) return (_cursor.TryCommit(_nextPeerCursor, out var next), next);
|
|
if (_nextPeerCursor is null) return (true, null);
|
|
// The lease deadline is measured from the original RPC start, not reply receipt.
|
|
var lifetime = _cursorLifetime > TimeSpan.FromSeconds(60) ? TimeSpan.FromSeconds(60) : _cursorLifetime;
|
|
return (true, _cursors.Issue(_binding, _nextPeerCursor, lifetime, _cursorStart));
|
|
}, out var committed, _maximumMappingNodes);
|
|
if (ok) _snapshot = committed!;
|
|
return ok;
|
|
}
|
|
catch (Exception ex) when (ex is ArgumentException or InvalidOperationException) { return false; }
|
|
finally { _cursor?.Dispose(); Release(); }
|
|
}
|
|
public void Dispose()
|
|
{
|
|
if (Interlocked.Exchange(ref _finished, 1) != 0) return;
|
|
_cursor?.Dispose(); Release();
|
|
}
|
|
private void Release() => _connection?.Release();
|
|
internal async Task DisposeAndWaitAsync()
|
|
{
|
|
Dispose();
|
|
if (_connection is not null) await _connection.Closed.ConfigureAwait(false);
|
|
}
|
|
}
|
|
|
|
/// <summary>Counts every prepared page that still owns one shared physical connection.</summary>
|
|
internal sealed class SharedPageConnection(IGrpcDataAdapterConnectionLease connection, SemaphoreSlim slots)
|
|
{
|
|
private int _references = 1;
|
|
private readonly TaskCompletionSource _closed = new(TaskCreationOptions.RunContinuationsAsynchronously);
|
|
internal Task Closed => _closed.Task;
|
|
public CancellationToken CancellationToken => connection.CancellationToken;
|
|
public void AddReference()
|
|
{
|
|
if (Interlocked.Increment(ref _references) <= 1) throw new ObjectDisposedException(nameof(SharedPageConnection));
|
|
}
|
|
public void Release()
|
|
{
|
|
if (Interlocked.Decrement(ref _references) == 0) _ = CloseAsync();
|
|
}
|
|
private async Task CloseAsync()
|
|
{
|
|
try { await connection.DisposeAsync().ConfigureAwait(false); }
|
|
catch (Exception) { }
|
|
finally { slots.Release(); _closed.TrySetResult(); }
|
|
}
|
|
}
|