702 lines
41 KiB
C#
702 lines
41 KiB
C#
using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections;
|
|
using System.Collections.Concurrent;
|
|
|
|
namespace ZB.MOM.WW.OtOpcUa.Runtime.DataConnections;
|
|
|
|
/// <summary>One bounded source owner; no network or caller callbacks run under its lock.</summary>
|
|
internal sealed class SamplePartition : IDisposable
|
|
{
|
|
private const long SourceOverhead = 768;
|
|
private const long ControlOverhead = 256;
|
|
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 ConcurrentQueue<Pending> _mailbox = new();
|
|
private readonly ConcurrentQueue<SourceState> _dirty = new();
|
|
private int _dirtyCount;
|
|
private int _producerState; // sign bit closes admission; remaining bits count active writers.
|
|
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;
|
|
private long _ordinal;
|
|
private int _queuedValues;
|
|
private int _queuedControls;
|
|
private int _reservations;
|
|
private int _scheduled;
|
|
private int _retiredSweepRequested;
|
|
private int _reclaimRequested;
|
|
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)
|
|
{
|
|
var k = ticket.Key;
|
|
return k is not null && !string.IsNullOrWhiteSpace(k.OriginClusterId) && !string.IsNullOrWhiteSpace(k.SourceKind) &&
|
|
!string.IsNullOrWhiteSpace(k.StableSourceId) && !string.IsNullOrWhiteSpace(k.ServingNodeId) &&
|
|
!string.IsNullOrWhiteSpace(k.ServingIncarnation) && ticket.Generation.Incarnation > 0 && ticket.Generation.Lifecycle > 0 &&
|
|
(long)k.OriginClusterId.Length + k.SourceKind.Length + k.StableSourceId.Length + k.ServingNodeId.Length + k.ServingIncarnation.Length <= 4096;
|
|
}
|
|
private static int Compare(SourceGeneration a, SourceGeneration b) => a.Incarnation != b.Incarnation ? a.Incarnation.CompareTo(b.Incarnation) : a.Lifecycle.CompareTo(b.Lifecycle);
|
|
private static long SourceCharge(BackingSourceKey key) => checked(SourceOverhead + 2L * (key.OriginClusterId.Length + key.SourceKind.Length + key.StableSourceId.Length + key.ServingNodeId.Length + key.ServingIncarnation.Length));
|
|
|
|
internal bool TryBind(SourceTicket ticket, ProducerFence? fence)
|
|
{
|
|
if (!Valid(ticket) || ticket.Binding is null || ticket.Binding.IsRetired || (fence is not null && (fence.IsRetired || fence.Incarnation != ticket.Generation.Incarnation))) return false;
|
|
if (!Monitor.TryEnter(_gate))
|
|
{
|
|
if (_sources.TryGetValue(ticket.Key, out var existing))
|
|
{
|
|
var gate = Volatile.Read(ref existing.Gate);
|
|
if (Compare(ticket.Generation, gate.Generation) > 0) { gate.Binding.Retire(); Interlocked.Exchange(ref gate.Retired, 1); Interlocked.Increment(ref gate.Invalidated); }
|
|
}
|
|
return false;
|
|
}
|
|
try
|
|
{
|
|
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);
|
|
ApplyGate(state);
|
|
ApplyPartitionEpoch(state);
|
|
if (order == 0)
|
|
{
|
|
if (state.Ticket != ticket || state.Removed || Volatile.Read(ref state.Gate.Retired) != 0 || state.Fence?.IsRetired == true ||
|
|
(state.Fence is not null && !ReferenceEquals(state.Fence, fence))) return false;
|
|
if (state.Fence is null && fence is not null) Volatile.Write(ref state.Fence, fence);
|
|
return state.Fence?.IsRetired != true;
|
|
}
|
|
if (order < 0) return false;
|
|
state.Ticket.Binding!.Retire();
|
|
Interlocked.Exchange(ref state.Gate.Retired, 1);
|
|
state.Generation = ticket.Generation; state.Removed = false; state.Readiness = DataReadiness.WaitingForInitialData; Interlocked.Increment(ref state.InvalidationVersion);
|
|
state.Ticket = ticket;
|
|
state.Fence = fence; state.PartitionEpoch = _epoch;
|
|
Volatile.Write(ref state.Gate, new SourceGate(ticket.Generation, ticket.Binding));
|
|
state.AppliedInvalidations = 0;
|
|
state.LastApplied = 0; state.Barrier = 0; ReleaseCache(state);
|
|
RecordChange(ticket.Key); return true;
|
|
}
|
|
var charge = SourceCharge(ticket.Key);
|
|
if (!_hub.TryTrackSource()) { InvalidatePartition(); return false; }
|
|
if (!_hub.Resources.TryReserve(charge)) { _hub.UntrackSource(); InvalidatePartition(); return false; }
|
|
if (!_sources.TryAdd(ticket.Key, new SourceState(ticket, charge, fence, _epoch))) { _hub.Resources.Release(charge); _hub.UntrackSource(); return false; }
|
|
return true;
|
|
}
|
|
finally { Monitor.Exit(_gate); }
|
|
}
|
|
|
|
internal bool TryGetCurrentTicket(BackingSourceKey key, out SourceTicket ticket)
|
|
{
|
|
lock (_gate)
|
|
{
|
|
if (!_disposed && _sources.TryGetValue(key, out var state))
|
|
{ ApplyGate(state); ApplyPartitionEpoch(state); if (!state.Removed && Volatile.Read(ref state.Gate.Retired) == 0 && state.Fence?.IsRetired != true) { ticket = state.Ticket; return true; } }
|
|
ticket = default; return false;
|
|
}
|
|
}
|
|
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)) &&
|
|
!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)
|
|
{
|
|
if (!_sources.TryGetValue(ticket.Key, out state!)) return false;
|
|
ApplyGate(state);
|
|
ApplyPartitionEpoch(state);
|
|
return !state.Removed && state.Ticket == ticket && ticket.Binding is { IsRetired: false } && Volatile.Read(ref state.Gate.Retired) == 0 && state.Fence?.IsRetired != true;
|
|
}
|
|
private void ApplyGate(SourceState state)
|
|
{
|
|
var gate = Volatile.Read(ref state.Gate);
|
|
var signal = Volatile.Read(ref gate.Invalidated);
|
|
if (state.AppliedInvalidations != signal)
|
|
{
|
|
InvalidateSource(state);
|
|
state.AppliedInvalidations = signal;
|
|
}
|
|
}
|
|
private void Signal(SourceTicket ticket, bool retired = false)
|
|
{
|
|
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;
|
|
Control.BeginQuiet();
|
|
try
|
|
{
|
|
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.ProducerStamp);
|
|
}
|
|
finally { Control.EndQuiet(); }
|
|
}
|
|
|
|
private static bool TryPin(SourceState state)
|
|
{
|
|
while (true)
|
|
{
|
|
if (Volatile.Read(ref state.RegistryRetired) != 0) return false;
|
|
var count = Volatile.Read(ref state.MetadataOwners);
|
|
if (count <= 0 || count == int.MaxValue) return false;
|
|
if (Interlocked.CompareExchange(ref state.MetadataOwners, count + 1, count) == count) return true;
|
|
}
|
|
}
|
|
private static bool TryIncrementBounded(ref int count, int maximum)
|
|
{
|
|
while (true)
|
|
{
|
|
var current = Volatile.Read(ref count);
|
|
if (current >= maximum) return false;
|
|
if (Interlocked.CompareExchange(ref count, current + 1, current) == current) return true;
|
|
}
|
|
}
|
|
private static bool TryAdvance(SourceGate gate, long sequence)
|
|
{
|
|
while (true)
|
|
{
|
|
var current = Interlocked.Read(ref gate.LastSubmitted);
|
|
if (sequence <= current) return false;
|
|
if (Interlocked.CompareExchange(ref gate.LastSubmitted, sequence, current) == current) return true;
|
|
}
|
|
}
|
|
internal bool TryReserve(SourceTicket ticket, long estimated, out IIngressReservation? reservation)
|
|
{
|
|
reservation = null;
|
|
if (_hub.IsDisposed || Volatile.Read(ref _disposed) || _hub.RoutingEpoch != _routingEpoch ||
|
|
!_sources.TryGetValue(ticket.Key, out var state) || !TryPin(state)) return false;
|
|
var gate = Volatile.Read(ref state.Gate);
|
|
var epoch = Interlocked.Read(ref _epoch);
|
|
var stamp = Interlocked.Read(ref gate.ProducerStamp);
|
|
var signal = Interlocked.Read(ref gate.Invalidated);
|
|
if (Volatile.Read(ref state.RegistryRetired) != 0 || !_sources.TryGetValue(ticket.Key, out var current) ||
|
|
!ReferenceEquals(current, state) || !IsTicketCurrentNonBlocking(ticket) ||
|
|
!ReferenceEquals(gate, Volatile.Read(ref state.Gate)))
|
|
{ ReleaseMetadataOwner(state); return false; }
|
|
if (estimated <= 0 || estimated > long.MaxValue - PartitionedSampleHub.SampleOverhead ||
|
|
!TryIncrementBounded(ref _reservations, (int)Math.Min(int.MaxValue, (long)_hub.Limits.MaxIngressItemsPerPartition + _hub.Limits.MaxDirtySourcesPerPartition)))
|
|
{ ReleaseMetadataOwner(state); SourceIngressDiagnostics.Count(SourceIngressDiagnostics.Event.ReserveCapacity); Signal(ticket); return false; }
|
|
var charge = estimated + PartitionedSampleHub.SampleOverhead;
|
|
if (!_hub.Resources.TryReserve(charge))
|
|
{ Interlocked.Decrement(ref _reservations); ReleaseMetadataOwner(state); SourceIngressDiagnostics.Count(SourceIngressDiagnostics.Event.ReserveCapacity); Signal(ticket); return false; }
|
|
Interlocked.Increment(ref state.Reservations);
|
|
if (!IsTicketCurrentNonBlocking(ticket) || !ReferenceEquals(gate, Volatile.Read(ref state.Gate)) ||
|
|
Interlocked.Read(ref _epoch) != epoch || Interlocked.Read(ref gate.ProducerStamp) != stamp || Interlocked.Read(ref gate.Invalidated) != signal)
|
|
{ ReleaseReservation(state); _hub.Resources.Release(charge); return false; }
|
|
reservation = new Reservation(this, state, gate, ticket, estimated, charge, stamp, signal, epoch, _hub.Clock.GetTimestamp());
|
|
return true;
|
|
}
|
|
private bool Commit(SourceState state, SourceGate gate, SourceTicket ticket, long estimate, long charge, long stamp,
|
|
long signal, long partitionEpoch, long receivedTimestamp, DataSample sample, long sequence)
|
|
{
|
|
if (!TryEnterProducer()) { ReleaseReservation(state); _hub.Resources.Release(charge); return false; }
|
|
if (Interlocked.CompareExchange(ref gate.Committing, 1, 0) != 0)
|
|
{
|
|
ReleaseReservation(state); _hub.Resources.Release(charge); Signal(ticket); ExitProducer(); return false;
|
|
}
|
|
try { return CommitEntered(state, gate, ticket, estimate, charge, stamp, signal, partitionEpoch, receivedTimestamp, sample, sequence); }
|
|
finally { Volatile.Write(ref gate.Committing, 0); ExitProducer(); }
|
|
}
|
|
private bool CommitEntered(SourceState state, SourceGate gate, SourceTicket ticket, long estimate, long charge, long stamp,
|
|
long signal, long partitionEpoch, long receivedTimestamp, DataSample sample, long sequence)
|
|
{
|
|
try
|
|
{
|
|
ArgumentNullException.ThrowIfNull(sample.Value);
|
|
ArgumentNullException.ThrowIfNull(sample.Serving);
|
|
sample.Serving.Validate(requireEpochs: false);
|
|
if (sample.Version != sequence || sample.Value.EstimatedRetainedBytes > estimate ||
|
|
sample.Serving.NodeId != ticket.Key.ServingNodeId || sample.Serving.Incarnation != ticket.Key.ServingIncarnation)
|
|
throw new ArgumentException("Invalid ingress sample.");
|
|
}
|
|
catch (Exception e) when (e is ArgumentException or ObjectDisposedException or OverflowException)
|
|
{ SourceIngressDiagnostics.Count(SourceIngressDiagnostics.Event.CommitInvalid); ReleaseReservation(state); _hub.Resources.Release(charge); Signal(ticket); return false; }
|
|
if (!IsTicketCurrentNonBlocking(ticket) || !ReferenceEquals(gate, Volatile.Read(ref state.Gate)) ||
|
|
partitionEpoch != Interlocked.Read(ref _epoch) || stamp != Interlocked.Read(ref gate.ProducerStamp) || signal != Interlocked.Read(ref gate.Invalidated))
|
|
{ ReleaseReservation(state); _hub.Resources.Release(charge); return false; }
|
|
if (!TryAdvance(gate, sequence))
|
|
{ ReleaseReservation(state); _hub.Resources.Release(charge); Signal(ticket); return false; }
|
|
_hub.AfterValueSequenceForTests?.Invoke();
|
|
var pending = new Pending(ticket, sequence, Interlocked.Increment(ref _ordinal), sample, charge, receivedTimestamp)
|
|
{ PartitionEpoch = partitionEpoch, Owner = state, Gate = gate, ProducerStamp = stamp, SignalStamp = signal };
|
|
var admitted = EnqueueValue(state, pending);
|
|
if (admitted != EnqueueResult.Accepted)
|
|
{
|
|
ReleaseReservation(state); _hub.Resources.Release(charge);
|
|
if (admitted == EnqueueResult.Capacity) InvalidatePartition();
|
|
else Signal(ticket);
|
|
return false;
|
|
}
|
|
// The mailbox owns the metadata pin; the in-flight copy permit ends at transfer.
|
|
Interlocked.Decrement(ref _reservations);
|
|
var lastReservation = Interlocked.Decrement(ref state.Reservations) == 0;
|
|
if (lastReservation && Volatile.Read(ref state.Gate.Retired) != 0 && !Volatile.Read(ref _disposed)) RequestReclaim();
|
|
_hub.Schedule(this);
|
|
return true;
|
|
}
|
|
private bool TryEnterProducer()
|
|
{
|
|
while (true)
|
|
{
|
|
var current = Volatile.Read(ref _producerState);
|
|
if (current < 0 || current == int.MaxValue) return false;
|
|
if (Interlocked.CompareExchange(ref _producerState, current + 1, current) == current) return true;
|
|
}
|
|
}
|
|
private void ExitProducer()
|
|
{
|
|
if (Interlocked.Decrement(ref _producerState) < 0) Schedule();
|
|
}
|
|
private enum EnqueueResult { Accepted, Stale, Capacity }
|
|
private EnqueueResult EnqueueValue(SourceState state, Pending pending)
|
|
{
|
|
while (true)
|
|
{
|
|
var existing = Volatile.Read(ref state.Dirty);
|
|
if (existing is not null)
|
|
{
|
|
if (ReferenceEquals(existing.Gate, pending.Gate) && existing.Sequence >= pending.Sequence ||
|
|
!ReferenceEquals(existing.Gate, pending.Gate) && existing.Gate is not null && pending.Gate is not null &&
|
|
Compare(existing.Gate.Generation, pending.Gate.Generation) >= 0) return EnqueueResult.Stale;
|
|
if (Interlocked.CompareExchange(ref state.Dirty, pending, existing) != existing) continue;
|
|
ReleasePending(existing); return EnqueueResult.Accepted;
|
|
}
|
|
if (TryIncrementBounded(ref _queuedValues, _hub.Limits.MaxIngressItemsPerPartition))
|
|
{
|
|
if (Volatile.Read(ref state.Dirty) is not null) { Interlocked.Decrement(ref _queuedValues); continue; }
|
|
_mailbox.Enqueue(pending); return EnqueueResult.Accepted;
|
|
}
|
|
if (!TryIncrementBounded(ref _dirtyCount, _hub.Limits.MaxDirtySourcesPerPartition))
|
|
{ if (Volatile.Read(ref state.Dirty) is not null) continue; return EnqueueResult.Capacity; }
|
|
if (Interlocked.CompareExchange(ref state.Dirty, pending, null) is null)
|
|
{ _dirty.Enqueue(state); return EnqueueResult.Accepted; }
|
|
Interlocked.Decrement(ref _dirtyCount);
|
|
}
|
|
}
|
|
private void ReleaseReservation(SourceState state)
|
|
{
|
|
Interlocked.Decrement(ref _reservations);
|
|
var lastReservation = Interlocked.Decrement(ref state.Reservations) == 0;
|
|
ReleaseMetadataOwner(state);
|
|
if (lastReservation && Volatile.Read(ref state.Gate.Retired) != 0 && !Volatile.Read(ref _disposed)) RequestReclaim();
|
|
}
|
|
private void Abandon(SourceState state, long charge) { ReleaseReservation(state); _hub.Resources.Release(charge); }
|
|
internal void Invalidate(SourceTicket ticket) { SourceIngressDiagnostics.Count(SourceIngressDiagnostics.Event.ExternalInvalidate); Signal(ticket); }
|
|
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)
|
|
{
|
|
if (!Monitor.TryEnter(_gate)) { Signal(ticket); return false; }
|
|
try
|
|
{
|
|
var partitionEpoch = Interlocked.Read(ref _epoch);
|
|
if (_disposed || !Current(ticket, out var state) || !TryAdvance(Volatile.Read(ref state.Gate), sequence)) return false;
|
|
if (_queuedControls >= _hub.Limits.MaxControlItemsPerPartition || !_hub.Resources.TryReserve(ControlOverhead)) { InvalidatePartition(); return false; }
|
|
var wasReady = state.Readiness == DataReadiness.Ready;
|
|
Control.Begin();
|
|
try { state.Readiness = DataReadiness.Invalidated; Interlocked.Increment(ref state.InvalidationVersion); Interlocked.Increment(ref state.Gate.ProducerStamp); state.Barrier = sequence; }
|
|
finally { Control.End(); }
|
|
_queue.Enqueue(new Pending(ticket, sequence, Interlocked.Increment(ref _ordinal), status, source, server, wasReady, ControlOverhead) { AdmissionEpoch = state.InvalidationVersion, PartitionEpoch = partitionEpoch }); _queuedControls++;
|
|
_hub.Schedule(this); return true;
|
|
}
|
|
finally { Monitor.Exit(_gate); }
|
|
}
|
|
internal bool TryRemove(SourceTicket ticket, long sequence)
|
|
{
|
|
if (!Monitor.TryEnter(_gate)) { Signal(ticket, retired: true); return false; }
|
|
try
|
|
{
|
|
// Retirement must still be able to release a source after its shared fence closed.
|
|
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 || !TryAdvance(Volatile.Read(ref state.Gate), sequence)) return false;
|
|
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); Interlocked.Increment(ref state.Gate.ProducerStamp); ReleaseCache(state);
|
|
}
|
|
finally { Control.EndQuiet(); }
|
|
RequestReclaim();
|
|
_queue.Enqueue(new Pending(ticket, sequence, Interlocked.Increment(ref _ordinal), ControlOverhead) { PartitionEpoch = _epoch }); _queuedControls++;
|
|
_hub.Schedule(this); return true;
|
|
}
|
|
finally { Monitor.Exit(_gate); }
|
|
}
|
|
|
|
internal void Schedule()
|
|
{
|
|
if (Interlocked.Exchange(ref _scheduled, 1) == 0)
|
|
ThreadPool.QueueUserWorkItem(static p => ((SamplePartition)p!).Run(), this);
|
|
}
|
|
private void Run()
|
|
{
|
|
try { Drain(); }
|
|
finally
|
|
{
|
|
Volatile.Write(ref _scheduled, 0);
|
|
lock (_gate) if ((!_disposed && (_cleanedEpoch != _epoch || Volatile.Read(ref _retiredSweepRequested) != 0 || Volatile.Read(ref _reclaimRequested) != 0 || _queue.Count != 0)) || !_mailbox.IsEmpty || !_dirty.IsEmpty) Schedule();
|
|
}
|
|
}
|
|
internal void Drain()
|
|
{
|
|
lock (_gate)
|
|
{
|
|
if (!_disposed) { CleanupInvalidatedEpoch(); CleanupRetiredSources(); }
|
|
// Controls present at entry cannot be replenished while this gate is held. Drain
|
|
// that finite bounded set first, then give values their own bounded work slice.
|
|
var controlsRemaining = _queue.Count;
|
|
var valueWork = 0;
|
|
while (controlsRemaining > 0 || valueWork < 128)
|
|
{
|
|
Pending? p = null;
|
|
if (controlsRemaining > 0 && _queue.TryDequeue(out var control)) { controlsRemaining--; p = control; _queuedControls--; }
|
|
else if (++valueWork > 128) break;
|
|
else if (_mailbox.TryPeek(out var first))
|
|
{
|
|
var dirtyFirst = _dirty.TryPeek(out var dirtyState) ? Volatile.Read(ref dirtyState.Dirty) : null;
|
|
if (dirtyFirst is not null && dirtyFirst.Ordinal < first.Ordinal)
|
|
{
|
|
if (!_dirty.TryDequeue(out dirtyState)) continue;
|
|
Interlocked.Decrement(ref _dirtyCount);
|
|
p = Interlocked.Exchange(ref dirtyState.Dirty, null);
|
|
}
|
|
else if (_mailbox.TryDequeue(out p)) Interlocked.Decrement(ref _queuedValues);
|
|
}
|
|
else if (_dirty.TryDequeue(out var dirtyState))
|
|
{
|
|
Interlocked.Decrement(ref _dirtyCount);
|
|
p = Interlocked.Exchange(ref dirtyState.Dirty, null);
|
|
}
|
|
else break;
|
|
if (p is null) continue;
|
|
if (_disposed || p.PartitionEpoch != _epoch ||
|
|
p.Owner is not null && (!ReferenceEquals(p.Gate, Volatile.Read(ref p.Owner.Gate)) ||
|
|
p.Gate is null || p.ProducerStamp != Interlocked.Read(ref p.Gate.ProducerStamp) || p.SignalStamp != Interlocked.Read(ref p.Gate.Invalidated)))
|
|
{ ReleasePending(p); continue; }
|
|
if (p.Owner is not null) _hub.BeforePendingValueCurrentForTests?.Invoke();
|
|
if (!Current(p.Ticket, out var state) || p.IsControl && p.AdmissionEpoch != state.InvalidationVersion || p.Sequence <= state.LastApplied ||
|
|
p.Owner is not null && (!ReferenceEquals(p.Owner, state) || p.PartitionEpoch != Interlocked.Read(ref _epoch) ||
|
|
!ReferenceEquals(p.Gate, Volatile.Read(ref state.Gate)) || p.Gate is null ||
|
|
p.ProducerStamp != Interlocked.Read(ref p.Gate.ProducerStamp) || p.SignalStamp != Interlocked.Read(ref p.Gate.Invalidated)))
|
|
{ ReleasePending(p); continue; }
|
|
state.LastApplied = p.Sequence;
|
|
if (p.Sample is not null)
|
|
{
|
|
ReleaseCache(state); state.Sample = p.Sample; state.SampleCharge = p.Charge; state.Received = p.Received;
|
|
state.Readiness = p.Sequence < state.Barrier ? DataReadiness.Invalidated : DataReadiness.Ready;
|
|
if (p.Owner is not null) ReleaseMetadataOwner(p.Owner);
|
|
}
|
|
else
|
|
{
|
|
if (p.IsStatus && state.Sample is not null)
|
|
{
|
|
var old = state.Sample;
|
|
state.Sample = old with { StatusCode = p.Status,
|
|
SourceTimestampUtc = p.SourceTimestamp ?? old.SourceTimestampUtc,
|
|
ServerTimestampUtc = p.ServerTimestamp ?? old.ServerTimestampUtc, Version = p.Sequence };
|
|
state.Readiness = p.WasReady ? DataReadiness.Ready : DataReadiness.Invalidated;
|
|
}
|
|
else if (state.Sample is null) state.Readiness = DataReadiness.WaitingForInitialData;
|
|
_hub.Resources.Release(p.Charge);
|
|
}
|
|
RecordChange(p.Ticket.Key);
|
|
}
|
|
if (!_disposed) ReclaimTombstones();
|
|
}
|
|
}
|
|
// Deterministic fixture helper: production workers always use the fixed Drain slice.
|
|
internal void DrainForTests()
|
|
{
|
|
var maximum = (long)_hub.Limits.MaxIngressItemsPerPartition + _hub.Limits.MaxDirtySourcesPerPartition + _hub.Limits.MaxControlItemsPerPartition;
|
|
for (long work = 0; work <= maximum / 128 + 1; work++)
|
|
{
|
|
Drain();
|
|
lock (_gate) if (_queue.Count == 0 && _mailbox.IsEmpty && _dirty.IsEmpty) return;
|
|
}
|
|
}
|
|
private void RecordChange(BackingSourceKey key)
|
|
{
|
|
_watermark++;
|
|
if (_changes.Count == _hub.Limits.MaxSnapshotCatchUpItems)
|
|
{ _changeIndex.Remove(_changes.First!.Value.Version); _changes.RemoveFirst(); _hub.Resources.Release(ChangeOverhead); }
|
|
if (!_hub.Resources.TryReserve(ChangeOverhead)) { InvalidatePartition(); return; }
|
|
_changeIndex.Add(_watermark, _changes.AddLast((_watermark, key)));
|
|
}
|
|
internal void InvalidatePartition()
|
|
{
|
|
SourceIngressDiagnostics.Count(SourceIngressDiagnostics.Event.PartitionInvalidated);
|
|
Control.BeginQuiet();
|
|
try { Interlocked.Increment(ref _epoch); }
|
|
finally { Control.EndQuiet(); }
|
|
_hub.Schedule(this);
|
|
}
|
|
private void ApplyPartitionEpoch(SourceState state)
|
|
{
|
|
if (state.PartitionEpoch == _epoch) return;
|
|
InvalidateSource(state);
|
|
state.PartitionEpoch = _epoch;
|
|
}
|
|
private void CleanupInvalidatedEpoch()
|
|
{
|
|
var epoch = Interlocked.Read(ref _epoch);
|
|
if (_cleanedEpoch == epoch) return;
|
|
foreach (var pair in _sources) ApplyPartitionEpoch(pair.Value);
|
|
while (_changes.First is not null) { _changes.RemoveFirst(); _hub.Resources.Release(ChangeOverhead); }
|
|
_changeIndex.Clear();
|
|
_cleanedEpoch = epoch;
|
|
}
|
|
private void CleanupRetiredSources()
|
|
{
|
|
if (Interlocked.Exchange(ref _retiredSweepRequested, 0) == 0) return;
|
|
foreach (var pair in _sources)
|
|
{
|
|
var state = pair.Value;
|
|
if (Volatile.Read(ref state.Gate.Retired) == 0) continue;
|
|
ApplyGate(state);
|
|
state.Removed = true;
|
|
InvalidateSource(state);
|
|
RequestReclaim();
|
|
}
|
|
}
|
|
private void RequestReclaim() { Interlocked.Exchange(ref _reclaimRequested, 1); _hub.Schedule(this); }
|
|
private void ReclaimTombstones()
|
|
{
|
|
if (Interlocked.Exchange(ref _reclaimRequested, 0) == 0) return;
|
|
foreach (var pair in _sources)
|
|
{
|
|
var state = pair.Value;
|
|
if (!state.Removed || Volatile.Read(ref state.Readers) != 0 || Volatile.Read(ref state.Reservations) != 0 || Volatile.Read(ref state.Snapshots) != 0) continue;
|
|
if (_sources.TryRemove(pair.Key, out var removed) && ReferenceEquals(removed, state))
|
|
RetireSourceState(state);
|
|
}
|
|
}
|
|
private void RetireSourceState(SourceState state)
|
|
{
|
|
state.Ticket.Binding!.Retire();
|
|
Interlocked.Exchange(ref state.Gate.Retired, 1);
|
|
if (Interlocked.Exchange(ref state.RegistryRetired, 1) == 0) ReleaseMetadataOwner(state);
|
|
}
|
|
private void ReleaseMetadataOwner(SourceState state)
|
|
{
|
|
if (Interlocked.Decrement(ref state.MetadataOwners) != 0) return;
|
|
_hub.Resources.Release(state.SourceCharge);
|
|
_hub.UntrackSource();
|
|
}
|
|
private void ReleaseCache(SourceState state) { if (state.Sample is not null) { state.Sample.Dispose(); state.Sample = null; _hub.Resources.Release(state.SampleCharge); state.SampleCharge = 0; } }
|
|
private void ReleasePending(Pending p) { p.Sample?.Dispose(); _hub.Resources.Release(p.Charge); if (p.Owner is not null) ReleaseMetadataOwner(p.Owner); }
|
|
|
|
internal CachedSourceRead Read(SourceTicket ticket) => Read(ticket, out _);
|
|
internal CachedSourceRead Read(SourceTicket ticket, out long watermark)
|
|
{
|
|
lock (_gate)
|
|
{
|
|
watermark = _watermark;
|
|
if (_disposed || !Current(ticket, out var state)) return _hub.EmptyRead(DataItemStatus.NotFound, DataReadiness.Unavailable, _epoch);
|
|
if (state.Readiness != DataReadiness.Ready || state.Sample is null)
|
|
{ SourceIngressDiagnostics.Count(SourceIngressDiagnostics.Event.ReadNotReady); return _hub.EmptyRead(state.Readiness == DataReadiness.WaitingForInitialData ? DataItemStatus.WaitingForInitialData : DataItemStatus.Unavailable, state.Readiness, _epoch); }
|
|
var gate = Volatile.Read(ref state.Gate);
|
|
var signal = Volatile.Read(ref gate.Invalidated);
|
|
if (signal != state.AppliedInvalidations) { SourceIngressDiagnostics.Count(SourceIngressDiagnostics.Event.ReadInvalidated); return _hub.EmptyRead(DataItemStatus.Unavailable, DataReadiness.Invalidated, _epoch); }
|
|
var charge = checked(state.Sample.Value.EstimatedRetainedBytes + PartitionedSampleHub.ReferenceOverhead);
|
|
if (!_hub.Resources.TryReserve(charge)) { SourceIngressDiagnostics.Count(SourceIngressDiagnostics.Event.ReadExhausted); return _hub.EmptyRead(DataItemStatus.ResourceExhausted, DataReadiness.Unavailable, _epoch); }
|
|
Interlocked.Increment(ref state.Readers);
|
|
Interlocked.Increment(ref state.MetadataOwners);
|
|
return new CachedSourceRead(_hub.Resources, DataItemStatus.Good, state.Readiness,
|
|
state.Sample with { Value = state.Sample.Value.Retain() }, state.LastApplied, state.PartitionEpoch, state.Received, charge,
|
|
this, state, gate, Volatile.Read(ref state.InvalidationVersion), signal, _routingEpoch);
|
|
}
|
|
}
|
|
internal void ReleaseRead(object source)
|
|
{
|
|
var state = (SourceState)source;
|
|
var lastRead = Interlocked.Decrement(ref state.Readers) == 0;
|
|
ReleaseMetadataOwner(state);
|
|
if (lastRead && Volatile.Read(ref state.Gate.Retired) != 0 && !Volatile.Read(ref _disposed)) RequestReclaim();
|
|
}
|
|
internal bool IsReadValid(object source, object sourceGate, long sourceVersion, long sourceSignal, long partitionEpoch, long routingEpoch)
|
|
{
|
|
var state = (SourceState)source;
|
|
var gate = (SourceGate)sourceGate;
|
|
return !_hub.IsDisposed && _hub.RoutingEpoch == routingEpoch && Interlocked.Read(ref _epoch) == partitionEpoch &&
|
|
ReferenceEquals(gate, Volatile.Read(ref state.Gate)) && !gate.Binding.IsRetired && Volatile.Read(ref gate.Retired) == 0 &&
|
|
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, SnapshotAdmissionScheduler.Permit? admission = null)
|
|
{
|
|
lock (_gate)
|
|
{
|
|
watermark = _watermark; epoch = _epoch;
|
|
if (_disposed) return false;
|
|
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 || 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, 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) { SourceIngressDiagnostics.Count(SourceIngressDiagnostics.Event.InterestEpoch); return false; }
|
|
if (position == _watermark) return true;
|
|
if (!_changeIndex.TryGetValue(position + 1, out var node)) { SourceIngressDiagnostics.Count(SourceIngressDiagnostics.Event.InterestHistoryGap); 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 _)) { SourceIngressDiagnostics.Count(SourceIngressDiagnostics.Event.InterestTicket); return false; }
|
|
changes.Add(new(ticket, change.Version));
|
|
}
|
|
node = node.Next;
|
|
}
|
|
return true;
|
|
}
|
|
}
|
|
internal void ReleaseSnapshot(object source)
|
|
{
|
|
var state = (SourceState)source;
|
|
var lastSnapshot = Interlocked.Decrement(ref state.Snapshots) == 0;
|
|
ReleaseMetadataOwner(state);
|
|
if (lastSnapshot && Volatile.Read(ref state.Gate.Retired) != 0 && !Volatile.Read(ref _disposed)) RequestReclaim();
|
|
}
|
|
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.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()
|
|
{
|
|
Interlocked.Or(ref _producerState, int.MinValue);
|
|
lock (_gate)
|
|
{
|
|
if (_disposed) return; _disposed = true; InvalidatePartition(); CleanupInvalidatedEpoch();
|
|
while (_queue.TryDequeue(out var p)) ReleasePending(p);
|
|
while (_mailbox.TryDequeue(out var value)) { Interlocked.Decrement(ref _queuedValues); ReleasePending(value); }
|
|
while (_dirty.TryDequeue(out var dirtyState))
|
|
{
|
|
Interlocked.Decrement(ref _dirtyCount);
|
|
var dirty = Interlocked.Exchange(ref dirtyState.Dirty, null);
|
|
if (dirty is not null) ReleasePending(dirty);
|
|
}
|
|
_queuedControls = 0;
|
|
foreach (var pair in _sources) { pair.Value.Removed = true; RetireSourceState(pair.Value); }
|
|
_sources.Clear();
|
|
}
|
|
}
|
|
|
|
private sealed class SourceGate(SourceGeneration generation, SourceBindingFence binding)
|
|
{ public readonly SourceGeneration Generation = generation; public readonly SourceBindingFence Binding = binding; public long Invalidated, ProducerStamp, LastSubmitted; public int Retired, Committing; }
|
|
private sealed class SourceState(SourceTicket ticket, long sourceCharge, ProducerFence? fence, long partitionEpoch)
|
|
{
|
|
public SourceTicket Ticket = ticket; public SourceGeneration Generation = ticket.Generation; public readonly long SourceCharge = sourceCharge;
|
|
public SourceGate Gate = new(ticket.Generation, ticket.Binding!);
|
|
public ProducerFence? Fence = fence; public long PartitionEpoch = partitionEpoch;
|
|
public long AppliedInvalidations;
|
|
// The registry owns one metadata reference; each retained read, snapshot and reservation owns one more.
|
|
public int MetadataOwners = 1; public int RegistryRetired;
|
|
public int Readers; public int Reservations; public int Snapshots;
|
|
public bool Removed; public DataReadiness Readiness = DataReadiness.WaitingForInitialData;
|
|
public DataSample? Sample; public long SampleCharge; public long Received;
|
|
public long LastApplied; public long Barrier; public long InvalidationVersion; public Pending? Dirty;
|
|
}
|
|
private sealed class Pending
|
|
{
|
|
public Pending(SourceTicket ticket, long sequence, long ordinal, DataSample sample, long charge, long received)
|
|
{ Ticket = ticket; Sequence = sequence; Ordinal = ordinal; Sample = sample; Charge = charge; Received = received; }
|
|
public Pending(SourceTicket ticket, long sequence, long ordinal, uint status, DateTimeOffset? source, DateTimeOffset? server, bool wasReady, long charge)
|
|
{ Ticket = ticket; Sequence = sequence; Ordinal = ordinal; Status = status; SourceTimestamp = source; ServerTimestamp = server; WasReady = wasReady; Charge = charge; IsControl = true; IsStatus = true; }
|
|
public Pending(SourceTicket ticket, long sequence, long ordinal, long charge) { Ticket = ticket; Sequence = sequence; Ordinal = ordinal; Charge = charge; IsControl = true; }
|
|
public SourceTicket Ticket; public long Sequence; public long Ordinal; public DataSample? Sample; public long Charge; public long Received; public long AdmissionEpoch; public long PartitionEpoch;
|
|
public SourceState? Owner; public SourceGate? Gate; public long ProducerStamp, SignalStamp;
|
|
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, SourceGate gate, SourceTicket ticket, long estimate, long charge,
|
|
long producerStamp, long signal, 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, gate, ticket, estimate, charge, producerStamp, signal, partitionEpoch, receivedTimestamp, owned, sequence); }
|
|
public void Dispose() { if (Interlocked.Exchange(ref _completed, 1) == 0) partition.Abandon(state, charge); }
|
|
}
|
|
}
|