Files
lmxopcua/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/DataSubscriptionSession.cs
T
Joseph Doherty 5cccfd75ce fix(grpc-data): #994 projected cohorts batch, pace and scale past one item; busy origins no longer reset quiet streams
Wave 3 of the 2026-12-02 review (docs/reviews/2026-12-02/01-runtime.md R-2/3/7/8/9/10/12/13/21/22/23/24,
02-opcuaserver.md U-10/11/12/13).

Consumer (ProjectedDataAccess cohort):
- R-2: a cohort's OpenSubscription declared a snapshot budget of 1 item, which the origin uses to size the stream's
  handle table, so the 2nd item was refused LimitExceeded and the cohort re-opened in a loop (two projected items of
  one interval broke each other). Opens/adds/removes are now batched (IDataSubscriptionCommandLimits, <=256 items,
  bounded by estimated snapshot bytes) and paced (32 burst, 32/s, <=4 commands or snapshots outstanding).
- R-7: control events no longer share the bounded frame queue; a failed Remove can no longer Stop() the cohort.
- R-10: a local capacity refusal (TryPublishOrBackpressure -> CapacityExhausted) is retried for up to 2 s instead of
  invalidating healthy evidence and retiring the route.
- R-13: RemoteSubscription mutates its handle/version tables in place; the cohort caches the source per binding and
  drops the per-sample LINQ in EvidenceFor.
- R-8: only an unselectable endpoint arms the discovery backoff; a caller cancel is OperationCanceledException.
- R-24: the condition stream cancels and observes a pending frame read before disposing the enumerator.

Origin (DataSubscriptionSession / SamplePartition / SourceInterestLease):
- R-2 (found by the perf harness): the delivery index was sized MaxPendingFrames x 16 = 1024, so the 1025th item of a
  stream stopped the session after its ack; it now covers MaxMonitoredItems.
- R-3: interest reads count only own-ticket matches (scan budget separate), re-queue a lagging tick, and catch up from
  per-source last-change versions when the bounded history rolled off - no more "Source change history expired".
- R-9: a partition quiet bump resets a lease only when one of ITS sources was invalidated (per-source quiet version)
  or its binding retired; partition-wide invalidation still resets all.
- R-12: the per-item publish verdict is memoised per (catalog instance, authority generation) for <=1 s; Commit
  under the session lock re-checks identity only.
- R-21/R-22/R-23: registry prune is interval/capacity driven; a cleared history session refuses chunks; the snapshot
  barrier is decided and armed under the same gate its release is decided under.

Node manager: U-10 projected live items indexed by node; U-11 anchor removal / root-leaf swap tombstone the anchor's
own monitored node; U-12 per-parent child count; U-13 per-condition verdict index.

Also: Issue934_r1_N1 test clears its metadata failure before ending the stream (test-only sequencing race,
reproduced with a 200 ms delay; production behaviour correct).

Perf (Category=Perf, OTOPCUA_GRPCDATA_PERF=1): 10k-item cohort opens in 3.3 s / 80 commands / 1 stream (before: never
opens); 100 source versions at 1k/s -> 11,036 item values in 569 ms.
2026-12-03 11:59:26 -05:00

