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
@@ -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); }
}
}