Files
lmxopcua/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/DataSubscriptionSession.cs
T

1190 lines
70 KiB
C#

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 class DataSubscriptionSession : IDataSubscriptionTransport
{
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 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 ServingIdentity? _serving;
private long _epoch, _sequence, _dirtySequence, _ackId, _lastHeartbeat;
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<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;
}
private sealed class SnapshotJob(SnapshotLease snapshot, IDisposable admission, InterestGroup group,
IReadOnlyList<Item> items, IReadOnlyList<PartitionWatermark> watermarks)
{
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;
}
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 });
_scheduler = new DeliveryScheduler(limits.MaxPendingFrames * 16, limits.MaxPendingFrames * 16);
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) },
_ => 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(); 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; }
if (command is ModifySubscriptionItems && HasIncompleteSnapshot())
{ _deferred.Enqueue(work); retained = true; Interlocked.CompareExchange(ref _barrier, 1, 0); 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;
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 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();
}
_sessionLease.Dispose();
}
}
private bool HasIncompleteSnapshot()
{
lock (_gate) return _interests.Any(group => !group.SnapshotComplete);
}
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; }
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();
await EnqueueAsync(Control(DataStreamControlKind.SnapshotBegin, marks, snapshot, admission.Permit)).ConfigureAwait(false);
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 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) { 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.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()
{
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++)
{
await EnqueueAsync(Control(DataStreamControlKind.SnapshotBegin, committed.Watermarks, committed.Snapshot,
((SnapshotOwnership)committed.Admission).Permit)).ConfigureAwait(false);
_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<SourceInterestLease> 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.Lease);
_interestCursor = current.Next ?? _interests.First;
}
}
await PumpSnapshotsAsync().ConfigureAwait(false);
foreach (var interest in interests)
{
if (!interest.TryReadChanges(32, out var changes)) { CloseWithReset("Source change history expired."); return; }
foreach (var change in changes) MarkDirty(change.Ticket.Key);
}
var availableValues = Math.Max(0, Math.Max(1, _limits.MaxPendingFrames - 2) - Volatile.Read(ref _queuedValues));
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 = Math.Max(0, Math.Max(1, _limits.MaxPendingFrames - 2) - Volatile.Read(ref _queuedValues));
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);
}
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();
await EnqueueAsync(Control(DataStreamControlKind.SnapshotBegin, marks, snapshot, admission.Permit)).ConfigureAwait(false);
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; _snapshotJobs.RemoveFirst();
if (job.Snapshot.IsReset || !((SnapshotOwnership)job.Admission).Permit.IsValid)
{ CloseWithReset("Snapshot catch-up expired; retry later."); return; }
if (job.Index < job.Items.Count)
{
if (Volatile.Read(ref _queuedValues) >= Math.Max(1, _limits.MaxPendingFrames - 2))
{ _snapshotJobs.AddFirst(job); 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)) { _snapshotJobs.AddLast(job); continue; }
CloseWithReset("Pending snapshot memory exhausted."); return;
}
await EnqueueAsync(delivery).ConfigureAwait(false);
}
_snapshotJobs.AddLast(job);
continue;
}
await EnqueueAsync(Control(DataStreamControlKind.SnapshotEnd, job.Watermarks, job.Snapshot,
((SnapshotOwnership)job.Admission).Permit, () =>
{
var allComplete = false;
lock (_gate)
{
job.Group.SnapshotComplete = true;
_snapshots.Remove(job.Snapshot); _snapshotAdmissions.Remove(job.Admission);
allComplete = _interests.All(group => group.SnapshotComplete);
}
job.Snapshot.Dispose(); job.Admission.Dispose(); QueueTick();
if (allComplete) ReleaseBarrier(1);
}, () => { job.Snapshot.Dispose(); job.Admission.Dispose(); })).ConfigureAwait(false);
}
}
private void MarkDirty(BackingSourceKey source) => _scheduler.TryMarkDirty(source, Interlocked.Increment(ref _dirtySequence));
private async Task ConsiderAsync(Item item)
{
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 Gate() => 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) && item.View.CanPublish();
bool Commit()
{
lock (_gate)
{
if (!Gate() || !_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 =>
{
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)], 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);
}
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)
{
PendingDelivery pending;
if (Interlocked.Exchange(ref owner._coalesced, 0) != 0) pending = owner.CoalescedControl();
else
{
if (!await owner._outbound.Reader.WaitToReadAsync(_linked!.Token).ConfigureAwait(false)) break;
if (!owner._outbound.Reader.TryRead(out pending!)) continue;
owner.Dequeued(pending);
}
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)
{
PendingDelivery pending;
if (Interlocked.Exchange(ref _coalesced, 0) != 0) pending = CoalescedControl();
else
{
if (!await _outbound.Reader.WaitToReadAsync(linked.Token).ConfigureAwait(false)) break;
if (!_outbound.Reader.TryRead(out pending!)) continue;
Dequeued(pending);
}
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); }
}