feat: add bounded shared grpc subscriptions and delivery scheduling

This commit is contained in:
Joseph Doherty
2026-11-16 07:31:57 -05:00
parent 09f4f18d0e
commit af30a0266a
51 changed files with 9182 additions and 184 deletions
@@ -0,0 +1,56 @@
using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections;
namespace ZB.MOM.WW.OtOpcUa.Runtime.DataConnections;
/// <summary>Per-registration baseline. Only a successful delivery may call Commit.</summary>
internal sealed class ClientFilterState : IDisposable
{
private DataSample? _baseline;
internal bool ShouldDeliver(DataSample sample, DataSubscriptionSettings settings)
{
ArgumentNullException.ThrowIfNull(sample);
ArgumentNullException.ThrowIfNull(settings);
settings.Validate();
var baseline = _baseline;
if (baseline is null || sample.StatusCode != baseline.StatusCode || sample.Serving != baseline.Serving)
return true;
if (settings.Trigger == DataChangeTrigger.Status) return false;
if (settings.Trigger == DataChangeTrigger.StatusValueTimestamp &&
(sample.SourceTimestampUtc != baseline.SourceTimestampUtc || sample.ServerTimestampUtc != baseline.ServerTimestampUtc))
return true;
if (sample.Value.Kind != baseline.Value.Kind) return true;
if (settings.Deadband is { } deadband)
{
if (!Numeric(sample.Value, out var current) || !Numeric(baseline.Value, out var previous))
throw new ArgumentException("A numeric deadband requires numeric scalar values.", nameof(settings));
// Integer conversion to double can collapse distinct values above 2^53. Deliver
// conservatively rather than suppressing a real change in that range.
if (sample.Value.Kind is DataValueKind.Int64 or DataValueKind.UInt64 &&
(Math.Abs(current) > 9_007_199_254_740_992d || Math.Abs(previous) > 9_007_199_254_740_992d) &&
!Equals(sample.Value.GetScalar(), baseline.Value.GetScalar())) return true;
return !double.IsFinite(current) || !double.IsFinite(previous) || Math.Abs(current - previous) > deadband;
}
return !sample.Value.ContentEquals(baseline.Value);
}
internal void Commit(DataSample sample)
{
ArgumentNullException.ThrowIfNull(sample);
var retained = sample with { Value = sample.Value.Retain() };
var previous = _baseline;
_baseline = retained;
previous?.Dispose();
}
private static bool Numeric(DataValue value, out double number)
{
if (value.Kind is DataValueKind.Int8 or DataValueKind.Int16 or DataValueKind.Int32 or DataValueKind.Int64 or
DataValueKind.UInt8 or DataValueKind.UInt16 or DataValueKind.UInt32 or DataValueKind.UInt64 or
DataValueKind.Float or DataValueKind.Double)
{ number = Convert.ToDouble(value.GetScalar(), System.Globalization.CultureInfo.InvariantCulture); return true; }
number = 0; return false;
}
public void Dispose() { _baseline?.Dispose(); _baseline = null; }
}
@@ -26,7 +26,7 @@ public sealed class DataCapabilitiesProvider
var ready = IsReady;
serving.Validate(requireEpochs: ready);
if (!string.Equals(serving.Role, "Primary", StringComparison.OrdinalIgnoreCase)) operations &= ~DataOperations.Write;
return new(1, 0, serving, ready ? DataReadiness.Ready : DataReadiness.Unavailable,
return new(1, 1, serving, ready ? DataReadiness.Ready : DataReadiness.Unavailable,
ready ? operations : DataOperations.None,
Enum.GetValues<DataValueKind>().Where(x => x != DataValueKind.Unspecified).ToHashSet(),
limits, true, 1, ClusterId);
@@ -3,6 +3,8 @@ namespace ZB.MOM.WW.OtOpcUa.Runtime.DataConnections;
/// <summary>Node-wide admission limits for the source cache and retained work.</summary>
public sealed class DataResourceLimits
{
/// <summary>Maximum bounded partition fan-out for a hub and its producer fences.</summary>
public const int MaxPartitionCount = 256;
public int PartitionCount { get; init; } = 4;
public long MaxRetainedBytes { get; init; } = 64 * 1024 * 1024;
public int MaxTrackedSources { get; init; } = 100_000;
@@ -16,7 +18,7 @@ public sealed class DataResourceLimits
internal void Validate()
{
if (PartitionCount <= 0 || MaxRetainedBytes <= 0 || MaxTrackedSources <= 0 ||
if (PartitionCount <= 0 || PartitionCount > MaxPartitionCount || MaxRetainedBytes <= 0 || MaxTrackedSources <= 0 ||
MaxIngressItemsPerPartition <= 0 || MaxDirtySourcesPerPartition <= 0 ||
MaxControlItemsPerPartition <= 0 || MaxSnapshotItems <= 0 || MaxSnapshotBytes <= 0 ||
MaxSnapshotCatchUpItems <= 0 || MaxSnapshotLifetime <= TimeSpan.Zero)
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,105 @@
namespace ZB.MOM.WW.OtOpcUa.Runtime.DataConnections;
internal readonly record struct ScheduledInterest(BackingSourceKey Source, long InterestId, long Generation);
/// <summary>Bounded source-dirty index with resumable round-robin interest slices.</summary>
internal sealed class DeliveryScheduler
{
private readonly object _gate = new();
private readonly int _maxSources, _maxInterests;
private readonly Dictionary<BackingSourceKey, Bucket> _buckets = new();
private readonly LinkedList<BackingSourceKey> _ready = new();
private int _interests;
private sealed class Bucket
{
internal readonly LinkedList<Interest> Interests = new();
internal readonly Dictionary<long, LinkedListNode<Interest>> Index = new();
internal LinkedListNode<Interest>? Cursor;
internal LinkedListNode<BackingSourceKey>? ReadyNode;
internal long ActiveGeneration, PendingGeneration;
internal int Remaining;
}
private sealed class Interest(long id, long lastVisited) { internal long Id = id, LastVisited = lastVisited; }
internal DeliveryScheduler(int maxSources, int maxInterests)
{
if (maxSources <= 0 || maxInterests <= 0) throw new ArgumentOutOfRangeException(nameof(maxSources));
_maxSources = maxSources; _maxInterests = maxInterests;
}
internal bool TryRegister(BackingSourceKey source, long interestId)
{
ArgumentNullException.ThrowIfNull(source);
if (interestId <= 0) throw new ArgumentOutOfRangeException(nameof(interestId));
lock (_gate)
{
if (_interests >= _maxInterests) return false;
if (!_buckets.TryGetValue(source, out var b))
{
if (_buckets.Count >= _maxSources) return false;
_buckets.Add(source, b = new Bucket());
}
if (b.Index.ContainsKey(interestId)) return false;
b.Index.Add(interestId, b.Interests.AddLast(new Interest(interestId, b.ActiveGeneration)));
_interests++; return true;
}
}
internal bool Unregister(BackingSourceKey source, long interestId)
{
lock (_gate)
{
if (!_buckets.TryGetValue(source, out var b) || !b.Index.Remove(interestId, out var node)) return false;
if (b.Cursor == node) b.Cursor = node.Next ?? b.Interests.First;
if (b.Remaining > 0 && node.Value.LastVisited != b.ActiveGeneration) b.Remaining--;
b.Interests.Remove(node); _interests--;
if (b.Interests.Count == 0)
{
if (b.ReadyNode is not null) _ready.Remove(b.ReadyNode);
_buckets.Remove(source);
}
else if (b.Cursor == node) b.Cursor = b.Interests.First;
return true;
}
}
internal bool TryMarkDirty(BackingSourceKey source, long generation)
{
ArgumentNullException.ThrowIfNull(source);
if (generation <= 0) throw new ArgumentOutOfRangeException(nameof(generation));
lock (_gate)
{
if (!_buckets.TryGetValue(source, out var b)) return false;
if (generation > b.ActiveGeneration) b.PendingGeneration = Math.Max(generation, b.PendingGeneration);
Queue(source, b); return true;
}
}
internal IReadOnlyList<ScheduledInterest> TakeSlice(int maximum)
{
if (maximum <= 0) throw new ArgumentOutOfRangeException(nameof(maximum));
lock (_gate)
{
var result = new List<ScheduledInterest>(Math.Min(maximum, _interests));
while (result.Count < maximum && _ready.First is { } ready)
{
var source = ready.Value; _ready.RemoveFirst();
if (!_buckets.TryGetValue(source, out var b)) continue;
b.ReadyNode = null;
if (b.Remaining == 0 && b.PendingGeneration > b.ActiveGeneration)
{
b.ActiveGeneration = b.PendingGeneration; b.PendingGeneration = 0;
b.Cursor = b.Interests.First; b.Remaining = b.Interests.Count;
}
if (b.Remaining > 0 && b.Cursor is { } node)
{
node.Value.LastVisited = b.ActiveGeneration;
result.Add(new(source, node.Value.Id, b.ActiveGeneration));
b.Cursor = node.Next ?? b.Interests.First; b.Remaining--;
}
if (b.Remaining > 0 || b.PendingGeneration > b.ActiveGeneration) Queue(source, b);
}
return result;
}
}
private void Queue(BackingSourceKey source, Bucket bucket)
{
if (bucket.ReadyNode is null && (bucket.Remaining > 0 || bucket.PendingGeneration > bucket.ActiveGeneration))
bucket.ReadyNode = _ready.AddLast(source);
}
}
@@ -0,0 +1,430 @@
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);
}
}
}
@@ -15,16 +15,16 @@ public sealed class LocalDataConnection : IDataConnection, IDataConnectionPublic
public bool CanPublish(ServingIdentity expectedServing) => Volatile.Read(ref _disposed) == 0 && _services.CanPublish(_context, expectedServing);
private void Check() => ObjectDisposedException.ThrowIf(Volatile.Read(ref _disposed) != 0, this);
public Task<DataCapabilities> GetCapabilitiesAsync(DataBudget budget, CancellationToken cancellationToken)
{ Check(); return _services.GetCapabilitiesAsync(_context, budget, cancellationToken); }
{ Check(); return _services.GetCapabilitiesAsync(_context, Target, budget, cancellationToken); }
public Task<DataBrowseBranch> BrowseAsync(BrowseRequest request, CancellationToken cancellationToken)
{ Check(); return _services.BrowseAsync(_context, request, cancellationToken); }
{ Check(); return _services.BrowseAsync(_context, Target, request, cancellationToken); }
public Task<IReadOnlyList<DataItemResult<DataMetadata>>> GetMetadataAsync(MetadataRequest request, CancellationToken cancellationToken)
{ Check(); return _services.GetMetadataAsync(_context, request, cancellationToken); }
{ Check(); return _services.GetMetadataAsync(_context, Target, request, cancellationToken); }
public Task<IReadOnlyList<ReadResult>> ReadAsync(ReadRequest request, CancellationToken cancellationToken)
{ Check(); return _services.ReadAsync(_context, request, cancellationToken); }
public Task<IReadOnlyList<WriteItemResult>> WriteAsync(WriteBatch request, CancellationToken cancellationToken)
{ Check(); return _services.WriteAsync(_context, request, cancellationToken); }
public Task<IDataSubscription> SubscribeAsync(CancellationToken cancellationToken)
{ Check(); return _services.SubscribeAsync(_context, cancellationToken); }
{ Check(); return _services.SubscribeAsync(_context, Target, cancellationToken); }
public ValueTask DisposeAsync() { Interlocked.Exchange(ref _disposed, 1); return ValueTask.CompletedTask; }
}
@@ -17,6 +17,7 @@ public sealed class LocalDataServices : IDataConnectionFactory
private readonly DataCapabilitiesProvider _capabilities;
private readonly Func<DataAuthenticatedContext, IDataWriteService>? _writes;
private readonly Func<DataAuthenticatedContext, IDataSubscriptionService>? _subscriptions;
private readonly Func<DataAuthenticatedContext, DataTarget, IDataSubscriptionService>? _targetSubscriptions;
private readonly byte[] _continuationKey = RandomNumberGenerator.GetBytes(32);
private readonly ConditionalWeakTable<DataAuthenticatedContext, DataCallerIdentity> _callers = new();
private sealed record Continuation(DataView Parent, string? Filter, int Offset, string Principal,
@@ -25,7 +26,8 @@ public sealed class LocalDataServices : IDataConnectionFactory
public LocalDataServices(Func<LocalExportCatalog?> catalog, PartitionedSampleHub hub,
DataOperationPolicy policy, DataCapabilitiesProvider capabilities, TimeProvider clock,
Func<DataAuthenticatedContext, IDataWriteService>? writes = null,
Func<DataAuthenticatedContext, IDataSubscriptionService>? subscriptions = null)
Func<DataAuthenticatedContext, IDataSubscriptionService>? subscriptions = null,
Func<DataAuthenticatedContext, DataTarget, IDataSubscriptionService>? targetSubscriptions = null)
{
_catalog = catalog ?? throw new ArgumentNullException(nameof(catalog));
_hub = hub ?? throw new ArgumentNullException(nameof(hub));
@@ -35,12 +37,14 @@ public sealed class LocalDataServices : IDataConnectionFactory
if (!ReferenceEquals(hub.Clock, clock)) throw new ArgumentException("Hub and facade must use one clock.", nameof(clock));
_writes = writes;
_subscriptions = subscriptions;
_targetSubscriptions = targetSubscriptions;
}
public TimeProvider Clock { get; }
private DataOperations Implemented => DataOperations.Browse | DataOperations.Metadata | DataOperations.Read
private DataOperations Implemented(DataTarget target) => DataOperations.Browse | DataOperations.Metadata | DataOperations.Read
| (_writes is null ? DataOperations.None : DataOperations.Write)
| (_subscriptions is null ? DataOperations.None : DataOperations.Subscribe);
| (_targetSubscriptions is not null || _subscriptions is not null && target.Mode == DataTargetMode.Node
? DataOperations.Subscribe : DataOperations.None);
private DataCallerIdentity Caller(DataAuthenticatedContext context) => _callers.GetValue(context, static value =>
new(value.PrincipalId, value.ApiKeyId, value.CredentialVersion, value.CredentialExpiresUtc));
@@ -93,6 +97,62 @@ public sealed class LocalDataServices : IDataConnectionFactory
return allowed && Ready(catalog);
}
internal DataItemStatus AuthorizeSubscription(DataAuthenticatedContext context, DataTarget target, DataView view,
out SubscriptionAuthorizedView? authorized)
{
authorized = null;
view.Validate(); target.Validate();
var catalog = _catalog();
if (catalog is null || !Ready(catalog)) return DataItemStatus.Unavailable;
if (context.AuthorityEpoch != catalog.AuthorityEpoch) return DataItemStatus.Denied;
if (!string.Equals(target.ExpectedClusterId, catalog.ClusterId, StringComparison.OrdinalIgnoreCase) ||
target.Mode == DataTargetMode.Node && !string.Equals(target.ExpectedNodeId, catalog.Serving.NodeId, StringComparison.OrdinalIgnoreCase))
return DataItemStatus.Unavailable;
if (!_policy.IsCallerUsable(Caller(context))) return DataItemStatus.Denied;
if (!catalog.TryResolve(view, out var node)) return catalog.ContainsAddress(view) ? DataItemStatus.Denied : DataItemStatus.NotFound;
if (!Allowed(catalog, context, node, DataOperations.Subscribe)) return DataItemStatus.Denied;
var source = node.Source;
if (!node.Supported || source is null) return DataItemStatus.Unsupported;
if (!node.SourceEnabled) return DataItemStatus.Unavailable;
var serving = catalog.Serving;
var consistency = string.Equals(serving.Role, "Primary", StringComparison.OrdinalIgnoreCase)
? DataConsistency.Primary : DataConsistency.ReadyReplica;
authorized = new(node.Metadata.View, source, serving, node.Metadata, context.PrincipalId,
catalog.SubscriptionExportScope(context.PrincipalId, node), target, consistency, () =>
{
var current = _catalog();
return current is not null && current.Serving == serving && current.TryResolve(view, out var now) &&
now.Source == source && Allowed(current, context, now, DataOperations.Subscribe);
});
return DataItemStatus.Good;
}
internal PartitionedSampleHub SubscriptionHub => _hub;
internal DataLimits SubscriptionLimits => _capabilities.Limits;
internal int SubscriptionItemLimit(DataAuthenticatedContext context)
{
var catalog = _catalog();
return catalog is null ? 0 : Limits(catalog, context).MaxMonitoredItems;
}
internal int SubscriptionStreamLimit(DataAuthenticatedContext context)
{
var catalog = _catalog();
return catalog is null ? 0 : Limits(catalog, context).MaxStreams;
}
internal bool CanUseSubscription(DataAuthenticatedContext context, DataTarget target, ServingIdentity? expected = null)
{
var catalog = _catalog();
return catalog is not null && Ready(catalog) && context.AuthorityEpoch == catalog.AuthorityEpoch &&
(expected is null || catalog.Serving == expected) && _policy.IsCallerUsable(Caller(context)) &&
string.Equals(target.ExpectedClusterId, catalog.ClusterId, StringComparison.OrdinalIgnoreCase) &&
(target.Mode != DataTargetMode.Node || string.Equals(target.ExpectedNodeId, catalog.Serving.NodeId, StringComparison.OrdinalIgnoreCase));
}
internal ServingIdentity? SubscriptionServing(DataAuthenticatedContext context, DataTarget target)
{
var catalog = _catalog();
return catalog is not null && CanUseSubscription(context, target, catalog.Serving) ? catalog.Serving : null;
}
private DataLimits Limits(LocalExportCatalog catalog, DataAuthenticatedContext context) =>
catalog.LimitsFor(context.PrincipalId, _capabilities.Limits);
private void CheckBudget(DataBudget budget, int count, int limit, CancellationToken cancellationToken)
@@ -103,31 +163,31 @@ public sealed class LocalDataServices : IDataConnectionFactory
throw new ArgumentOutOfRangeException(nameof(count), "Request exceeds the admitted item/byte budget.");
}
private bool Expired(long start, DataBudget budget) => Clock.GetElapsedTime(start) >= budget.Timeout;
private DataMetadata Metadata(LocalExportCatalog catalog, DataAuthenticatedContext context, LocalDataNode node)
private DataMetadata Metadata(LocalExportCatalog catalog, DataAuthenticatedContext context, DataTarget target, LocalDataNode node)
{
var operations = DataOperations.None;
foreach (var operation in new[] { DataOperations.Browse, DataOperations.Metadata, DataOperations.Read, DataOperations.Write, DataOperations.Subscribe })
if ((node.Supported || operation == DataOperations.Browse)
&& (node.SourceEnabled || operation is DataOperations.Browse or DataOperations.Metadata)
&& (Implemented & operation) != 0 && (node.Metadata.AllowedOperations & operation) != 0
&& (Implemented(target) & operation) != 0 && (node.Metadata.AllowedOperations & operation) != 0
&& (operation != DataOperations.Write || node.Metadata.Writable
&& string.Equals(_capabilities.Serving.Role, "Primary", StringComparison.OrdinalIgnoreCase))
&& Allowed(catalog, context, node, operation)) operations |= operation;
return node.Metadata with { AllowedOperations = operations, Writable = node.Metadata.Writable && operations.HasFlag(DataOperations.Write) };
}
internal Task<DataCapabilities> GetCapabilitiesAsync(DataAuthenticatedContext context, DataBudget budget, CancellationToken cancellationToken)
internal Task<DataCapabilities> GetCapabilitiesAsync(DataAuthenticatedContext context, DataTarget target, DataBudget budget, CancellationToken cancellationToken)
{
CheckBudget(budget, 0, 0, cancellationToken);
var catalog = _catalog();
if (!_policy.IsCallerUsable(Caller(context))) throw new UnauthorizedAccessException();
var capabilities = _capabilities.Get(catalog is null ? DataOperations.None : catalog.ExportOperations(context.PrincipalId) & Implemented,
var capabilities = _capabilities.Get(catalog is null ? DataOperations.None : catalog.ExportOperations(context.PrincipalId) & Implemented(target),
catalog is null ? _capabilities.Limits : Limits(catalog, context));
if (catalog is null || !Ready(catalog)) capabilities = capabilities with { Readiness = DataReadiness.Unavailable, Operations = DataOperations.None };
return Task.FromResult(capabilities);
}
internal Task<IReadOnlyList<DataItemResult<DataMetadata>>> GetMetadataAsync(DataAuthenticatedContext context, MetadataRequest request, CancellationToken cancellationToken)
internal Task<IReadOnlyList<DataItemResult<DataMetadata>>> GetMetadataAsync(DataAuthenticatedContext context, DataTarget target, MetadataRequest request, CancellationToken cancellationToken)
{
ArgumentNullException.ThrowIfNull(request); ArgumentNullException.ThrowIfNull(request.Views);
var catalog = _catalog();
@@ -152,7 +212,7 @@ public sealed class LocalDataServices : IDataConnectionFactory
else if (!node.Supported) status = DataItemStatus.Unsupported;
else
{
metadata = Metadata(catalog, context, node);
metadata = Metadata(catalog, context, target, node);
bytes = checked(bytes + MetadataBytes(metadata));
if (bytes > Math.Min(request.Budget.MaxBytes, _capabilities.Limits.MaxMessageBytes))
{ status = DataItemStatus.LimitExceeded; metadata = null; }
@@ -207,7 +267,7 @@ public sealed class LocalDataServices : IDataConnectionFactory
{ read.Dispose(); results.Add(Empty(DataItemStatus.LimitExceeded)); continue; }
var age = Clock.GetElapsedTime(read.ReceivedTimestamp);
if (age < TimeSpan.Zero) { read.Dispose(); results.Add(Empty(DataItemStatus.Unavailable)); continue; }
// Catalog/authority headers describe current serving. Acquisition age, value version
// Catalog/authority headers describe current serving. Cache ingress age, value version
// and original timestamps remain unchanged, including provisional boot acquisitions.
var exposed = sample with { Value = sample.Value.Retain(), Serving = catalog.Serving };
exposed.Validate();
@@ -217,7 +277,7 @@ public sealed class LocalDataServices : IDataConnectionFactory
var publication = new PublicationReadLease(read, () => CanPublish(context, exposed.Serving)
&& !Expired(start, request.Budget));
results.Add(new(item.CorrelationId, item.MaximumAge is { } max && age > max ? DataItemStatus.Stale : DataItemStatus.Good,
DataReadiness.Ready, age, exposed, null, publication));
DataReadiness.Ready, age, exposed, null, publication, new DataAgeBounds(age, age)));
}
if (!Ready(catalog) || !_policy.IsCallerUsable(Caller(context)))
for (var i = 0; i < results.Count; i++)
@@ -228,7 +288,7 @@ public sealed class LocalDataServices : IDataConnectionFactory
catch { foreach (var result in results) result.Dispose(); throw; }
}
internal Task<DataBrowseBranch> BrowseAsync(DataAuthenticatedContext context, BrowseRequest request, CancellationToken cancellationToken)
internal Task<DataBrowseBranch> BrowseAsync(DataAuthenticatedContext context, DataTarget target, BrowseRequest request, CancellationToken cancellationToken)
{
ArgumentNullException.ThrowIfNull(request); request.Parent.Validate();
var catalog = _catalog();
@@ -263,7 +323,7 @@ public sealed class LocalDataServices : IDataConnectionFactory
var child = children[offset++];
if ((request.Filter is { Length: > 0 } filter && !child.Metadata.BrowseName.Contains(filter, StringComparison.Ordinal))
|| !Allowed(catalog, context, child, DataOperations.Browse)) continue;
var metadata = Metadata(catalog, context, child);
var metadata = Metadata(catalog, context, target, child);
var size = MetadataBytes(metadata);
if (bytes + size > Math.Min(request.Budget.MaxBytes, limits.MaxMessageBytes))
{
@@ -307,13 +367,14 @@ public sealed class LocalDataServices : IDataConnectionFactory
return results;
}
internal Task<IDataSubscription> SubscribeAsync(DataAuthenticatedContext context, CancellationToken cancellationToken)
internal Task<IDataSubscription> SubscribeAsync(DataAuthenticatedContext context, DataTarget target, CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();
var catalog = _catalog();
if (_subscriptions is null || catalog is null || !Ready(catalog) || !_policy.IsCallerUsable(Caller(context)))
if ((_targetSubscriptions is null && (_subscriptions is null || target.Mode != DataTargetMode.Node)) ||
catalog is null || !Ready(catalog) || !_policy.IsCallerUsable(Caller(context)))
throw new InvalidOperationException("Subscriptions are unavailable.");
return _subscriptions(context).SubscribeAsync(cancellationToken);
return (_targetSubscriptions?.Invoke(context, target) ?? _subscriptions!(context)).SubscribeAsync(cancellationToken);
}
private static bool ValueMatches(DataMetadata metadata, DataValue value) => value.Kind == DataValueKind.Null || metadata.ValueKind == value.Kind
@@ -17,7 +17,7 @@ public sealed partial class LocalExportCatalog
private readonly Dictionary<DataView, LocalDataNode[]> _children;
private readonly ExportRule[] _exports;
private readonly IDataMappedCatalogAuthority _activation;
private sealed record ExportRule(string Principal, DataRealm Realm, DataView? Root, bool WholeRealm,
private sealed record ExportRule(string Identity, string Principal, DataRealm Realm, DataView? Root, bool WholeRealm,
DataOperations Operations, int Batch, int Page, int Items, int Streams);
public LocalExportCatalog(string clusterId, ServingIdentity serving, IDataMappedCatalogAuthority activation,
@@ -88,7 +88,7 @@ public sealed partial class LocalExportCatalog
|| export.AllowedOperations == DataOperations.None || export.MaxBatchItems <= 0 || export.MaxPageItems <= 0
|| export.MaxMonitoredItems <= 0 || export.MaxStreams <= 0)
throw new ArgumentException("Export has no valid origin root or policy.", nameof(exports));
rules.Add(new(export.PrincipalId, export.Realm, wholeRealm ? null : roots[0].Metadata.View, wholeRealm,
rules.Add(new(export.DataExportId, export.PrincipalId, export.Realm, wholeRealm ? null : roots[0].Metadata.View, wholeRealm,
export.AllowedOperations, export.MaxBatchItems, export.MaxPageItems, export.MaxMonitoredItems, export.MaxStreams));
}
_exports = rules.ToArray();
@@ -147,6 +147,18 @@ public sealed partial class LocalExportCatalog
return false;
}
internal string SubscriptionExportScope(string principal, LocalDataNode node)
{
var ids = _exports.Where(rule => string.Equals(principal, rule.Principal, StringComparison.OrdinalIgnoreCase) &&
rule.Realm == node.Metadata.View.Realm && (rule.Operations & DataOperations.Subscribe) != 0 &&
(rule.WholeRealm || IsAncestor(rule.Root!, node.Metadata.View)))
.Select(rule => rule.Identity).Order(StringComparer.Ordinal).ToArray();
// Invalid/missing export identities must not accidentally share across views.
if (ids.Length == 0 || ids.Any(string.IsNullOrWhiteSpace))
return $"view:{node.Metadata.View.Realm}:{node.Metadata.View.Address.NamespaceUri.Length}:{node.Metadata.View.Address.NamespaceUri}:{node.Metadata.View.Address.IdentifierKind.Length}:{node.Metadata.View.Address.IdentifierKind}:{node.Metadata.View.Address.Identifier.Length}:{node.Metadata.View.Address.Identifier}";
return string.Concat(ids.Select(id => $"{id.Length}:{id}"));
}
private bool IsAncestor(DataView ancestor, DataView candidate)
{
var current = candidate;
@@ -0,0 +1,62 @@
using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections;
namespace ZB.MOM.WW.OtOpcUa.Runtime.DataConnections;
/// <summary>An independently authorized view and its current publication fence.</summary>
internal sealed record SubscriptionAuthorizedView(DataView View, BackingSourceKey Source, ServingIdentity Serving,
DataMetadata Metadata, string PrincipalId, string ExportScope, DataTarget Target, DataConsistency Consistency,
Func<bool> CanPublish);
/// <summary>Physical upstream establishment, independently of the downstream stream.</summary>
internal interface ISubscriptionDemandSource
{
ValueTask<SubscriptionDemandResult> AcquireAsync(SubscriptionAuthorizedView view,
DataSubscriptionSettings settings, CancellationToken cancellationToken);
}
internal sealed record SubscriptionDemandResult(DataItemStatus Status, DataSubscriptionSettings? RevisedSettings,
long Boundary, IDisposable? Lease);
internal sealed record SubscriptionSessionLimits(int MaxCommands, int MaxPendingFrames, long MaxPendingBytes,
TimeSpan MaxSessionLifetime, TimeSpan? PreOpenTimeout = null)
{
internal void Validate()
{
if (MaxCommands <= 0 || MaxPendingFrames <= 0 || MaxPendingBytes <= 0 || MaxSessionLifetime <= TimeSpan.Zero ||
PreOpenTimeout is { } timeout && (timeout <= TimeSpan.Zero || timeout > TimeSpan.FromMilliseconds(uint.MaxValue - 1)))
throw new ArgumentOutOfRangeException(nameof(MaxCommands));
}
}
/// <summary>Caller-bound subscription service; authorization is resolved through the same local facade.</summary>
internal sealed class LocalSubscriptionService : IDataSubscriptionService
{
private readonly LocalDataServices _services;
private readonly DataAuthenticatedContext _context;
private readonly DataTarget _target;
private readonly ISubscriptionDemandSource _demand;
private readonly SubscriptionSessionLimits _limits;
private readonly SubscriptionTransportCapacity _capacity;
internal LocalSubscriptionService(LocalDataServices services, DataAuthenticatedContext context, DataTarget target,
ISubscriptionDemandSource demand, SubscriptionSessionLimits limits, SubscriptionTransportCapacity capacity)
{
_services = services; _context = context; _target = target; _demand = demand; _limits = limits; _capacity = capacity;
ArgumentNullException.ThrowIfNull(services); ArgumentNullException.ThrowIfNull(context); ArgumentNullException.ThrowIfNull(target);
ArgumentNullException.ThrowIfNull(demand); ArgumentNullException.ThrowIfNull(limits); ArgumentNullException.ThrowIfNull(capacity);
context.Validate(); target.Validate(); limits.Validate();
}
public Task<IDataSubscription> SubscribeAsync(CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();
if (!_services.CanUseSubscription(_context, _target)) throw new InvalidOperationException("Subscription authority is unavailable.");
var fixedBytes = checked(4096L + 128L * _limits.MaxCommands + 256L * _limits.MaxPendingFrames);
var streamLimit = _services.SubscriptionStreamLimit(_context);
if (streamLimit <= 0 || !_capacity.TryOpenSession(_context.PrincipalId, fixedBytes, streamLimit, out var reservation))
throw new InvalidOperationException("Subscription stream capacity exhausted.");
try
{
return Task.FromResult<IDataSubscription>(new DataSubscriptionSession(_services, _context, _target,
_demand, _limits, _capacity, reservation!, cancellationToken));
}
catch { reservation!.Dispose(); throw; }
}
}
@@ -0,0 +1,45 @@
namespace ZB.MOM.WW.OtOpcUa.Runtime.DataConnections;
// Active controls bracket each generation change. Overflow poisons the signal
// permanently, rather than allowing a wrapped generation to match a snapshot.
internal sealed class PartitionControlSignal
{
private long _generation;
private long _active;
private int _poisoned;
// Only the outer signal owns this additional lifecycle counter; its child is a leaf.
internal PartitionControlSignal Quiet { get; } = null!;
internal PartitionControlSignal() : this(true) { }
private PartitionControlSignal(bool includeQuiet)
{
if (includeQuiet) Quiet = new PartitionControlSignal(false);
}
internal void BeginQuiet() { Begin(); Quiet.Begin(); }
internal void EndQuiet() { Quiet.End(); End(); }
internal void Begin()
{
if (Volatile.Read(ref _poisoned) != 0) return;
if (Interlocked.Increment(ref _active) <= 0) { Interlocked.Exchange(ref _poisoned, 1); return; }
if (Interlocked.Increment(ref _generation) < 0) Interlocked.Exchange(ref _poisoned, 1);
}
internal void End()
{
if (Volatile.Read(ref _poisoned) != 0) return;
if (Interlocked.Increment(ref _generation) < 0) { Interlocked.Exchange(ref _poisoned, 1); return; }
if (Interlocked.Decrement(ref _active) < 0) Interlocked.Exchange(ref _poisoned, 1);
}
internal bool TryCapture(out long stamp)
{
stamp = -1;
if (Volatile.Read(ref _poisoned) != 0 || Volatile.Read(ref _active) != 0) return false;
var generation = Volatile.Read(ref _generation);
if (generation < 0 || Volatile.Read(ref _active) != 0 || Volatile.Read(ref _poisoned) != 0) return false;
stamp = generation;
return true;
}
internal bool Matches(long stamp) => stamp >= 0 && Volatile.Read(ref _poisoned) == 0 &&
Volatile.Read(ref _active) == 0 && Volatile.Read(ref _generation) == stamp &&
Volatile.Read(ref _active) == 0 && Volatile.Read(ref _poisoned) == 0;
}
@@ -9,9 +9,23 @@ public sealed record BackingSourceKey(string OriginClusterId, string SourceKind,
public readonly record struct SourceGeneration(long Incarnation, long Lifecycle);
internal sealed class SourceBindingFence
{
private int _retired;
internal bool IsRetired => Volatile.Read(ref _retired) != 0;
internal void Retire() => Interlocked.Exchange(ref _retired, 1);
private int _state;
private PartitionControlSignal? _signal;
internal bool IsRetired => Volatile.Read(ref _state) == 2;
internal bool TryAttach(PartitionControlSignal signal)
{
if (Volatile.Read(ref _state) != 0) return false;
var old = Interlocked.CompareExchange(ref _signal, signal, null);
return (old is null || ReferenceEquals(old, signal)) && Volatile.Read(ref _state) == 0;
}
internal void Retire()
{
if (Interlocked.CompareExchange(ref _state, 1, 0) == 2 || Volatile.Read(ref _state) == 2) return;
var signal = Volatile.Read(ref _signal);
signal?.BeginQuiet();
Interlocked.Exchange(ref _state, 2);
signal?.EndQuiet();
}
}
/// <summary>An individual binding; two bindings of the same key and generation remain distinct.</summary>
public readonly record struct SourceTicket(BackingSourceKey Key, SourceGeneration Generation)
@@ -22,15 +36,45 @@ public readonly record struct SourceTicket(BackingSourceKey Key, SourceGeneratio
/// <summary>Shared producer lifetime; retirement immediately fences every source bound to this token.</summary>
public sealed class ProducerFence
{
private int _retired;
private sealed record Attachments(PartitionedSampleHub Owner, long Epoch, PartitionControlSignal[] Signals);
private int _state;
private Attachments? _attachments;
public ProducerFence(long incarnation)
{
if (incarnation <= 0) throw new ArgumentOutOfRangeException(nameof(incarnation));
Incarnation = incarnation;
}
public long Incarnation { get; }
public bool IsRetired => Volatile.Read(ref _retired) != 0;
public void Retire() => Interlocked.Exchange(ref _retired, 1);
public bool IsRetired => Volatile.Read(ref _state) == 2;
internal Action? BeforeRetirementPublicationForTests { get; set; }
internal Action? AfterSignalBegunForTests { get; set; }
internal int AttachedSignalCountForTests => Volatile.Read(ref _attachments)?.Signals.Length ?? 0;
internal bool TryAttach(PartitionedSampleHub owner, long epoch, PartitionControlSignal signal)
{
// Bounded retries keep producer admission from spinning indefinitely under churn.
for (var attempt = 0; attempt < 32; attempt++)
{
if (Volatile.Read(ref _state) != 0) return false;
var old = Volatile.Read(ref _attachments);
if (old is not null && (!ReferenceEquals(old.Owner, owner) || epoch < old.Epoch)) return false;
if (old is not null && old.Epoch == epoch && Array.IndexOf(old.Signals, signal) >= 0)
return Volatile.Read(ref _state) == 0;
PartitionControlSignal[] signals = old is null || old.Epoch != epoch ? [signal] : old.Signals.Append(signal).ToArray();
var next = new Attachments(owner, epoch, signals);
if (Interlocked.CompareExchange(ref _attachments, next, old) == old)
return Volatile.Read(ref _state) == 0;
}
return false;
}
public void Retire()
{
if (Interlocked.CompareExchange(ref _state, 1, 0) == 2 || Volatile.Read(ref _state) == 2) return;
var signals = Volatile.Read(ref _attachments)?.Signals;
if (signals is not null) foreach (var signal in signals) { signal.BeginQuiet(); AfterSignalBegunForTests?.Invoke(); }
BeforeRetirementPublicationForTests?.Invoke();
Interlocked.Exchange(ref _state, 2);
if (signals is not null) foreach (var signal in signals) signal.EndQuiet();
}
}
public interface IIngressReservation : IDisposable
@@ -102,9 +146,16 @@ public sealed class PartitionedSampleHub : ISourceSampleHub, IDisposable
private readonly bool _autoDrain;
private readonly object _routingLock = new();
private readonly ConcurrentDictionary<SnapshotLease, byte> _snapshots = new();
private readonly ConcurrentDictionary<SourceInterestLease, byte> _interests = new();
private SamplePartition[] _partitions;
private int _trackedSources;
private int _snapshotItems;
private int _interestItems;
private long _snapshotValidationWork;
internal Action<SourceTicket>? BeforeReadForTests { get; set; }
internal Action? BeforeSnapshotValidationForTests { get; set; }
internal long SnapshotValidationWorkForTests => Interlocked.Read(ref _snapshotValidationWork);
internal void CountSnapshotValidationForTests() => Interlocked.Increment(ref _snapshotValidationWork);
private long _routingEpoch = 1;
private int _disposed;
@@ -135,6 +186,17 @@ public sealed class PartitionedSampleHub : ISourceSampleHub, IDisposable
internal bool TryTrackSnapshotItems(int count) { while (true) { var current = Volatile.Read(ref _snapshotItems); if (count > _limits.MaxSnapshotItems - current) return false; if (Interlocked.CompareExchange(ref _snapshotItems, current + count, current) == current) return true; } }
internal void UntrackSnapshotItems(int count) => Interlocked.Add(ref _snapshotItems, -count);
internal void ForgetSnapshot(SnapshotLease snapshot) => _snapshots.TryRemove(snapshot, out _);
internal void ForgetInterest(SourceInterestLease interest) => _interests.TryRemove(interest, out _);
internal void UntrackInterestItems(int count) => Interlocked.Add(ref _interestItems, -count);
private bool TryTrackInterestItems(int count)
{
while (true)
{
var current = Volatile.Read(ref _interestItems);
if (count > _limits.MaxSnapshotItems - current) return false;
if (Interlocked.CompareExchange(ref _interestItems, current + count, current) == current) return true;
}
}
internal void Schedule(SamplePartition partition) { if (_autoDrain) partition.Schedule(); }
private static bool ValidKey(BackingSourceKey? key) => key is not null &&
@@ -155,30 +217,37 @@ public sealed class PartitionedSampleHub : ISourceSampleHub, IDisposable
public bool TryPublishStatus(SourceTicket ticket, long sequence, uint statusCode, DateTimeOffset? sourceTimestampUtc, DateTimeOffset? serverTimestampUtc) =>
!IsDisposed && ValidKey(ticket.Key) && Partition(ticket.Key).TryStatus(ticket, sequence, statusCode, sourceTimestampUtc, serverTimestampUtc);
public bool TryRemove(SourceTicket ticket, long sequence) => !IsDisposed && ValidKey(ticket.Key) && Partition(ticket.Key).TryRemove(ticket, sequence);
public CachedSourceRead Read(SourceTicket ticket) => IsDisposed || !ValidKey(ticket.Key) ? EmptyRead(DataItemStatus.Unavailable, DataReadiness.Unavailable, 0) : Partition(ticket.Key).Read(ticket);
public CachedSourceRead Read(SourceTicket ticket)
{
BeforeReadForTests?.Invoke(ticket);
return IsDisposed || !ValidKey(ticket.Key) ? EmptyRead(DataItemStatus.Unavailable, DataReadiness.Unavailable, 0) : Partition(ticket.Key).Read(ticket);
}
internal CachedSourceRead EmptyRead(DataItemStatus status, DataReadiness readiness, long epoch) => new(Resources, status, readiness, null, 0, epoch, 0, 0);
internal void ProcessPending() { foreach (var partition in Volatile.Read(ref _partitions)) partition.Drain(); }
internal void WithPartitionLockForTest(BackingSourceKey key, Action action) => Partition(key).WithLockForTest(action);
internal PartitionControlSignal ControlSignalForTests(BackingSourceKey key) => Partition(key).Control;
public bool TryCaptureSnapshot(IReadOnlyList<SourceTicket> tickets, DataBudget budget, CancellationToken cancellationToken, out SnapshotLease? snapshot)
{
snapshot = null; ArgumentNullException.ThrowIfNull(tickets); ArgumentNullException.ThrowIfNull(budget); budget.Validate();
if (IsDisposed || cancellationToken.IsCancellationRequested || tickets.Count == 0 || tickets.Count > budget.MaxItems ||
tickets.Count > _limits.MaxSnapshotItems || tickets.Any(t => !ValidKey(t.Key)) || tickets.Distinct().Count() != tickets.Count || !TryTrackSnapshotItems(tickets.Count)) return false;
var routing = RoutingEpoch; var items = new Dictionary<SourceTicket, SnapshotItem>(); var watermarks = new Dictionary<int, long>(); var epochs = new Dictionary<int, long>();
var routing = RoutingEpoch; var items = new Dictionary<SourceTicket, SnapshotItem>(); var watermarks = new Dictionary<int, long>(); var epochs = new Dictionary<int, long>(); var controls = new Dictionary<int, long>();
long charge = 0;
try
{
var partitions = Volatile.Read(ref _partitions);
foreach (var group in tickets.GroupBy(t => GetPartitionFor(t.Key, partitions.Length)))
{
if (cancellationToken.IsCancellationRequested || routing != RoutingEpoch ||
if (cancellationToken.IsCancellationRequested || routing != RoutingEpoch || partitions[group.Key].RoutingEpoch != routing || !partitions[group.Key].Control.TryCapture(out var control) ||
!partitions[group.Key].Capture(group, items, out var watermark, out var epoch, ref charge, Math.Min(budget.MaxBytes, _limits.MaxSnapshotBytes))) return false;
if (!partitions[group.Key].Control.Matches(control)) return false;
watermarks.Add(group.Key, watermark);
epochs.Add(group.Key, epoch);
controls.Add(group.Key, control);
}
if (cancellationToken.IsCancellationRequested || routing != RoutingEpoch) return false;
snapshot = new SnapshotLease(this, items, watermarks, epochs, partitions, routing, charge, tickets.Count,
snapshot = new SnapshotLease(this, items, watermarks, epochs, controls, partitions, routing, charge, tickets.Count,
budget.Timeout < _limits.MaxSnapshotLifetime ? budget.Timeout : _limits.MaxSnapshotLifetime, cancellationToken);
charge = 0; items = null!;
_snapshots.TryAdd(snapshot, 0);
@@ -191,14 +260,79 @@ public sealed class PartitionedSampleHub : ISourceSampleHub, IDisposable
}
}
/// <summary>Atomically retains interests and captures a watermark within each source partition.</summary>
public bool TryCaptureInterestSnapshot(IReadOnlyList<SourceTicket> tickets, DataBudget budget,
CancellationToken cancellationToken, out SnapshotLease? snapshot, out SourceInterestLease? interest)
=> TryCaptureInterestSnapshotCore(tickets, budget, cancellationToken, out snapshot, out interest, null);
internal bool TryCaptureInterestSnapshot(IReadOnlyList<SourceTicket> tickets, DataBudget budget,
CancellationToken cancellationToken, out SnapshotLease? snapshot, out SourceInterestLease? interest,
SnapshotAdmissionScheduler.Permit admission)
=> TryCaptureInterestSnapshotCore(tickets, budget, cancellationToken, out snapshot, out interest, admission);
private bool TryCaptureInterestSnapshotCore(IReadOnlyList<SourceTicket> tickets, DataBudget budget,
CancellationToken cancellationToken, out SnapshotLease? snapshot, out SourceInterestLease? interest,
SnapshotAdmissionScheduler.Permit? admission)
{
snapshot = null; interest = null;
ArgumentNullException.ThrowIfNull(tickets); ArgumentNullException.ThrowIfNull(budget); budget.Validate();
if (IsDisposed || cancellationToken.IsCancellationRequested || tickets.Count == 0 || tickets.Count > budget.MaxItems ||
tickets.Count > _limits.MaxSnapshotItems || tickets.Any(t => !ValidKey(t.Key)) ||
tickets.Select(t => t.Key).Distinct().Count() != tickets.Count || !TryTrackSnapshotItems(tickets.Count)) return false;
if (!TryTrackInterestItems(tickets.Count)) { UntrackSnapshotItems(tickets.Count); return false; }
var routing = RoutingEpoch;
var items = new Dictionary<SourceTicket, SnapshotItem>();
var watermarks = new Dictionary<int, long>();
var epochs = new Dictionary<int, long>();
var controls = new Dictionary<int, long>();
var quietControls = new Dictionary<int, long>();
var owners = new Dictionary<SourceTicket, (SamplePartition Partition, object Source)>();
long snapshotCharge = 0, interestCharge = 0;
try
{
var partitions = Volatile.Read(ref _partitions);
foreach (var group in tickets.GroupBy(t => GetPartitionFor(t.Key, partitions.Length)))
{
var captured = new Dictionary<SourceTicket, object>();
long watermark = 0, epoch = 0, control = 0, quietControl = 0;
var ok = !cancellationToken.IsCancellationRequested && routing == RoutingEpoch && partitions[group.Key].RoutingEpoch == routing && partitions[group.Key].Control.TryCapture(out control) &&
partitions[group.Key].Control.Quiet.TryCapture(out quietControl) &&
partitions[group.Key].CaptureAndRegister(group.ToArray(), items, captured, out watermark,
out epoch, ref snapshotCharge, ref interestCharge, Math.Min(budget.MaxBytes, _limits.MaxSnapshotBytes), admission);
foreach (var pair in captured) owners.Add(pair.Key, (partitions[group.Key], pair.Value));
if (!ok || !partitions[group.Key].Control.Matches(control) || !partitions[group.Key].Control.Quiet.Matches(quietControl)) return false;
watermarks.Add(group.Key, watermark); epochs.Add(group.Key, epoch);
controls.Add(group.Key, control);
quietControls.Add(group.Key, quietControl);
}
if (cancellationToken.IsCancellationRequested || routing != RoutingEpoch) return false;
snapshot = new SnapshotLease(this, items, watermarks, epochs, controls, partitions, routing, snapshotCharge, tickets.Count,
budget.Timeout < _limits.MaxSnapshotLifetime ? budget.Timeout : _limits.MaxSnapshotLifetime, cancellationToken);
snapshotCharge = 0; items = null!; _snapshots.TryAdd(snapshot, 0);
interest = new SourceInterestLease(this, owners, watermarks, epochs, quietControls, routing, interestCharge, cancellationToken);
interestCharge = 0; owners = null!; _interests.TryAdd(interest, 0);
if (!snapshot.IsReset && !interest.IsReset) return true;
snapshot.Dispose(); ForgetSnapshot(snapshot); interest.Dispose(); snapshot = null; interest = null; return false;
}
finally
{
if (items is not null)
{ foreach (var item in items.Values) { item.Sample?.Dispose(); item.ReleaseSource(); } Resources.Release(snapshotCharge); UntrackSnapshotItems(tickets.Count); }
if (owners is not null)
{ foreach (var owner in owners.Values) owner.Partition.ReleaseInterest(owner.Source); Resources.Release(interestCharge); UntrackInterestItems(tickets.Count); }
}
}
public void Repartition(int count)
{
if (count <= 0) throw new ArgumentOutOfRangeException(nameof(count));
if (count <= 0 || count > DataResourceLimits.MaxPartitionCount) throw new ArgumentOutOfRangeException(nameof(count));
lock (_routingLock)
{
if (IsDisposed) throw new ObjectDisposedException(nameof(PartitionedSampleHub));
if (RoutingEpoch == long.MaxValue) throw new InvalidOperationException("The routing epoch is exhausted.");
Interlocked.Increment(ref _routingEpoch);
var old = Volatile.Read(ref _partitions);
foreach (var interest in _interests.Keys) interest.Dispose();
foreach (var snapshot in _snapshots.Keys) snapshot.Dispose();
foreach (var partition in old) partition.Dispose();
// Retire all old binding tokens before exposing new owners; otherwise an old
@@ -211,7 +345,8 @@ public sealed class PartitionedSampleHub : ISourceSampleHub, IDisposable
lock (_routingLock)
{
if (Interlocked.Exchange(ref _disposed, 1) != 0) return;
Interlocked.Increment(ref _routingEpoch);
if (RoutingEpoch != long.MaxValue) Interlocked.Increment(ref _routingEpoch);
foreach (var interest in _interests.Keys) interest.Dispose();
foreach (var snapshot in _snapshots.Keys) snapshot.Dispose();
foreach (var partition in _partitions) partition.Dispose();
}
@@ -8,13 +8,14 @@ internal sealed class SamplePartition : IDisposable
{
private const long SourceOverhead = 768;
private const long ControlOverhead = 256;
private const long ChangeOverhead = 192;
private const long ChangeOverhead = 256;
private readonly PartitionedSampleHub _hub;
private readonly object _gate = new();
private readonly ConcurrentDictionary<BackingSourceKey, SourceState> _sources = new();
private readonly Queue<Pending> _queue = new();
private readonly Dictionary<BackingSourceKey, Pending> _dirty = new();
private readonly Queue<(long Version, BackingSourceKey Key)> _changes = new();
private readonly LinkedList<(long Version, BackingSourceKey Key)> _changes = new();
private readonly Dictionary<long, LinkedListNode<(long Version, BackingSourceKey Key)>> _changeIndex = new();
private long _epoch = 1;
private long _cleanedEpoch = 1;
private long _watermark;
@@ -28,8 +29,10 @@ internal sealed class SamplePartition : IDisposable
private bool _disposed;
private readonly long _routingEpoch;
internal readonly PartitionControlSignal Control = new();
internal SamplePartition(PartitionedSampleHub hub, int id) { _hub = hub; Id = id; _routingEpoch = hub.RoutingEpoch; }
internal int Id { get; }
internal long RoutingEpoch => _routingEpoch;
internal long Epoch { get { lock (_gate) return _epoch; } }
private static bool Valid(SourceTicket ticket)
@@ -57,7 +60,8 @@ internal sealed class SamplePartition : IDisposable
}
try
{
if (_disposed || ticket.Binding.IsRetired) return false;
if (_disposed || _hub.RoutingEpoch != _routingEpoch || ticket.Binding.IsRetired ||
!ticket.Binding.TryAttach(Control) || (fence is not null && !fence.TryAttach(_hub, _routingEpoch, Control))) return false;
if (_sources.TryGetValue(ticket.Key, out var state))
{
var order = Compare(ticket.Generation, state.Generation);
@@ -101,11 +105,13 @@ internal sealed class SamplePartition : IDisposable
}
internal bool IsTicketCurrentNonBlocking(SourceTicket ticket)
{
if (_hub.IsDisposed || Volatile.Read(ref _disposed) || _hub.RoutingEpoch != _routingEpoch) return false;
if (!_sources.TryGetValue(ticket.Key, out var state)) return false;
var gate = Volatile.Read(ref state.Gate);
var fence = Volatile.Read(ref state.Fence);
return gate.Generation == ticket.Generation && ReferenceEquals(gate.Binding, ticket.Binding) && !gate.Binding.IsRetired && Volatile.Read(ref gate.Retired) == 0 &&
fence?.IsRetired != true && ReferenceEquals(gate, Volatile.Read(ref state.Gate));
fence?.IsRetired != true && ReferenceEquals(gate, Volatile.Read(ref state.Gate)) &&
!Volatile.Read(ref _disposed) && !_hub.IsDisposed && _hub.RoutingEpoch == _routingEpoch;
}
internal void WithLockForTest(Action action) { lock (_gate) action(); }
private bool Current(SourceTicket ticket, out SourceState state)
@@ -130,14 +136,19 @@ internal sealed class SamplePartition : IDisposable
if (!_sources.TryGetValue(ticket.Key, out var state)) return;
var gate = Volatile.Read(ref state.Gate);
if (gate.Generation != ticket.Generation || !ReferenceEquals(gate.Binding, ticket.Binding)) return;
if (retired)
Control.BeginQuiet();
try
{
gate.Binding.Retire();
Interlocked.Exchange(ref gate.Retired, 1);
Interlocked.Exchange(ref _retiredSweepRequested, 1);
_hub.Schedule(this);
if (retired)
{
gate.Binding.Retire();
Interlocked.Exchange(ref gate.Retired, 1);
Interlocked.Exchange(ref _retiredSweepRequested, 1);
_hub.Schedule(this);
}
Interlocked.Increment(ref gate.Invalidated);
}
Interlocked.Increment(ref gate.Invalidated);
finally { Control.EndQuiet(); }
}
internal bool TryReserve(SourceTicket ticket, long estimated, out IIngressReservation? reservation)
@@ -155,12 +166,13 @@ internal sealed class SamplePartition : IDisposable
Interlocked.Increment(ref state.Reservations);
Interlocked.Increment(ref state.MetadataOwners);
reservation = new Reservation(this, state, ticket, estimated, estimated + PartitionedSampleHub.SampleOverhead,
state.InvalidationVersion, _epoch);
state.InvalidationVersion, _epoch, _hub.Clock.GetTimestamp());
return true;
}
finally { Monitor.Exit(_gate); }
}
private bool Commit(SourceState reservedState, SourceTicket ticket, long estimate, long charge, long invalidationVersion, long partitionEpoch, DataSample sample, long sequence)
private bool Commit(SourceState reservedState, SourceTicket ticket, long estimate, long charge, long invalidationVersion,
long partitionEpoch, long receivedTimestamp, DataSample sample, long sequence)
{
if (!Monitor.TryEnter(_gate))
{ ReleaseReservation(reservedState); _hub.Resources.Release(charge); Signal(ticket); return false; }
@@ -180,7 +192,7 @@ internal sealed class SamplePartition : IDisposable
}
catch (Exception e) when (e is ArgumentException or ObjectDisposedException or OverflowException)
{ _hub.Resources.Release(charge); InvalidateSource(state); return false; }
var pending = new Pending(ticket, sequence, ++_ordinal, sample, charge, _hub.Clock.GetTimestamp()) { AdmissionEpoch = state.InvalidationVersion, PartitionEpoch = partitionEpoch };
var pending = new Pending(ticket, sequence, ++_ordinal, sample, charge, receivedTimestamp) { AdmissionEpoch = state.InvalidationVersion, PartitionEpoch = partitionEpoch };
if (_queuedValues < _hub.Limits.MaxIngressItemsPerPartition)
{ _queue.Enqueue(pending); _queuedValues++; }
else if (_dirty.TryGetValue(ticket.Key, out var previous))
@@ -202,7 +214,12 @@ internal sealed class SamplePartition : IDisposable
}
private void Abandon(SourceState state, long charge) { ReleaseReservation(state); _hub.Resources.Release(charge); }
internal void Invalidate(SourceTicket ticket) => Signal(ticket);
private void InvalidateSource(SourceState state) { state.Readiness = DataReadiness.Invalidated; Interlocked.Increment(ref state.InvalidationVersion); ReleaseCache(state); }
private void InvalidateSource(SourceState state)
{
Control.BeginQuiet();
try { state.Readiness = DataReadiness.Invalidated; Interlocked.Increment(ref state.InvalidationVersion); ReleaseCache(state); }
finally { Control.EndQuiet(); }
}
internal bool TryStatus(SourceTicket ticket, long sequence, uint status, DateTimeOffset? source, DateTimeOffset? server)
{
@@ -213,7 +230,9 @@ internal sealed class SamplePartition : IDisposable
if (_disposed || !Current(ticket, out var state) || sequence <= state.LastSubmitted) return false;
if (_queuedControls >= _hub.Limits.MaxControlItemsPerPartition || !_hub.Resources.TryReserve(ControlOverhead)) { InvalidatePartition(); return false; }
var wasReady = state.Readiness == DataReadiness.Ready;
state.Readiness = DataReadiness.Invalidated; Interlocked.Increment(ref state.InvalidationVersion); state.Barrier = sequence; state.LastSubmitted = sequence;
Control.Begin();
try { state.Readiness = DataReadiness.Invalidated; Interlocked.Increment(ref state.InvalidationVersion); state.Barrier = sequence; state.LastSubmitted = sequence; }
finally { Control.End(); }
_queue.Enqueue(new Pending(ticket, sequence, ++_ordinal, status, source, server, wasReady, ControlOverhead) { AdmissionEpoch = state.InvalidationVersion, PartitionEpoch = partitionEpoch }); _queuedControls++;
_hub.Schedule(this); return true;
}
@@ -228,9 +247,14 @@ internal sealed class SamplePartition : IDisposable
if (_disposed || !_sources.TryGetValue(ticket.Key, out var state)) return false;
ApplyGate(state); ApplyPartitionEpoch(state);
if (state.Removed || state.Ticket != ticket || Volatile.Read(ref state.Gate.Retired) != 0 || sequence <= state.LastSubmitted) return false;
if (_queuedControls >= _hub.Limits.MaxControlItemsPerPartition || !_hub.Resources.TryReserve(ControlOverhead))
{ state.Removed = true; ticket.Binding!.Retire(); Interlocked.Exchange(ref state.Gate.Retired, 1); RequestReclaim(); InvalidatePartition(); return false; }
state.Removed = true; ticket.Binding!.Retire(); Interlocked.Exchange(ref state.Gate.Retired, 1); state.Readiness = DataReadiness.Invalidated; Interlocked.Increment(ref state.InvalidationVersion); state.LastSubmitted = sequence; ReleaseCache(state);
Control.BeginQuiet();
try
{
if (_queuedControls >= _hub.Limits.MaxControlItemsPerPartition || !_hub.Resources.TryReserve(ControlOverhead))
{ state.Removed = true; ticket.Binding!.Retire(); Interlocked.Exchange(ref state.Gate.Retired, 1); RequestReclaim(); InvalidatePartition(); return false; }
state.Removed = true; ticket.Binding!.Retire(); Interlocked.Exchange(ref state.Gate.Retired, 1); state.Readiness = DataReadiness.Invalidated; Interlocked.Increment(ref state.InvalidationVersion); state.LastSubmitted = sequence; ReleaseCache(state);
}
finally { Control.EndQuiet(); }
RequestReclaim();
_queue.Enqueue(new Pending(ticket, sequence, ++_ordinal, ControlOverhead) { PartitionEpoch = _epoch }); _queuedControls++;
_hub.Schedule(this); return true;
@@ -298,13 +322,15 @@ internal sealed class SamplePartition : IDisposable
{
_watermark++;
if (_changes.Count == _hub.Limits.MaxSnapshotCatchUpItems)
{ _changes.Dequeue(); _hub.Resources.Release(ChangeOverhead); }
{ _changeIndex.Remove(_changes.First!.Value.Version); _changes.RemoveFirst(); _hub.Resources.Release(ChangeOverhead); }
if (!_hub.Resources.TryReserve(ChangeOverhead)) { InvalidatePartition(); return; }
_changes.Enqueue((_watermark, key));
_changeIndex.Add(_watermark, _changes.AddLast((_watermark, key)));
}
internal void InvalidatePartition()
{
Interlocked.Increment(ref _epoch);
Control.BeginQuiet();
try { Interlocked.Increment(ref _epoch); }
finally { Control.EndQuiet(); }
_hub.Schedule(this);
}
private void ApplyPartitionEpoch(SourceState state)
@@ -318,7 +344,8 @@ internal sealed class SamplePartition : IDisposable
var epoch = Interlocked.Read(ref _epoch);
if (_cleanedEpoch == epoch) return;
foreach (var pair in _sources) ApplyPartitionEpoch(pair.Value);
while (_changes.TryDequeue(out _)) _hub.Resources.Release(ChangeOverhead);
while (_changes.First is not null) { _changes.RemoveFirst(); _hub.Resources.Release(ChangeOverhead); }
_changeIndex.Clear();
_cleanedEpoch = epoch;
}
private void CleanupRetiredSources()
@@ -398,7 +425,8 @@ internal sealed class SamplePartition : IDisposable
Volatile.Read(ref gate.Invalidated) == sourceSignal && Volatile.Read(ref state.InvalidationVersion) == sourceVersion &&
Volatile.Read(ref state.Fence)?.IsRetired != true;
}
internal bool Capture(IEnumerable<SourceTicket> tickets, Dictionary<SourceTicket, SnapshotItem> items, out long watermark, out long epoch, ref long charge, long limit)
internal bool Capture(IEnumerable<SourceTicket> tickets, Dictionary<SourceTicket, SnapshotItem> items, out long watermark, out long epoch,
ref long charge, long limit, SnapshotAdmissionScheduler.Permit? admission = null)
{
lock (_gate)
{
@@ -407,15 +435,60 @@ internal sealed class SamplePartition : IDisposable
foreach (var ticket in tickets)
{
var exists = Current(ticket, out var state);
if (!exists) return false;
var ready = exists && state.Readiness == DataReadiness.Ready && state.Sample is not null;
var bytes = PartitionedSampleHub.ReferenceOverhead + (ready ? state.Sample!.Value.EstimatedRetainedBytes : 0);
if (bytes > limit - charge || !_hub.Resources.TryReserve(bytes)) return false;
if (bytes > limit - charge || admission is not null && !admission.TryGrow(bytes) || !_hub.Resources.TryReserve(bytes)) return false;
charge += bytes;
var sample = ready ? state.Sample! with { Value = state.Sample.Value.Retain() } : null;
if (exists) { Interlocked.Increment(ref state.Snapshots); Interlocked.Increment(ref state.MetadataOwners); }
items.Add(ticket, new SnapshotItem(exists ? state.Readiness : DataReadiness.Unavailable,
exists ? (ready ? DataItemStatus.Good : DataItemStatus.Unavailable) : DataItemStatus.NotFound, sample,
exists ? state.InvalidationVersion : -1) { Owner = exists ? this : null, Source = exists ? state : null });
exists ? state.InvalidationVersion : -1, ready ? state.Received : null)
{ Owner = exists ? this : null, Source = exists ? state : null });
}
return true;
}
}
internal bool CaptureAndRegister(IReadOnlyList<SourceTicket> tickets, Dictionary<SourceTicket, SnapshotItem> items,
Dictionary<SourceTicket, object> interests, out long watermark, out long epoch,
ref long snapshotCharge, ref long interestCharge, long limit, SnapshotAdmissionScheduler.Permit? admission)
{
lock (_gate)
{
if (!Capture(tickets, items, out watermark, out epoch, ref snapshotCharge, limit, admission)) return false;
foreach (var ticket in tickets)
{
if (!Current(ticket, out var state) || interestCharge > limit - snapshotCharge - PartitionedSampleHub.ReferenceOverhead ||
admission is not null && !admission.TryGrow(PartitionedSampleHub.ReferenceOverhead) ||
!_hub.Resources.TryReserve(PartitionedSampleHub.ReferenceOverhead)) return false;
interestCharge += PartitionedSampleHub.ReferenceOverhead;
Interlocked.Increment(ref state.MetadataOwners);
interests.Add(ticket, state);
}
return true;
}
}
internal void ReleaseInterest(object source) => ReleaseMetadataOwner((SourceState)source);
internal bool ReadInterestChanges(long epoch, ref long position, IReadOnlyDictionary<BackingSourceKey, SourceTicket> tickets,
int maximum, List<SourceInterestChange> changes, out int scanned)
{
scanned = 0;
lock (_gate)
{
if (_disposed || epoch != _epoch) return false;
if (position == _watermark) return true;
if (!_changeIndex.TryGetValue(position + 1, out var node)) return false;
while (node is not null && scanned < maximum)
{
var change = node.Value; position = change.Version; scanned++;
if (tickets.TryGetValue(change.Key, out var ticket))
{
if (!Current(ticket, out _)) return false;
changes.Add(new(ticket, change.Version));
}
node = node.Next;
}
return true;
}
@@ -427,14 +500,21 @@ internal sealed class SamplePartition : IDisposable
ReleaseMetadataOwner(state);
if (lastSnapshot && Volatile.Read(ref state.Gate.Retired) != 0 && !Volatile.Read(ref _disposed)) RequestReclaim();
}
internal bool IsSnapshotCurrent(long epoch, long watermark, IEnumerable<KeyValuePair<SourceTicket, SnapshotItem>> tickets)
internal bool IsSnapshotCurrent(long epoch, long watermark, long control)
{
if (!Control.Matches(control)) return false;
lock (_gate)
{
if (_disposed || epoch != _epoch || (_changes.Count > 0 && watermark < _changes.Peek().Version - 1)) return false;
return tickets.All(t => Current(t.Key, out var state) && state.InvalidationVersion == t.Value.InvalidationVersion);
if (_disposed || epoch != _epoch || (_changes.Count > 0 && watermark < _changes.First!.Value.Version - 1)) return false;
return Control.Matches(control);
}
}
internal bool IsSnapshotItemCurrent(SourceTicket ticket, SnapshotItem item, long control)
{
if (!Control.Matches(control)) return false;
lock (_gate)
return !_disposed && Current(ticket, out var state) && state.InvalidationVersion == item.InvalidationVersion && Control.Matches(control);
}
internal long CurrentWatermark { get { lock (_gate) return _watermark; } }
public void Dispose()
@@ -476,11 +556,11 @@ internal sealed class SamplePartition : IDisposable
public bool IsControl; public bool IsStatus; public uint Status; public DateTimeOffset? SourceTimestamp; public DateTimeOffset? ServerTimestamp; public bool WasReady;
}
private sealed class Reservation(SamplePartition partition, SourceState state, SourceTicket ticket, long estimate, long charge,
long invalidationVersion, long partitionEpoch) : IIngressReservation
long invalidationVersion, long partitionEpoch, long receivedTimestamp) : IIngressReservation
{
private int _completed;
public bool TryCommit(DataSample owned, long sequence)
{ ArgumentNullException.ThrowIfNull(owned); return Interlocked.Exchange(ref _completed, 1) == 0 && partition.Commit(state, ticket, estimate, charge, invalidationVersion, partitionEpoch, owned, sequence); }
{ ArgumentNullException.ThrowIfNull(owned); return Interlocked.Exchange(ref _completed, 1) == 0 && partition.Commit(state, ticket, estimate, charge, invalidationVersion, partitionEpoch, receivedTimestamp, owned, sequence); }
public void Dispose() { if (Interlocked.Exchange(ref _completed, 1) == 0) partition.Abandon(state, charge); }
}
}
@@ -0,0 +1,162 @@
namespace ZB.MOM.WW.OtOpcUa.Runtime.DataConnections;
/// <summary>Node-wide and per-principal snapshot slots, bytes, lifetime and send-rate limits.</summary>
internal sealed class SnapshotAdmissionScheduler
{
private readonly object _gate = new();
private readonly int _maxConcurrent, _maxPerPrincipal, _maxPrincipals;
private readonly long _maxBytes, _maxPrincipalBytes, _globalRate, _principalRate;
private readonly TimeSpan _lifetime;
private readonly TimeProvider _clock;
private readonly Dictionary<string, Principal> _principals = new(StringComparer.OrdinalIgnoreCase);
private int _count;
private long _bytes, _windowStart, _windowBytes;
private sealed class Principal(long now)
{
internal int Count;
internal long Bytes, WindowStart = now, WindowBytes;
}
internal sealed class Permit : IDisposable
{
private readonly SnapshotAdmissionScheduler _owner;
private readonly object _state = new();
internal readonly string Principal;
internal long Bytes;
private ITimer? _timer;
private int _references = 1, _expired;
private sealed class Hold(Permit permit) : IDisposable
{
private Permit? _permit = permit;
public void Dispose() => Interlocked.Exchange(ref _permit, null)?.ReleaseHold();
}
internal Permit(SnapshotAdmissionScheduler owner, string principal, long bytes, TimeSpan lifetime)
{
_owner = owner; Principal = principal; Bytes = bytes;
_timer = owner._clock.CreateTimer(static state => ((Permit)state!).Dispose(), this, lifetime, Timeout.InfiniteTimeSpan);
}
internal bool IsValid => Volatile.Read(ref _expired) == 0;
internal bool TryRetain(out IDisposable? hold)
{
hold = null;
lock (_state)
{
if (_expired != 0) return false;
_references = checked(_references + 1); hold = new Hold(this); return true;
}
}
internal bool TryGrow(long bytes)
{
if (bytes <= 0) throw new ArgumentOutOfRangeException(nameof(bytes));
return IsValid && _owner.Grow(this, bytes);
}
internal bool OwnedBy(SnapshotAdmissionScheduler owner) => ReferenceEquals(_owner, owner) && IsValid;
public void Dispose()
{
var release = false;
lock (_state)
{
if (_expired != 0) return;
Volatile.Write(ref _expired, 1);
release = --_references == 0;
}
_timer?.Dispose();
if (release) _owner.Release(this);
}
private void ReleaseHold()
{
var release = false;
lock (_state) release = --_references == 0;
if (release) _owner.Release(this);
}
}
internal SnapshotAdmissionScheduler(int maxConcurrent, int maxPerPrincipal, long maxBytes,
long? maxPrincipalBytes = null, long globalBytesPerSecond = long.MaxValue,
long principalBytesPerSecond = long.MaxValue, TimeSpan? maxLifetime = null, TimeProvider? clock = null)
{
if (maxConcurrent <= 0 || maxPerPrincipal <= 0 || maxBytes <= 0 || maxPrincipalBytes is <= 0 ||
globalBytesPerSecond <= 0 || principalBytesPerSecond <= 0 || maxLifetime is { } lifetime && lifetime <= TimeSpan.Zero)
throw new ArgumentOutOfRangeException(nameof(maxConcurrent));
_maxConcurrent = maxConcurrent; _maxPerPrincipal = maxPerPrincipal; _maxBytes = maxBytes;
_maxPrincipalBytes = maxPrincipalBytes ?? maxBytes;
_globalRate = globalBytesPerSecond; _principalRate = principalBytesPerSecond;
_lifetime = maxLifetime ?? TimeSpan.FromSeconds(30); _clock = clock ?? TimeProvider.System;
_maxPrincipals = checked(maxConcurrent * 16); _windowStart = _clock.GetTimestamp();
}
internal bool TryAcquire(string principal, long bytes, out IDisposable? lease) => TryAcquire(principal, bytes, out lease, out _);
internal bool TryAcquire(string principal, long bytes, out IDisposable? lease, out TimeSpan retryAfter)
{
ArgumentException.ThrowIfNullOrWhiteSpace(principal);
if (bytes <= 0) throw new ArgumentOutOfRangeException(nameof(bytes));
lease = null; retryAfter = Jitter(principal);
lock (_gate)
{
var now = _clock.GetTimestamp();
if (!TryPrincipal(principal, now, out var state)) return false;
if (_count >= _maxConcurrent || state.Count >= _maxPerPrincipal || bytes > _maxBytes - _bytes ||
bytes > _maxPrincipalBytes - state.Bytes)
{
if (state.Count == 0 && state.WindowBytes == 0) _principals.Remove(principal);
return false;
}
state.Count++; state.Bytes += bytes; _count++; _bytes += bytes;
try { lease = new Permit(this, principal, bytes, _lifetime); return true; }
catch { state.Count--; state.Bytes -= bytes; _count--; _bytes -= bytes; throw; }
}
}
/// <summary>Charges actual snapshot bytes immediately before the delivery handoff; no waiting queue.</summary>
internal bool TryConsume(string principal, long bytes, out TimeSpan retryAfter)
{
ArgumentException.ThrowIfNullOrWhiteSpace(principal);
if (bytes < 0) throw new ArgumentOutOfRangeException(nameof(bytes));
retryAfter = Jitter(principal);
lock (_gate)
{
var now = _clock.GetTimestamp();
if (!TryPrincipal(principal, now, out var state)) return false;
if (_clock.GetElapsedTime(_windowStart, now) >= TimeSpan.FromSeconds(1)) { _windowStart = now; _windowBytes = 0; }
if (_clock.GetElapsedTime(state.WindowStart, now) >= TimeSpan.FromSeconds(1)) { state.WindowStart = now; state.WindowBytes = 0; }
var globalExceeded = bytes > _globalRate - _windowBytes;
var principalExceeded = bytes > _principalRate - state.WindowBytes;
if (globalExceeded || principalExceeded)
{
var globalRemaining = globalExceeded ? TimeSpan.FromSeconds(1) - _clock.GetElapsedTime(_windowStart, now) : TimeSpan.Zero;
var principalRemaining = principalExceeded ? TimeSpan.FromSeconds(1) - _clock.GetElapsedTime(state.WindowStart, now) : TimeSpan.Zero;
var remaining = globalRemaining > principalRemaining ? globalRemaining : principalRemaining;
if (remaining > TimeSpan.Zero) retryAfter += remaining;
return false;
}
_windowBytes += bytes; state.WindowBytes += bytes; return true;
}
}
private bool TryPrincipal(string principal, long now, out Principal state)
{
if (_principals.TryGetValue(principal, out state!)) return true;
if (_principals.Count >= _maxPrincipals)
{
var expired = _principals.FirstOrDefault(pair => pair.Value.Count == 0 &&
_clock.GetElapsedTime(pair.Value.WindowStart, now) >= TimeSpan.FromSeconds(1));
if (expired.Key is null) return false;
_principals.Remove(expired.Key);
}
state = new Principal(now); _principals.Add(principal, state); return true;
}
private static TimeSpan Jitter(string principal) => TimeSpan.FromMilliseconds(50 +
(unchecked((uint)StringComparer.OrdinalIgnoreCase.GetHashCode(principal)) % 101));
private bool Grow(Permit permit, long bytes)
{
lock (_gate)
{
if (!permit.OwnedBy(this) || !_principals.TryGetValue(permit.Principal, out var state) ||
bytes > _maxBytes - _bytes || bytes > _maxPrincipalBytes - state.Bytes) return false;
state.Bytes += bytes; _bytes += bytes; permit.Bytes += bytes; return true;
}
}
private void Release(Permit permit)
{
lock (_gate)
{
var state = _principals[permit.Principal]; state.Count--; state.Bytes -= permit.Bytes; _count--; _bytes -= permit.Bytes;
if (state.Count == 0 && (_principalRate == long.MaxValue || state.WindowBytes == 0)) _principals.Remove(permit.Principal);
}
}
}
@@ -4,7 +4,8 @@ using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections;
namespace ZB.MOM.WW.OtOpcUa.Runtime.DataConnections;
/// <summary>Frozen item state. Its sample belongs to the containing snapshot.</summary>
public sealed record SnapshotItem(DataReadiness Readiness, DataItemStatus Status, DataSample? Sample, long InvalidationVersion)
public sealed record SnapshotItem(DataReadiness Readiness, DataItemStatus Status, DataSample? Sample, long InvalidationVersion,
long? ReceivedTimestamp = null)
{
internal SamplePartition? Owner { get; init; }
internal object? Source { get; init; }
@@ -14,12 +15,29 @@ public sealed record SnapshotItem(DataReadiness Readiness, DataItemStatus Status
/// <summary>Retained immutable snapshots and per-partition catch-up watermarks.</summary>
public sealed class SnapshotLease : IDisposable
{
private sealed class PartitionCursor(SamplePartition partition, long epoch, long control, long watermark, int count)
{
internal readonly SamplePartition Partition = partition;
internal readonly long Epoch = epoch, Control = control;
private readonly SortedDictionary<long, int> _positions = new() { [watermark] = count };
private long _minimum = watermark;
internal long Minimum => _minimum;
internal void Advance(long oldPosition, long newPosition)
{
if (oldPosition == newPosition) return;
var removed = --_positions[oldPosition] == 0;
if (removed) _positions.Remove(oldPosition);
_positions.TryGetValue(newPosition, out var count);
_positions[newPosition] = count + 1;
if (removed && oldPosition == _minimum) _minimum = _positions.First().Key;
}
}
private readonly PartitionedSampleHub _hub;
private readonly SamplePartition[] _partitions;
private readonly long _routingEpoch;
private readonly long _charge;
private readonly int _itemCount;
private readonly Dictionary<int, long> _epochs;
private readonly Dictionary<int, PartitionCursor> _cursors;
private readonly Dictionary<SourceTicket, int> _owners;
private readonly Dictionary<SourceTicket, long> _positions;
private readonly Dictionary<SourceTicket, long> _versions;
@@ -29,14 +47,15 @@ public sealed class SnapshotLease : IDisposable
private int _released;
internal SnapshotLease(PartitionedSampleHub hub, Dictionary<SourceTicket, SnapshotItem> items,
Dictionary<int, long> watermarks, Dictionary<int, long> epochs, SamplePartition[] partitions,
Dictionary<int, long> watermarks, Dictionary<int, long> epochs, Dictionary<int, long> controls, SamplePartition[] partitions,
long routingEpoch, long charge, int itemCount, TimeSpan lifetime, CancellationToken cancellationToken)
{
_hub = hub; _partitions = partitions; _routingEpoch = routingEpoch; _charge = charge; _itemCount = itemCount;
_epochs = epochs;
Items = new ReadOnlyDictionary<SourceTicket, SnapshotItem>(items);
Watermarks = new ReadOnlyDictionary<int, long>(watermarks);
_owners = items.Keys.ToDictionary(t => t, t => PartitionedSampleHub.GetPartitionFor(t.Key, partitions.Length));
_cursors = _owners.Values.GroupBy(i => i).ToDictionary(g => g.Key,
g => new PartitionCursor(partitions[g.Key], epochs[g.Key], controls[g.Key], watermarks[g.Key], g.Count()));
_positions = items.Keys.ToDictionary(t => t, t => watermarks[_owners[t]]);
_versions = items.ToDictionary(p => p.Key, p => p.Value.Sample?.Version ?? 0);
_timer = hub.Clock.CreateTimer(static o => ((SnapshotLease)o!).Dispose(), this, lifetime, Timeout.InfiniteTimeSpan);
@@ -52,15 +71,29 @@ public sealed class SnapshotLease : IDisposable
{
if (_released != 0) return true;
if (_hub.IsDisposed || _hub.RoutingEpoch != _routingEpoch) { Release(); return true; }
foreach (var group in Items.GroupBy(p => _owners[p.Key]))
foreach (var cursor in _cursors.Values)
{
var watermark = group.Min(p => _positions[p.Key]);
if (!_partitions[group.Key].IsSnapshotCurrent(_epochs[group.Key], watermark, group)) { Release(); return true; }
_hub.BeforeSnapshotValidationForTests?.Invoke();
_hub.CountSnapshotValidationForTests();
if (!cursor.Partition.IsSnapshotCurrent(cursor.Epoch, cursor.Minimum, cursor.Control)) { Release(); return true; }
}
if (_hub.IsDisposed || _hub.RoutingEpoch != _routingEpoch) { Release(); return true; }
return false;
}
}
}
/// <summary>Validates the captured source and read fence immediately before its value is handed off.</summary>
internal bool IsItemCurrent(SourceTicket ticket)
{
lock (_gate)
{
if (IsReset || !_owners.TryGetValue(ticket, out var owner) || !Items.TryGetValue(ticket, out var item)) return false;
var cursor = _cursors[owner];
if (!cursor.Partition.IsSnapshotItemCurrent(ticket, item, cursor.Control) ||
_hub.IsDisposed || _hub.RoutingEpoch != _routingEpoch) { Release(); return false; }
return true;
}
}
/// <summary>Returns the latest newer sample as an independently disposable, globally charged read.</summary>
public bool TryReadDelta(SourceTicket ticket, out CachedSourceRead? delta)
{
@@ -75,6 +108,7 @@ public sealed class SnapshotLease : IDisposable
var version = read.Sample.Version;
if (version <= _versions[ticket]) { read.Dispose(); return false; }
_versions[ticket] = version;
_cursors[owner].Advance(_positions[ticket], readWatermark);
_positions[ticket] = readWatermark;
delta = read; return true;
}
@@ -0,0 +1,98 @@
namespace ZB.MOM.WW.OtOpcUa.Runtime.DataConnections;
/// <summary>A dirty source generation, distinct from an individual delivered sample version.</summary>
public readonly record struct SourceInterestChange(SourceTicket Ticket, long Generation);
/// <summary>Retains source metadata after the finite snapshot payload has been released.</summary>
public sealed class SourceInterestLease : IDisposable
{
private sealed class Cursor(SamplePartition partition, long position, long epoch, long quietControl,
Dictionary<BackingSourceKey, SourceTicket> tickets)
{
internal readonly SamplePartition Partition = partition;
internal long Position = position;
internal readonly long Epoch = epoch;
internal readonly long QuietControl = quietControl;
internal readonly Dictionary<BackingSourceKey, SourceTicket> Tickets = tickets;
}
private readonly object _gate = new();
private readonly PartitionedSampleHub _hub;
private readonly Dictionary<SourceTicket, (SamplePartition Partition, object Source)> _owners;
private Cursor[] _cursors;
private readonly long _routingEpoch;
private long _charge;
private CancellationTokenRegistration _cancellation;
private int _released, _next;
internal SourceInterestLease(PartitionedSampleHub hub,
Dictionary<SourceTicket, (SamplePartition Partition, object Source)> owners,
IReadOnlyDictionary<int, long> watermarks, IReadOnlyDictionary<int, long> epochs, IReadOnlyDictionary<int, long> quietControls,
long routingEpoch, long charge, CancellationToken cancellationToken)
{
_hub = hub; _owners = owners; _routingEpoch = routingEpoch; _charge = charge;
_cursors = owners.GroupBy(x => x.Value.Partition.Id).Select(group => new Cursor(group.First().Value.Partition,
watermarks[group.Key], epochs[group.Key], quietControls[group.Key], group.ToDictionary(x => x.Key.Key, x => x.Key))).ToArray();
_cancellation = cancellationToken.Register(static state => ((SourceInterestLease)state!).Dispose(), this);
}
internal bool ReleaseTicket(SourceTicket ticket)
{
lock (_gate)
{
if (_released != 0 || !_owners.Remove(ticket, out var owner)) return false;
foreach (var cursor in _cursors) cursor.Tickets.Remove(ticket.Key);
_cursors = _cursors.Where(cursor => cursor.Tickets.Count != 0).ToArray();
if (_next >= _cursors.Length) _next = 0;
owner.Partition.ReleaseInterest(owner.Source);
_hub.Resources.Release(PartitionedSampleHub.ReferenceOverhead);
_hub.UntrackInterestItems(1);
_charge -= PartitionedSampleHub.ReferenceOverhead;
if (_owners.Count == 0) Release();
return true;
}
}
public bool IsReset
{
get
{
if (Volatile.Read(ref _released) != 0 || _hub.IsDisposed || _hub.RoutingEpoch != _routingEpoch) return true;
foreach (var cursor in Volatile.Read(ref _cursors))
if (!cursor.Partition.Control.Quiet.Matches(cursor.QuietControl)) return true;
return Volatile.Read(ref _released) != 0 || _hub.IsDisposed || _hub.RoutingEpoch != _routingEpoch;
}
}
/// <summary>Scans at most maximum retained partition changes, returning false on a gap or epoch reset.</summary>
public bool TryReadChanges(int maximum, out IReadOnlyList<SourceInterestChange> changes)
{
if (maximum <= 0) throw new ArgumentOutOfRangeException(nameof(maximum));
lock (_gate)
{
var result = new List<SourceInterestChange>();
changes = result;
if (IsReset) { Release(); return false; }
var scanned = 0;
for (var visited = 0; visited < _cursors.Length && scanned < maximum; visited++)
{
var cursor = _cursors[_next]; _next = (_next + 1) % _cursors.Length;
if (!cursor.Partition.ReadInterestChanges(cursor.Epoch, ref cursor.Position, cursor.Tickets,
maximum - scanned, result, out var used)) { Release(); result.Clear(); return false; }
scanned += used;
}
if (IsReset) { Release(); result.Clear(); return false; }
return true;
}
}
private void Release()
{
if (Interlocked.Exchange(ref _released, 1) == 0)
{
_cancellation.Unregister();
var count = _owners.Count;
foreach (var owner in _owners.Values) owner.Partition.ReleaseInterest(owner.Source);
_owners.Clear(); _cursors = [];
_hub.Resources.Release(_charge); _hub.UntrackInterestItems(count);
}
_hub.ForgetInterest(this);
}
public void Dispose() { lock (_gate) Release(); }
}
@@ -57,7 +57,7 @@ public sealed class SourceSamplePublisher
private readonly Dictionary<BackingSourceKey, SourceTicket> _tickets = new();
private readonly Dictionary<(string Driver, string Reference), BackingSourceKey> _drivers = new();
private readonly Dictionary<string, BackingSourceKey> _virtuals = new(StringComparer.Ordinal);
private sealed class SourceSlot
internal sealed class SourceSlot
{
public readonly object Gate = new();
public SourceBinding? Current;
@@ -65,7 +65,7 @@ public sealed class SourceSamplePublisher
public int RepairQueued;
public int RepairAttempts;
}
private sealed class SourceBinding(SourceTicket ticket, SourceSlot slot, ProducerFence? producer, SourceValueShape? shape)
internal sealed class SourceBinding(SourceTicket ticket, SourceSlot slot, ProducerFence? producer, SourceValueShape? shape)
{
public SourceTicket Ticket { get; } = ticket;
public SourceSlot Slot { get; } = slot;
@@ -365,6 +365,138 @@ public sealed class SourceSamplePublisher
}
}
/// <summary>An owned, budgeted callback sample whose handle has not yet been acknowledged.</summary>
internal sealed class StagedSourceSample : IDisposable
{
private readonly SourceSamplePublisher _owner;
private readonly SourceBinding _binding;
private readonly SourceTicket _ticket;
private readonly uint _status;
private readonly DateTimeOffset? _source, _server;
private IIngressReservation? _reservation;
private DataValue? _value;
private int _finished;
internal StagedSourceSample(SourceSamplePublisher owner, SourceBinding binding, SourceTicket ticket,
DataValueSnapshot snapshot, IIngressReservation reservation, DataValue value)
{
_owner = owner; _binding = binding; _ticket = ticket; _status = snapshot.StatusCode;
_source = OwnedDataSample.Timestamp(snapshot.SourceTimestampUtc);
_server = OwnedDataSample.Timestamp(snapshot.ServerTimestampUtc);
_reservation = reservation; _value = value;
}
internal bool Commit()
{
if (Interlocked.Exchange(ref _finished, 1) != 0) return false;
var reservation = _reservation!; _reservation = null;
var value = _value!; _value = null;
DataSample? sample = null;
try
{
var slot = _binding.Slot;
if (!Monitor.TryEnter(slot.Gate)) { _owner._hub.Invalidate(_ticket, "staged source contention"); return false; }
try
{
if (!_binding.Active || !ReferenceEquals(Volatile.Read(ref slot.Current), _binding)) return false;
var serving = _owner._serving();
if (serving is null || serving.NodeId != _ticket.Key.ServingNodeId ||
serving.Incarnation != _ticket.Key.ServingIncarnation || string.IsNullOrWhiteSpace(serving.Role))
{ _owner._hub.Invalidate(_ticket, "staged source identity unavailable"); return false; }
var sequence = checked(++slot.Sequence);
sample = new DataSample(value, _status, _source, _server, serving, sequence);
value = null!;
if (!reservation.TryCommit(sample, sequence))
{ _owner._hub.Invalidate(_ticket, "staged source admission rejected"); return false; }
sample = null;
return true;
}
finally { Monitor.Exit(slot.Gate); }
}
catch (Exception ex) when (ex is ArgumentException or OverflowException or InvalidOperationException)
{ _owner._hub.Invalidate(_ticket, "staged source commit failed"); return false; }
finally
{
value?.Dispose(); sample?.Dispose(); reservation.Dispose();
Interlocked.Decrement(ref _binding.InFlight);
}
}
public void Dispose()
{
if (Interlocked.Exchange(ref _finished, 1) != 0) return;
_value?.Dispose(); _value = null;
_reservation?.Dispose(); _reservation = null;
Interlocked.Decrement(ref _binding.InFlight);
}
}
/// <summary>Reserves and owns a borrowed callback value synchronously, before handle validation.</summary>
internal bool TryStage(SourceTicket ticket, DataValueSnapshot snapshot, out StagedSourceSample? staged)
{
staged = null;
if (!_slots.TryGetValue(ticket.Key, out var slot)) return false;
var binding = Volatile.Read(ref slot.Current);
if (binding is null || binding.Ticket != ticket || !binding.Active) return false;
Interlocked.Increment(ref binding.InFlight);
IIngressReservation? reservation = null;
DataValue? value = null;
try
{
if (!binding.Active || !ReferenceEquals(Volatile.Read(ref slot.Current), binding)) return false;
var size = OwnedDataSample.Estimate(snapshot.Value, binding.Shape);
if (!_hub.TryReserveIngress(ticket, size, out reservation) || reservation is null)
{ _hub.Invalidate(ticket, "staged source ingress capacity"); return false; }
value = OwnedDataSample.Copy(snapshot.Value, binding.Shape);
staged = new StagedSourceSample(this, binding, ticket, snapshot, reservation, value);
reservation = null; value = null;
return true;
}
catch (Exception ex) when (ex is ArgumentException or OverflowException or InvalidOperationException)
{ _hub.Invalidate(ticket, "staged source value invalid"); return false; }
finally
{
if (staged is null) { value?.Dispose(); reservation?.Dispose(); Interlocked.Decrement(ref binding.InFlight); }
}
}
/// <summary>Attempts status-only acquisition ingress without waiting or refreshing value age.</summary>
public bool TryPublishAcquisitionStatus(SourceTicket ticket, uint status)
{
if (!_slots.TryGetValue(ticket.Key, out var slot)) return false;
if (!Monitor.TryEnter(slot.Gate))
{
_hub.Invalidate(ticket, "source status contention");
return false;
}
try
{
var binding = Volatile.Read(ref slot.Current);
if (binding is null || binding.Ticket != ticket || !binding.Active) return false;
if (Volatile.Read(ref binding.InFlight) != 0)
{
_hub.Invalidate(ticket, "source status overtook in-flight sample");
return false;
}
if (_hub.TryPublishStatus(ticket, checked(++slot.Sequence), status, null, null)) return true;
_hub.Invalidate(ticket, "source status admission failed");
return false;
}
catch (OverflowException)
{
_hub.Invalidate(ticket, "source status sequence exhausted");
return false;
}
finally { Monitor.Exit(slot.Gate); }
}
internal void WithAcquisitionStatusLockForTest(SourceTicket ticket, bool publisherGate, Action action)
{
if (publisherGate) { lock (_gate) action(); return; }
if (!_slots.TryGetValue(ticket.Key, out var slot)) throw new InvalidOperationException("Source slot is unavailable.");
lock (slot.Gate) action();
}
/// <summary>Synchronously invalidates a malformed callback's captured source generation.</summary>
public void Invalidate(SourceTicket ticket, string reason) => _hub.Invalidate(ticket, reason);
@@ -0,0 +1,76 @@
using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections;
namespace ZB.MOM.WW.OtOpcUa.Runtime.DataConnections;
/// <summary>Epoch-local non-reusable item identifiers and revision fences.</summary>
internal sealed class SubscriptionItemHandleTable
{
private readonly object _gate = new();
private readonly string _subscription;
private readonly long _epoch;
private readonly int _capacity;
private readonly Dictionary<ulong, (string ClientId, long Revision)> _items = new();
private readonly HashSet<string> _clientIds = new(StringComparer.Ordinal);
private readonly Dictionary<ulong, (DataItemHandle Previous, string ClientId, long Revision)> _reserved = new();
private readonly Dictionary<ulong, ulong> _replacementByOld = new();
private ulong _next;
internal SubscriptionItemHandleTable(string subscriptionId, long epoch, int capacity)
{
ArgumentException.ThrowIfNullOrWhiteSpace(subscriptionId);
if (epoch <= 0 || capacity <= 0) throw new ArgumentOutOfRangeException(nameof(epoch));
_subscription = subscriptionId; _epoch = epoch; _capacity = capacity;
}
internal DataItemHandle Add(string clientItemId)
{
ArgumentException.ThrowIfNullOrWhiteSpace(clientItemId);
lock (_gate)
{
if (_items.Count >= _capacity || _clientIds.Contains(clientItemId)) throw new InvalidOperationException("Item capacity or ID conflict.");
var id = checked(++_next);
_clientIds.Add(clientItemId); _items.Add(id, (clientItemId, 1));
return new(_subscription, _epoch, id, 1);
}
}
internal bool Remove(DataItemHandle handle)
{
lock (_gate)
{
if (!Current(handle) || !_items.Remove(handle.Handle, out var item)) return false;
if (_replacementByOld.Remove(handle.Handle, out var reserved)) _reserved.Remove(reserved);
_clientIds.Remove(item.ClientId); return true;
}
}
internal bool IsCurrent(DataItemHandle handle) { lock (_gate) return Current(handle); }
internal DataItemHandle ReserveReplacement(DataItemHandle previous)
{
lock (_gate)
{
if (!Current(previous) || _replacementByOld.ContainsKey(previous.Handle) || _reserved.Count >= _capacity)
throw new InvalidOperationException("Item cannot be revised.");
var id = checked(++_next);
var item = _items[previous.Handle];
var revision = checked(item.Revision + 1);
_reserved.Add(id, (previous, item.ClientId, revision)); _replacementByOld.Add(previous.Handle, id);
return new(_subscription, _epoch, id, revision);
}
}
internal bool CommitReplacement(DataItemHandle previous, DataItemHandle replacement)
{
lock (_gate)
{
if (!Current(previous) || replacement.SubscriptionId != _subscription || replacement.StreamEpoch != _epoch ||
!_reserved.TryGetValue(replacement.Handle, out var reserved) || reserved.Previous != previous || reserved.Revision != replacement.ItemRevision)
return false;
_reserved.Remove(replacement.Handle); _replacementByOld.Remove(previous.Handle);
_items.Remove(previous.Handle); _items.Add(replacement.Handle, (reserved.ClientId, reserved.Revision));
return true;
}
}
internal void CancelReplacement(DataItemHandle replacement)
{
lock (_gate)
if (_reserved.Remove(replacement.Handle, out var reserved)) _replacementByOld.Remove(reserved.Previous.Handle);
}
private bool Current(DataItemHandle handle) => handle is not null && handle.SubscriptionId == _subscription &&
handle.StreamEpoch == _epoch && _items.TryGetValue(handle.Handle, out var item) && item.Revision == handle.ItemRevision;
}
@@ -0,0 +1,16 @@
using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections;
namespace ZB.MOM.WW.OtOpcUa.Runtime.DataConnections;
/// <summary>Computes a shared demand that cannot suppress any admitted consumer's changes.</summary>
internal static class SubscriptionSettingsAggregator
{
internal static DataSubscriptionSettings Aggregate(IReadOnlyCollection<DataSubscriptionSettings> settings)
{
ArgumentNullException.ThrowIfNull(settings);
if (settings.Count == 0) throw new ArgumentException("At least one interest is required.", nameof(settings));
foreach (var item in settings) item.Validate();
return new(settings.Min(x => x.SamplingInterval), settings.Min(x => x.PublishingInterval),
settings.Max(x => x.Trigger), null);
}
}
@@ -0,0 +1,231 @@
namespace ZB.MOM.WW.OtOpcUa.Runtime.DataConnections;
/// <summary>Shared physical prepare/write slots and byte reservations across all sessions.</summary>
internal sealed class SubscriptionTransportCapacity
{
private readonly object _gate = new();
private readonly int _maximum, _perPrincipal;
private readonly long _maximumBytes;
private readonly TimeProvider _clock;
private readonly int _maxCommandsPerSecond, _maxRatePrincipals;
private readonly Dictionary<string, (long Started, int Count)> _commandRates = new(StringComparer.OrdinalIgnoreCase);
private readonly Dictionary<string, int> _principals = new(StringComparer.OrdinalIgnoreCase);
private readonly Dictionary<string, int> _sessionsByPrincipal = new(StringComparer.OrdinalIgnoreCase);
private readonly Dictionary<string, int> _interestsByPrincipal = new(StringComparer.OrdinalIgnoreCase);
private readonly Dictionary<string, PrincipalWaiters> _waiters = new(StringComparer.OrdinalIgnoreCase);
private readonly LinkedList<PrincipalWaiters> _roundRobin = new();
private int _waiting;
private int _active;
private int _sessions;
private int _interests;
private const int MaxGlobalInterests = 100_000;
private sealed class PrincipalWaiters(string principal)
{
internal readonly string Principal = principal;
internal readonly LinkedList<Waiter> Queue = new();
internal LinkedListNode<PrincipalWaiters>? Node;
}
private sealed class Waiter(SubscriptionTransportCapacity owner, PrincipalWaiters group, long bytes, CancellationToken token)
{
internal readonly SubscriptionTransportCapacity Owner = owner;
internal readonly PrincipalWaiters Group = group;
internal readonly long Bytes = bytes;
internal readonly CancellationToken Token = token;
internal readonly TaskCompletionSource<IDisposable?> Completion = new(TaskCreationOptions.RunContinuationsAsynchronously);
internal LinkedListNode<Waiter>? Node;
internal CancellationTokenRegistration Registration;
internal bool Pending = true;
}
private long _bytes;
internal SnapshotAdmissionScheduler Snapshots { get; }
private sealed class Lease(SubscriptionTransportCapacity owner, string principal, long bytes) : IDisposable
{
private SubscriptionTransportCapacity? _owner = owner;
public void Dispose() => Interlocked.Exchange(ref _owner, null)?.Release(principal, bytes);
}
private sealed class SessionLease(SubscriptionTransportCapacity owner, string principal, long bytes) : IDisposable
{
private SubscriptionTransportCapacity? _owner = owner;
public void Dispose() => Interlocked.Exchange(ref _owner, null)?.ReleaseSession(principal, bytes);
}
private sealed class InterestLease(SubscriptionTransportCapacity owner, string principal, long bytes) : IDisposable
{
private SubscriptionTransportCapacity? _owner = owner;
public void Dispose() => Interlocked.Exchange(ref _owner, null)?.ReleaseInterest(principal, bytes);
}
internal SubscriptionTransportCapacity(int maximum, int perPrincipal, long maximumBytes, TimeProvider? clock = null,
int? maxSnapshots = null, int? maxSnapshotsPerPrincipal = null, long? maxSnapshotBytes = null,
long? maxPrincipalSnapshotBytes = null, long? globalSnapshotBytesPerSecond = null,
long? principalSnapshotBytesPerSecond = null, TimeSpan? maxSnapshotLifetime = null, int maxCommandsPerSecond = 128)
{
if (maximum <= 0 || perPrincipal <= 0 || maximumBytes <= 0 || maxCommandsPerSecond <= 0) throw new ArgumentOutOfRangeException(nameof(maximum));
_maximum = maximum; _perPrincipal = perPrincipal; _maximumBytes = maximumBytes;
_clock = clock ?? TimeProvider.System; _maxCommandsPerSecond = maxCommandsPerSecond; _maxRatePrincipals = checked(maximum * 16);
Snapshots = new(maxSnapshots ?? maximum, maxSnapshotsPerPrincipal ?? perPrincipal, maxSnapshotBytes ?? maximumBytes,
maxPrincipalBytes: maxPrincipalSnapshotBytes, globalBytesPerSecond: globalSnapshotBytesPerSecond ?? maximumBytes,
principalBytesPerSecond: principalSnapshotBytesPerSecond ?? maximumBytes, maxLifetime: maxSnapshotLifetime, clock: clock);
}
internal int ActiveOperations { get { lock (_gate) return _active; } }
internal bool TryAdmitCommand(string principal)
{
ArgumentException.ThrowIfNullOrWhiteSpace(principal);
lock (_gate)
{
var now = _clock.GetTimestamp();
if (!_commandRates.TryGetValue(principal, out var rate))
{
if (_commandRates.Count >= _maxRatePrincipals)
{
var expired = _commandRates.FirstOrDefault(pair => _clock.GetElapsedTime(pair.Value.Started, now) >= TimeSpan.FromSeconds(1));
if (expired.Key is null) return false;
_commandRates.Remove(expired.Key);
}
_commandRates.Add(principal, (now, 1)); return true;
}
if (_clock.GetElapsedTime(rate.Started, now) >= TimeSpan.FromSeconds(1)) rate = (now, 0);
if (rate.Count >= _maxCommandsPerSecond) return false;
_commandRates[principal] = (rate.Started, rate.Count + 1); return true;
}
}
internal bool TryOpenSession(string principal, long fixedBytes, int admittedLimit, out IDisposable? lease)
{
ArgumentException.ThrowIfNullOrWhiteSpace(principal);
if (fixedBytes <= 0 || admittedLimit <= 0) throw new ArgumentOutOfRangeException(nameof(fixedBytes));
lease = null;
lock (_gate)
{
_sessionsByPrincipal.TryGetValue(principal, out var count);
if (_waiting != 0 || _sessions >= _maximum || count >= Math.Min(_perPrincipal, admittedLimit) ||
fixedBytes > _maximumBytes - _bytes) return false;
_sessionsByPrincipal[principal] = count + 1; _sessions++; _bytes += fixedBytes;
lease = new SessionLease(this, principal, fixedBytes); return true;
}
}
internal bool TryReserveInterest(string principal, int principalLimit, long fixedBytes, out IDisposable? lease)
{
ArgumentException.ThrowIfNullOrWhiteSpace(principal);
if (principalLimit <= 0 || fixedBytes <= 0) throw new ArgumentOutOfRangeException(nameof(principalLimit));
lease = null;
lock (_gate)
{
_interestsByPrincipal.TryGetValue(principal, out var count);
if (_waiting != 0 || _interests >= MaxGlobalInterests || count >= principalLimit || fixedBytes > _maximumBytes - _bytes) return false;
_interestsByPrincipal[principal] = count + 1; _interests++; _bytes += fixedBytes;
lease = new InterestLease(this, principal, fixedBytes); return true;
}
}
internal bool TryReserve(string principal, long bytes, out IDisposable? lease)
{
ArgumentException.ThrowIfNullOrWhiteSpace(principal);
if (bytes <= 0) throw new ArgumentOutOfRangeException(nameof(bytes));
lease = null;
lock (_gate)
{
if (_waiting != 0) return false;
return TryReserveCore(principal, bytes, out lease);
}
}
/// <summary>Waits in a bounded principal-round-robin queue without blocking producers or actors.</summary>
internal ValueTask<IDisposable?> ReserveAsync(string principal, long bytes, CancellationToken cancellationToken)
{
ArgumentException.ThrowIfNullOrWhiteSpace(principal);
if (bytes <= 0) throw new ArgumentOutOfRangeException(nameof(bytes));
cancellationToken.ThrowIfCancellationRequested();
lock (_gate)
{
if (bytes > _maximumBytes) return ValueTask.FromResult<IDisposable?>(null);
if (_waiting == 0 && TryReserveCore(principal, bytes, out var lease)) return ValueTask.FromResult(lease);
if (_waiting >= _maximum) return ValueTask.FromResult<IDisposable?>(null);
if (!_waiters.TryGetValue(principal, out var group))
{
group = new PrincipalWaiters(principal); group.Node = _roundRobin.AddLast(group); _waiters.Add(principal, group);
}
var waiter = new Waiter(this, group, bytes, cancellationToken);
waiter.Node = group.Queue.AddLast(waiter); _waiting++;
waiter.Registration = cancellationToken.Register(static state =>
{
var pending = (Waiter)state!; pending.Owner.CancelWaiter(pending);
}, waiter);
if (!waiter.Pending) waiter.Registration.Unregister();
GrantWaiters();
return new ValueTask<IDisposable?>(waiter.Completion.Task);
}
}
private bool TryReserveCore(string principal, long bytes, out IDisposable? lease)
{
lease = null;
_principals.TryGetValue(principal, out var current);
if (_active >= _maximum || current >= _perPrincipal || bytes > _maximumBytes - _bytes) return false;
_principals[principal] = current + 1; _active++; _bytes += bytes;
lease = new Lease(this, principal, bytes); return true;
}
private void CancelWaiter(Waiter waiter)
{
lock (_gate)
{
if (!waiter.Pending) return;
RemoveWaiter(waiter);
waiter.Completion.TrySetCanceled(waiter.Token);
GrantWaiters();
}
}
private void RemoveWaiter(Waiter waiter)
{
waiter.Pending = false; waiter.Group.Queue.Remove(waiter.Node!); _waiting--;
if (waiter.Group.Queue.Count == 0)
{ _roundRobin.Remove(waiter.Group.Node!); _waiters.Remove(waiter.Group.Principal); waiter.Group.Node = null; }
waiter.Registration.Unregister();
}
private void GrantWaiters()
{
var visited = _roundRobin.Count;
while (_active < _maximum && visited-- > 0 && _roundRobin.First is { } node)
{
var group = node.Value;
_roundRobin.RemoveFirst(); group.Node = _roundRobin.AddLast(group);
var waiter = group.Queue.First!.Value;
_principals.TryGetValue(group.Principal, out var activeForPrincipal);
if (activeForPrincipal >= _perPrincipal) continue;
// Preserve the oldest principal's turn rather than starving a large reservation
// behind an unlimited stream of smaller ones.
if (waiter.Bytes > _maximumBytes - _bytes)
{
_roundRobin.Remove(group.Node!); group.Node = _roundRobin.AddFirst(group); break;
}
RemoveWaiter(waiter);
if (!TryReserveCore(group.Principal, waiter.Bytes, out var lease)) throw new InvalidOperationException("Invalid transport reservation state.");
waiter.Completion.TrySetResult(lease);
visited = _roundRobin.Count;
}
}
private void Release(string principal, long bytes)
{
lock (_gate)
{
var count = _principals[principal] - 1;
if (count == 0) _principals.Remove(principal); else _principals[principal] = count;
_active--; _bytes -= bytes;
GrantWaiters();
}
}
private void ReleaseSession(string principal, long bytes)
{
lock (_gate)
{
var count = _sessionsByPrincipal[principal] - 1;
if (count == 0) _sessionsByPrincipal.Remove(principal); else _sessionsByPrincipal[principal] = count;
_sessions--; _bytes -= bytes;
GrantWaiters();
}
}
private void ReleaseInterest(string principal, long bytes)
{
lock (_gate)
{
var count = _interestsByPrincipal[principal] - 1;
if (count == 0) _interestsByPrincipal.Remove(principal); else _interestsByPrincipal[principal] = count;
_interests--; _bytes -= bytes;
GrantWaiters();
}
}
}
@@ -0,0 +1,131 @@
using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections;
namespace ZB.MOM.WW.OtOpcUa.Runtime.DataConnections;
/// <summary>A sharing boundary, established only after independently authorizing the view.</summary>
internal sealed record DemandSharingKey(BackingSourceKey Source, DataTarget Target, DataConsistency Consistency,
string PrincipalId, string ExportScope, long CatalogEpoch, long AuthorityEpoch);
internal sealed record UpstreamDemandState(int InterestCount, DataSubscriptionSettings Desired,
long DesiredRevision, long AppliedRevision, long AppliedBoundary);
/// <summary>Bounded demand accounting. It does not itself establish a physical driver subscription.</summary>
internal sealed class UpstreamDemandRegistry
{
private readonly object _gate = new();
private readonly int _maxKeys, _maxInterests;
private readonly Dictionary<DemandSharingKey, Entry> _entries = new(new KeyComparer());
private long _nextInterest, _nextRevision;
private int _interestCount;
private sealed class Entry
{
internal readonly Dictionary<long, DataSubscriptionSettings> Interests = new();
internal readonly CountedValues<TimeSpan> SamplingIntervals = new();
internal readonly CountedValues<TimeSpan> PublishingIntervals = new();
internal readonly CountedValues<DataChangeTrigger> Triggers = new();
internal DataSubscriptionSettings Desired = null!;
internal long Revision, Applied, Boundary;
internal void Add(DataSubscriptionSettings settings)
{
SamplingIntervals.Add(settings.SamplingInterval);
PublishingIntervals.Add(settings.PublishingInterval);
Triggers.Add(settings.Trigger);
}
internal void Remove(DataSubscriptionSettings settings)
{
SamplingIntervals.Remove(settings.SamplingInterval);
PublishingIntervals.Remove(settings.PublishingInterval);
Triggers.Remove(settings.Trigger);
}
}
// Track multiplicity separately so duplicate extrema survive until their last interest leaves.
private sealed class CountedValues<T> where T : notnull
{
private readonly Dictionary<T, int> _counts = new();
private readonly SortedSet<T> _values = new();
internal T Min => _values.Min!;
internal T Max => _values.Max!;
internal void Add(T value)
{
if (_counts.TryGetValue(value, out var count)) _counts[value] = count + 1;
else { _counts.Add(value, 1); _values.Add(value); }
}
internal void Remove(T value)
{
var count = _counts[value];
if (count > 1) _counts[value] = count - 1;
else { _counts.Remove(value); _values.Remove(value); }
}
}
private sealed class KeyComparer : IEqualityComparer<DemandSharingKey>
{
public bool Equals(DemandSharingKey? a, DemandSharingKey? b) => ReferenceEquals(a, b) || a is not null && b is not null &&
a.Source == b.Source && a.Target == b.Target && a.Consistency == b.Consistency &&
StringComparer.OrdinalIgnoreCase.Equals(a.PrincipalId, b.PrincipalId) && a.ExportScope == b.ExportScope &&
a.CatalogEpoch == b.CatalogEpoch && a.AuthorityEpoch == b.AuthorityEpoch;
public int GetHashCode(DemandSharingKey key) => HashCode.Combine(key.Source, key.Target, key.Consistency,
StringComparer.OrdinalIgnoreCase.GetHashCode(key.PrincipalId), key.ExportScope, key.CatalogEpoch, key.AuthorityEpoch);
}
private sealed class Lease(UpstreamDemandRegistry owner, DemandSharingKey key, long id) : IDisposable
{
private UpstreamDemandRegistry? _owner = owner;
public void Dispose() => Interlocked.Exchange(ref _owner, null)?.Remove(key, id);
}
internal UpstreamDemandRegistry(int maxKeys, int maxInterests)
{
if (maxKeys <= 0 || maxInterests <= 0) throw new ArgumentOutOfRangeException(nameof(maxKeys));
_maxKeys = maxKeys; _maxInterests = maxInterests;
}
internal bool TryAdd(DemandSharingKey key, DataSubscriptionSettings settings, out IDisposable? lease)
{
ArgumentNullException.ThrowIfNull(key); ArgumentNullException.ThrowIfNull(settings);
key.Target.Validate(); DataContractValidation.Required(key.Consistency); settings.Validate();
ArgumentException.ThrowIfNullOrWhiteSpace(key.PrincipalId); ArgumentException.ThrowIfNullOrWhiteSpace(key.ExportScope);
if (key.CatalogEpoch <= 0 || key.AuthorityEpoch <= 0) throw new ArgumentOutOfRangeException(nameof(key));
lease = null;
lock (_gate)
{
if (_interestCount >= _maxInterests || (!_entries.ContainsKey(key) && _entries.Count >= _maxKeys)) return false;
if (!_entries.TryGetValue(key, out var entry)) _entries.Add(key, entry = new Entry());
var id = checked(++_nextInterest);
entry.Interests.Add(id, settings); entry.Add(settings); _interestCount++;
Update(entry);
lease = new Lease(this, key, id); return true;
}
}
internal UpstreamDemandState? GetState(DemandSharingKey key)
{
lock (_gate) return _entries.TryGetValue(key, out var e)
? new(e.Interests.Count, e.Desired, e.Revision, e.Applied, e.Boundary) : null;
}
internal bool TryAcknowledge(DemandSharingKey key, long revision, DataSubscriptionSettings effective, long boundary)
{
ArgumentNullException.ThrowIfNull(effective); effective.Validate();
lock (_gate)
{
if (!_entries.TryGetValue(key, out var e) || revision != e.Revision || boundary <= 0 ||
effective.SamplingInterval > e.Desired.SamplingInterval || effective.PublishingInterval > e.Desired.PublishingInterval ||
(int)effective.Trigger < (int)e.Desired.Trigger || effective.Deadband is not null) return false;
e.Applied = revision; e.Boundary = boundary; return true;
}
}
private void Remove(DemandSharingKey key, long id)
{
lock (_gate)
{
if (!_entries.TryGetValue(key, out var e) || !e.Interests.Remove(id, out var settings)) return;
e.Remove(settings);
_interestCount--;
if (e.Interests.Count == 0) _entries.Remove(key); else Update(e);
}
}
private void Update(Entry e)
{
var desired = new DataSubscriptionSettings(e.SamplingIntervals.Min, e.PublishingIntervals.Min, e.Triggers.Max, null);
if (e.Revision == 0 || e.Desired != desired) { e.Desired = desired; e.Revision = checked(++_nextRevision); }
}
}
@@ -60,6 +60,43 @@ namespace ZB.MOM.WW.OtOpcUa.Runtime.Drivers;
/// </summary>
public sealed class DriverHostActor : ReceiveActor, IWithTimers, IWithUnboundedStash
{
/// <summary>Replace the bounded physical gRPC interest for one driver; empty removes it.</summary>
public sealed record ApplyAcquisitionDemand(string DriverInstanceId, IReadOnlyList<string> FullReferences,
TimeSpan SamplingInterval, long DesiredRevision, long OwnerGeneration = 0, long KeyGeneration = 0);
internal sealed record RegisterAcquisitionOwner(Guid OwnerId, long OwnerSerial);
internal sealed record AcquisitionOwnerRegistered(bool Succeeded, long Generation);
internal sealed record OpenAcquisitionDemand(string DriverInstanceId, long OwnerGeneration, long RequestedKeyGeneration = 0);
internal sealed record AcquisitionDemandOpened(bool Succeeded, long KeyGeneration,
bool OwnerInvalid = false, bool StaleGeneration = false);
internal sealed record AbortOpenAcquisitionDemand(string DriverInstanceId, long OwnerGeneration, long KeyGeneration);
internal sealed record AcquisitionOpenAborted(bool Succeeded, bool OwnerInvalid = false);
internal sealed record GateOpenReplyForTest(string DriverInstanceId, TaskCompletionSource Allocated, Task Release);
internal sealed record OpenReplyGateInstalledForTest;
internal sealed record GateAbortReplyForTest(string DriverInstanceId, TaskCompletionSource Processed, Task Release);
internal sealed record AbortReplyGateInstalledForTest;
internal sealed record GetOpenAcquisitionCountForTest;
internal sealed record OpenAcquisitionCountForTest(int Count);
internal sealed record CrashForTest;
internal sealed record SetLegacySubscriptionsForTest(string DriverInstanceId, IReadOnlyList<string> ValueReferences,
IReadOnlyList<string> AlarmReferences);
internal sealed record LegacySubscriptionsTestApplied;
private sealed record AcquisitionApplyCompleted(HostDemandPending Pending, DriverInstanceActor.AcquisitionDemandApplied Result);
private sealed record AcquisitionRetryReady(string DriverInstanceId, long Revision, long OwnerGeneration, long KeyGeneration, bool Succeeded);
private sealed record ActiveAcquisitionDemand(IReadOnlyList<string> References, TimeSpan Interval, long Revision);
private sealed record HostDemandPending(ApplyAcquisitionDemand Request, IActorRef Child, IActorRef ReplyTo,
DriverInstanceActor.SetDesiredSubscriptions Sent, CancellationTokenSource Stop, TaskCompletionSource<bool> Idle);
private readonly Dictionary<string, ActiveAcquisitionDemand> _acquisitionDemands = new(StringComparer.Ordinal);
private readonly Dictionary<string, HostDemandPending> _acquisitionPending = new(StringComparer.Ordinal);
private readonly Dictionary<string, long> _acquisitionRevisions = new(StringComparer.Ordinal);
private readonly Dictionary<string, long> _acquisitionKeyGenerations = new(StringComparer.Ordinal);
private Guid _acquisitionOwnerId;
private long _acquisitionOwnerSerial, _acquisitionOwnerGeneration;
private long _retiredAcquisitionKeyFloor;
private readonly long _acquisitionHostGeneration;
private GateOpenReplyForTest? _openReplyGateForTest;
private GateAbortReplyForTest? _abortReplyGateForTest;
private readonly HashSet<string> _acquisitionRetryWaiting = new(StringComparer.Ordinal);
private readonly SubscriptionAcquisitionCapacity? _acquisitionCapacity;
public const string DeploymentsTopic = "deployments";
public const string DeploymentAcksTopic = "deployment-acks";
public const string DriverControlTopic = ZB.MOM.WW.OtOpcUa.Commons.Messages.Admin.DriverControlTopic.Name;
@@ -801,7 +838,8 @@ public sealed class DriverHostActor : ReceiveActor, IWithTimers, IWithUnboundedS
bool enforceSnapshotOrdering = false,
ZB.MOM.WW.OtOpcUa.Runtime.DataConnections.SourceSamplePublisher? sourcePublisher = null,
ZB.MOM.WW.OtOpcUa.Runtime.DataConnections.LocalCatalogCoordinator? catalogCoordinator = null,
DataWriteRuntime? dataWriteRuntime = null) =>
DataWriteRuntime? dataWriteRuntime = null,
SubscriptionAcquisitionCapacity? acquisitionCapacity = null) =>
// WARNING: this forwarding list is POSITIONAL, and Props.Create compiles it into an
// expression tree. Six IActorRef? parameters and several interface-typed ones mean a
// mis-ordered argument is usually type-compatible and therefore compiles clean, then binds
@@ -816,7 +854,7 @@ public sealed class DriverHostActor : ReceiveActor, IWithTimers, IWithUnboundedS
sharesHistorizationScopeWithLocal, applyWedgeTimeout, reprovisionBackoff, commsRecoveryAuditDelay,
sharesAlarmQueueWithLocal, applyOutcomeTimeout, captureWhilePrimaryUnreachable, historyUpdateRoleView,
scripting, ackPreflightView, writeBounds, writeClock, scriptedAlarmRunner, childShutdownTimeout,
enforceSnapshotOrdering, sourcePublisher, catalogCoordinator, dataWriteRuntime));
enforceSnapshotOrdering, sourcePublisher, catalogCoordinator, dataWriteRuntime, acquisitionCapacity));
/// <summary>Initializes a new DriverHostActor with the specified dependencies.</summary>
/// <param name="dbFactory">Database context factory for configuration database access.</param>
@@ -955,9 +993,12 @@ public sealed class DriverHostActor : ReceiveActor, IWithTimers, IWithUnboundedS
bool enforceSnapshotOrdering = false,
ZB.MOM.WW.OtOpcUa.Runtime.DataConnections.SourceSamplePublisher? sourcePublisher = null,
ZB.MOM.WW.OtOpcUa.Runtime.DataConnections.LocalCatalogCoordinator? catalogCoordinator = null,
DataWriteRuntime? dataWriteRuntime = null)
DataWriteRuntime? dataWriteRuntime = null,
SubscriptionAcquisitionCapacity? acquisitionCapacity = null)
{
_dataWriteRuntime = dataWriteRuntime;
_acquisitionCapacity = acquisitionCapacity;
_acquisitionHostGeneration = acquisitionCapacity?.NextControlGeneration() ?? 0;
_sourcePublisher = sourcePublisher;
_catalogCoordinator = catalogCoordinator;
_snapshotOrdering = enforceSnapshotOrdering ? new SnapshotRevisionGate() : null;
@@ -1641,6 +1682,18 @@ public sealed class DriverHostActor : ReceiveActor, IWithTimers, IWithUnboundedS
private void Steady()
{
Receive<RegisterAcquisitionOwner>(OnRegisterAcquisitionOwner);
Receive<OpenAcquisitionDemand>(OnOpenAcquisitionDemand);
Receive<AbortOpenAcquisitionDemand>(OnAbortOpenAcquisitionDemand);
Receive<GateOpenReplyForTest>(OnGateOpenReplyForTest);
Receive<GateAbortReplyForTest>(OnGateAbortReplyForTest);
Receive<GetOpenAcquisitionCountForTest>(_ => Sender.Tell(new OpenAcquisitionCountForTest(_acquisitionKeyGenerations.Count)));
Receive<CrashForTest>(_ => throw new InvalidOperationException("test host restart"));
Receive<ApplyAcquisitionDemand>(HandleAcquisitionDemand);
Receive<AcquisitionApplyCompleted>(OnAcquisitionApplyCompleted);
Receive<AcquisitionRetryReady>(OnAcquisitionRetryReady);
Receive<SetLegacySubscriptionsForTest>(OnSetLegacySubscriptionsForTest);
Receive<DriverInstanceActor.AcquisitionDemandApplied>(_ => { });
Receive<DispatchDeployment>(HandleDispatchFromSteady);
// The held Applied ack is released by the address-space outcome (or its timeout); both can
// land in any behaviour, so all three register them.
@@ -1678,6 +1731,18 @@ public sealed class DriverHostActor : ReceiveActor, IWithTimers, IWithUnboundedS
private void Applying()
{
Receive<RegisterAcquisitionOwner>(OnRegisterAcquisitionOwner);
Receive<OpenAcquisitionDemand>(OnOpenAcquisitionDemand);
Receive<AbortOpenAcquisitionDemand>(OnAbortOpenAcquisitionDemand);
Receive<GateOpenReplyForTest>(OnGateOpenReplyForTest);
Receive<GateAbortReplyForTest>(OnGateAbortReplyForTest);
Receive<GetOpenAcquisitionCountForTest>(_ => Sender.Tell(new OpenAcquisitionCountForTest(_acquisitionKeyGenerations.Count)));
Receive<CrashForTest>(_ => throw new InvalidOperationException("test host restart"));
Receive<ApplyAcquisitionDemand>(HandleAcquisitionDemand);
Receive<AcquisitionApplyCompleted>(OnAcquisitionApplyCompleted);
Receive<AcquisitionRetryReady>(OnAcquisitionRetryReady);
Receive<SetLegacySubscriptionsForTest>(OnSetLegacySubscriptionsForTest);
Receive<DriverInstanceActor.AcquisitionDemandApplied>(_ => { });
Receive<DispatchDeployment>(msg =>
{
if (_applyingDeploymentId is not null && msg.DeploymentId == _applyingDeploymentId.Value)
@@ -1878,6 +1943,9 @@ public sealed class DriverHostActor : ReceiveActor, IWithTimers, IWithUnboundedS
/// </summary>
private void OnDriverConnectivityChanged(DriverInstanceActor.ConnectivityChanged msg)
{
if (msg.Connected && _acquisitionDemands.ContainsKey(msg.DriverInstanceId) &&
_children.TryGetValue(msg.DriverInstanceId, out var activeChild) && Equals(activeChild.Actor, Sender))
SendDesiredSubscriptions(activeChild.Actor, msg.DriverInstanceId);
// The mux fan-out is independent of the OPC UA sink — a node with scripted alarms but no
// publish actor (the mux-only test/dev path) must still see comms loss. Done before the early
// return for exactly that reason.
@@ -2748,6 +2816,13 @@ public sealed class DriverHostActor : ReceiveActor, IWithTimers, IWithUnboundedS
private void Stale()
{
Receive<ApplyAcquisitionDemand>(HandleAcquisitionDemand);
Receive<AcquisitionApplyCompleted>(OnAcquisitionApplyCompleted);
Receive<AcquisitionRetryReady>(OnAcquisitionRetryReady);
Receive<RegisterAcquisitionOwner>(OnRegisterAcquisitionOwner);
Receive<OpenAcquisitionDemand>(OnOpenAcquisitionDemand);
Receive<AbortOpenAcquisitionDemand>(OnAbortOpenAcquisitionDemand);
Receive<CrashForTest>(_ => throw new InvalidOperationException("test host restart"));
// lmxopcua#765: a native ack routed here while Stale is dropped before the projector records it, so it
// could not be reverted and the node would show Acknowledged for an ack no driver saw. Refuse it
// synchronously at the node manager instead (cleared by BecomeSteady, the only way out of Stale).
@@ -4050,13 +4125,306 @@ public sealed class DriverHostActor : ReceiveActor, IWithTimers, IWithUnboundedS
/// <param name="driverId">The driver instance whose set to send.</param>
/// <returns>The value-ref count, for the bulk loop's log total.</returns>
private int SendDesiredSubscriptions(IActorRef actor, string driverId)
{
var demand = _acquisitionDemands.GetValueOrDefault(driverId);
var message = BuildDesiredSubscriptions(driverId, demand);
if (demand is null) actor.Tell(message);
else if (!_acquisitionPending.ContainsKey(driverId)) StartAcquisitionDemand(driverId, demand, ActorRefs.Nobody);
return message.FullReferences.Count;
}
private void OnSetLegacySubscriptionsForTest(SetLegacySubscriptionsForTest message)
{
_desiredByDriver[message.DriverInstanceId] = new DesiredSubscriptionSet(message.ValueReferences, message.AlarmReferences);
if (_children.TryGetValue(message.DriverInstanceId, out var child))
SendDesiredSubscriptions(child.Actor, message.DriverInstanceId);
Sender.Tell(new LegacySubscriptionsTestApplied());
}
private void OnRegisterAcquisitionOwner(RegisterAcquisitionOwner message)
{
if (_acquisitionCapacity is null || message.OwnerId == Guid.Empty || message.OwnerSerial <= 0 ||
message.OwnerSerial != _acquisitionCapacity.CurrentOwnerSerial || message.OwnerSerial < _acquisitionOwnerSerial ||
(message.OwnerSerial == _acquisitionOwnerSerial && message.OwnerId != _acquisitionOwnerId))
{
Sender.Tell(new AcquisitionOwnerRegistered(false, 0));
return;
}
if (message.OwnerSerial == _acquisitionOwnerSerial && _acquisitionOwnerGeneration > 0)
{
Sender.Tell(new AcquisitionOwnerRegistered(true, _acquisitionOwnerGeneration));
return;
}
var previous = _acquisitionDemands.Keys.ToArray();
_acquisitionDemands.Clear();
_acquisitionRevisions.Clear();
_acquisitionKeyGenerations.Clear();
_retiredAcquisitionKeyFloor = 0;
foreach (var pending in _acquisitionPending.Values) pending.Stop.Cancel();
_acquisitionOwnerId = message.OwnerId;
_acquisitionOwnerSerial = message.OwnerSerial;
_acquisitionOwnerGeneration = _acquisitionCapacity.NextControlGeneration();
if (_acquisitionOwnerGeneration <= _acquisitionHostGeneration) throw new InvalidOperationException("Invalid host generation.");
foreach (var id in previous)
if (_children.TryGetValue(id, out var child)) SendDesiredSubscriptions(child.Actor, id);
Sender.Tell(new AcquisitionOwnerRegistered(true, _acquisitionOwnerGeneration));
}
private void OnOpenAcquisitionDemand(OpenAcquisitionDemand message)
{
if (_acquisitionCapacity is null || message.OwnerGeneration <= 0 || message.OwnerGeneration != _acquisitionOwnerGeneration)
{
Sender.Tell(new AcquisitionDemandOpened(false, 0, OwnerInvalid: true));
return;
}
if (string.IsNullOrWhiteSpace(message.DriverInstanceId) || message.RequestedKeyGeneration < 0 ||
message.RequestedKeyGeneration > _acquisitionCapacity.ControlGeneration)
{
Sender.Tell(new AcquisitionDemandOpened(false, 0));
return;
}
if (_acquisitionKeyGenerations.TryGetValue(message.DriverInstanceId, out var key))
{
if (message.RequestedKeyGeneration != 0 && message.RequestedKeyGeneration != key)
{
Sender.Tell(new AcquisitionDemandOpened(false, 0));
return;
}
}
else
{
if (_acquisitionKeyGenerations.Count >= _acquisitionCapacity.MaxReservations)
{
Sender.Tell(new AcquisitionDemandOpened(false, 0));
return;
}
key = message.RequestedKeyGeneration == 0 ? _acquisitionCapacity.NextControlGeneration() : message.RequestedKeyGeneration;
if (key <= _retiredAcquisitionKeyFloor)
{
Sender.Tell(new AcquisitionDemandOpened(false, 0, StaleGeneration: true));
return;
}
_acquisitionKeyGenerations.Add(message.DriverInstanceId, key);
}
var reply = new AcquisitionDemandOpened(true, key);
if (_openReplyGateForTest is { } gate && gate.DriverInstanceId == message.DriverInstanceId)
{
_openReplyGateForTest = null;
var recipient = Sender;
gate.Allocated.TrySetResult();
_ = gate.Release.ContinueWith(_ => recipient.Tell(reply), CancellationToken.None,
TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default);
}
else Sender.Tell(reply);
}
private void OnAbortOpenAcquisitionDemand(AbortOpenAcquisitionDemand message)
{
if (_acquisitionCapacity is null || message.OwnerGeneration <= 0 || message.OwnerGeneration != _acquisitionOwnerGeneration)
{
Sender.Tell(new AcquisitionOpenAborted(false, OwnerInvalid: true));
return;
}
if (string.IsNullOrWhiteSpace(message.DriverInstanceId) || message.KeyGeneration <= 0 ||
message.KeyGeneration > _acquisitionCapacity.ControlGeneration)
{
Sender.Tell(new AcquisitionOpenAborted(false));
return;
}
_retiredAcquisitionKeyFloor = Math.Max(_retiredAcquisitionKeyFloor, message.KeyGeneration);
if (_acquisitionKeyGenerations.TryGetValue(message.DriverInstanceId, out var key) && key == message.KeyGeneration)
{
_acquisitionKeyGenerations.Remove(message.DriverInstanceId);
var hadDemand = _acquisitionDemands.Remove(message.DriverInstanceId);
_acquisitionRevisions.Remove(message.DriverInstanceId);
if (hadDemand && _children.TryGetValue(message.DriverInstanceId, out var child))
SendDesiredSubscriptions(child.Actor, message.DriverInstanceId);
}
var reply = new AcquisitionOpenAborted(true);
if (_abortReplyGateForTest is { } gate && gate.DriverInstanceId == message.DriverInstanceId)
{
_abortReplyGateForTest = null;
var recipient = Sender;
gate.Processed.TrySetResult();
_ = gate.Release.ContinueWith(_ => recipient.Tell(reply), CancellationToken.None,
TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default);
}
else Sender.Tell(reply);
}
private void OnGateAbortReplyForTest(GateAbortReplyForTest message)
{
if (_abortReplyGateForTest is not null) throw new InvalidOperationException("An Abort test gate is already installed.");
_abortReplyGateForTest = message;
Sender.Tell(new AbortReplyGateInstalledForTest());
}
private void OnGateOpenReplyForTest(GateOpenReplyForTest message)
{
if (_openReplyGateForTest is not null) throw new InvalidOperationException("An Open test gate is already installed.");
_openReplyGateForTest = message;
Sender.Tell(new OpenReplyGateInstalledForTest());
}
private DriverInstanceActor.SetDesiredSubscriptions BuildDesiredSubscriptions(string driverId, ActiveAcquisitionDemand? demand)
{
var set = _desiredByDriver.TryGetValue(driverId, out var s)
? s
: new DesiredSubscriptionSet(Array.Empty<string>(), Array.Empty<string>());
actor.Tell(new DriverInstanceActor.SetDesiredSubscriptions(
set.ValueRefs, SubscriptionPublishingInterval, set.AlarmRefs));
return set.ValueRefs.Count;
? s : new DesiredSubscriptionSet(Array.Empty<string>(), Array.Empty<string>());
if (demand is null) return new(set.ValueRefs, SubscriptionPublishingInterval, set.AlarmRefs);
var refs = set.ValueRefs.Concat(demand.References).Distinct(StringComparer.Ordinal).ToArray();
var interval = demand.Interval < SubscriptionPublishingInterval ? demand.Interval : SubscriptionPublishingInterval;
var incarnation = _children.TryGetValue(driverId, out var entry) ? entry.SourceIncarnation ?? 0 : 0;
return new(refs, interval, set.AlarmRefs, demand.Revision, incarnation, true);
}
private void HandleAcquisitionDemand(ApplyAcquisitionDemand request)
{
var id = request.DriverInstanceId;
var replyTo = Sender;
if (request.OwnerGeneration != _acquisitionOwnerGeneration ||
(request.OwnerGeneration == 0 && request.KeyGeneration != 0))
{
replyTo.Tell(new DriverInstanceActor.AcquisitionDemandApplied(request.DesiredRevision, 0, TimeSpan.Zero, false, OwnerInvalid: true));
return;
}
if (request.OwnerGeneration != 0 &&
(!_acquisitionKeyGenerations.TryGetValue(id, out var key) || request.KeyGeneration != key))
{
replyTo.Tell(new DriverInstanceActor.AcquisitionDemandApplied(request.DesiredRevision, 0, TimeSpan.Zero, false, KeyInvalid: true));
return;
}
if (request.DesiredRevision <= 0 || _acquisitionCapacity is null ||
(!_acquisitionRevisions.ContainsKey(id) && _acquisitionRevisions.Count >= _acquisitionCapacity.MaxReservations) ||
(_acquisitionRevisions.TryGetValue(id, out var last) && request.DesiredRevision < last))
{
replyTo.Tell(new DriverInstanceActor.AcquisitionDemandApplied(request.DesiredRevision, 0, TimeSpan.Zero, false));
return;
}
if (_acquisitionRevisions.TryGetValue(id, out last) && request.DesiredRevision == last && request.FullReferences.Count > 0 &&
(!_acquisitionDemands.TryGetValue(id, out var prior) ||
!prior.References.SequenceEqual(request.FullReferences, StringComparer.Ordinal) || prior.Interval != request.SamplingInterval))
{
replyTo.Tell(new DriverInstanceActor.AcquisitionDemandApplied(request.DesiredRevision, 0, TimeSpan.Zero, false));
return;
}
if (_acquisitionRevisions.TryGetValue(id, out last) && request.DesiredRevision == last &&
request.FullReferences.Count == 0 && _acquisitionDemands.ContainsKey(id))
{
replyTo.Tell(new DriverInstanceActor.AcquisitionDemandApplied(request.DesiredRevision, 0, TimeSpan.Zero, false));
return;
}
_acquisitionRevisions[id] = request.DesiredRevision;
if (request.FullReferences.Count == 0)
{
_acquisitionDemands.Remove(id);
_acquisitionRevisions.Remove(id);
if (request.OwnerGeneration != 0)
{
_acquisitionKeyGenerations.Remove(id);
_retiredAcquisitionKeyFloor = Math.Max(_retiredAcquisitionKeyFloor, request.KeyGeneration);
}
if (_children.TryGetValue(id, out var existing)) SendDesiredSubscriptions(existing.Actor, id);
replyTo.Tell(new DriverInstanceActor.AcquisitionDemandApplied(request.DesiredRevision,
_children.GetValueOrDefault(id)?.SourceIncarnation ?? 0, TimeSpan.Zero, true));
return;
}
var demand = new ActiveAcquisitionDemand(request.FullReferences.ToArray(), request.SamplingInterval, request.DesiredRevision);
_acquisitionDemands[id] = demand;
if (_acquisitionPending.TryGetValue(id, out var pending))
{
replyTo.Tell(new DriverInstanceActor.AcquisitionDemandApplied(request.DesiredRevision,
_children.GetValueOrDefault(id)?.SourceIncarnation ?? 0, TimeSpan.Zero, false, true, pending.Idle.Task));
return;
}
StartAcquisitionDemand(id, demand, replyTo);
}
private void StartAcquisitionDemand(string id, ActiveAcquisitionDemand demand, IActorRef replyTo)
{
if (_acquisitionPending.ContainsKey(id)) return;
if (!_children.TryGetValue(id, out var child) || child.Stubbed || child.SourceIncarnation is not { } incarnation)
{
replyTo.Tell(new DriverInstanceActor.AcquisitionDemandApplied(demand.Revision, 0, TimeSpan.Zero, false));
return;
}
var message = BuildDesiredSubscriptions(id, demand);
var request = new ApplyAcquisitionDemand(id, demand.References, demand.Interval, demand.Revision,
_acquisitionOwnerGeneration, _acquisitionKeyGenerations.GetValueOrDefault(id));
var stop = new CancellationTokenSource();
var pending = new HostDemandPending(request, child.Actor, replyTo, message, stop,
new TaskCompletionSource<bool>(TaskCreationOptions.RunContinuationsAsynchronously));
_acquisitionPending.Add(id, pending);
var self = Self;
_ = child.Actor.Ask<DriverInstanceActor.AcquisitionDemandApplied>(message, TimeSpan.FromSeconds(15), stop.Token)
.ContinueWith(t => self.Tell(new AcquisitionApplyCompleted(pending,
t.Status == TaskStatus.RanToCompletion ? t.Result :
new DriverInstanceActor.AcquisitionDemandApplied(demand.Revision, incarnation, TimeSpan.Zero, false))),
CancellationToken.None, TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default);
}
private void OnAcquisitionApplyCompleted(AcquisitionApplyCompleted completed)
{
var pending = completed.Pending;
var id = pending.Request.DriverInstanceId;
if (!_acquisitionPending.TryGetValue(id, out var current) || !ReferenceEquals(current, pending)) return;
_acquisitionPending.Remove(id);
pending.Stop.Dispose();
pending.Idle.TrySetResult(true);
if (pending.Request.OwnerGeneration != _acquisitionOwnerGeneration ||
(pending.Request.OwnerGeneration != 0 &&
(!_acquisitionKeyGenerations.TryGetValue(id, out var activeKey) || activeKey != pending.Request.KeyGeneration)))
{
pending.ReplyTo.Tell(completed.Result with { Succeeded = false });
if (_acquisitionDemands.TryGetValue(id, out var newer)) StartAcquisitionDemand(id, newer, ActorRefs.Nobody);
return;
}
if (!_acquisitionDemands.TryGetValue(id, out var desired))
{
pending.ReplyTo.Tell(completed.Result with { Succeeded = false, Busy = false, RetryWhenReady = null });
return;
}
if (desired.Revision != pending.Request.DesiredRevision)
{
pending.ReplyTo.Tell(completed.Result with { Succeeded = false, Busy = false, RetryWhenReady = null });
StartAcquisitionDemand(id, desired, ActorRefs.Nobody);
return;
}
if (!_children.TryGetValue(id, out var child) || !Equals(child.Actor, pending.Child))
{
StartAcquisitionDemand(id, desired, pending.ReplyTo);
return;
}
if (completed.Result.Busy && completed.Result.RetryWhenReady is { } ready)
{
pending.ReplyTo.Tell(completed.Result);
if (_acquisitionRetryWaiting.Add(id))
{
var self = Self;
_ = ready.ContinueWith(t => self.Tell(new AcquisitionRetryReady(id, desired.Revision,
pending.Request.OwnerGeneration, pending.Request.KeyGeneration,
t.Status == TaskStatus.RanToCompletion && t.Result)), CancellationToken.None,
TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default);
}
return;
}
var latest = BuildDesiredSubscriptions(id, desired);
if (completed.Result.Succeeded &&
(!latest.FullReferences.SequenceEqual(pending.Sent.FullReferences, StringComparer.Ordinal) ||
!(latest.AlarmReferences ?? Array.Empty<string>()).SequenceEqual(pending.Sent.AlarmReferences ?? Array.Empty<string>(), StringComparer.Ordinal) ||
latest.PublishingInterval != pending.Sent.PublishingInterval || latest.ProducerIncarnation != pending.Sent.ProducerIncarnation))
{
StartAcquisitionDemand(id, desired, pending.ReplyTo);
return;
}
pending.ReplyTo.Tell(completed.Result);
}
private void OnAcquisitionRetryReady(AcquisitionRetryReady ready)
{
_acquisitionRetryWaiting.Remove(ready.DriverInstanceId);
if (ready.Succeeded && _acquisitionDemands.TryGetValue(ready.DriverInstanceId, out var desired) &&
!_acquisitionPending.ContainsKey(ready.DriverInstanceId))
StartAcquisitionDemand(ready.DriverInstanceId, desired, ActorRefs.Nobody);
}
private void SpawnChild(DriverInstanceSpec spec, bool deferSubscriptions = false)
@@ -4113,12 +4481,13 @@ public sealed class DriverHostActor : ReceiveActor, IWithTimers, IWithUnboundedS
reconnectInterval: null,
startStubbed: true,
healthPublisher: _healthPublisher,
clusterId: clusterId, sourcePublisher: _sourcePublisher, sourceIncarnation: sourceIncarnation)
clusterId: clusterId, sourcePublisher: _sourcePublisher, sourceIncarnation: sourceIncarnation,
acquisitionCapacity: _acquisitionCapacity)
: DriverInstanceActor.PropsForRichWrites(new StubbedDriver(spec.DriverInstanceId, spec.DriverType),
startStubbed: true, healthPublisher: _healthPublisher, clusterId: clusterId,
sourcePublisher: _sourcePublisher, sourceIncarnation: sourceIncarnation,
writeDispatchGate: _dataWriteRuntime.Gate, lateWriteObserver: _dataWriteRuntime.Observer,
writeRouteState: _dataWriteRuntime.Routes),
writeRouteState: _dataWriteRuntime.Routes, acquisitionCapacity: _acquisitionCapacity),
actorName);
}
else
@@ -4137,12 +4506,13 @@ public sealed class DriverHostActor : ReceiveActor, IWithTimers, IWithUnboundedS
writeTimeout: _writeBounds.Timeout,
writeClock: _writeClock,
shutdownTimeout: _childShutdownTimeout,
sourcePublisher: _sourcePublisher, sourceIncarnation: sourceIncarnation)
sourcePublisher: _sourcePublisher, sourceIncarnation: sourceIncarnation, acquisitionCapacity: _acquisitionCapacity)
: DriverInstanceActor.PropsForRichWrites(driver!, healthPublisher: _healthPublisher, clusterId: clusterId,
invoker: invoker, writeTimeout: _writeBounds.Timeout, writeClock: _writeClock,
shutdownTimeout: _childShutdownTimeout, sourcePublisher: _sourcePublisher,
sourceIncarnation: sourceIncarnation, writeDispatchGate: _dataWriteRuntime.Gate,
lateWriteObserver: _dataWriteRuntime.Observer, writeRouteState: _dataWriteRuntime.Routes),
lateWriteObserver: _dataWriteRuntime.Observer, writeRouteState: _dataWriteRuntime.Routes,
acquisitionCapacity: _acquisitionCapacity),
actorName);
child.Tell(new DriverInstanceActor.InitializeRequested(spec.DriverConfig));
}
@@ -4264,6 +4634,8 @@ public sealed class DriverHostActor : ReceiveActor, IWithTimers, IWithUnboundedS
/// <param name="child">The child being stopped.</param>
private void RetireChild(IActorRef child)
{
foreach (var pending in _acquisitionPending.Values)
if (Equals(pending.Child, child)) pending.Stop.Cancel();
_retiredChildren.Add(child);
Context.Watch(child);
}
@@ -18,6 +18,70 @@ file sealed class HealthPollTick
private HealthPollTick() { }
}
/// <summary>Process-lifetime bound for physical subscription establishments and late cleanup.</summary>
public sealed class SubscriptionAcquisitionCapacity
{
private readonly object _gate = new();
private readonly Dictionary<(string Cluster, string Driver), TaskCompletionSource<bool>> _inFlight = new();
private readonly int _limit;
private long _ownerSerial;
private long _controlGeneration;
/// <summary>Creates a shared capacity with a fixed maximum number of in-flight drivers.</summary>
public SubscriptionAcquisitionCapacity(int limit)
{
if (limit <= 0) throw new ArgumentOutOfRangeException(nameof(limit));
_limit = limit;
}
/// <summary>Number of driver keys held by active subscriptions, establishments, or cleanup.</summary>
public int ReservedDriverCount { get { lock (_gate) return _inFlight.Count; } }
/// <summary>Configured maximum concurrent driver reservations.</summary>
public int MaxReservations => _limit;
/// <summary>Issues a process-lifetime serial for a new bridge owner.</summary>
public long NextOwnerSerial()
{
var serial = Interlocked.Increment(ref _ownerSerial);
return serial > 0 ? serial : throw new InvalidOperationException("Acquisition owner serial exhausted.");
}
/// <summary>Latest issued bridge owner serial.</summary>
public long CurrentOwnerSerial => Interlocked.Read(ref _ownerSerial);
/// <summary>Latest process-lifetime control generation.</summary>
public long ControlGeneration => Interlocked.Read(ref _controlGeneration);
internal long NextControlGeneration()
{
var generation = Interlocked.Increment(ref _controlGeneration);
return generation > 0 ? generation : throw new InvalidOperationException("Acquisition generation exhausted.");
}
internal IDisposable? TryAcquire(string cluster, string driver, out Task<bool>? ready)
{
var key = (cluster.ToUpperInvariant(), driver);
lock (_gate)
{
if (_inFlight.TryGetValue(key, out var existing)) { ready = existing.Task; return null; }
ready = null;
if (_inFlight.Count >= _limit) return null;
var completion = new TaskCompletionSource<bool>(TaskCreationOptions.RunContinuationsAsynchronously);
_inFlight.Add(key, completion);
return new Reservation(this, key, completion);
}
}
private sealed class Reservation(SubscriptionAcquisitionCapacity owner, (string Cluster, string Driver) key,
TaskCompletionSource<bool> completion) : IDisposable
{
private SubscriptionAcquisitionCapacity? _owner = owner;
public void Dispose()
{
var current = Interlocked.Exchange(ref _owner, null);
if (current is null) return;
lock (current._gate) current._inFlight.Remove(key);
completion.TrySetResult(true);
}
}
}
/// <summary>
/// Akka wrapper for a single <see cref="IDriver"/> instance. States:
///
@@ -127,7 +191,12 @@ public sealed class DriverInstanceActor : ReceiveActor, IWithTimers
public sealed record SetDesiredSubscriptions(
IReadOnlyList<string> FullReferences,
TimeSpan PublishingInterval,
IReadOnlyList<string>? AlarmReferences = null);
IReadOnlyList<string>? AlarmReferences = null,
long DesiredRevision = 0, long ProducerIncarnation = 0, bool RequireAcquisition = false);
/// <summary>Physical demand installation result, including the driver-acknowledged fence.</summary>
public sealed record AcquisitionDemandApplied(long DesiredRevision, long ProducerIncarnation,
TimeSpan NominalSamplingInterval, bool Succeeded, bool Busy = false, Task<bool>? RetryWhenReady = null,
bool OwnerInvalid = false, bool KeyInvalid = false);
public sealed record SubscriptionEstablished(string DiagnosticId, int ReferenceCount);
public sealed record SubscriptionFailed(string Reason);
public sealed record Unsubscribe;
@@ -404,6 +473,27 @@ public sealed class DriverInstanceActor : ReceiveActor, IWithTimers
private readonly ZB.MOM.WW.OtOpcUa.Runtime.DataConnections.SourceSamplePublisher? _sourcePublisher;
private long? _sourceIncarnation;
private long _sourceBindingVersion;
private sealed class AcquisitionFence(long revision, long producer)
{
internal readonly long Revision = revision;
internal readonly long Producer = producer;
}
private AcquisitionFence? _activeAcquisition;
private int _acquisitionPending;
private readonly SubscriptionAcquisitionCapacity? _acquisitionCapacity;
private PendingAcquisition? _pendingAcquisition;
private PendingAcquisition? _abandonedAcquisition;
private readonly TimeSpan _acquisitionTimeout;
private readonly TimeProvider _acquisitionClock;
private SharedAcquisitionReservation? _activeCapacity;
private IDisposable? _activeCapacityReference;
private Task<bool>? _previousAcquisitionCleanup;
private bool _fenceLegacyHandles;
private LegacyAdmission? _legacyAdmission;
private SetDesiredSubscriptions? _desiredAcquisition;
private TimeSpan _acquisitionNominal;
private SetDesiredSubscriptions? _deferredLegacyDemand;
private sealed record ResumeDeferredLegacy;
private const int SourceBindingBatchSize = 128;
private EventHandler<AlarmEventArgs>? _alarmEventHandler;
private EventHandler<RediscoveryEventArgs>? _rediscoveryHandler;
@@ -509,7 +599,9 @@ public sealed class DriverInstanceActor : ReceiveActor, IWithTimers
TimeSpan? writeTimeout = null,
TimeProvider? writeClock = null,
ZB.MOM.WW.OtOpcUa.Runtime.DataConnections.SourceSamplePublisher? sourcePublisher = null,
long? sourceIncarnation = null) =>
long? sourceIncarnation = null,
SubscriptionAcquisitionCapacity? acquisitionCapacity = null,
TimeSpan? acquisitionTimeout = null, TimeProvider? acquisitionClock = null) =>
Akka.Actor.Props.Create(() => new DriverInstanceActor(
driver,
reconnectInterval ?? DefaultReconnectInterval,
@@ -524,17 +616,20 @@ public sealed class DriverInstanceActor : ReceiveActor, IWithTimers
queuedWriteBudget,
initializeTimeout,
writeTimeout,
writeClock, sourcePublisher, sourceIncarnation));
writeClock, sourcePublisher, sourceIncarnation, acquisitionCapacity, acquisitionTimeout, acquisitionClock));
internal static Props PropsForRichWrites(IDriver driver, IDriverCapabilityInvoker? invoker = null,
TimeSpan? commsLossTimeout = null, int? maxWritesInFlight = null, TimeSpan? writeTimeout = null,
IWriteDispatchGate? writeDispatchGate = null, LateWriteObserver? lateWriteObserver = null,
WriteRouteState? writeRouteState = null, TimeProvider? writeClock = null,
IDriverHealthPublisher? healthPublisher = null, string? clusterId = null, TimeSpan? shutdownTimeout = null,
SourceSamplePublisher? sourcePublisher = null, long? sourceIncarnation = null, bool startStubbed = false) =>
SourceSamplePublisher? sourcePublisher = null, long? sourceIncarnation = null, bool startStubbed = false,
SubscriptionAcquisitionCapacity? acquisitionCapacity = null,
TimeSpan? acquisitionTimeout = null, TimeProvider? acquisitionClock = null) =>
Akka.Actor.Props.CreateBy(new RichWriteActorProducer(() => new DriverInstanceActor(driver, DefaultReconnectInterval, startStubbed, healthPublisher, clusterId,
invoker, null, commsLossTimeout, shutdownTimeout, maxWritesInFlight, null, null, writeTimeout, writeClock,
sourcePublisher, sourceIncarnation, writeDispatchGate, lateWriteObserver, writeRouteState)));
sourcePublisher, sourceIncarnation, writeDispatchGate, lateWriteObserver, writeRouteState, acquisitionCapacity,
acquisitionTimeout, acquisitionClock)));
private sealed class RichWriteActorProducer(Func<DriverInstanceActor> create) : IIndirectActorProducer
{
@@ -605,10 +700,13 @@ public sealed class DriverInstanceActor : ReceiveActor, IWithTimers
TimeSpan? writeTimeout = null,
TimeProvider? writeClock = null,
ZB.MOM.WW.OtOpcUa.Runtime.DataConnections.SourceSamplePublisher? sourcePublisher = null,
long? sourceIncarnation = null)
long? sourceIncarnation = null,
SubscriptionAcquisitionCapacity? acquisitionCapacity = null,
TimeSpan? acquisitionTimeout = null, TimeProvider? acquisitionClock = null)
: this(driver, reconnectInterval, startStubbed, healthPublisher, clusterId, invoker, healthPollInterval,
commsLossTimeout, shutdownTimeout, maxWritesInFlight, queuedWriteBudget, initializeTimeout,
writeTimeout, writeClock, sourcePublisher, sourceIncarnation, null, null, null) { }
writeTimeout, writeClock, sourcePublisher, sourceIncarnation, null, null, null, acquisitionCapacity,
acquisitionTimeout, acquisitionClock) { }
private DriverInstanceActor(IDriver driver, TimeSpan reconnectInterval, bool startStubbed,
IDriverHealthPublisher? healthPublisher, string? clusterId, IDriverCapabilityInvoker? invoker,
@@ -616,12 +714,16 @@ public sealed class DriverInstanceActor : ReceiveActor, IWithTimers
int? maxWritesInFlight, TimeSpan? queuedWriteBudget, TimeSpan? initializeTimeout,
TimeSpan? writeTimeout, TimeProvider? writeClock, SourceSamplePublisher? sourcePublisher,
long? sourceIncarnation, IWriteDispatchGate? writeDispatchGate, LateWriteObserver? lateWriteObserver,
WriteRouteState? writeRouteState)
WriteRouteState? writeRouteState, SubscriptionAcquisitionCapacity? acquisitionCapacity,
TimeSpan? acquisitionTimeout, TimeProvider? acquisitionClock)
{
_writeDispatchGate = writeDispatchGate;
_lateWriteObserver = lateWriteObserver;
_writeRouteState = writeRouteState;
_sourcePublisher = sourcePublisher;
_acquisitionCapacity = acquisitionCapacity;
_acquisitionTimeout = acquisitionTimeout is { } timeout && timeout > TimeSpan.Zero ? timeout : TimeSpan.FromSeconds(10);
_acquisitionClock = acquisitionClock ?? TimeProvider.System;
_sourceIncarnation = sourceIncarnation;
_writeTimeout = writeTimeout is { } wt && wt > TimeSpan.Zero ? wt : DefaultWriteTimeout;
_writeClock = writeClock ?? TimeProvider.System;
@@ -709,7 +811,7 @@ public sealed class DriverInstanceActor : ReceiveActor, IWithTimers
Receive<DisconnectObserved>(_ => { /* stubbed drivers don't disconnect */ });
Receive<ConnectionLossRaised>(IgnoreConnectionLoss);
Receive<ForceReconnect>(_ => { /* stubbed drivers don't reconnect */ });
Receive<SetDesiredSubscriptions>(StoreDesiredSubscriptions);
Receive<SetDesiredSubscriptions>(StoreDisconnectedDesiredSubscriptions);
// Stubbed drivers never enter Connected, so they never kick discovery; swallow defensively in case a
// re-discovery self-tick is ever routed here so it doesn't surface as an Akka Unhandled message.
Receive<RediscoveryRaised>(HandleRediscoveryRaised);
@@ -755,7 +857,7 @@ public sealed class DriverInstanceActor : ReceiveActor, IWithTimers
Become(Reconnecting);
PublishHealthSnapshot();
});
Receive<SetDesiredSubscriptions>(StoreDesiredSubscriptions);
Receive<SetDesiredSubscriptions>(StoreDisconnectedDesiredSubscriptions);
Receive<ForceReconnect>(_ => { /* already connecting — no-op */ });
Receive<ConnectionLossRaised>(IgnoreConnectionLoss);
// ResubscribeDesired self-Tells Subscribe; HandleSubscribeAsync replies SubscriptionEstablished to the
@@ -812,8 +914,45 @@ public sealed class DriverInstanceActor : ReceiveActor, IWithTimers
ReceiveAsync<Subscribe>(HandleSubscribeAsync);
ReceiveAsync<Unsubscribe>(_ => { CancelSourceBindingRetry(); return UnsubscribeAsync(); });
Receive<RetrySourceBindings>(RetrySourceBindingBatch);
Receive<SetDesiredSubscriptions>(msg =>
ReceiveAsync<SetDesiredSubscriptions>(async msg =>
{
if (msg.RequireAcquisition) { await ApplyAcquisitionDemandAsync(msg, Sender); return; }
if (_abandonedAcquisition is { } abandoned && !abandoned.Finished.IsCompleted)
{
var schedule = _deferredLegacyDemand is null;
_deferredLegacyDemand = msg;
if (schedule)
{
var self = Self;
_ = abandoned.Finished.ContinueWith(t => { if (t.Status == TaskStatus.RanToCompletion && t.Result) self.Tell(new ResumeDeferredLegacy()); },
CancellationToken.None, TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default);
}
return;
}
if (_abandonedAcquisition is { Finished: { IsCompletedSuccessfully: true, Result: false } })
{
_deferredLegacyDemand = msg;
return;
}
if (_previousAcquisitionCleanup is { IsCompletedSuccessfully: true, Result: false } && _activeCapacityReference is not null)
{
_deferredLegacyDemand = msg;
return;
}
if (_previousAcquisitionCleanup is { IsCompleted: false } cleanup && _activeCapacityReference is not null)
{
var schedule = _deferredLegacyDemand is null;
_deferredLegacyDemand = msg;
if (schedule)
{
var self = Self;
_ = cleanup.ContinueWith(t => { if (t.Status == TaskStatus.RanToCompletion && t.Result) self.Tell(new ResumeDeferredLegacy()); },
CancellationToken.None, TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default);
}
return;
}
_deferredLegacyDemand = null;
_desiredAcquisition = null;
CancelSourceBindingRetry();
StoreDesiredSubscriptions(msg);
if (_desiredRefs.Count > 0) Self.Tell(new Subscribe(_desiredRefs, _desiredInterval));
@@ -831,6 +970,12 @@ public sealed class DriverInstanceActor : ReceiveActor, IWithTimers
// removed alarm.
SubscribeDesiredAlarms();
});
Receive<ResumeDeferredLegacy>(_ =>
{
if (_deferredLegacyDemand is not { } desired) return;
_deferredLegacyDemand = null;
Self.Tell(desired);
});
ReceiveAsync<SubscribeAlarms>(HandleSubscribeAlarmsAsync);
Receive<DataChangeForward>(OnDataChangeForward);
Receive<DataChangeBatchForward>(OnDataChangeBatchForward);
@@ -985,7 +1130,8 @@ public sealed class DriverInstanceActor : ReceiveActor, IWithTimers
_log.Info(
"DriverInstance {Id}: connected with {Count} desired subscription ref(s) but no live subscription handle — re-subscribing (periodic reconcile)",
_driverInstanceId, _desiredRefs.Count);
Self.Tell(new Subscribe(_desiredRefs, _desiredInterval));
if (_desiredAcquisition is { } acquisition) Self.Tell(acquisition);
else Self.Tell(new Subscribe(_desiredRefs, _desiredInterval));
}
/// <summary>
@@ -1065,7 +1211,7 @@ public sealed class DriverInstanceActor : ReceiveActor, IWithTimers
{
if (msg.Generation == _initGeneration) CompleteInitAttempt();
});
Receive<SetDesiredSubscriptions>(StoreDesiredSubscriptions);
Receive<SetDesiredSubscriptions>(StoreDisconnectedDesiredSubscriptions);
Receive<ForceReconnect>(_ => { /* already reconnecting — no-op */ });
Receive<ConnectionLossRaised>(IgnoreConnectionLoss);
// A watchdog DisconnectObserved self-sent on the Connected tick can still be queued when a ConnectionLossRaised
@@ -1742,44 +1888,9 @@ public sealed class DriverInstanceActor : ReceiveActor, IWithTimers
sourceBindingNeedsRetry |= !TryEnsureSourceBinding(msg.FullReferences[i], incarnation);
sourceBindingNeedsRetry |= count < msg.FullReferences.Count;
}
// EXACTLY ONE of the two data-change events is subscribed. An IBatchSubscribable driver raises
// OnDataChangeBatch once per production burst AND the per-tag OnDataChange for every item in
// that same burst (the per-tag event is kept for legacy consumers — Galaxy cold reads, driver
// CLIs). Attaching both here would forward every value twice. The batch event is preferred: one
// Tell, one parent hop, one mux pass per burst instead of per tag.
if (subscribable is IBatchSubscribable batchable)
{
_batchChangeHandler = (_, args) =>
{
// A null/empty raise from a buggy driver must never enter the mailbox: an unguarded null
// would throw in the handler, restart the actor, and tear down the driver transport.
if (args?.Items is not { Count: > 0 }) return;
var owned = new DataChangeItem[args.Items.Count];
for (var i = 0; i < owned.Length; i++)
{
var item = args.Items[i];
if (item is null) { owned[i] = null!; continue; }
PublishSource(item.FullReference, item.Snapshot);
owned[i] = new DataChangeItem(item.FullReference, CopyLegacySnapshot(item.Snapshot));
}
self.Tell(new DataChangeBatchForward(owned, _sourceIncarnation));
};
batchable.OnDataChangeBatch += _batchChangeHandler;
}
else
{
_dataChangeHandler = (_, args) =>
{
if (args is null)
{
self.Tell(new DataChangeForward(string.Empty, null!, _sourceIncarnation));
return;
}
PublishSource(args.FullReference, args.Snapshot);
self.Tell(new DataChangeForward(args.FullReference, CopyLegacySnapshot(args.Snapshot), _sourceIncarnation));
};
subscribable.OnDataChange += _dataChangeHandler;
}
var legacyAdmission = _fenceLegacyHandles ? new LegacyAdmission(this, self) : null;
Volatile.Write(ref _legacyAdmission, legacyAdmission);
AttachDataChangeHandler(subscribable, self);
using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(10));
// A bulk subscribe spans potentially many hosts, so key the pipeline on the driver
@@ -1790,6 +1901,13 @@ public sealed class DriverInstanceActor : ReceiveActor, IWithTimers
async ct => await subscribable.SubscribeAsync(msg.FullReferences, msg.PublishingInterval, ct),
cts.Token);
if (legacyAdmission is not null && !legacyAdmission.Finish(_subscriptionHandle))
{
await UnsubscribeAsync();
replyTo.Tell(new SubscriptionFailed("Legacy initial callback staging capacity exceeded."));
return;
}
if (sourceBindingNeedsRetry && _sourceIncarnation is { } retryIncarnation)
Timers.StartSingleTimer("source-binding-retry", new RetrySourceBindings(msg.FullReferences,
0, false, 0, sourceBindingVersion, retryIncarnation), TimeSpan.FromMilliseconds(250));
@@ -1806,6 +1924,449 @@ public sealed class DriverInstanceActor : ReceiveActor, IWithTimers
}
}
private void AttachDataChangeHandler(ISubscribable subscribable, IActorRef self)
{
if (_dataChangeHandler is not null || _batchChangeHandler is not null) return;
// EXACTLY ONE of the two data-change events is subscribed. An IBatchSubscribable driver raises
// OnDataChangeBatch once per production burst AND the per-tag OnDataChange for every item in
// that same burst (the per-tag event is kept for legacy consumers — Galaxy cold reads, driver
// CLIs). Attaching both here would forward every value twice. The batch event is preferred: one
// Tell, one parent hop, one mux pass per burst instead of per tag.
if (subscribable is IBatchSubscribable batchable)
{
_batchChangeHandler = (_, args) =>
{
// A null/empty raise from a buggy driver must never enter the mailbox: an unguarded null
// would throw in the handler, restart the actor, and tear down the driver transport.
if (args?.Items is not { Count: > 0 }) return;
var admission = Volatile.Read(ref _legacyAdmission);
if (admission is not null ? !admission.Admit(args.SubscriptionHandle, args.Items) : !AcceptLegacyHandle(args.SubscriptionHandle)) return;
var owned = new DataChangeItem[args.Items.Count];
for (var i = 0; i < owned.Length; i++)
{
var item = args.Items[i];
if (item is null) { owned[i] = null!; continue; }
if (Volatile.Read(ref _activeAcquisition) is null) PublishSource(item.FullReference, item.Snapshot);
owned[i] = new DataChangeItem(item.FullReference, CopyLegacySnapshot(item.Snapshot));
}
self.Tell(new DataChangeBatchForward(owned, _sourceIncarnation));
};
batchable.OnDataChangeBatch += _batchChangeHandler;
}
else
{
_dataChangeHandler = (_, args) =>
{
if (args is null)
{
self.Tell(new DataChangeForward(string.Empty, null!, _sourceIncarnation));
return;
}
var admission = Volatile.Read(ref _legacyAdmission);
if (admission is not null ? !admission.Admit(args.SubscriptionHandle,
[new DataChangeItem(args.FullReference, args.Snapshot)]) : !AcceptLegacyHandle(args.SubscriptionHandle)) return;
if (Volatile.Read(ref _activeAcquisition) is null) PublishSource(args.FullReference, args.Snapshot);
self.Tell(new DataChangeForward(args.FullReference, CopyLegacySnapshot(args.Snapshot), _sourceIncarnation));
};
subscribable.OnDataChange += _dataChangeHandler;
}
}
private bool AcceptLegacyHandle(ISubscriptionHandle handle)
{
var current = Volatile.Read(ref _subscriptionHandle);
if (Volatile.Read(ref _fenceLegacyHandles)) return current is not null && ReferenceEquals(current, handle);
return Volatile.Read(ref _acquisitionPending) == 0 && Volatile.Read(ref _activeAcquisition) is null ||
current is not null && ReferenceEquals(current, handle);
}
// The legacy API permits callbacks before SubscribeAsync returns its handle. Stage those
// callbacks under a bounded generation gate, then accept only the returned handle. Source
// reservations capture their own monotonic ingress time at callback time; SDK delivery does
// not depend on source-hub admission.
private sealed class LegacyAdmission(DriverInstanceActor owner, IActorRef self) : IDisposable
{
private const int MaxItems = 4096;
private const long MaxBytes = 16 * 1024 * 1024;
private readonly object _gate = new();
private readonly List<StagedEvent> _events = new();
private ISubscriptionHandle? _handle;
private long _bytes;
private int _items, _failed;
private int _closed;
private sealed record StagedEvent(ISubscriptionHandle Handle, DataChangeItem[] Items, StagedSource?[] Sources);
internal sealed record StagedSource(SourceSamplePublisher.StagedSourceSample? Sample, SourceTicket Ticket, uint? Status);
// True means the caller may deliver directly; false means staged or rejected.
internal bool Admit(ISubscriptionHandle handle, IReadOnlyList<DataChangeItem> items)
{
var installed = Volatile.Read(ref _handle);
if (installed is not null) return Volatile.Read(ref _closed) == 0 && ReferenceEquals(handle, installed);
if (!Monitor.TryEnter(_gate))
{
Interlocked.Exchange(ref _failed, 1);
owner.InvalidateLegacySources(items);
return false;
}
try
{
if (Volatile.Read(ref _closed) != 0 || Volatile.Read(ref _failed) != 0) return false;
if (_handle is not null) return ReferenceEquals(handle, _handle);
if (items.Count == 0 || items.Count > MaxItems - _items)
{ Interlocked.Exchange(ref _failed, 1); owner.InvalidateLegacySources(items); return false; }
var copied = new DataChangeItem[items.Count];
var sources = new StagedSource?[items.Count];
long bytes = 0;
try
{
for (var i = 0; i < items.Count; i++)
{
var item = items[i];
if (item?.Snapshot is null) throw new ArgumentException("Malformed legacy callback.");
bytes = checked(bytes + OwnedDataSample.Estimate(item.Snapshot.Value) + 2L * item.FullReference.Length);
if (bytes > MaxBytes - _bytes) throw new ArgumentException("Legacy initial callback budget exceeded.");
copied[i] = new DataChangeItem(item.FullReference, CopyLegacySnapshot(item.Snapshot));
sources[i] = owner.StageLegacySource(item);
}
_items += items.Count; _bytes += bytes;
_events.Add(new StagedEvent(handle, copied, sources));
}
catch (Exception ex) when (ex is ArgumentException or OverflowException or InvalidOperationException)
{
foreach (var source in sources) source?.Sample?.Dispose();
Interlocked.Exchange(ref _failed, 1);
owner.InvalidateLegacySources(items);
}
return false;
}
finally { Monitor.Exit(_gate); }
}
internal bool Finish(ISubscriptionHandle handle)
{
lock (_gate)
{
if (Volatile.Read(ref _closed) != 0 || Volatile.Read(ref _failed) != 0)
{ DisposeEvents(); Volatile.Write(ref _closed, 1); return false; }
foreach (var staged in _events)
{
if (ReferenceEquals(staged.Handle, handle))
{
foreach (var source in staged.Sources)
{
if (source?.Sample is { } sample) sample.Commit();
else if (source?.Status is { } status) owner._sourcePublisher?.TryPublishAcquisitionStatus(source.Ticket, status);
}
self.Tell(new DataChangeBatchForward(staged.Items, owner._sourceIncarnation));
}
else foreach (var source in staged.Sources) source?.Sample?.Dispose();
}
_events.Clear(); _items = 0; _bytes = 0;
if (Volatile.Read(ref _failed) == 0) { Volatile.Write(ref _handle, handle); return true; }
Volatile.Write(ref _closed, 1);
return false;
}
}
private void DisposeEvents()
{
foreach (var entry in _events) foreach (var source in entry.Sources) source?.Sample?.Dispose();
_events.Clear();
}
public void Dispose() { lock (_gate) { Volatile.Write(ref _closed, 1); DisposeEvents(); } }
internal static StagedSource? Stage(SourceSamplePublisher publisher, SourceTicket ticket, DataValueSnapshot snapshot)
{
if (snapshot.Value is null && !OpcUaStatus.IsGood(snapshot.StatusCode)) return new(null, ticket, snapshot.StatusCode);
return publisher.TryStage(ticket, snapshot, out var sample) ? new(sample, ticket, null) : null;
}
}
private LegacyAdmission.StagedSource? StageLegacySource(DataChangeItem item)
{
if (_sourcePublisher is null || _sourceIncarnation is not { } incarnation) return null;
if (!_sourcePublisher.TryCaptureDriver(_driverInstanceId, item.FullReference, incarnation, out var ticket) &&
(!TryEnsureSourceBinding(item.FullReference, incarnation) ||
!_sourcePublisher.TryCaptureDriver(_driverInstanceId, item.FullReference, incarnation, out ticket))) return null;
return LegacyAdmission.Stage(_sourcePublisher, ticket, item.Snapshot);
}
private void InvalidateLegacySources(IReadOnlyList<DataChangeItem> items)
{
if (_sourcePublisher is null || _sourceIncarnation is not { } incarnation) return;
foreach (var item in items)
if (item is not null && _sourcePublisher.TryCaptureDriver(_driverInstanceId, item.FullReference, incarnation, out var ticket))
_sourcePublisher.Invalidate(ticket, "legacy callback staging overflow");
}
private sealed class SharedAcquisitionReservation(IDisposable reservation)
{
private readonly IDisposable _reservation = reservation;
private int _references = 1;
private int _uncertain;
internal bool IsUncertain => Volatile.Read(ref _uncertain) != 0;
internal void MarkUncertain() => Interlocked.Exchange(ref _uncertain, 1);
internal IDisposable Retain()
{
if (Interlocked.Increment(ref _references) <= 1) throw new InvalidOperationException("Reservation already released.");
return new Reference(this);
}
internal IDisposable InitialReference() => new Reference(this);
private sealed class Reference(SharedAcquisitionReservation owner) : IDisposable
{
private SharedAcquisitionReservation? _owner = owner;
public void Dispose()
{
var current = Interlocked.Exchange(ref _owner, null);
if (current is not null && Interlocked.Decrement(ref current._references) == 0) current._reservation.Dispose();
}
}
}
// Owns the backend task independently of the actor. Admission remains pinned across actor
// death and until an abandoned operation's eventual handle has actually been released.
private sealed class PendingAcquisition(IDisposable reservation, ISubscribable subscribable, SharedAcquisitionReservation shared)
{
private readonly object _gate = new();
private readonly CancellationTokenSource _stop = new();
private readonly TaskCompletionSource<AcquisitionSubscriptionResult> _completion =
new(TaskCreationOptions.RunContinuationsAsynchronously);
private readonly TaskCompletionSource<bool> _finished = new(TaskCreationOptions.RunContinuationsAsynchronously);
private AcquisitionSubscriptionResult? _result;
private bool _abandoned, _settled;
internal Task<AcquisitionSubscriptionResult> Completion => _completion.Task;
internal Task<bool> Finished => _finished.Task;
internal void CancelBeforeStart()
{
lock (_gate) _settled = true;
reservation.Dispose();
_stop.Dispose();
_finished.TrySetResult(true);
}
internal void Start(IAcknowledgedAcquisitionSource source, AcquisitionSubscriptionRequest request,
Action<AcquisitionBatch> callback) => _ = ObserveAsync(Task.Run(() =>
source.SubscribeAcquisitionAsync(request, callback, _stop.Token)));
private async Task ObserveAsync(Task<AcquisitionSubscriptionResult> operation)
{
try
{
var result = await operation.ConfigureAwait(false) ?? throw new InvalidOperationException("Acquisition returned no acknowledgment.");
var clean = false;
lock (_gate)
{
if (_abandoned) { _settled = true; clean = true; }
else { _result = result; _completion.TrySetResult(result); }
}
if (clean) await CleanupAsync(result).ConfigureAwait(false);
}
catch (Exception ex)
{
lock (_gate) { _settled = true; _completion.TrySetException(ex); }
reservation.Dispose();
_stop.Dispose();
_finished.TrySetResult(true);
}
}
internal bool TryAdopt(AcquisitionSubscriptionResult result)
{
lock (_gate)
{
if (_abandoned || _settled || !ReferenceEquals(_result, result)) return false;
_settled = true;
}
reservation.Dispose();
_stop.Dispose();
_finished.TrySetResult(true);
return true;
}
internal void Abandon()
{
AcquisitionSubscriptionResult? clean = null;
lock (_gate)
{
if (_settled || _abandoned) return;
_abandoned = true;
if (_result is not null) { _settled = true; clean = _result; }
}
try { _stop.Cancel(); } catch (Exception) { }
if (clean is not null) _ = CleanupAsync(clean);
}
private async Task CleanupAsync(AcquisitionSubscriptionResult result)
{
try
{
if (result.Handle is not null)
await ((IDriverCapabilityInvoker)NullDriverCapabilityInvoker.Instance).ExecuteAsync(DriverCapability.Subscribe, "acquisition-cleanup",
async ct => await subscribable.UnsubscribeAsync(result.Handle, ct), CancellationToken.None).ConfigureAwait(false);
reservation.Dispose();
_finished.TrySetResult(true);
}
catch (Exception) { shared.MarkUncertain(); _finished.TrySetResult(false); /* retain reservation */ }
finally { _stop.Dispose(); }
}
}
private async Task ApplyAcquisitionDemandAsync(SetDesiredSubscriptions desired, IActorRef replyTo)
{
var failed = new AcquisitionDemandApplied(desired.DesiredRevision, desired.ProducerIncarnation, TimeSpan.Zero, false);
if (_abandonedAcquisition is { } abandoned)
{
if (!abandoned.Finished.IsCompleted)
{
replyTo.Tell(failed with { Busy = true, RetryWhenReady = abandoned.Finished });
return;
}
if (!abandoned.Finished.IsCompletedSuccessfully || !abandoned.Finished.Result)
{
replyTo.Tell(failed);
return;
}
_abandonedAcquisition = null;
}
if (_desiredAcquisition is { } current && _subscriptionHandle is not null &&
Volatile.Read(ref _activeAcquisition) is not null && current.DesiredRevision == desired.DesiredRevision &&
current.ProducerIncarnation == desired.ProducerIncarnation && current.PublishingInterval == desired.PublishingInterval &&
current.FullReferences.SequenceEqual(desired.FullReferences, StringComparer.Ordinal))
{
StoreDesiredSubscriptions(desired);
SubscribeDesiredAlarms();
replyTo.Tell(new AcquisitionDemandApplied(desired.DesiredRevision, desired.ProducerIncarnation, _acquisitionNominal, true));
return;
}
if (_previousAcquisitionCleanup is { IsCompleted: false } cleanup)
{
replyTo.Tell(failed with { Busy = true, RetryWhenReady = cleanup });
return;
}
if (_driver is not IAcknowledgedAcquisitionSource source || _driver is not ISubscribable subscribable ||
desired.DesiredRevision <= 0 || desired.ProducerIncarnation <= 0 ||
_sourceIncarnation != desired.ProducerIncarnation || desired.FullReferences.Count == 0 ||
_acquisitionCapacity is null || _activeCapacity?.IsUncertain == true || _previousAcquisitionCleanup is { IsCompleted: false } ||
_previousAcquisitionCleanup is { IsCompletedSuccessfully: true, Result: false })
{
replyTo.Tell(failed);
return;
}
var shared = _activeCapacity;
IDisposable operationReference;
if (shared is null)
{
var reservation = _acquisitionCapacity.TryAcquire(_clusterId, _driverInstanceId, out var ready);
if (reservation is null)
{
replyTo.Tell(ready is null ? failed : failed with { Busy = true, RetryWhenReady = ready });
return;
}
shared = new SharedAcquisitionReservation(reservation);
operationReference = shared.InitialReference();
}
else operationReference = shared.Retain();
var hadHandler = _dataChangeHandler is not null || _batchChangeHandler is not null;
var previousHandle = _subscriptionHandle;
var fence = new AcquisitionFence(desired.DesiredRevision, desired.ProducerIncarnation);
var permittedReferences = new HashSet<string>(desired.FullReferences, StringComparer.Ordinal);
using var cts = new CancellationTokenSource(_acquisitionTimeout, _acquisitionClock);
var operation = new PendingAcquisition(operationReference, subscribable, shared);
_pendingAcquisition = operation;
Volatile.Write(ref _acquisitionPending, 1);
var started = false;
try
{
AttachDataChangeHandler(subscribable, Self);
CancelSourceBindingRetry();
var sourceBindingVersion = _sourceBindingVersion;
var sourceBindingNeedsRetry = false;
if (_sourcePublisher is not null)
{
var count = Math.Min(desired.FullReferences.Count, SourceBindingBatchSize);
for (var i = 0; i < count; i++)
sourceBindingNeedsRetry |= !TryEnsureSourceBinding(desired.FullReferences[i], fence.Producer);
sourceBindingNeedsRetry |= count < desired.FullReferences.Count;
}
operation.Start(source, new AcquisitionSubscriptionRequest(desired.FullReferences,
desired.PublishingInterval, fence.Revision, fence.Producer), batch =>
{
if (!ReferenceEquals(Volatile.Read(ref _activeAcquisition), fence) || batch is null ||
batch.DesiredRevision != fence.Revision || batch.ProducerIncarnation != fence.Producer) return;
foreach (var item in batch.Items)
{
if (!ReferenceEquals(Volatile.Read(ref _activeAcquisition), fence)) return;
if (item is not null && permittedReferences.Contains(item.FullReference) && _sourcePublisher is not null &&
_sourcePublisher.TryCaptureDriver(_driverInstanceId, item.FullReference, fence.Producer, out var ticket))
{
if (item.Snapshot.Value is null && !OpcUaStatus.IsGood(item.Snapshot.StatusCode))
_sourcePublisher.TryPublishAcquisitionStatus(ticket, item.Snapshot.StatusCode);
else _sourcePublisher.TryPublish(ticket, item.Snapshot);
}
}
});
started = true;
var installed = await operation.Completion.WaitAsync(cts.Token);
if (installed.Handle is null || installed.DesiredRevision != fence.Revision ||
installed.ProducerIncarnation != fence.Producer || installed.NominalSamplingInterval <= TimeSpan.Zero)
{
operation.Abandon();
_abandonedAcquisition = operation;
if (!hadHandler) DetachDataSubscription();
replyTo.Tell(failed);
return;
}
var activeReference = _activeCapacityReference is null ? shared.Retain() : null;
if (!operation.TryAdopt(installed))
{
activeReference?.Dispose();
replyTo.Tell(failed);
return;
}
if (activeReference is not null) { _activeCapacity = shared; _activeCapacityReference = activeReference; }
_subscriptionHandle = installed.Handle;
Volatile.Write(ref _fenceLegacyHandles, true);
Interlocked.Exchange(ref _legacyAdmission, null)?.Dispose();
Volatile.Write(ref _activeAcquisition, fence);
Volatile.Write(ref _acquisitionPending, 0);
StoreDesiredSubscriptions(desired);
_desiredAcquisition = desired;
_acquisitionNominal = installed.NominalSamplingInterval;
if (sourceBindingNeedsRetry)
Timers.StartSingleTimer("source-binding-retry", new RetrySourceBindings(desired.FullReferences,
0, false, 0, sourceBindingVersion, fence.Producer), TimeSpan.FromMilliseconds(250));
SubscribeDesiredAlarms();
if (previousHandle is not null && !ReferenceEquals(previousHandle, installed.Handle))
_previousAcquisitionCleanup = CleanupAcquiredHandleAsync(subscribable, previousHandle, shared.Retain(), shared);
replyTo.Tell(new AcquisitionDemandApplied(fence.Revision, fence.Producer, installed.NominalSamplingInterval, true));
}
catch (Exception ex) when (ex is not OutOfMemoryException)
{
if (started) { operation.Abandon(); _abandonedAcquisition = operation; }
else operation.CancelBeforeStart();
if (!hadHandler) DetachDataSubscription();
_log.Warning(ex, "DriverInstance {Id}: acquisition demand failed", _driverInstanceId);
replyTo.Tell(failed);
}
finally { _pendingAcquisition = null; Volatile.Write(ref _acquisitionPending, 0); }
}
private static async Task<bool> CleanupAcquiredHandleAsync(ISubscribable subscribable, ISubscriptionHandle handle,
IDisposable reservation, SharedAcquisitionReservation shared)
{
try
{
await ((IDriverCapabilityInvoker)NullDriverCapabilityInvoker.Instance).ExecuteAsync(DriverCapability.Subscribe, "acquisition-cleanup",
async ct => await subscribable.UnsubscribeAsync(handle, ct), CancellationToken.None).ConfigureAwait(false);
reservation.Dispose();
return true;
}
catch (Exception) { shared.MarkUncertain(); return false; } // retain capacity after an uncertain release
}
private void CancelSourceBindingRetry()
{
Timers.Cancel("source-binding-retry");
@@ -1846,6 +2407,11 @@ public sealed class DriverInstanceActor : ReceiveActor, IWithTimers
private async Task UnsubscribeAsync()
{
if (RetireAcquisitionHandle())
{
DetachDataSubscription();
return;
}
if (_driver is not ISubscribable subscribable || _subscriptionHandle is null)
{
DetachDataSubscription();
@@ -1879,10 +2445,28 @@ public sealed class DriverInstanceActor : ReceiveActor, IWithTimers
private void DetachSubscription()
{
CancelSourceBindingRetry();
RetireAcquisitionHandle();
Volatile.Write(ref _activeAcquisition, null);
DetachDataSubscription();
DetachAlarmSource();
}
private bool RetireAcquisitionHandle()
{
var capacityReference = _activeCapacityReference;
var shared = _activeCapacity;
if (capacityReference is null || shared is null) return false;
_activeCapacityReference = null;
_activeCapacity = null;
var handle = _subscriptionHandle;
_subscriptionHandle = null;
Volatile.Write(ref _activeAcquisition, null);
if (handle is not null && _driver is ISubscribable subscribable)
_previousAcquisitionCleanup = CleanupAcquiredHandleAsync(subscribable, handle, capacityReference, shared);
else capacityReference.Dispose();
return true;
}
/// <summary>Tear down the data-change (per-tag AND batch) handlers + null the data handle, leaving the
/// native-alarm handler and handle alone.
/// <para>The data Unsubscribe / re-subscribe path used to run the full <see cref="DetachSubscription"/>,
@@ -1895,6 +2479,8 @@ public sealed class DriverInstanceActor : ReceiveActor, IWithTimers
/// driver's event would keep Telling a dead actor.</para></summary>
private void DetachDataSubscription()
{
Volatile.Write(ref _activeAcquisition, null);
Interlocked.Exchange(ref _legacyAdmission, null)?.Dispose();
if (_driver is ISubscribable subscribable && _dataChangeHandler is not null)
{
subscribable.OnDataChange -= _dataChangeHandler;
@@ -2200,15 +2786,20 @@ public sealed class DriverInstanceActor : ReceiveActor, IWithTimers
_desiredAlarmRefs = msg.AlarmReferences ?? Array.Empty<string>();
}
private void StoreDisconnectedDesiredSubscriptions(SetDesiredSubscriptions msg)
{
if (msg.RequireAcquisition)
Sender.Tell(new AcquisitionDemandApplied(msg.DesiredRevision, msg.ProducerIncarnation, TimeSpan.Zero, false));
else StoreDesiredSubscriptions(msg);
}
/// <summary>Re-establish the desired subscription after (re)connecting. Self-sends the one-shot
/// <see cref="Subscribe"/> the Connected behaviour already handles (which drops any prior handle
/// first), so values resume streaming after a reconnect or redeploy without host involvement.</summary>
private void ResubscribeDesired()
{
if (_desiredRefs.Count > 0)
{
Self.Tell(new Subscribe(_desiredRefs, _desiredInterval));
}
if (_desiredAcquisition is { } acquisition) Self.Tell(acquisition);
else if (_desiredRefs.Count > 0) Self.Tell(new Subscribe(_desiredRefs, _desiredInterval));
}
/// <summary>Forward a per-tag-only driver's data change to the parent for OPC UA publication, as a
@@ -2396,6 +2987,7 @@ public sealed class DriverInstanceActor : ReceiveActor, IWithTimers
/// <inheritdoc />
protected override void PostStop()
{
_pendingAcquisition?.Abandon();
if (_writeIncarnation is { } writeIncarnation) _writeRouteState?.RetireDriver(_driverInstanceId, writeIncarnation);
if (_sourceIncarnation is { } incarnation) _sourcePublisher?.RetireDriver(_driverInstanceId, incarnation);
// Archreview 03/S15 — announce comms loss on the way out. Every OTHER route into Reconnecting