1356 lines
79 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
using System.Threading.Channels;
using System.Collections.Concurrent;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections;
namespace ZB.MOM.WW.OtOpcUa.Runtime.DataConnections;
/// <summary>One caller-bound subscription with bounded commands and one ordered delivery mode.</summary>
internal sealed partial class DataSubscriptionSession : IDataSubscriptionTransport, IDataSubscriptionCommandLimits
{
/// <summary>#994 (R-2): one command may carry up to the origin's batch limit.</summary>
public int MaxCommandItems => _services.SubscriptionLimits.MaxBatchItems;
private readonly LocalDataServices _services;
private readonly DataAuthenticatedContext _context;
private readonly DataTarget _target;
private readonly ISubscriptionDemandSource _demand;
private readonly SubscriptionSessionLimits _limits;
private readonly SubscriptionTransportCapacity _capacity;
private readonly SharedSessionLease _sessionLease;
private readonly Channel<Work> _commands;
private readonly Queue<Work> _deferred = new();
private readonly Channel<PendingDelivery> _outbound;
private readonly CancellationTokenSource _stop = new();
private readonly object _gate = new();
private readonly Dictionary<ulong, Item> _items = new();
private readonly Dictionary<string, Item> _itemsByClient = new(StringComparer.Ordinal);
private readonly LinkedList<InterestGroup> _interests = new();
private readonly HashSet<InterestGroup> _temporaryInterests = [];
private readonly Dictionary<ulong, int> _challengedHandles = new();
private LinkedListNode<InterestGroup>? _interestCursor;
private readonly List<SnapshotLease> _snapshots = [];
private readonly List<IDisposable> _snapshotAdmissions = [];
private readonly DeliveryScheduler _scheduler;
private readonly SortedSet<(long Due, ulong Handle)> _due = new();
private readonly LinkedList<ulong> _waiting = new();
private readonly LinkedList<SnapshotJob> _snapshotJobs = new();
private readonly ConcurrentQueue<SnapshotJob> _committedSnapshots = new();
private readonly HashSet<StagedChange> _pendingChanges = new();
private readonly SortedSet<(long Deadline, long Id)> _ackDeadlines = new();
private readonly Dictionary<string, (long Deadline, long Id)> _ackByCommand = new(StringComparer.Ordinal);
private SubscriptionItemHandleTable? _handles;
private ITimer? _expiry, _tick, _ackTimer, _preOpen;
private string? _subscriptionId;
private string? _freshnessChallengeId;
private ServingIdentity? _serving;
private long _epoch, _sequence, _dirtySequence, _ackId, _lastHeartbeat;
private long _lastFreshnessSequence;
private int _mode, _closed, _closing, _tickQueued, _queuedValues, _barrier, _admissionCursor, _coalesced;
private readonly Task _worker;
internal Task Completion => _worker;
internal Action? BeforeDirectCommitForTests { get; set; }
internal Action? SnapshotEndCommittedForTests { get; set; }
internal Action<int, int, int>? BeforeDirtyTickForTests { get; set; }
internal Action? AfterTickForTests { get; set; }
internal Action<DataItemHandle, long>? OnCandidateQueuedForTests { get; set; }
private sealed class SharedSessionLease(IDisposable lease) : IDisposable
{
private IDisposable? _lease = lease;
private int _references = 1;
private sealed class Hold(SharedSessionLease owner) : IDisposable
{
private SharedSessionLease? _owner = owner;
public void Dispose() => Interlocked.Exchange(ref _owner, null)?.Dispose();
}
internal IDisposable Retain()
{
while (true)
{
var current = Volatile.Read(ref _references);
if (current <= 0) throw new ObjectDisposedException(nameof(SharedSessionLease));
if (Interlocked.CompareExchange(ref _references, checked(current + 1), current) == current) return new Hold(this);
}
}
public void Dispose()
{
if (Interlocked.Decrement(ref _references) == 0) Interlocked.Exchange(ref _lease, null)?.Dispose();
}
}
private sealed record Work(DataSubscriptionCommand? Command, long Started, IDisposable? Charge = null);
private sealed class Item(string clientItemId, DataItemHandle handle, SubscriptionAuthorizedView view,
DataSubscriptionSettings settings, IDisposable demandLease, IDisposable itemReservation) : IDisposable
{
internal readonly string ClientItemId = clientItemId;
internal readonly DataItemHandle Handle = handle;
internal readonly SubscriptionAuthorizedView View = view;
internal DataSubscriptionSettings Settings = settings;
internal IDisposable DemandLease = demandLease;
internal readonly SharedSessionLease Resources = new(itemReservation);
internal readonly ClientFilterState Filter = new();
internal IDisposable? BaselineCharge;
internal SourceTicket? Ticket;
internal long LastConsidered, LastPublished, NextDue = 0;
internal long? LastDeliveryTimestamp;
internal long? QueuedDue;
internal LinkedListNode<ulong>? WaitingNode;
internal InterestGroup? Interest;
public void Dispose() { Filter.Dispose(); BaselineCharge?.Dispose(); DemandLease.Dispose(); Resources.Dispose(); }
}
private sealed class InterestGroup(SourceInterestLease lease)
{
internal readonly SourceInterestLease Lease = lease;
internal int Count;
internal readonly Dictionary<BackingSourceKey, int> Sources = new();
internal LinkedListNode<InterestGroup>? Node;
internal bool SnapshotComplete;
/// <summary>Set under the session gate when the session itself releases the group (its last item went).</summary>
internal bool Released;
}
private sealed class SnapshotJob(SnapshotLease snapshot, IDisposable admission, InterestGroup group,
IReadOnlyList<Item> items, IReadOnlyList<PartitionWatermark> watermarks, bool temporaryInterest = false)
{
internal readonly SnapshotLease Snapshot = snapshot;
internal readonly IDisposable Admission = admission;
internal readonly InterestGroup Group = group;
internal readonly IReadOnlyList<Item> Items = items;
internal readonly IReadOnlyList<PartitionWatermark> Watermarks = watermarks;
internal int Index;
internal bool Started;
internal readonly bool TemporaryInterest = temporaryInterest;
}
private sealed class StagedChange(Item previous, SubscriptionAuthorizedView view, DataSubscriptionSettings settings,
IDisposable demand, SnapshotLease snapshot, SourceInterestLease interest, IDisposable admission,
Item? replacement)
{
internal readonly Item Previous = previous;
internal readonly SubscriptionAuthorizedView View = view;
internal readonly DataSubscriptionSettings Settings = settings;
internal readonly IDisposable Demand = demand;
internal readonly SnapshotLease Snapshot = snapshot;
internal readonly SourceInterestLease Interest = interest;
internal readonly IDisposable Admission = admission;
internal readonly Item? Replacement = replacement;
internal int State = 0;
}
private sealed class BudgetLease(DataResourceBudget budget, long charge) : IDisposable
{
private DataResourceBudget? _budget = budget;
public void Dispose() => Interlocked.Exchange(ref _budget, null)?.Release(charge);
}
private sealed class CompositeLease(IDisposable first, IDisposable second) : IDisposable
{
private IDisposable? _first = first, _second = second;
public void Dispose()
{
try { Interlocked.Exchange(ref _first, null)?.Dispose(); }
finally { Interlocked.Exchange(ref _second, null)?.Dispose(); }
}
}
private sealed class SnapshotOwnership(SnapshotAdmissionScheduler.Permit permit, IDisposable hold) : IDisposable
{
internal readonly SnapshotAdmissionScheduler.Permit Permit = permit;
private IDisposable? _hold = hold;
public void Dispose()
{
Permit.Dispose();
Interlocked.Exchange(ref _hold, null)?.Dispose();
}
}
private sealed class PendingDelivery(Func<long, DataSubscriptionFrame> create, Func<bool> gate,
Func<bool>? commit = null, Action? drop = null, bool isValue = false, Func<bool>? obsolete = null,
Func<bool>? eligible = null, Func<long, (bool Accepted, TimeSpan Retry)>? consumeSnapshot = null,
long directSnapshotBytes = 0, Action? settle = null, Action? failed = null,
Func<bool>? finalAuthority = null) : IDisposable
{
private int _transferred, _settled;
internal bool IsValue { get; } = isValue;
internal bool IsObsolete() => obsolete?.Invoke() == true;
internal bool IsEligible() => eligible?.Invoke() ?? true;
internal (bool Accepted, TimeSpan Retry) ConsumeSnapshot(long? bytes = null) =>
consumeSnapshot?.Invoke(bytes ?? directSnapshotBytes) ?? (true, TimeSpan.Zero);
internal bool Gate() => gate();
internal bool FinalAuthority() => finalAuthority?.Invoke() ?? true;
internal bool Commit()
{
var success = false;
try { success = commit?.Invoke() ?? true; return success; }
finally { Settle(success); }
}
internal void Fail() => Settle(false);
private void Settle(bool success)
{
if (Interlocked.Exchange(ref _settled, 1) != 0) return;
try { if (!success) failed?.Invoke(); }
finally { settle?.Invoke(); }
}
internal DataSubscriptionFrame Take(long sequence)
{
if (Interlocked.Exchange(ref _transferred, 1) != 0) throw new InvalidOperationException();
try { return create(sequence); }
catch { drop?.Invoke(); Settle(false); throw; }
}
public void Dispose()
{
try { if (Interlocked.Exchange(ref _transferred, 1) == 0) drop?.Invoke(); }
finally { Settle(false); }
}
}
internal DataSubscriptionSession(LocalDataServices services, DataAuthenticatedContext context, DataTarget target,
ISubscriptionDemandSource demand, SubscriptionSessionLimits limits, SubscriptionTransportCapacity capacity,
IDisposable sessionReservation, CancellationToken lifetimeToken = default)
{
_services = services; _context = context; _target = target; _demand = demand; _limits = limits; _capacity = capacity;
_sessionLease = new(sessionReservation);
limits.Validate();
_commands = Channel.CreateBounded<Work>(new BoundedChannelOptions(limits.MaxCommands)
{ SingleReader = true, FullMode = BoundedChannelFullMode.Wait });
_outbound = Channel.CreateBounded<PendingDelivery>(new BoundedChannelOptions(limits.MaxPendingFrames)
{ SingleReader = true, SingleWriter = true, FullMode = BoundedChannelFullMode.Wait });
// #994 (R-2): the delivery index must hold every item (and every distinct source) the stream may admit. It was sized
// from the frame window alone (MaxPendingFrames × 16 = 1024 by default), so the 1025th item — inside the advertised
// MaxMonitoredItems — failed registration AFTER its acknowledgement and stopped the whole session.
var schedulerCapacity = checked(Math.Max(limits.MaxPendingFrames * 16, services.SubscriptionLimits.MaxMonitoredItems) +
limits.MaxPendingFrames * 16);
_scheduler = new DeliveryScheduler(schedulerCapacity, schedulerCapacity);
var preOpen = limits.PreOpenTimeout ?? TimeSpan.FromSeconds(10);
_preOpen = services.Clock.CreateTimer(static state => ((DataSubscriptionSession)state!).Stop(), this,
preOpen, Timeout.InfiniteTimeSpan);
_worker = Task.Run(() => ProcessCommandsAsync(lifetimeToken));
}
public Task SendAsync(DataSubscriptionCommand command, CancellationToken cancellationToken)
{
ArgumentNullException.ThrowIfNull(command); cancellationToken.ThrowIfCancellationRequested();
if (Volatile.Read(ref _closed) != 0 || Volatile.Read(ref _closing) != 0) throw new InvalidOperationException("Subscription is closed.");
if (command.AcknowledgementTimeout <= TimeSpan.Zero || command.AcknowledgementTimeout > TimeSpan.FromMilliseconds(uint.MaxValue - 1))
throw new ArgumentOutOfRangeException(nameof(command));
ArgumentException.ThrowIfNullOrWhiteSpace(command.CommandId);
ArgumentException.ThrowIfNullOrWhiteSpace(command.SubscriptionId);
if (!_capacity.TryAdmitCommand(_context.PrincipalId)) { Stop(); throw new InvalidOperationException("Principal command rate exceeded."); }
var reservedBytes = _limits.MaxPendingBytes;
if (!_services.SubscriptionHub.Resources.TryReserve(reservedBytes)) throw new InvalidOperationException("Command memory capacity exhausted.");
var commandCharge = new BudgetLease(_services.SubscriptionHub.Resources, reservedBytes);
try { command = CopyCommand(command); }
catch { commandCharge.Dispose(); throw; }
var started = _services.Clock.GetTimestamp();
try
{
lock (_gate)
{
if (_ackByCommand.ContainsKey(command.CommandId) || _ackByCommand.Count >= _limits.MaxCommands)
throw new InvalidOperationException("Command ID is pending or command capacity is exhausted.");
var delta = (decimal)command.AcknowledgementTimeout.Ticks * _services.Clock.TimestampFrequency / TimeSpan.TicksPerSecond;
var deadline = delta >= (decimal)long.MaxValue - started ? long.MaxValue : started + (long)decimal.Ceiling(delta);
var entry = (deadline, checked(++_ackId));
_ackByCommand.Add(command.CommandId, entry); _ackDeadlines.Add(entry);
try { ArmAckTimer(); }
catch { _ackByCommand.Remove(command.CommandId); _ackDeadlines.Remove(entry); throw; }
}
if (!_commands.Writer.TryWrite(new(command, started, commandCharge)))
{ Stop(); throw new InvalidOperationException("Subscription command capacity exhausted."); }
}
catch { commandCharge.Dispose(); throw; }
return Task.CompletedTask;
}
private DataSubscriptionCommand CopyCommand(DataSubscriptionCommand command)
{
long bytes = checked(256L + 2L * (command.SubscriptionId.Length + command.CommandId.Length));
DataSubscriptionItem[] CopyItems(IReadOnlyList<DataSubscriptionItem> source)
{
ArgumentNullException.ThrowIfNull(source);
if (source.Count > _services.SubscriptionLimits.MaxBatchItems) throw new ArgumentOutOfRangeException(nameof(source));
var copy = new DataSubscriptionItem[source.Count];
for (var i = 0; i < copy.Length; i++)
{
var item = source[i] ?? throw new ArgumentException("Null subscription item.");
var view = item.View ?? throw new ArgumentException("Missing subscription view.");
var address = view.Address ?? throw new ArgumentException("Missing subscription address.");
bytes = checked(bytes + 512L + 2L * ((long)(item.ClientItemId?.Length ?? 0) + (view.Subject?.Length ?? 0) +
(view.MappingId?.Length ?? 0) + (address.OriginClusterId?.Length ?? 0) + (address.NamespaceUri?.Length ?? 0) +
(address.IdentifierKind?.Length ?? 0) + (address.Identifier?.Length ?? 0)));
if (bytes > _limits.MaxPendingBytes) throw new ArgumentOutOfRangeException(nameof(source));
copy[i] = item;
}
return copy;
}
DataItemHandle[] CopyHandles(IReadOnlyList<DataItemHandle> source)
{
ArgumentNullException.ThrowIfNull(source);
if (source.Count > _services.SubscriptionLimits.MaxBatchItems) throw new ArgumentOutOfRangeException(nameof(source));
var copy = new DataItemHandle[source.Count];
for (var i = 0; i < copy.Length; i++)
{
var item = source[i] ?? throw new ArgumentException("Null item handle.");
bytes = checked(bytes + 128L + 2L * (item.SubscriptionId?.Length ?? 0));
if (bytes > _limits.MaxPendingBytes) throw new ArgumentOutOfRangeException(nameof(source));
copy[i] = item;
}
return copy;
}
DataSubscriptionCommand result = command switch
{
OpenSubscription open => open with { Items = CopyItems(open.Items) },
AddSubscriptionItems add => add with { Items = CopyItems(add.Items) },
ModifySubscriptionItems modify => modify with { Items = CopyItems(modify.Items) },
RemoveSubscriptionItems remove => remove with { Items = CopyHandles(remove.Items) },
ChallengeSubscriptionFreshness challenge => challenge with { Items = CopyHandles(challenge.Items) },
_ => throw new ArgumentException("Unknown subscription command.", nameof(command))
};
if (bytes > _limits.MaxPendingBytes) throw new ArgumentOutOfRangeException(nameof(command));
return result;
}
private void ArmAckTimer()
{
if (_ackDeadlines.Count == 0) { _ackTimer?.Change(Timeout.InfiniteTimeSpan, Timeout.InfiniteTimeSpan); return; }
var now = _services.Clock.GetTimestamp();
var deadline = _ackDeadlines.Min.Deadline;
var due = deadline <= now ? TimeSpan.Zero : _services.Clock.GetElapsedTime(now, deadline);
_ackTimer ??= _services.Clock.CreateTimer(static state => ((DataSubscriptionSession)state!).Stop(), this,
Timeout.InfiniteTimeSpan, Timeout.InfiniteTimeSpan);
_ackTimer.Change(due, Timeout.InfiniteTimeSpan);
}
private bool CompleteAck(string command)
{
lock (_gate)
{
if (!_ackByCommand.Remove(command, out var entry) || _services.Clock.GetTimestamp() >= entry.Deadline) return false;
_ackDeadlines.Remove(entry); ArmAckTimer();
}
ActivateConditionItems(command); // A2: a condition item's frames follow its delivered ack
return true;
}
private async Task ProcessCommandsAsync(CancellationToken lifetimeToken)
{
using var lifetime = lifetimeToken.Register(static state => ((DataSubscriptionSession)state!).Stop(), this);
try
{
while (!_stop.IsCancellationRequested)
{
Work work;
if (Volatile.Read(ref _barrier) == 0 && _deferred.TryDequeue(out var deferred)) work = deferred;
else work = await _commands.Reader.ReadAsync(_stop.Token).ConfigureAwait(false);
var retained = false;
try
{
if (work.Command is null) { Interlocked.Exchange(ref _tickQueued, 0); await TickAsync().ConfigureAwait(false); continue; }
if (Volatile.Read(ref _barrier) != 0)
{
if (_deferred.Count >= _limits.MaxCommands) { Stop(); break; }
_deferred.Enqueue(work); retained = true; continue;
}
var command = work.Command;
if (_services.Clock.GetElapsedTime(work.Started) >= command.AcknowledgementTimeout) { Stop(); break; }
if (command is OpenSubscription open) await OpenAsync(open, work.Started).ConfigureAwait(false);
else
{
if (_handles is null || command.SubscriptionId != _subscriptionId || command.StreamEpoch != _epoch) { Stop(); break; }
// #994 (R-23): decide AND arm under the gate the SnapshotEnd commit decides its release under. A check
// released before the CAS let that commit's ReleaseBarrier(1) find 0 and no-op, after which the CAS
// armed a barrier nothing would release: every later command deferred until its ack timeout.
if (TryArmSnapshotBarrier(command))
{ AfterSnapshotBarrierCheckForTests?.Invoke(); _deferred.Enqueue(work); retained = true; continue; }
switch (command)
{
case AddSubscriptionItems add: await AddAsync(add.Items, add.CommandId, work.Started, add.AcknowledgementTimeout).ConfigureAwait(false); break;
case ModifySubscriptionItems modify: await ModifyAsync(modify, work.Started).ConfigureAwait(false); break;
case RemoveSubscriptionItems remove: await RemoveAsync(remove).ConfigureAwait(false); break;
case ChallengeSubscriptionFreshness challenge: await ChallengeFreshnessAsync(challenge).ConfigureAwait(false); break;
default: Stop(); break;
}
}
}
finally { if (!retained) work.Charge?.Dispose(); }
}
}
catch (OperationCanceledException) when (_stop.IsCancellationRequested) { }
catch { Stop(); }
finally
{
_outbound.Writer.TryComplete();
while (_commands.Reader.TryRead(out var abandoned)) abandoned.Charge?.Dispose();
while (_deferred.TryDequeue(out var deferredWork)) deferredWork.Charge?.Dispose();
while (_outbound.Reader.TryRead(out var pending)) { Dequeued(pending); pending.Dispose(); }
lock (_gate)
{
foreach (var item in _items.Values) item.Dispose();
_items.Clear();
_itemsByClient.Clear();
foreach (var interest in _interests) interest.Lease.Dispose();
_interests.Clear();
foreach (var interest in _temporaryInterests) interest.Lease.Dispose();
_temporaryInterests.Clear();
foreach (var snapshot in _snapshots) snapshot.Dispose();
_snapshots.Clear();
foreach (var admission in _snapshotAdmissions) admission.Dispose();
_snapshotAdmissions.Clear();
_snapshotJobs.Clear();
foreach (var change in _pendingChanges.ToArray()) CleanupStaged(change);
_pendingChanges.Clear();
TearDownConditions();
}
_sessionLease.Dispose();
}
}
private bool HasIncompleteSnapshot()
{
lock (_gate) return _interests.Any(group => !group.SnapshotComplete);
}
private bool HasOutstandingSnapshots()
{
lock (_gate) return _snapshots.Count != 0;
}
internal Action? AfterSnapshotBarrierCheckForTests { get; set; }
internal Action? SnapshotEndReleasedForTests { get; set; }
private bool TryArmSnapshotBarrier(DataSubscriptionCommand command)
{
lock (_gate)
{
var defer = command is ModifySubscriptionItems && _interests.Any(group => !group.SnapshotComplete) ||
command is ChallengeSubscriptionFreshness && _snapshots.Count != 0;
if (defer) Interlocked.CompareExchange(ref _barrier, 1, 0);
return defer;
}
}
private void ReleaseBarrier(int expected)
{
if (Interlocked.CompareExchange(ref _barrier, 0, expected) != expected) return;
// A full command queue already wakes the worker; otherwise this bounded signal does.
_commands.Writer.TryWrite(new(null, 0));
}
private async Task OpenAsync(OpenSubscription open, long started)
{
if (_handles is not null || string.IsNullOrWhiteSpace(open.SubscriptionId) || open.StreamEpoch <= 0 ||
open.SessionLifetime <= TimeSpan.Zero || open.SessionLifetime > _limits.MaxSessionLifetime ||
open.SessionLifetime > _services.SubscriptionLimits.MaxSessionLifetime)
{ Stop(); return; }
open.SnapshotBudget.Validate();
_serving = _services.SubscriptionServing(_context, _target);
if (_serving is null) { Stop(); return; }
_subscriptionId = open.SubscriptionId; _epoch = open.StreamEpoch;
_lastHeartbeat = _services.Clock.GetTimestamp();
_handles = new SubscriptionItemHandleTable(open.SubscriptionId, open.StreamEpoch,
Math.Min(open.SnapshotBudget.MaxItems, _services.SubscriptionItemLimit(_context)));
Interlocked.Exchange(ref _preOpen, null)?.Dispose();
var duration = open.SessionLifetime;
if (_context.CredentialExpiresUtc is { } expires)
{
var untilExpiry = expires - _services.Clock.GetUtcNow();
if (untilExpiry <= TimeSpan.Zero) { Stop(); return; }
if (untilExpiry < duration) duration = untilExpiry;
}
_expiry = _services.Clock.CreateTimer(static s => ((DataSubscriptionSession)s!).Stop(), this, duration, Timeout.InfiniteTimeSpan);
_tick = _services.Clock.CreateTimer(static s => ((DataSubscriptionSession)s!).QueueTick(), this,
TimeSpan.FromMilliseconds(100), TimeSpan.FromMilliseconds(100));
await AddAsync(open.Items, open.CommandId, started, open.AcknowledgementTimeout, open.SnapshotBudget).ConfigureAwait(false);
}
private async Task AddAsync(IReadOnlyList<DataSubscriptionItem> requested, string commandId, long started,
TimeSpan timeout, DataBudget? snapshotBudget = null)
{
var acks = new List<DataSubscriptionItemAck>(requested.Count);
var admitted = new List<Item>();
foreach (var request in requested)
{
_stop.Token.ThrowIfCancellationRequested();
if (request is null || string.IsNullOrWhiteSpace(request.ClientItemId) || request.View is null || request.Settings is null)
{ acks.Add(new(request?.ClientItemId ?? "", DataItemStatus.InvalidArgument, null, null, null)); continue; }
// A2: a root-scoped condition item (the host only lets one through on a call that negotiated `conditions`).
if (request.ConditionScope is not null) { acks.Add(AddConditionItem(request, commandId)); continue; }
DataItemStatus status;
SubscriptionAuthorizedView? view;
try { request.Settings.Validate(); status = _services.AuthorizeSubscription(_context, _target, request.View, out view); }
catch (ArgumentException) { acks.Add(new(request.ClientItemId, DataItemStatus.InvalidArgument, null, null, null)); continue; }
if (status != DataItemStatus.Good || view is null)
{ acks.Add(new(request.ClientItemId, status, null, null, null)); continue; }
if (view.Serving != _serving)
{ acks.Add(new(request.ClientItemId, DataItemStatus.Unavailable, null, null, null)); continue; }
if (request.Settings.Deadband is not null && view.Metadata.ValueKind is not (DataValueKind.Int8 or DataValueKind.Int16 or
DataValueKind.Int32 or DataValueKind.Int64 or DataValueKind.UInt8 or DataValueKind.UInt16 or DataValueKind.UInt32 or
DataValueKind.UInt64 or DataValueKind.Float or DataValueKind.Double))
{ acks.Add(new(request.ClientItemId, DataItemStatus.Unsupported, null, null, "Deadband requires a numeric scalar.")); continue; }
var fixedBytes = checked(1024L + 2L * (request.ClientItemId.Length + view.View.Subject.Length +
view.View.Address.Identifier.Length + view.View.Address.NamespaceUri.Length + view.Source.StableSourceId.Length));
var itemLimit = _services.SubscriptionItemLimit(_context);
if (itemLimit <= 0 || !_capacity.TryReserveInterest(_context.PrincipalId, itemLimit, fixedBytes, out var itemReservation))
{ acks.Add(new(request.ClientItemId, DataItemStatus.LimitExceeded, null, null, null)); continue; }
var remaining = timeout - _services.Clock.GetElapsedTime(started);
if (remaining <= TimeSpan.Zero) { itemReservation!.Dispose(); Stop(); return; }
Task<SubscriptionDemandResult> pending;
try { pending = _demand.AcquireAsync(view, request.Settings, _stop.Token).AsTask(); }
catch (Exception ex) when (ex is not OutOfMemoryException)
{ itemReservation!.Dispose(); acks.Add(new(request.ClientItemId, DataItemStatus.Unavailable, null, null, null)); continue; }
SubscriptionDemandResult result;
try { result = await pending.WaitAsync(remaining, _services.Clock, _stop.Token).ConfigureAwait(false); }
catch (Exception ex) when (ex is TimeoutException or OperationCanceledException)
{
itemReservation!.Dispose();
_ = pending.ContinueWith(static task => { if (task.Status == TaskStatus.RanToCompletion) task.Result.Lease?.Dispose(); },
CancellationToken.None, TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default);
Stop(); return;
}
catch (Exception ex) when (ex is not OutOfMemoryException)
{ itemReservation!.Dispose(); acks.Add(new(request.ClientItemId, DataItemStatus.Unavailable, null, null, null)); continue; }
if (result.Status != DataItemStatus.Good || result.Lease is null || result.RevisedSettings is null || result.Boundary <= 0 || !view.CanPublish())
{
itemReservation!.Dispose(); result.Lease?.Dispose(); acks.Add(new(request.ClientItemId,
result.Status == DataItemStatus.Good ? DataItemStatus.Unavailable : result.Status, null, null, null)); continue;
}
DataItemHandle handle;
try { handle = _handles!.Add(request.ClientItemId); }
catch (Exception ex) when (ex is InvalidOperationException or OverflowException)
{ itemReservation!.Dispose(); result.Lease.Dispose(); acks.Add(new(request.ClientItemId, DataItemStatus.LimitExceeded, null, null, null)); continue; }
var item = new Item(request.ClientItemId, handle, view, result.RevisedSettings, result.Lease, itemReservation!);
if (_services.SubscriptionHub.TryGetCurrentTicket(view.Source, out var ticket)) item.Ticket = ticket;
lock (_gate) { _items.Add(handle.Handle, item); _itemsByClient.Add(item.ClientItemId, item); }
if (item.Ticket is null) lock (_gate) item.WaitingNode = _waiting.AddLast(handle.Handle);
admitted.Add(item);
acks.Add(new(request.ClientItemId, item.Ticket is null ? DataItemStatus.WaitingForInitialData : DataItemStatus.Good,
handle, result.RevisedSettings, null));
}
if (_services.Clock.GetElapsedTime(started) >= timeout) { Stop(); return; }
if (admitted.Count == 0) { await EnqueueAsync(ControlAck(commandId, acks)).ConfigureAwait(false); return; }
var tickets = admitted.Where(x => x.Ticket is not null).Select(x => x.Ticket!.Value).Distinct().ToArray();
if (tickets.Length == 0)
{ await EnqueueAsync(ControlAck(commandId, acks, () => admitted.All(item => item.View.CanPublish()))).ConfigureAwait(false); return; }
var budget = snapshotBudget ?? new DataBudget(timeout, Math.Max(tickets.Length, 1), _limits.MaxPendingBytes);
if (!_capacity.Snapshots.TryAcquire(_context.PrincipalId, 1, out var rawAdmission)) { CloseWithReset("Snapshot admission exhausted; retry later."); return; }
var permit = (SnapshotAdmissionScheduler.Permit)rawAdmission!;
if (!permit.TryRetain(out var snapshotHold)) { permit.Dispose(); CloseWithReset("Snapshot admission expired."); return; }
var admission = new SnapshotOwnership(permit, snapshotHold!);
if (!_services.SubscriptionHub.TryCaptureInterestSnapshot(tickets, budget, _stop.Token, out var snapshot, out var interest,
permit))
{ admission.Dispose(); Stop(); return; }
InterestGroup group;
lock (_gate)
{
_snapshots.Add(snapshot!); _snapshotAdmissions.Add(admission!);
group = new InterestGroup(interest!);
foreach (var item in admitted.Where(x => x.Ticket is not null))
{
item.Interest = group; group.Count++;
group.Sources.TryGetValue(item.View.Source, out var count);
group.Sources[item.View.Source] = count + 1;
}
group.Node = _interests.AddLast(group);
}
var byHandle = admitted.ToDictionary(x => x.Handle.Handle);
for (var i = 0; i < acks.Count; i++)
{
if (acks[i].Handle is not { } handle) continue;
var item = byHandle[handle.Handle];
if (item.Ticket is not { } ticket || !snapshot!.Items.TryGetValue(ticket, out var captured) ||
captured.Readiness != DataReadiness.Ready || captured.Sample is null)
acks[i] = acks[i] with { Status = DataItemStatus.WaitingForInitialData };
}
await EnqueueAsync(ControlAck(commandId, acks,
() => !snapshot!.IsReset && admission.Permit.IsValid && admitted.All(item => item.View.CanPublish()))).ConfigureAwait(false);
var marks = snapshot!.Watermarks.Select(x => new PartitionWatermark(x.Key, x.Value)).ToArray();
foreach (var item in admitted)
{
if (item.Ticket is not { } ticket || !snapshot.Items.TryGetValue(ticket, out var captured)) continue;
if (!_scheduler.TryRegister(item.View.Source, checked((long)item.Handle.Handle))) { Stop(); return; }
if (captured.Sample is not null) item.LastConsidered = captured.Sample.Version;
}
_snapshotJobs.AddLast(new SnapshotJob(snapshot, admission, group, admitted, marks));
await PumpSnapshotsAsync().ConfigureAwait(false);
}
private async Task ChallengeFreshnessAsync(ChallengeSubscriptionFreshness challenge)
{
// Limit both capture work and retained memory through the same snapshot admission as Open/Add.
if (challenge.CommandId.Length > 32 || !challenge.CommandId.StartsWith("freshness-", StringComparison.Ordinal) ||
!long.TryParse(challenge.CommandId.AsSpan("freshness-".Length), System.Globalization.NumberStyles.None,
System.Globalization.CultureInfo.InvariantCulture, out var sequence) || sequence <= _lastFreshnessSequence ||
challenge.Items.Count == 0 || challenge.Items.Count > _services.SubscriptionLimits.MaxBatchItems ||
challenge.Items.Distinct().Count() != challenge.Items.Count) { Stop(); return; }
var items = new List<Item>(challenge.Items.Count);
lock (_gate)
{
foreach (var handle in challenge.Items)
{
if (!_handles!.IsCurrent(handle) || !_items.TryGetValue(handle.Handle, out var item) ||
item.Handle != handle || item.Ticket is null || !item.View.CanPublish()) { Stop(); return; }
items.Add(item);
}
}
var tickets = items.Select(x => x.Ticket!.Value).Distinct().ToArray();
if (!_capacity.Snapshots.TryAcquire(_context.PrincipalId, 1, out var rawAdmission))
{ CloseWithReset("Freshness snapshot admission exhausted; retry later."); return; }
var permit = (SnapshotAdmissionScheduler.Permit)rawAdmission!;
if (!permit.TryRetain(out var hold)) { permit.Dispose(); Stop(); return; }
var admission = new SnapshotOwnership(permit, hold!);
var budget = new DataBudget(challenge.AcknowledgementTimeout, tickets.Length, _limits.MaxPendingBytes);
if (!_services.SubscriptionHub.TryCaptureInterestSnapshot(tickets, budget, _stop.Token, out var snapshot, out var interest, permit))
{ admission.Dispose(); Stop(); return; }
var group = new InterestGroup(interest!);
_lastFreshnessSequence = sequence;
lock (_gate)
{
_snapshots.Add(snapshot!); _snapshotAdmissions.Add(admission); _temporaryInterests.Add(group);
foreach (var item in items)
{
_challengedHandles.TryGetValue(item.Handle.Handle, out var count);
_challengedHandles[item.Handle.Handle] = checked(count + 1);
}
}
// Values created after this store compute their age after the causal challenge.
Volatile.Write(ref _freshnessChallengeId, challenge.CommandId);
var acks = items.Select(item => new DataSubscriptionItemAck(item.ClientItemId, DataItemStatus.Good, item.Handle, item.Settings, null)).ToArray();
await EnqueueAsync(ControlAck(challenge.CommandId, acks,
() => !snapshot!.IsReset && permit.IsValid && items.All(item => item.View.CanPublish()))).ConfigureAwait(false);
var marks = snapshot!.Watermarks.Select(x => new PartitionWatermark(x.Key, x.Value)).ToArray();
_snapshotJobs.AddLast(new SnapshotJob(snapshot, admission, group, items, marks, temporaryInterest: true));
await PumpSnapshotsAsync().ConfigureAwait(false);
}
private async Task RemoveAsync(RemoveSubscriptionItems remove)
{
var acks = new List<DataSubscriptionItemAck>();
foreach (var handle in remove.Items)
{
Item? item;
lock (_gate)
{
if (!_handles!.IsCurrent(handle) || !_items.Remove(handle.Handle, out item)) item = null;
else { _handles.Remove(handle); _itemsByClient.Remove(item.ClientItemId); }
}
if (item is null && TryRemoveConditionItem(handle, out var conditionAck)) { acks.Add(conditionAck); continue; }
if (item is null) { acks.Add(new("", DataItemStatus.NotFound, null, null, null)); continue; }
ReleaseItem(item);
acks.Add(new(item.ClientItemId, DataItemStatus.Good, handle, null, null));
}
await EnqueueAsync(ControlAck(remove.CommandId, acks)).ConfigureAwait(false);
}
private async Task ModifyAsync(ModifySubscriptionItems modify, long started)
{
var acks = new List<DataSubscriptionItemAck>(modify.Items.Count);
var changes = new List<StagedChange>();
var seen = new HashSet<string>(StringComparer.Ordinal);
foreach (var request in modify.Items)
{
if (request is null || string.IsNullOrWhiteSpace(request.ClientItemId) || request.View is null || request.Settings is null || !seen.Add(request.ClientItemId))
{ acks.Add(new(request?.ClientItemId ?? "", DataItemStatus.InvalidArgument, null, null, null)); continue; }
Item? previous;
lock (_gate) _itemsByClient.TryGetValue(request.ClientItemId, out previous);
if (previous is null) { acks.Add(new(request.ClientItemId, DataItemStatus.NotFound, null, null, null)); continue; }
DataItemStatus status;
SubscriptionAuthorizedView? view;
try { request.Settings.Validate(); status = _services.AuthorizeSubscription(_context, _target, request.View, out view); }
catch (ArgumentException) { acks.Add(new(request.ClientItemId, DataItemStatus.InvalidArgument, null, null, null)); continue; }
if (status != DataItemStatus.Good || view is null || view.Serving != _serving)
{ acks.Add(new(request.ClientItemId, status == DataItemStatus.Good ? DataItemStatus.Unavailable : status, null, null, null)); continue; }
if (request.Settings.Deadband is not null && view.Metadata.ValueKind is not (DataValueKind.Int8 or DataValueKind.Int16 or
DataValueKind.Int32 or DataValueKind.Int64 or DataValueKind.UInt8 or DataValueKind.UInt16 or DataValueKind.UInt32 or
DataValueKind.UInt64 or DataValueKind.Float or DataValueKind.Double))
{ acks.Add(new(request.ClientItemId, DataItemStatus.Unsupported, null, null, null)); continue; }
var remaining = modify.AcknowledgementTimeout - _services.Clock.GetElapsedTime(started);
if (remaining <= TimeSpan.Zero) { foreach (var c in changes) CleanupStaged(c); Stop(); return; }
Task<SubscriptionDemandResult> pending;
try { pending = _demand.AcquireAsync(view, request.Settings, _stop.Token).AsTask(); }
catch (Exception ex) when (ex is not OutOfMemoryException)
{ acks.Add(new(request.ClientItemId, DataItemStatus.Unavailable, null, null, null)); continue; }
SubscriptionDemandResult result;
try { result = await pending.WaitAsync(remaining, _services.Clock, _stop.Token).ConfigureAwait(false); }
catch (Exception ex) when (ex is TimeoutException or OperationCanceledException)
{
_ = pending.ContinueWith(static task => { if (task.Status == TaskStatus.RanToCompletion) task.Result.Lease?.Dispose(); },
CancellationToken.None, TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default);
foreach (var c in changes) CleanupStaged(c); Stop(); return;
}
catch (Exception ex) when (ex is not OutOfMemoryException)
{ acks.Add(new(request.ClientItemId, DataItemStatus.Unavailable, null, null, null)); continue; }
if (result.Status != DataItemStatus.Good || result.Lease is null || result.RevisedSettings is null || result.Boundary <= 0 ||
!view.CanPublish() || !_services.SubscriptionHub.TryGetCurrentTicket(view.Source, out var ticket))
{
result.Lease?.Dispose(); acks.Add(new(request.ClientItemId,
result.Status == DataItemStatus.Good ? DataItemStatus.WaitingForInitialData : result.Status, null, null, null)); continue;
}
var budget = new DataBudget(remaining, 1, _limits.MaxPendingBytes);
if (!_capacity.Snapshots.TryAcquire(_context.PrincipalId, 1, out var rawAdmission))
{
result.Lease.Dispose();
acks.Add(new(request.ClientItemId, DataItemStatus.ResourceExhausted, null, null, null)); continue;
}
var permit = (SnapshotAdmissionScheduler.Permit)rawAdmission!;
if (!permit.TryRetain(out var snapshotHold))
{ permit.Dispose(); result.Lease.Dispose(); acks.Add(new(request.ClientItemId, DataItemStatus.ResourceExhausted, null, null, null)); continue; }
var admission = new SnapshotOwnership(permit, snapshotHold!);
if (!_services.SubscriptionHub.TryCaptureInterestSnapshot([ticket], budget, _stop.Token, out var snapshot, out var interest, permit))
{ admission.Dispose(); result.Lease.Dispose(); acks.Add(new(request.ClientItemId, DataItemStatus.ResourceExhausted, null, null, null)); continue; }
var captured = snapshot!.Items[ticket];
if (captured.Readiness != DataReadiness.Ready || captured.Sample is null)
{
snapshot.Dispose(); interest!.Dispose(); admission!.Dispose(); result.Lease.Dispose();
acks.Add(new(request.ClientItemId, DataItemStatus.WaitingForInitialData, null, null, null)); continue;
}
var intervalOnly = previous.View.View == view.View && previous.Settings.Trigger == result.RevisedSettings.Trigger &&
previous.Settings.Deadband == result.RevisedSettings.Deadband;
Item? replacement = null;
if (!intervalOnly)
{
var fixedBytes = checked(1024L + 2L * (request.ClientItemId.Length + view.View.Subject.Length +
view.View.Address.Identifier.Length + view.View.Address.NamespaceUri.Length + view.Source.StableSourceId.Length));
if (!_capacity.TryReserveInterest(_context.PrincipalId, _services.SubscriptionItemLimit(_context), fixedBytes, out var itemReservation))
{
snapshot.Dispose(); interest!.Dispose(); admission!.Dispose(); result.Lease.Dispose();
acks.Add(new(request.ClientItemId, DataItemStatus.LimitExceeded, null, null, null)); continue;
}
DataItemHandle handle;
try { handle = _handles!.ReserveReplacement(previous.Handle); }
catch (Exception ex) when (ex is InvalidOperationException or OverflowException)
{
itemReservation!.Dispose(); snapshot.Dispose(); interest!.Dispose(); admission!.Dispose(); result.Lease.Dispose();
acks.Add(new(request.ClientItemId, DataItemStatus.LimitExceeded, null, null, null)); continue;
}
replacement = new Item(request.ClientItemId, handle, view, result.RevisedSettings, result.Lease, itemReservation!)
{ Ticket = ticket, LastConsidered = captured.Sample.Version };
if (!_scheduler.TryRegister(view.Source, checked((long)handle.Handle)))
{
_handles.CancelReplacement(handle); replacement.Dispose(); snapshot.Dispose(); interest!.Dispose(); admission!.Dispose();
acks.Add(new(request.ClientItemId, DataItemStatus.ResourceExhausted, null, null, null)); continue;
}
}
var change = new StagedChange(previous, view, result.RevisedSettings, result.Lease, snapshot, interest!, admission!, replacement);
lock (_gate) _pendingChanges.Add(change);
changes.Add(change);
acks.Add(new(request.ClientItemId, DataItemStatus.Good, replacement?.Handle ?? previous.Handle, result.RevisedSettings, null));
}
if (_services.Clock.GetElapsedTime(started) >= modify.AcknowledgementTimeout)
{ foreach (var change in changes) CleanupStaged(change); Stop(); return; }
if (changes.Count == 0) { await EnqueueAsync(ControlAck(modify.CommandId, acks)).ConfigureAwait(false); return; }
Interlocked.Exchange(ref _barrier, 2);
await EnqueueAsync(ControlAck(modify.CommandId, acks,
() => changes.All(change => change.State == 0 && !change.Snapshot.IsReset &&
((SnapshotOwnership)change.Admission).Permit.IsValid) && changes.All(change => change.View.CanPublish()),
() => CommitStaged(changes),
() => { foreach (var change in changes) CleanupStaged(change); },
() => changes.All(change => change.View.CanPublish()))).ConfigureAwait(false);
}
private bool CommitStaged(IReadOnlyList<StagedChange> changes)
{
lock (_gate)
{
if (Volatile.Read(ref _closed) != 0 || changes.Any(change => change.State != 0 || !change.View.CanPublish() ||
change.Snapshot.IsReset || !((SnapshotOwnership)change.Admission).Permit.IsValid ||
!_handles!.IsCurrent(change.Previous.Handle))) return false;
foreach (var change in changes)
{
if (change.Replacement is null)
{
var oldDemand = change.Previous.DemandLease;
change.Previous.Settings = change.Settings; change.Previous.DemandLease = change.Demand;
change.Previous.NextDue = DueFor(change.Previous.LastDeliveryTimestamp, change.Settings);
if (change.Previous.QueuedDue is { } previousDue)
{
_due.Remove((previousDue, change.Previous.Handle.Handle));
change.Previous.QueuedDue = change.Previous.NextDue;
_due.Add((change.Previous.NextDue, change.Previous.Handle.Handle));
}
MarkDirty(change.Previous.View.Source);
oldDemand.Dispose(); change.Snapshot.Dispose(); change.Interest.Dispose(); change.Admission.Dispose();
}
else
{
var item = change.Replacement;
if (!_handles!.CommitReplacement(change.Previous.Handle, item.Handle)) return false;
_items.Remove(change.Previous.Handle.Handle); _itemsByClient.Remove(change.Previous.ClientItemId);
ReleaseItem(change.Previous);
_items.Add(item.Handle.Handle, item); _itemsByClient.Add(item.ClientItemId, item);
var group = new InterestGroup(change.Interest) { Count = 1 };
group.Sources.Add(item.View.Source, 1); group.Node = _interests.AddLast(group); item.Interest = group;
_snapshots.Add(change.Snapshot); _snapshotAdmissions.Add(change.Admission);
var marks = change.Snapshot.Watermarks.Select(x => new PartitionWatermark(x.Key, x.Value)).ToArray();
_committedSnapshots.Enqueue(new SnapshotJob(change.Snapshot, change.Admission, group, [item], marks));
}
change.State = 1; _pendingChanges.Remove(change);
}
}
ReleaseBarrier(2); return true;
}
private void CleanupStaged(StagedChange change)
{
lock (_gate)
{
if (change.State != 0) return;
change.State = 2; _pendingChanges.Remove(change);
if (change.Replacement is { } replacement)
{
_handles?.CancelReplacement(replacement.Handle);
_scheduler.Unregister(replacement.View.Source, checked((long)replacement.Handle.Handle));
replacement.Dispose();
}
else change.Demand.Dispose();
change.Snapshot.Dispose(); change.Interest.Dispose(); change.Admission.Dispose();
}
}
private void ReleaseItem(Item item)
{
lock (_gate)
{
_scheduler.Unregister(item.View.Source, checked((long)item.Handle.Handle));
if (item.QueuedDue is { } due) _due.Remove((due, item.Handle.Handle));
if (item.WaitingNode is not null) { _waiting.Remove(item.WaitingNode); item.WaitingNode = null; }
if (item.Interest is { } group)
{
var sourceCount = group.Sources[item.View.Source] - 1;
if (sourceCount == 0)
{
group.Sources.Remove(item.View.Source);
if (item.Ticket is { } ticket) group.Lease.ReleaseTicket(ticket);
}
else group.Sources[item.View.Source] = sourceCount;
if (--group.Count == 0)
{
if (_interestCursor == group.Node) _interestCursor = group.Node!.Next ?? _interests.First;
_interests.Remove(group.Node!);
if (_interestCursor == group.Node) _interestCursor = _interests.First;
group.Released = true;
group.Lease.Dispose();
}
}
}
item.Dispose();
}
private void QueueTick()
{
if (Interlocked.Exchange(ref _tickQueued, 1) != 0 || Volatile.Read(ref _closed) != 0) return;
if (!_commands.Writer.TryWrite(new(null, 0))) { Interlocked.Exchange(ref _tickQueued, 0); Stop(); }
}
private async Task TickAsync()
{
try
{
lock (_gate)
{
for (var count = 0; count < Math.Min(32, _snapshotAdmissions.Count); count++)
{
if (_admissionCursor >= _snapshotAdmissions.Count) _admissionCursor = 0;
if (_snapshotAdmissions[_admissionCursor++] is SnapshotOwnership ownership && !ownership.Permit.IsValid)
{ CloseWithReset("Snapshot lifetime expired; retry later."); return; }
}
}
for (var count = 0; count < 32 && _committedSnapshots.TryDequeue(out var committed); count++)
{
_snapshotJobs.AddLast(committed);
}
if (_services.Clock.GetElapsedTime(_lastHeartbeat) >= TimeSpan.FromSeconds(5))
{
_lastHeartbeat = _services.Clock.GetTimestamp();
var serving = _serving!;
await EnqueueAsync(new PendingDelivery(sequence => new DataSubscriptionControl(_subscriptionId!, _epoch,
sequence, DataStreamControlKind.Heartbeat, [], serving.CatalogEpoch, serving.AuthorityEpoch, null),
() => Volatile.Read(ref _closed) == 0 && _services.CanUseSubscription(_context, _target, _serving))).ConfigureAwait(false);
}
int retryCount;
lock (_gate) retryCount = Math.Min(32, _waiting.Count);
for (var count = 0; count < retryCount; count++)
{
Item? waiting;
lock (_gate)
{
if (_waiting.First is not { } node) break;
_waiting.RemoveFirst(); _items.TryGetValue(node.Value, out waiting);
if (waiting is not null) waiting.WaitingNode = null;
}
if (waiting is null) continue;
if (!_services.SubscriptionHub.TryGetCurrentTicket(waiting.View.Source, out var ticket))
{
lock (_gate) if (_items.ContainsKey(waiting.Handle.Handle)) waiting.WaitingNode = _waiting.AddLast(waiting.Handle.Handle);
continue;
}
waiting.Ticket = ticket;
if (!await RecoverWaitingAsync(waiting, ticket).ConfigureAwait(false))
{
lock (_gate) if (_items.ContainsKey(waiting.Handle.Handle))
{ waiting.Ticket = null; waiting.WaitingNode = _waiting.AddLast(waiting.Handle.Handle); }
}
}
List<InterestGroup> interests = [];
lock (_gate)
{
_interestCursor ??= _interests.First;
for (var count = 0; count < Math.Min(32, _interests.Count); count++)
{
var current = _interestCursor!;
if (current.Value.SnapshotComplete) interests.Add(current.Value);
_interestCursor = current.Next ?? _interests.First;
}
}
await PumpSnapshotsAsync().ConfigureAwait(false);
await PumpConditionsAsync().ConfigureAwait(false);
BeforeDirtyTickForTests?.Invoke(_outbound.Reader.Count, Volatile.Read(ref _queuedValues), interests.Count);
// #994 (R-3): each group drains up to 256 of ITS OWN changes per tick, walking at most 4096 partition entries (unrelated
// traffic no longer eats the budget); a group still behind re-queues a tick instead of waiting 100 ms, and a group that
// fell off the bounded history catches up from per-source versions rather than resetting the stream.
var behind = false;
foreach (var group in interests)
{
if (!group.Lease.TryReadChanges(256, 4096, out var changes, out var more))
{
// #962: a modify's ack commit runs on the delivery side and can release a group this tick captured
// above (the replaced item's interest); its disposed lease then reads like a reset. That group is gone
// by design and its replacement re-snapshots, so only a group the session still owns lost its history.
bool released;
lock (_gate) released = group.Released;
if (released) continue;
CloseWithReset("Source change history expired."); return;
}
foreach (var change in changes) MarkDirty(change.Ticket.Key);
behind |= more;
}
if (behind) QueueTick();
var availableValues = AvailableValueSlots();
if (availableValues > 0)
foreach (var scheduled in _scheduler.TakeSlice(Math.Min(32, availableValues)))
{
Item? item;
lock (_gate) _items.TryGetValue((ulong)scheduled.InterestId, out item);
if (item is not null) await ConsiderAsync(item).ConfigureAwait(false);
}
var now = _services.Clock.GetTimestamp();
var dueItems = new List<Item>();
lock (_gate)
{
availableValues = AvailableValueSlots();
for (var count = 0; count < Math.Min(32, availableValues) && _due.Count > 0 && _due.Min.Due <= now; count++)
{
var entry = _due.Min; _due.Remove(entry);
if (!_items.TryGetValue(entry.Handle, out var item)) continue;
item.QueuedDue = null; dueItems.Add(item);
}
}
foreach (var item in dueItems) await ConsiderAsync(item).ConfigureAwait(false);
}
finally { AfterTickForTests?.Invoke(); }
}
private async Task<bool> RecoverWaitingAsync(Item item, SourceTicket ticket)
{
var budget = new DataBudget(TimeSpan.FromSeconds(5), 1, _limits.MaxPendingBytes);
if (!_capacity.Snapshots.TryAcquire(_context.PrincipalId, 1, out var rawAdmission)) return false;
var permit = (SnapshotAdmissionScheduler.Permit)rawAdmission!;
if (!permit.TryRetain(out var snapshotHold)) { permit.Dispose(); return false; }
var admission = new SnapshotOwnership(permit, snapshotHold!);
if (!_services.SubscriptionHub.TryCaptureInterestSnapshot([ticket], budget, _stop.Token, out var snapshot, out var interest,
permit))
{ admission.Dispose(); return false; }
InterestGroup group;
lock (_gate)
{
if (!_items.TryGetValue(item.Handle.Handle, out var current) || !ReferenceEquals(current, item))
{ snapshot!.Dispose(); interest!.Dispose(); admission!.Dispose(); return true; }
if (!_scheduler.TryRegister(item.View.Source, checked((long)item.Handle.Handle)))
{ snapshot!.Dispose(); interest!.Dispose(); admission!.Dispose(); CloseWithReset("Interest capacity exhausted."); return true; }
_snapshots.Add(snapshot!); _snapshotAdmissions.Add(admission!);
group = new InterestGroup(interest!) { Count = 1 };
group.Sources.Add(item.View.Source, 1);
group.Node = _interests.AddLast(group); item.Interest = group;
}
var marks = snapshot!.Watermarks.Select(x => new PartitionWatermark(x.Key, x.Value)).ToArray();
var captured = snapshot.Items[ticket];
if (captured.Sample is not null) item.LastConsidered = captured.Sample.Version;
_snapshotJobs.AddLast(new SnapshotJob(snapshot, admission!, group, [item], marks));
await PumpSnapshotsAsync().ConfigureAwait(false);
return true;
}
private async Task PumpSnapshotsAsync()
{
var budget = Math.Min(32, _snapshotJobs.Count * 2);
while (budget-- > 0 && _snapshotJobs.First is { } node && Volatile.Read(ref _closing) == 0)
{
var job = node.Value;
if (job.Snapshot.IsReset || !((SnapshotOwnership)job.Admission).Permit.IsValid)
{ CloseWithReset("Snapshot catch-up expired; retry later."); return; }
if (!job.Started)
{
// Leave a control slot available for command acknowledgements. A dequeued
// frame queues another tick, so a blocked boundary remains resumable.
if (_outbound.Reader.Count >= Math.Max(1, _limits.MaxPendingFrames - 1)) return;
await EnqueueAsync(Control(DataStreamControlKind.SnapshotBegin, job.Watermarks, job.Snapshot,
((SnapshotOwnership)job.Admission).Permit)).ConfigureAwait(false);
job.Started = true;
}
if (job.Index < job.Items.Count)
{
if (AvailableValueSlots() == 0) return;
var item = job.Items[job.Index++];
if (_handles!.IsCurrent(item.Handle) && item.Ticket is { } ticket &&
job.Snapshot.Items.TryGetValue(ticket, out var captured) && captured.Sample is not null &&
captured.ReceivedTimestamp is { } received)
{
var delivery = MakeValue(item, captured.Sample, received, true, job.Snapshot,
((SnapshotOwnership)job.Admission).Permit);
if (delivery is null)
{
if (!_handles.IsCurrent(item.Handle)) continue;
CloseWithReset("Pending snapshot memory exhausted."); return;
}
await EnqueueAsync(delivery).ConfigureAwait(false);
}
continue;
}
if (_outbound.Reader.Count >= Math.Max(1, _limits.MaxPendingFrames - 1)) return;
_snapshotJobs.RemoveFirst();
await EnqueueAsync(Control(DataStreamControlKind.SnapshotEnd, job.Watermarks, job.Snapshot,
((SnapshotOwnership)job.Admission).Permit, () =>
{
var allComplete = false;
lock (_gate)
{
SnapshotEndCommittedForTests?.Invoke();
job.Group.SnapshotComplete = true;
if (job.TemporaryInterest) _temporaryInterests.Remove(job.Group);
_snapshots.Remove(job.Snapshot); _snapshotAdmissions.Remove(job.Admission);
allComplete = _snapshots.Count == 0 && _interests.All(group => group.SnapshotComplete);
}
job.Snapshot.Dispose(); job.Admission.Dispose();
if (job.TemporaryInterest) FinishChallengeSnapshot(job);
QueueTick();
if (allComplete) ReleaseBarrier(1);
SnapshotEndReleasedForTests?.Invoke();
}, () =>
{
job.Snapshot.Dispose(); job.Admission.Dispose();
if (job.TemporaryInterest)
{
FinishChallengeSnapshot(job);
}
})).ConfigureAwait(false);
}
}
private void MarkDirty(BackingSourceKey source) => _scheduler.TryMarkDirty(source, Interlocked.Increment(ref _dirtySequence));
private void FinishChallengeSnapshot(SnapshotJob job)
{
lock (_gate)
{
_temporaryInterests.Remove(job.Group);
foreach (var item in job.Items)
{
if (!_challengedHandles.TryGetValue(item.Handle.Handle, out var count)) continue;
if (count > 1) _challengedHandles[item.Handle.Handle] = count - 1;
else
{
_challengedHandles.Remove(item.Handle.Handle);
if (_handles?.IsCurrent(item.Handle) == true) MarkDirty(item.View.Source);
}
}
}
job.Group.Lease.Dispose();
}
private async Task ConsiderAsync(Item item)
{
lock (_gate)
{
if (_challengedHandles.ContainsKey(item.Handle.Handle)) return;
// #966: no live delta before the item's own snapshot. A modify's replacement (or an added/recovered item) is
// scheduler-registered and in _items before its SnapshotEnd commits; a dirty mark for its source (from a
// sibling group, or a commit landing mid-tick after the snapshot dequeue) would otherwise emit a newer live
// value ahead of its SnapshotBegin. Nothing is lost: LastConsidered is untouched and the group's own lease
// (cursor from the snapshot capture) yields the change once the group is snapshot-complete.
if (item.Interest is { SnapshotComplete: false }) return;
}
if (item.Ticket is not { } ticket) return;
using var read = _services.SubscriptionHub.Read(ticket);
if (read.Readiness != DataReadiness.Ready || read.Sample is null) { CloseWithReset("Source became unavailable."); return; }
if (read.Sample.Version <= item.LastConsidered) return;
var now = _services.Clock.GetTimestamp();
lock (_gate)
{
if (!_items.TryGetValue(item.Handle.Handle, out var current) || !ReferenceEquals(current, item)) return;
if (now < item.NextDue)
{
if (item.QueuedDue is null) { item.QueuedDue = item.NextDue; _due.Add((item.NextDue, item.Handle.Handle)); }
return;
}
item.LastConsidered = read.Sample.Version;
if (!item.Filter.ShouldDeliver(read.Sample, item.Settings)) return;
}
var delivery = MakeValue(item, read.Sample, read.ReceivedTimestamp, false, null);
if (delivery is null) { if (!_handles!.IsCurrent(item.Handle)) return; CloseWithReset("Pending value memory exhausted."); return; }
await EnqueueAsync(delivery).ConfigureAwait(false);
OnCandidateQueuedForTests?.Invoke(item.Handle, read.Sample.Version);
}
private PendingDelivery? MakeValue(Item item, DataSample sample, long received, bool snapshot, SnapshotLease? snapshotLease,
SnapshotAdmissionScheduler.Permit? snapshotPermit = null)
{
var charge = checked(sample.Value.EstimatedRetainedBytes + PartitionedSampleHub.ReferenceOverhead);
IDisposable? snapshotHold = null;
if (snapshotPermit is not null && !snapshotPermit.TryRetain(out snapshotHold)) return null;
if (!_services.SubscriptionHub.Resources.TryReserve(charge)) { snapshotHold?.Dispose(); return null; }
DataSample owned;
try { owned = sample with { Value = sample.Value.Retain(), Serving = item.View.Serving }; }
catch { snapshotHold?.Dispose(); _services.SubscriptionHub.Resources.Release(charge); throw; }
IDisposable lease;
try
{
lease = new CompositeLease(new BudgetLease(_services.SubscriptionHub.Resources, charge), item.Resources.Retain());
if (snapshotHold is not null) lease = new CompositeLease(lease, snapshotHold);
}
catch { owned.Dispose(); snapshotHold?.Dispose(); _services.SubscriptionHub.Resources.Release(charge); return null; }
bool Identity() => item.Ticket is { } ticket &&
(snapshotLease is null || snapshotLease.IsItemCurrent(ticket) && snapshotPermit?.IsValid == true) &&
Volatile.Read(ref _closed) == 0 && Volatile.Read(ref _closing) == 0 && _handles!.IsCurrent(item.Handle) &&
_services.SubscriptionHub.IsTicketCurrentNonBlocking(ticket);
bool Gate() => Identity() && item.View.CanPublish();
bool Commit()
{
// #994 (R-12): the frame was authorized by Gate() right before the transport write it now commits; under the session
// lock only the cheap identity fences are re-checked (the authorization walk no longer runs while holding _gate).
lock (_gate)
{
if (!Identity() || !_items.TryGetValue(item.Handle.Handle, out var current) || !ReferenceEquals(current, item)) return false;
if (!_services.SubscriptionHub.Resources.TryReserve(charge)) return false;
var next = new BudgetLease(_services.SubscriptionHub.Resources, charge);
item.Filter.Commit(owned); item.BaselineCharge?.Dispose(); item.BaselineCharge = next;
item.LastPublished = owned.Version;
var now = _services.Clock.GetTimestamp();
item.LastDeliveryTimestamp = now; item.NextDue = DueFor(now, item.Settings);
return true;
}
}
bool Eligible()
{
if (snapshot) return true;
if (item.Ticket is not { } ticket) return false;
using var latest = _services.SubscriptionHub.Read(ticket);
if (latest.Readiness != DataReadiness.Ready || latest.Sample is null) { CloseWithReset("Source became unavailable."); return false; }
if (latest.Sample.Version > owned.Version)
{
Interlocked.Exchange(ref _coalesced, 1);
MarkDirty(item.View.Source); QueueTick(); return false;
}
lock (_gate)
{
if (_services.Clock.GetTimestamp() < item.NextDue)
{
if (item.LastConsidered == owned.Version) item.LastConsidered = item.LastPublished;
if (item.QueuedDue is null) { item.QueuedDue = item.NextDue; _due.Add((item.NextDue, item.Handle.Handle)); }
return false;
}
return item.Filter.ShouldDeliver(owned, item.Settings);
}
}
return new PendingDelivery(sequence =>
{
// Capture the admitted challenge before computing the age; queued/prepared frames retain this witness.
var freshnessChallengeId = Volatile.Read(ref _freshnessChallengeId);
var age = _services.Clock.GetElapsedTime(received);
if (age < TimeSpan.Zero) throw new InvalidOperationException("Invalid monotonic age.");
return new DataSubscriptionValues(_subscriptionId!, _epoch, sequence, snapshot,
[new(item.Handle, owned, new DataAgeBounds(age, null), DataReadiness.Ready, freshnessChallengeId)], lease);
}, Gate, Commit, () => { owned.Dispose(); lease.Dispose(); }, true,
() => Volatile.Read(ref _closing) != 0 || !_handles!.IsCurrent(item.Handle), Eligible,
snapshot ? bytes =>
{
if (snapshotPermit?.IsValid != true) return (false, TimeSpan.FromSeconds(1));
var accepted = _capacity.Snapshots.TryConsume(_context.PrincipalId, bytes, out var retry);
return (accepted, retry);
} : null, charge);
}
private long DueFor(long? observedStart, DataSubscriptionSettings settings)
{
if (observedStart is not { } start) return 0;
var interval = settings.SamplingInterval > settings.PublishingInterval ? settings.SamplingInterval : settings.PublishingInterval;
var delta = (decimal)interval.Ticks * _services.Clock.TimestampFrequency / TimeSpan.TicksPerSecond;
return delta >= (decimal)long.MaxValue - start ? long.MaxValue : start + (long)decimal.Ceiling(delta);
}
private PendingDelivery ControlAck(string command, IReadOnlyList<DataSubscriptionItemAck> acks,
Func<bool>? additionalGate = null, Func<bool>? onDelivered = null, Action? onFailed = null,
Func<bool>? finalAuthority = null)
{
long bytes = checked(256L + 2L * command.Length);
foreach (var ack in acks)
bytes = checked(bytes + 256L + 2L * ((ack.ClientItemId?.Length ?? 0) + (ack.Diagnostic?.Length ?? 0)));
if (bytes > _limits.MaxPendingBytes || !_services.SubscriptionHub.Resources.TryReserve(bytes))
throw new InvalidOperationException("Acknowledgement memory capacity exhausted.");
var charge = new BudgetLease(_services.SubscriptionHub.Resources, bytes);
return new PendingDelivery(sequence => new DataSubscriptionAck(_subscriptionId!, _epoch, sequence, command, acks),
() => (additionalGate?.Invoke() ?? true) && Volatile.Read(ref _closed) == 0 &&
_services.CanUseSubscription(_context, _target, _serving),
() => CompleteAck(command) && (onDelivered?.Invoke() ?? true), settle: charge.Dispose, failed: onFailed,
finalAuthority: finalAuthority);
}
private PendingDelivery Control(DataStreamControlKind kind, IReadOnlyList<PartitionWatermark> marks, SnapshotLease snapshot,
SnapshotAdmissionScheduler.Permit permit, Action? delivered = null, Action? dropped = null)
{
var serving = _serving ?? throw new InvalidOperationException("Stream serving identity is unavailable.");
return new(sequence => new DataSubscriptionControl(_subscriptionId!, _epoch, sequence, kind, marks,
serving.CatalogEpoch, serving.AuthorityEpoch, null),
() => !snapshot.IsReset && permit.IsValid && Volatile.Read(ref _closed) == 0 && Volatile.Read(ref _closing) == 0 &&
_services.CanUseSubscription(_context, _target, _serving),
() => { delivered?.Invoke(); return true; }, dropped, obsolete: () => Volatile.Read(ref _closing) != 0);
}
// Snapshot controls and ACKs share the same bounded channel as values. Check
// both limits before removing scheduler work or advancing a snapshot item.
private int AvailableValueSlots()
{
var valueSlots = Math.Max(0, Math.Max(1, _limits.MaxPendingFrames - 2) - Volatile.Read(ref _queuedValues));
var channelSlots = Math.Max(0, _limits.MaxPendingFrames - _outbound.Reader.Count);
return Math.Min(valueSlots, channelSlots);
}
private Task EnqueueAsync(PendingDelivery delivery)
{
if (Volatile.Read(ref _closed) != 0 || Volatile.Read(ref _closing) != 0) { delivery.Dispose(); return Task.CompletedTask; }
if (delivery.IsValue && Interlocked.Increment(ref _queuedValues) > Math.Max(1, _limits.MaxPendingFrames - 2))
{
Interlocked.Decrement(ref _queuedValues); delivery.Dispose(); CloseWithReset("Pending value capacity exhausted."); return Task.CompletedTask;
}
if (!_outbound.Writer.TryWrite(delivery))
{
Dequeued(delivery); delivery.Dispose(); CloseWithReset("Pending control capacity exhausted.");
}
return Task.CompletedTask;
}
private void Dequeued(PendingDelivery delivery)
{
if (delivery.IsValue) Interlocked.Decrement(ref _queuedValues);
QueueTick();
}
private PendingDelivery CoalescedControl()
{
var serving = _serving ?? throw new InvalidOperationException("Stream serving identity is unavailable.");
return new PendingDelivery(sequence => new DataSubscriptionControl(_subscriptionId!, _epoch, sequence,
DataStreamControlKind.Coalesced, [], serving.CatalogEpoch, serving.AuthorityEpoch, null),
() => Volatile.Read(ref _closed) == 0 && Volatile.Read(ref _closing) == 0 &&
_services.CanUseSubscription(_context, _target, serving));
}
private void CloseWithReset(string diagnostic)
{
if (Interlocked.Exchange(ref _closing, 1) != 0) return;
_tick?.Dispose();
var serving = _serving;
if (serving is null || !_outbound.Writer.TryWrite(new PendingDelivery(sequence =>
new DataSubscriptionControl(_subscriptionId!, _epoch, sequence, DataStreamControlKind.Reset, [],
serving.CatalogEpoch, serving.AuthorityEpoch, diagnostic), () => Volatile.Read(ref _closed) == 0 &&
_services.CanUseSubscription(_context, _target, serving),
() => { Stop(); return true; }))) Stop();
}
public IAsyncEnumerable<DataSubscriptionFrame> ReadAllAsync(CancellationToken cancellationToken) => new DirectReader(this, cancellationToken);
private sealed class DirectReader(DataSubscriptionSession owner, CancellationToken token) : IAsyncEnumerable<DataSubscriptionFrame>, IAsyncEnumerator<DataSubscriptionFrame>
{
private CancellationTokenSource? _linked;
private int _disposed;
public DataSubscriptionFrame Current { get; private set; } = null!;
public IAsyncEnumerator<DataSubscriptionFrame> GetAsyncEnumerator(CancellationToken cancellationToken = default)
{
if (Interlocked.CompareExchange(ref owner._mode, 1, 0) != 0) throw new InvalidOperationException("Delivery mode already selected.");
_linked = CancellationTokenSource.CreateLinkedTokenSource(token, cancellationToken, owner._stop.Token); return this;
}
public async ValueTask<bool> MoveNextAsync()
{
try
{
while (true)
{
if (await owner.NextPendingAsync(_linked!.Token).ConfigureAwait(false) is not { } pending) break;
if (!pending.Gate()) { pending.Dispose(); if (pending.IsObsolete()) continue; owner.Stop(); return false; }
if (!pending.IsEligible()) { pending.Dispose(); continue; }
var rate = pending.ConsumeSnapshot();
if (!rate.Accepted) { pending.Dispose(); owner.CloseWithReset($"Snapshot pacing; retry after {rate.Retry.TotalMilliseconds:F0} ms."); continue; }
var frame = pending.Take(checked(Interlocked.Read(ref owner._sequence) + 1));
if (frame is DataSubscriptionValues) owner.BeforeDirectCommitForTests?.Invoke();
if (!pending.Gate() || !pending.Commit())
{ pending.Fail(); (frame as IDisposable)?.Dispose(); if (pending.IsObsolete()) continue; owner.Stop(); return false; }
if (frame is DataSubscriptionAck &&
(!owner._services.CanUseSubscription(owner._context, owner._target, owner._serving) || !pending.FinalAuthority()))
{ (frame as IDisposable)?.Dispose(); owner.Stop(); return false; }
Interlocked.Increment(ref owner._sequence); Current = frame; return true;
}
}
catch (OperationCanceledException) when (_linked!.IsCancellationRequested) { }
catch { owner.Stop(); throw; }
return false;
}
public ValueTask DisposeAsync()
{
if (Interlocked.Exchange(ref _disposed, 1) == 0)
{ owner.Stop(); _linked?.Cancel(); _linked?.Dispose(); }
return ValueTask.CompletedTask;
}
}
public async Task RunDeliveryAsync(IDataSubscriptionDeliverySink sink, CancellationToken cancellationToken)
{
ArgumentNullException.ThrowIfNull(sink);
if (Interlocked.CompareExchange(ref _mode, 2, 0) != 0) throw new InvalidOperationException("Delivery mode already selected.");
using var linked = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, _stop.Token);
try
{
while (true)
{
if (await NextPendingAsync(linked.Token).ConfigureAwait(false) is not { } pending) break;
if (!pending.Gate()) { pending.Dispose(); if (pending.IsObsolete()) continue; Stop(); return; }
IDisposable? reservation;
try { reservation = await _capacity.ReserveAsync(_context.PrincipalId, _limits.MaxPendingBytes, linked.Token).ConfigureAwait(false); }
catch { pending.Dispose(); throw; }
if (reservation is null) { pending.Dispose(); CloseWithReset("Transport capacity exhausted."); continue; }
var frame = pending.Take(checked(Interlocked.Read(ref _sequence) + 1));
IDisposable sessionHold;
try { sessionHold = _sessionLease.Retain(); }
catch { pending.Fail(); (frame as IDisposable)?.Dispose(); reservation!.Dispose(); Stop(); throw; }
var physical = DeliverAsync(sink, frame, pending, reservation!, sessionHold, linked.Token);
await physical.WaitAsync(linked.Token).ConfigureAwait(false);
}
}
catch (OperationCanceledException) when (linked.IsCancellationRequested) { }
finally { Stop(); }
}
private async Task DeliverAsync(IDataSubscriptionDeliverySink sink, DataSubscriptionFrame frame,
PendingDelivery pending, IDisposable reservation, IDisposable sessionHold, CancellationToken cancellationToken)
{
IDataPreparedSubscriptionDelivery? prepared = null;
try
{
prepared = await sink.PrepareAsync(frame, _limits.MaxPendingBytes, cancellationToken).ConfigureAwait(false);
if (prepared is null || prepared.RetainedBytes < 0 || prepared.RetainedBytes > _limits.MaxPendingBytes)
{ if (!pending.IsObsolete()) Stop(); return; }
if (prepared is IDataPreparedSubscriptionPublication publication)
publication.SetPublicationGuard(pending.Gate);
if (!pending.IsEligible()) return;
var rate = pending.ConsumeSnapshot(prepared.RetainedBytes);
if (!rate.Accepted) { CloseWithReset($"Snapshot pacing; retry after {rate.Retry.TotalMilliseconds:F0} ms."); return; }
if (!pending.Gate()) { if (!pending.IsObsolete()) Stop(); return; }
await sink.WriteAsync(prepared, cancellationToken).ConfigureAwait(false);
if (!pending.Commit()) Stop(); else Interlocked.Increment(ref _sequence);
}
catch { Stop(); }
finally
{
pending.Fail(); (frame as IDisposable)?.Dispose(); reservation.Dispose(); sessionHold.Dispose(); prepared?.Dispose();
}
}
private void Stop()
{
if (Interlocked.Exchange(ref _closed, 1) != 0) return;
_preOpen?.Dispose(); _expiry?.Dispose(); _tick?.Dispose(); _ackTimer?.Dispose(); _commands.Writer.TryComplete(); _stop.Cancel();
}
public async ValueTask DisposeAsync() { Stop(); await _worker.ConfigureAwait(false); }
}