using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections;
namespace ZB.MOM.WW.OtOpcUa.Runtime.DataConnections;
/// Retained, deployment-authorized configured projection acquisition.
public interface IConfiguredProjectionLease : IAsyncDisposable { bool IsValid { get; } }
/// Discovers a configured projection from current deployed scope and verified origin pages.
public interface IConfiguredProjectionDiscovery { Task ResolveAsync(string reference, CancellationToken cancellationToken); }
/// Bounded aggregate interests driven by a fixed worker pool and one shared retry sweep.
public sealed class ConfiguredProjectedInterestOwner : IProjectedDependencyInterestSink, IAsyncDisposable
{
private sealed class Entry(string reference, long bytes)
{
internal readonly string Reference = reference;
internal readonly long Bytes = bytes;
internal bool Desired = true, Queued, Running;
internal IConfiguredProjectionLease? Lease;
internal CancellationTokenSource? InFlight;
}
private readonly object _sync = new();
private readonly Dictionary _entries = new(StringComparer.Ordinal);
private readonly Queue _ready = new();
private readonly SemaphoreSlim _available = new(0);
private readonly CancellationTokenSource _stop = new();
private readonly IConfiguredProjectionDiscovery _discovery;
private readonly int _maxInterests;
private readonly long _maxBytes;
private readonly TimeProvider _clock;
private readonly Task[] _workers;
private readonly Task _sweep;
private long _bytes;
private bool _disposed;
public ConfiguredProjectedInterestOwner(IConfiguredProjectionDiscovery discovery, int maxInterests,
int maxConcurrentCalls = 4, long maxTransportBytes = 16 * 1024 * 1024, TimeProvider? clock = null)
{
_discovery = discovery ?? throw new ArgumentNullException(nameof(discovery));
if (maxInterests <= 0 || maxConcurrentCalls <= 0 || maxTransportBytes <= 0) throw new ArgumentOutOfRangeException(nameof(maxInterests));
_maxInterests = maxInterests; _maxBytes = maxTransportBytes; _clock = clock ?? TimeProvider.System;
_workers = Enumerable.Range(0, maxConcurrentCalls).Select(_ => Task.Run(WorkAsync)).ToArray();
_sweep = Task.Run(SweepAsync);
}
private void Queue(Entry entry)
{
if (entry.Queued || entry.Running) return;
entry.Queued = true; _ready.Enqueue(entry); _available.Release();
}
public void SetInterest(string projectedReference, bool active)
{
if (!ProjectedDataIds.TryParseDependencyReference(projectedReference, out _, out _)) return;
lock (_sync)
{
if (_disposed) return;
if (_entries.TryGetValue(projectedReference, out var old))
{
if (old.Desired == active) return;
old.Desired = active; if (!active && old.InFlight is { } stop) _ = stop.CancelAsync();
Queue(old); return;
}
var bytes = checked(256L + 2L * projectedReference.Length);
if (!active || _entries.Count >= _maxInterests || bytes > _maxBytes - _bytes) return;
var entry = new Entry(projectedReference, bytes); _entries.Add(projectedReference, entry); _bytes += bytes; Queue(entry);
}
}
private async Task WorkAsync()
{
while (true)
{
await _available.WaitAsync().ConfigureAwait(false);
Entry? entry;
lock (_sync)
{
if (_ready.Count == 0) { if (_disposed) return; continue; }
entry = _ready.Dequeue(); entry.Queued = false; entry.Running = true;
}
IConfiguredProjectionLease? old;
bool desired;
lock (_sync) { desired = !_disposed && entry.Desired; old = entry.Lease; entry.Lease = null; }
var oldValid = false;
try { oldValid = old is not null && old.IsValid; } catch (Exception) { }
if (old is not null && desired && oldValid)
{
lock (_sync) { entry.Lease = old; entry.Running = false; if (!entry.Desired || _disposed) Queue(entry); }
continue;
}
if (old is not null) { try { await old.DisposeAsync().ConfigureAwait(false); } catch (Exception) { } }
CancellationTokenSource? operation = null;
lock (_sync)
{
desired = !_disposed && entry.Desired;
if (desired) { operation = new CancellationTokenSource(); entry.InFlight = operation; }
}
IConfiguredProjectionLease? acquired = null;
var canceled = false;
if (operation is not null)
{
try { acquired = await _discovery.ResolveAsync(entry.Reference, operation.Token).ConfigureAwait(false); }
catch (Exception) { }
lock (_sync) entry.InFlight = null;
canceled = operation.IsCancellationRequested; operation.Dispose();
}
bool retain;
try { retain = !canceled && acquired is { IsValid: true }; } catch (Exception) { retain = false; }
lock (_sync) retain = retain && !_disposed && entry.Desired;
if (!retain && acquired is not null) { try { await acquired.DisposeAsync().ConfigureAwait(false); } catch (Exception) { } acquired = null; }
lock (_sync)
{
entry.Lease = acquired; entry.Running = false;
if (!entry.Desired || _disposed)
{
if (entry.Lease is not null) Queue(entry);
else { _entries.Remove(entry.Reference); _bytes -= entry.Bytes; if (_disposed && _entries.Count == 0) for (var i = 0; i < _workers.Length; i++) _available.Release(); }
}
}
}
}
private async Task SweepAsync()
{
try
{
using var timer = new PeriodicTimer(TimeSpan.FromSeconds(1), _clock);
while (await timer.WaitForNextTickAsync(_stop.Token).ConfigureAwait(false))
lock (_sync) foreach (var entry in _entries.Values) if (entry.Desired) Queue(entry);
}
catch (OperationCanceledException) { }
}
public async ValueTask DisposeAsync()
{
lock (_sync)
{
if (_disposed) return;
_disposed = true; _stop.Cancel();
foreach (var entry in _entries.Values) { entry.Desired = false; if (entry.InFlight is { } operation) _ = operation.CancelAsync(); Queue(entry); }
if (_entries.Count == 0) for (var i = 0; i < _workers.Length; i++) _available.Release();
}
await _sweep.ConfigureAwait(false); await Task.WhenAll(_workers).ConfigureAwait(false);
_stop.Dispose(); _available.Dispose();
}
}