Files
lmxopcua/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/DriverHostSubscriptionDemandSource.cs
T

431 lines
21 KiB
C#

using Akka.Actor;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections;
using ZB.MOM.WW.OtOpcUa.Runtime.Drivers;
namespace ZB.MOM.WW.OtOpcUa.Runtime.DataConnections;
/// <summary>Bridges independently authorized views to bounded per-driver physical demand.</summary>
internal sealed class DriverHostSubscriptionDemandSource : ISubscriptionDemandSource, IDisposable
{
private sealed record Interest(long Id, DemandSharingKey Key, string Reference, DataSubscriptionSettings Settings,
IDisposable RegistryLease, Func<bool> CanPublish, DriverState Driver);
private sealed record Applied(string[] References, TimeSpan Interval, long Revision, long Producer, TimeSpan Nominal);
private sealed record ApplyOutcome(Applied? Applied, Task<bool>? Busy);
private sealed class DriverState(string id)
{
internal readonly string Id = id;
internal readonly SemaphoreSlim Serial = new(1, 1);
internal readonly Dictionary<string, int> References = new(StringComparer.Ordinal);
internal readonly SortedDictionary<TimeSpan, int> Intervals = new();
internal string[]? Snapshot;
internal int Interests;
internal long Change;
internal Applied? Applied;
internal long OwnerGeneration, KeyGeneration, LastIssuedRevision;
internal string[]? LastIssuedReferences;
internal TimeSpan LastIssuedInterval;
internal bool Scheduled;
internal bool RetryCleanupRequested;
internal Task<bool>? BusySource, BusyAdmissionWait;
internal Task<bool>? PendingOpenCleanup;
internal long PendingOpenOwner, PendingOpenKey;
internal readonly TaskCompletionSource IdleForTest = new(TaskCreationOptions.RunContinuationsAsynchronously);
internal readonly TaskCompletionSource OpenAbortFailedForTest = new(TaskCreationOptions.RunContinuationsAsynchronously);
}
private readonly object _gate = new();
private readonly IActorRef _host;
private readonly UpstreamDemandRegistry _registry;
private readonly int _maxDrivers, _maxInterests;
private readonly TimeSpan _timeout;
private readonly TimeSpan _abortRetryDelay;
private readonly Guid _ownerId = Guid.NewGuid();
private readonly long _ownerSerial;
private readonly SubscriptionAcquisitionCapacity _ownership;
private Task<long>? _ownerRegistration;
private readonly Dictionary<long, Interest> _interests = new();
private readonly Dictionary<string, DriverState> _drivers = new(StringComparer.Ordinal);
private long _nextId, _nextRevision, _referenceVisits;
private bool _disposed;
internal DriverHostSubscriptionDemandSource(IActorRef host, UpstreamDemandRegistry registry,
int maxDrivers, int maxInterests, TimeSpan timeout, SubscriptionAcquisitionCapacity ownership,
TimeSpan? abortRetryDelay = null)
{
ArgumentNullException.ThrowIfNull(host); ArgumentNullException.ThrowIfNull(registry); ArgumentNullException.ThrowIfNull(ownership);
if (host is not IActorRefScope { IsLocal: true })
throw new ArgumentException("Physical subscription demand requires a local driver host.", nameof(host));
if (maxDrivers <= 0 || maxInterests <= 0 || timeout <= TimeSpan.Zero || abortRetryDelay < TimeSpan.Zero)
throw new ArgumentOutOfRangeException(nameof(maxDrivers));
_host = host; _registry = registry; _maxDrivers = maxDrivers; _maxInterests = maxInterests; _timeout = timeout;
_abortRetryDelay = abortRetryDelay ?? TimeSpan.FromMilliseconds(100);
_ownership = ownership;
_ownerSerial = ownership.NextOwnerSerial();
}
// Counts actual reference keys visited to materialize physical desired sets.
internal long ReferenceVisitCount => Interlocked.Read(ref _referenceVisits);
internal Task WaitForDriverIdleForTest(string driver)
{
lock (_gate) return _drivers.TryGetValue(driver, out var state) ? state.IdleForTest.Task : Task.CompletedTask;
}
internal Task WaitForOpenAbortFailureForTest(string driver)
{
lock (_gate)
return _drivers.TryGetValue(driver, out var state)
? state.OpenAbortFailedForTest.Task
: Task.FromException(new InvalidOperationException("The driver has no active Open cleanup."));
}
public async ValueTask<SubscriptionDemandResult> AcquireAsync(SubscriptionAuthorizedView view,
DataSubscriptionSettings settings, CancellationToken cancellationToken)
{
ArgumentNullException.ThrowIfNull(view); ArgumentNullException.ThrowIfNull(settings);
cancellationToken.ThrowIfCancellationRequested(); settings.Validate();
if (!view.CanPublish() || !SourceKey.TryDriver(view.Source, out var driver, out var reference) ||
string.IsNullOrWhiteSpace(driver) || string.IsNullOrWhiteSpace(reference)) return Failed(DataItemStatus.Unavailable);
var key = new DemandSharingKey(view.Source, view.Target, view.Consistency, view.PrincipalId, view.ExportScope,
view.Serving.CatalogEpoch, view.Serving.AuthorityEpoch);
Interest interest;
lock (_gate)
{
if (_disposed || _interests.Count >= _maxInterests)
return Failed(DataItemStatus.ResourceExhausted);
if (!_drivers.ContainsKey(driver) && _drivers.Count >= _maxDrivers)
{
// Reclaim inactive logical Open aborts under pressure. Each driver has one
// coalescing worker, so one unavailable host or key does not serialize others.
foreach (var candidate in _drivers.Values)
if (candidate.Interests == 0 && candidate.PendingOpenCleanup is not null)
Schedule(candidate, retryOpenCleanup: true);
return Failed(DataItemStatus.ResourceExhausted);
}
if (!_registry.TryAdd(key, settings, out var registryLease) || registryLease is null) return Failed(DataItemStatus.ResourceExhausted);
if (!_drivers.TryGetValue(driver, out var state)) _drivers.Add(driver, state = new DriverState(driver));
interest = new Interest(checked(++_nextId), key, reference, settings, registryLease, view.CanPublish, state);
_interests.Add(interest.Id, interest);
Add(state, interest);
}
try
{
while (true)
{
await interest.Driver.Serial.WaitAsync(cancellationToken).ConfigureAwait(false);
ApplyOutcome outcome;
try
{
lock (_gate)
if (_disposed || !_interests.ContainsKey(interest.Id) || !interest.CanPublish())
return Reject(interest, DataItemStatus.Unavailable);
outcome = await ApplyAsync(interest.Driver, cancellationToken, retryOpenCleanup: true).ConfigureAwait(false);
}
finally { interest.Driver.Serial.Release(); }
if (outcome.Busy is { } ready)
{
if (!await SharedBusyWait(interest.Driver, ready).WaitAsync(cancellationToken).ConfigureAwait(false))
return Reject(interest, DataItemStatus.Unavailable);
continue;
}
var applied = outcome.Applied;
if (applied is null || applied.Nominal > settings.SamplingInterval || !interest.CanPublish())
return Reject(interest, DataItemStatus.Unavailable);
var state = _registry.GetState(key);
if (state is null || !_registry.TryAcknowledge(key, state.DesiredRevision,
state.Desired with { SamplingInterval = applied.Nominal, Deadband = null }, applied.Revision))
return Reject(interest, DataItemStatus.Unavailable);
// Boundary is a physical demand generation, not a sample version or freshness claim.
return new(DataItemStatus.Good, settings, applied.Revision, new InterestLease(this, interest.Id));
}
}
catch (OperationCanceledException) { Reject(interest, DataItemStatus.Unavailable); throw; }
catch (Exception) { return Reject(interest, DataItemStatus.Unavailable); }
}
private void Add(DriverState state, Interest interest)
{
if (!state.References.TryGetValue(interest.Reference, out var refs)) { state.Snapshot = null; refs = 0; }
state.References[interest.Reference] = refs + 1;
state.Intervals[interest.Settings.SamplingInterval] = state.Intervals.GetValueOrDefault(interest.Settings.SamplingInterval) + 1;
state.Interests++; state.Change++;
}
private void Subtract(DriverState state, Interest interest)
{
var refs = state.References[interest.Reference];
if (refs == 1) { state.References.Remove(interest.Reference); state.Snapshot = null; }
else state.References[interest.Reference] = refs - 1;
var interval = interest.Settings.SamplingInterval;
if (state.Intervals[interval] == 1) state.Intervals.Remove(interval); else state.Intervals[interval]--;
state.Interests--; state.Change++;
}
private async Task<ApplyOutcome> ApplyAsync(DriverState state, CancellationToken cancellationToken,
bool retryOpenCleanup = false)
{
if (state.PendingOpenCleanup is { } cleanup)
{
if (!await cleanup.WaitAsync(cancellationToken).ConfigureAwait(false))
{
// Abort is an idempotent owner/key-fenced control operation. Retry only when a
// new acquisition requests this driver; the driver slot remains held throughout.
if (!retryOpenCleanup) return new(null, null);
cleanup = ObserveOpenAbortForTest(RetryOpenAbortAsync(state.Id, state.PendingOpenOwner, state.PendingOpenKey), state);
state.PendingOpenCleanup = cleanup;
if (!await cleanup.WaitAsync(cancellationToken).ConfigureAwait(false)) return new(null, null);
}
state.PendingOpenCleanup = null;
state.PendingOpenOwner = 0; state.PendingOpenKey = 0;
}
string[] refs; TimeSpan interval;
lock (_gate)
{
if (state.Snapshot is null)
{
Interlocked.Add(ref _referenceVisits, state.References.Count);
state.Snapshot = state.References.Keys.Order(StringComparer.Ordinal).ToArray();
}
refs = state.Snapshot;
interval = state.Intervals.Count == 0 ? TimeSpan.Zero : state.Intervals.First().Key;
}
if (refs.Length == 0 && state.KeyGeneration == 0) return new(null, null);
for (var attempt = 0; attempt < 2; attempt++)
{
var owner = await GetOwnerAsync(cancellationToken).ConfigureAwait(false);
if (owner <= 0) return new(null, null);
if (state.OwnerGeneration != owner) { state.OwnerGeneration = owner; state.KeyGeneration = 0; state.Applied = null; }
if (state.KeyGeneration == 0)
{
if (refs.Length == 0) return new(null, null);
var proposedKey = _ownership.NextControlGeneration();
var opening = _host.Ask<DriverHostActor.AcquisitionDemandOpened>(
new DriverHostActor.OpenAcquisitionDemand(state.Id, owner, proposedKey), _timeout);
DriverHostActor.AcquisitionDemandOpened opened;
try
{
opened = await opening.WaitAsync(cancellationToken).ConfigureAwait(false);
}
catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested)
{
ObserveAbandonedOpen(opening);
state.PendingOpenOwner = owner; state.PendingOpenKey = proposedKey;
state.PendingOpenCleanup = ObserveOpenAbortForTest(AbortOpenAsync(state.Id, owner, proposedKey), state);
throw;
}
catch (Exception)
{
ObserveAbandonedOpen(opening);
state.PendingOpenOwner = owner; state.PendingOpenKey = proposedKey;
state.PendingOpenCleanup = ObserveOpenAbortForTest(AbortOpenAsync(state.Id, owner, proposedKey), state);
return new(null, null);
}
if (opened.OwnerInvalid)
{
InvalidateOwner(owner);
state.OwnerGeneration = 0; state.KeyGeneration = 0; state.Applied = null;
continue;
}
if (opened.StaleGeneration) continue;
if (!opened.Succeeded || opened.KeyGeneration != proposedKey) return new(null, null);
state.KeyGeneration = opened.KeyGeneration;
state.LastIssuedRevision = 0; state.LastIssuedReferences = null;
}
long revision;
lock (_gate)
{
revision = state.LastIssuedRevision != 0 && ReferenceEquals(state.LastIssuedReferences, refs) && state.LastIssuedInterval == interval
? state.LastIssuedRevision : checked(++_nextRevision);
// Record issued state before dispatch, even when cancellation hides its eventual ACK.
state.LastIssuedRevision = revision; state.LastIssuedReferences = refs; state.LastIssuedInterval = interval;
}
DriverInstanceActor.AcquisitionDemandApplied result;
try
{
result = await _host.Ask<DriverInstanceActor.AcquisitionDemandApplied>(
new DriverHostActor.ApplyAcquisitionDemand(state.Id, refs, interval, revision, owner, state.KeyGeneration),
_timeout, cancellationToken).ConfigureAwait(false);
}
catch (Exception) when (!cancellationToken.IsCancellationRequested) { return new(null, null); }
if (result.OwnerInvalid)
{
InvalidateOwner(owner);
state.OwnerGeneration = 0; state.KeyGeneration = 0; state.Applied = null;
continue;
}
if (result.KeyInvalid)
{
state.KeyGeneration = 0; state.Applied = null;
continue;
}
if (refs.Length == 0)
{
if (!result.Succeeded || result.DesiredRevision != revision) return new(null, null);
state.KeyGeneration = 0; state.Applied = null; state.LastIssuedRevision = 0; state.LastIssuedReferences = null;
return new(null, null);
}
if (result.Busy && !result.Succeeded && result.DesiredRevision == revision &&
result.ProducerIncarnation > 0 && result.RetryWhenReady is not null)
return new(null, result.RetryWhenReady);
if (!result.Succeeded || result.DesiredRevision != revision || result.ProducerIncarnation <= 0 || result.NominalSamplingInterval <= TimeSpan.Zero)
return new(null, null);
var applied = new Applied(refs, interval, revision, result.ProducerIncarnation, result.NominalSamplingInterval);
lock (_gate) state.Applied = applied;
return new(applied, null);
}
return new(null, null);
}
private Task<long> GetOwnerAsync(CancellationToken cancellationToken)
{
Task<long> registration;
lock (_gate)
{
if (_ownerRegistration is { IsCompletedSuccessfully: true } previous && previous.Result == 0)
_ownerRegistration = null;
registration = _ownerRegistration ??= RegisterOwnerAsync();
}
return registration.WaitAsync(cancellationToken);
}
private static void ObserveAbandonedOpen(Task<DriverHostActor.AcquisitionDemandOpened> opening)
{
_ = opening.ContinueWith(static task => { _ = task.Exception; }, CancellationToken.None,
TaskContinuationOptions.OnlyOnFaulted | TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default);
}
private static async Task<bool> ObserveOpenAbortForTest(Task<bool> attempt, DriverState state)
{
var completed = await attempt.ConfigureAwait(false);
if (!completed) state.OpenAbortFailedForTest.TrySetResult();
return completed;
}
private async Task<bool> AbortOpenAsync(string driver, long owner, long key)
{
try
{
var result = await _host.Ask<DriverHostActor.AcquisitionOpenAborted>(
new DriverHostActor.AbortOpenAcquisitionDemand(driver, owner, key), _timeout).ConfigureAwait(false);
if (result.OwnerInvalid) { InvalidateOwner(owner); return true; }
return result.Succeeded;
}
catch (Exception) { return false; }
}
private async Task<bool> RetryOpenAbortAsync(string driver, long owner, long key)
{
if (_abortRetryDelay > TimeSpan.Zero) await Task.Delay(_abortRetryDelay).ConfigureAwait(false);
return await AbortOpenAsync(driver, owner, key).ConfigureAwait(false);
}
private async Task<long> RegisterOwnerAsync()
{
try
{
var result = await _host.Ask<DriverHostActor.AcquisitionOwnerRegistered>(
new DriverHostActor.RegisterAcquisitionOwner(_ownerId, _ownerSerial), _timeout).ConfigureAwait(false);
return result.Succeeded && result.Generation > 0 ? result.Generation : 0;
}
catch (Exception) { return 0; }
}
private void InvalidateOwner(long generation)
{
lock (_gate)
if (_ownerRegistration is { IsCompletedSuccessfully: true } task && task.Result == generation)
_ownerRegistration = null;
}
private static SubscriptionDemandResult Failed(DataItemStatus status) => new(status, null, 0, null);
private Task<bool> SharedBusyWait(DriverState state, Task<bool> ready)
{
lock (_gate)
{
if (!ReferenceEquals(state.BusySource, ready))
{
state.BusySource = ready;
state.BusyAdmissionWait = AwaitBusyAsync(ready);
}
return state.BusyAdmissionWait!;
}
}
private async Task<bool> AwaitBusyAsync(Task<bool> ready)
{
try { return await ready.WaitAsync(_timeout).ConfigureAwait(false); }
catch (Exception) { return false; }
}
private SubscriptionDemandResult Reject(Interest interest, DataItemStatus status) { Remove(interest.Id); return Failed(status); }
private sealed class InterestLease(DriverHostSubscriptionDemandSource owner, long id) : IDisposable
{
private DriverHostSubscriptionDemandSource? _owner = owner;
public void Dispose() => Interlocked.Exchange(ref _owner, null)?.Remove(id);
}
private void Remove(long id)
{
lock (_gate)
{
if (!_interests.Remove(id, out var interest)) return;
interest.RegistryLease.Dispose(); Subtract(interest.Driver, interest);
Schedule(interest.Driver);
}
}
// One coalescing reconciliation or cleanup waiter per charged driver; no per-update task.
private void Schedule(DriverState state, bool retryOpenCleanup = false)
{
if (retryOpenCleanup) state.RetryCleanupRequested = true;
if (state.Scheduled) return;
state.Scheduled = true;
_ = Task.Run(() => ReconcileAsync(state));
}
private async Task ReconcileAsync(DriverState state)
{
while (true)
{
long version;
bool retryOpenCleanup;
lock (_gate)
{
version = state.Change;
retryOpenCleanup = state.RetryCleanupRequested;
state.RetryCleanupRequested = false;
}
ApplyOutcome? outcome = null;
await state.Serial.WaitAsync().ConfigureAwait(false);
try { outcome = await ApplyAsync(state, CancellationToken.None, retryOpenCleanup).ConfigureAwait(false); }
catch (Exception) { }
finally { state.Serial.Release(); }
if (outcome?.Busy is { } ready)
{
_ = WaitForReadyAsync(state, ready);
return;
}
lock (_gate)
{
if (state.Change != version || state.RetryCleanupRequested) continue;
state.Scheduled = false;
if (state.Interests == 0 && state.Applied is null && state.KeyGeneration == 0 && state.PendingOpenCleanup is null)
{
_drivers.Remove(state.Id);
state.IdleForTest.TrySetResult();
}
return;
}
}
}
private async Task WaitForReadyAsync(DriverState state, Task<bool> ready)
{
try
{
if (await ready.ConfigureAwait(false)) await ReconcileAsync(state).ConfigureAwait(false);
// A failed/uncertain cleanup leaves the key charged and is never replayed.
}
catch (Exception) { }
}
public void Dispose()
{
lock (_gate)
{
if (_disposed) return;
_disposed = true;
foreach (var interest in _interests.Values) { interest.RegistryLease.Dispose(); Subtract(interest.Driver, interest); }
_interests.Clear();
foreach (var state in _drivers.Values) Schedule(state);
}
}
}