feat: add immutable partitioned data publication hub

This commit is contained in:
Joseph Doherty
2026-11-16 01:13:10 -05:00
parent b2249ce2cb
commit 8f28a0eabf
47 changed files with 6184 additions and 173 deletions
@@ -0,0 +1,486 @@
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 = 192;
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 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 SamplePartition(PartitionedSampleHub hub, int id) { _hub = hub; Id = id; _routingEpoch = hub.RoutingEpoch; }
internal int Id { get; }
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 || ticket.Binding.IsRetired) 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.LastSubmitted = 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 (!_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));
}
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;
if (retired)
{
gate.Binding.Retire();
Interlocked.Exchange(ref gate.Retired, 1);
Interlocked.Exchange(ref _retiredSweepRequested, 1);
_hub.Schedule(this);
}
Interlocked.Increment(ref gate.Invalidated);
}
internal bool TryReserve(SourceTicket ticket, long estimated, out IIngressReservation? reservation)
{
reservation = null;
if (!Monitor.TryEnter(_gate)) { Signal(ticket); return false; }
try
{
if (_disposed || !Current(ticket, out var state)) return false;
if (estimated <= 0 || estimated > long.MaxValue - PartitionedSampleHub.SampleOverhead ||
Volatile.Read(ref _reservations) >= _hub.Limits.MaxIngressItemsPerPartition + _hub.Limits.MaxDirtySourcesPerPartition ||
!_hub.Resources.TryReserve(estimated + PartitionedSampleHub.SampleOverhead))
{ InvalidateSource(state); return false; }
Interlocked.Increment(ref _reservations);
Interlocked.Increment(ref state.Reservations);
Interlocked.Increment(ref state.MetadataOwners);
reservation = new Reservation(this, state, ticket, estimated, estimated + PartitionedSampleHub.SampleOverhead,
state.InvalidationVersion, _epoch);
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)
{
if (!Monitor.TryEnter(_gate))
{ ReleaseReservation(reservedState); _hub.Resources.Release(charge); Signal(ticket); return false; }
try
{
ReleaseReservation(reservedState);
if (_disposed || !Current(ticket, out var state)) { _hub.Resources.Release(charge); return false; }
if (state.InvalidationVersion != invalidationVersion || _epoch != partitionEpoch) { _hub.Resources.Release(charge); return false; }
try
{
ArgumentNullException.ThrowIfNull(sample.Value);
ArgumentNullException.ThrowIfNull(sample.Serving);
sample.Serving.Validate(requireEpochs: false);
if (sequence <= state.LastSubmitted || sample.Version != sequence || sample.Value.EstimatedRetainedBytes > estimate ||
sample.Serving.NodeId != ticket.Key.ServingNodeId || sample.Serving.Incarnation != ticket.Key.ServingIncarnation)
{ _hub.Resources.Release(charge); InvalidateSource(state); return false; }
}
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 };
if (_queuedValues < _hub.Limits.MaxIngressItemsPerPartition)
{ _queue.Enqueue(pending); _queuedValues++; }
else if (_dirty.TryGetValue(ticket.Key, out var previous))
{ ReleasePending(previous); _dirty[ticket.Key] = pending; }
else if (_dirty.Count < _hub.Limits.MaxDirtySourcesPerPartition) _dirty.Add(ticket.Key, pending);
else { _hub.Resources.Release(charge); InvalidatePartition(); return false; }
state.LastSubmitted = sequence;
_hub.Schedule(this);
return true;
}
finally { Monitor.Exit(_gate); }
}
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) => Signal(ticket);
private void InvalidateSource(SourceState state) { state.Readiness = DataReadiness.Invalidated; Interlocked.Increment(ref state.InvalidationVersion); ReleaseCache(state); }
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) || 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;
_queue.Enqueue(new Pending(ticket, sequence, ++_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 || 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);
RequestReclaim();
_queue.Enqueue(new Pending(ticket, sequence, ++_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 || _dirty.Count != 0)) Schedule();
}
}
internal void Drain()
{
lock (_gate)
{
CleanupInvalidatedEpoch();
CleanupRetiredSources();
while (!_disposed && (_queue.Count != 0 || _dirty.Count != 0))
{
Pending? dirty = null;
foreach (var value in _dirty.Values) if (dirty is null || value.Ordinal < dirty.Ordinal) dirty = value;
Pending p;
if (dirty is not null && (_queue.Count == 0 || dirty.Ordinal < _queue.Peek().Ordinal))
{ p = dirty; _dirty.Remove(p.Ticket.Key); }
else
{ p = _queue.Dequeue(); if (p.IsControl) _queuedControls--; else _queuedValues--; }
if (p.PartitionEpoch != _epoch || !Current(p.Ticket, out var state) || p.AdmissionEpoch != state.InvalidationVersion || p.Sequence <= state.LastApplied)
{ 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;
}
else
{
if (p.IsStatus && state.Sample is not null)
{
var old = state.Sample;
// Missing timestamps on a status-only event mean no new acquisition timestamp.
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);
}
ReclaimTombstones();
}
}
private void RecordChange(BackingSourceKey key)
{
_watermark++;
if (_changes.Count == _hub.Limits.MaxSnapshotCatchUpItems)
{ _changes.Dequeue(); _hub.Resources.Release(ChangeOverhead); }
if (!_hub.Resources.TryReserve(ChangeOverhead)) { InvalidatePartition(); return; }
_changes.Enqueue((_watermark, key));
}
internal void InvalidatePartition()
{
Interlocked.Increment(ref _epoch);
_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.TryDequeue(out _)) _hub.Resources.Release(ChangeOverhead);
_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); }
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)
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) return _hub.EmptyRead(DataItemStatus.Unavailable, DataReadiness.Invalidated, _epoch);
var charge = checked(state.Sample.Value.EstimatedRetainedBytes + PartitionedSampleHub.ReferenceOverhead);
if (!_hub.Resources.TryReserve(charge)) 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)
{
lock (_gate)
{
watermark = _watermark; epoch = _epoch;
if (_disposed) return false;
foreach (var ticket in tickets)
{
var exists = Current(ticket, out var state);
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;
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 });
}
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, IEnumerable<KeyValuePair<SourceTicket, SnapshotItem>> tickets)
{
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);
}
}
internal long CurrentWatermark { get { lock (_gate) return _watermark; } }
public void Dispose()
{
lock (_gate)
{
if (_disposed) return; _disposed = true; InvalidatePartition(); CleanupInvalidatedEpoch();
while (_queue.TryDequeue(out var p)) ReleasePending(p);
foreach (var p in _dirty.Values) ReleasePending(p);
_dirty.Clear(); _queuedValues = 0; _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; public int Retired; }
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 LastSubmitted; public long LastApplied; public long Barrier; public long InvalidationVersion;
}
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 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
{
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); }
public void Dispose() { if (Interlocked.Exchange(ref _completed, 1) == 0) partition.Abandon(state, charge); }
}
}