using System.Collections.Concurrent; using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections; namespace ZB.MOM.WW.OtOpcUa.Runtime.DataConnections; /// Canonical acquisition identity, independent of any authorized view or principal. public sealed record BackingSourceKey(string OriginClusterId, string SourceKind, string StableSourceId, string ServingNodeId, string ServingIncarnation); public readonly record struct SourceGeneration(long Incarnation, long Lifecycle); internal sealed class SourceBindingFence { 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(); } } /// An individual binding; two bindings of the same key and generation remain distinct. public readonly record struct SourceTicket(BackingSourceKey Key, SourceGeneration Generation) { internal SourceBindingFence? Binding { get; } = new(); } /// Shared producer lifetime; retirement immediately fences every source bound to this token. public sealed class ProducerFence { 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 _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 { /// On success transfers the sample; on failure it remains owned by the caller. bool TryCommit(DataSample owned, long sequence); } public interface ISourceSampleHub { bool TryBind(SourceTicket ticket); bool TryBind(SourceTicket ticket, ProducerFence? fence); bool TryGetCurrentTicket(BackingSourceKey key, out SourceTicket ticket); bool IsTicketCurrentNonBlocking(SourceTicket ticket); void InvalidatePartitionFor(BackingSourceKey key, string reason); bool TryReserveIngress(SourceTicket ticket, long estimatedRetainedBytes, out IIngressReservation? reservation); void Invalidate(SourceTicket ticket, string reason); bool TryPublishStatus(SourceTicket ticket, long sequence, uint statusCode, DateTimeOffset? sourceTimestampUtc, DateTimeOffset? serverTimestampUtc); bool TryRemove(SourceTicket ticket, long sequence); } /// A recipient-owned cache read. Dispose releases its independent sample lease and admission charge. public sealed class CachedSourceRead : IDisposable { private readonly DataResourceBudget _budget; private readonly SamplePartition? _guard; private readonly object? _source; private readonly object? _sourceGate; private readonly long _sourceVersion, _routingEpoch; private readonly long _sourceSignal; private long _charge; internal CachedSourceRead(DataResourceBudget budget, DataItemStatus status, DataReadiness readiness, DataSample? sample, long version, long partitionEpoch, long receivedTimestamp, long charge, SamplePartition? guard = null, object? source = null, object? sourceGate = null, long sourceVersion = 0, long sourceSignal = 0, long routingEpoch = 0) { _budget = budget; Status = status; Readiness = readiness; Sample = sample; SourceVersion = version; PartitionEpoch = partitionEpoch; ReceivedTimestamp = receivedTimestamp; _charge = charge; _guard = guard; _source = source; _sourceGate = sourceGate; _sourceVersion = sourceVersion; _sourceSignal = sourceSignal; _routingEpoch = routingEpoch; } public DataItemStatus Status { get; } public DataReadiness Readiness { get; } public DataSample? Sample { get; } public long SourceVersion { get; } public long PartitionEpoch { get; } public long ReceivedTimestamp { get; } /// True only while the captured source, producer and partition fences remain current. public bool IsValid => Volatile.Read(ref _charge) != 0 && _guard is not null && _source is not null && _sourceGate is not null && _guard.IsReadValid(_source, _sourceGate, _sourceVersion, _sourceSignal, PartitionEpoch, _routingEpoch); public void Dispose() { var charge = Interlocked.Exchange(ref _charge, 0); if (charge == 0) return; Sample?.Dispose(); _budget.Release(charge); if (_guard is not null && _source is not null) _guard.ReleaseRead(_source); } } /// /// Partitioned source owner. Producer admission never waits on a worker or socket. /// Reads and snapshots are raw runtime acquisition state, not authorized external results. /// A facade must prove current catalog and authority and attach current trusted serving /// provenance before returning a sample; acquisitions may have zero preactivation epochs. /// public sealed class PartitionedSampleHub : ISourceSampleHub, IDisposable { internal const long SampleOverhead = 256; internal const long ReferenceOverhead = 256; private readonly DataResourceLimits _limits; private readonly bool _autoDrain; private readonly object _routingLock = new(); private readonly ConcurrentDictionary _snapshots = new(); private readonly ConcurrentDictionary _interests = new(); private SamplePartition[] _partitions; private int _trackedSources; private int _snapshotItems; private int _interestItems; private long _snapshotValidationWork; internal Action? 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; public PartitionedSampleHub(DataResourceLimits limits, TimeProvider clock) : this(limits, clock, true) { } internal PartitionedSampleHub(DataResourceLimits limits, TimeProvider clock, bool autoDrain) { ArgumentNullException.ThrowIfNull(limits); ArgumentNullException.ThrowIfNull(clock); limits.Validate(); _limits = limits; Clock = clock; _autoDrain = autoDrain; Resources = new(limits.MaxRetainedBytes); _partitions = CreatePartitions(limits.PartitionCount); } public TimeProvider Clock { get; } public DataResourceBudget Resources { get; } internal DataResourceLimits Limits => _limits; internal long RoutingEpoch => Interlocked.Read(ref _routingEpoch); internal bool IsDisposed => Volatile.Read(ref _disposed) != 0; private SamplePartition[] CreatePartitions(int count) => Enumerable.Range(0, count).Select(i => new SamplePartition(this, i)).ToArray(); // Routing stays stable for this process; repartitioning resets affected epochs. public int GetPartition(BackingSourceKey key) { ArgumentNullException.ThrowIfNull(key); return GetPartitionFor(key, Volatile.Read(ref _partitions).Length); } private SamplePartition Partition(BackingSourceKey key) { var partitions = Volatile.Read(ref _partitions); return partitions[GetPartitionFor(key, partitions.Length)]; } internal static int GetPartitionFor(BackingSourceKey key, int count) => (int)(unchecked((uint)key.GetHashCode()) % (uint)count); internal bool TryTrackSource() { while (true) { var current = Volatile.Read(ref _trackedSources); if (current >= _limits.MaxTrackedSources) return false; if (Interlocked.CompareExchange(ref _trackedSources, current + 1, current) == current) return true; } } internal void UntrackSource() => Interlocked.Decrement(ref _trackedSources); 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 && !string.IsNullOrWhiteSpace(key.OriginClusterId) && !string.IsNullOrWhiteSpace(key.SourceKind) && !string.IsNullOrWhiteSpace(key.StableSourceId) && !string.IsNullOrWhiteSpace(key.ServingNodeId) && !string.IsNullOrWhiteSpace(key.ServingIncarnation) && (long)key.OriginClusterId.Length + key.SourceKind.Length + key.StableSourceId.Length + key.ServingNodeId.Length + key.ServingIncarnation.Length <= 4096; public bool TryBind(SourceTicket ticket) => TryBind(ticket, null); public bool TryBind(SourceTicket ticket, ProducerFence? fence) => !IsDisposed && ValidKey(ticket.Key) && Partition(ticket.Key).TryBind(ticket, fence); public bool TryGetCurrentTicket(BackingSourceKey key, out SourceTicket ticket) { if (!IsDisposed && ValidKey(key)) return Partition(key).TryGetCurrentTicket(key, out ticket); ticket = default; return false; } public bool IsTicketCurrentNonBlocking(SourceTicket ticket) => !IsDisposed && ValidKey(ticket.Key) && Partition(ticket.Key).IsTicketCurrentNonBlocking(ticket); public void InvalidatePartitionFor(BackingSourceKey key, string reason) { ArgumentException.ThrowIfNullOrWhiteSpace(reason); if (!IsDisposed && ValidKey(key)) Partition(key).InvalidatePartition(); } public bool TryReserveIngress(SourceTicket ticket, long estimatedRetainedBytes, out IIngressReservation? reservation) { if (!IsDisposed && ValidKey(ticket.Key)) return Partition(ticket.Key).TryReserve(ticket, estimatedRetainedBytes, out reservation); reservation = null; return false; } public void Invalidate(SourceTicket ticket, string reason) { ArgumentException.ThrowIfNullOrWhiteSpace(reason); if (!IsDisposed && ValidKey(ticket.Key)) Partition(ticket.Key).Invalidate(ticket); } 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) { 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 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(); var watermarks = new Dictionary(); var epochs = new Dictionary(); var controls = new Dictionary(); 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 || 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, controls, partitions, routing, charge, tickets.Count, budget.Timeout < _limits.MaxSnapshotLifetime ? budget.Timeout : _limits.MaxSnapshotLifetime, cancellationToken); charge = 0; items = null!; _snapshots.TryAdd(snapshot, 0); if (!snapshot.IsReset) return true; snapshot.Dispose(); ForgetSnapshot(snapshot); snapshot = null; return false; } finally { if (items is not null) { foreach (var item in items.Values) { item.Sample?.Dispose(); item.ReleaseSource(); } Resources.Release(charge); UntrackSnapshotItems(tickets.Count); } } } /// Atomically retains interests and captures a watermark within each source partition. public bool TryCaptureInterestSnapshot(IReadOnlyList tickets, DataBudget budget, CancellationToken cancellationToken, out SnapshotLease? snapshot, out SourceInterestLease? interest) => TryCaptureInterestSnapshotCore(tickets, budget, cancellationToken, out snapshot, out interest, null); internal bool TryCaptureInterestSnapshot(IReadOnlyList 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 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(); var watermarks = new Dictionary(); var epochs = new Dictionary(); var controls = new Dictionary(); var quietControls = new Dictionary(); var owners = new Dictionary(); 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(); 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 || 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 // ticket can race the swap and bind in a new partition before its fence closes. Volatile.Write(ref _partitions, CreatePartitions(count)); } } public void Dispose() { lock (_routingLock) { if (Interlocked.Exchange(ref _disposed, 1) != 0) return; 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(); } } }