Files
lmxopcua/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/DataSubscriptionSession.Conditions.cs
T
Joseph Doherty 78eb98ea13 fix(grpc-data): A4 #930/#931 — in-stream condition retries (no refresh storm), ConditionCapacity recovery, reconnect backoff, ledger, single RefreshRequired, parked-runner release; condition diagnostics core
#930 N2: an Unavailable mapping (refused item, failed root, snapshot timeout) is retried on the OPEN stream by
re-adding its item (AddSubscriptionItems) on its own backoff — definitive refusals (Denied/NotFound/Unsupported)
on LongRetryDelay (5 min, doubling to 4x), transient ones on the snapshot timeout x 2^n (<= 8x) — so healthy
mappings are never re-snapshotted for it; an incomplete barrier whose incomplete set equals the previous barrier's
sends no RefreshRequired. N3: ConditionCapacity is retried in-stream on the long timer and recovers.
#931 N4 exponential reconnect backoff (MaxReconnectDelay 60 s); N5 held-but-unlisted keys charged beside known
claims (overlapping unknown ones) + SetMaterialised cap report; N6 method calls read Serving without _gate;
N7 a capacity reset that removed conditions sends no second RefreshRequired; N8 a parked runner is released once
its removal finished.
A4 diagnostics core: DataConnectionConditionDiagnostics (side-labelled items/resyncs/capacity/method metrics, new
refresh_required counter, consumer + origin evidence), Commons contracts, DI + deployment-runtime + driver-host wiring.

Co-Authored-By: Claude <noreply@anthropic.com>
2026-11-24 23:03:53 -05:00

289 lines
17 KiB
C#

using System.Threading.Channels;
using ZB.MOM.WW.OtOpcUa.Commons.Observability;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections;
namespace ZB.MOM.WW.OtOpcUa.Runtime.DataConnections;
/// <summary>
/// A2: root-scoped condition items (plan §5.5). They share the stream, the handle table (one monitored item each) and the
/// principal's interest capacity with value items, but have their own non-coalescing bounded queue: the delivery loop
/// takes a queued control/ack first, then a condition frame, then a value (priority control &gt; condition &gt; value,
/// with a fairness cap: after <see cref="ConditionFramesPerValueFrame"/> condition frames in a row a queued v1 frame goes
/// next). Production is pull-based (<see cref="ConditionItemStream"/>): an item produces only while the queue has room,
/// so a slow consumer back-pressures into the hub, whose eviction resets the item to a fresh snapshot.
/// </summary>
internal sealed partial class DataSubscriptionSession
{
/// <summary>A2 review N1: after this many condition frames in a row, a queued value/heartbeat frame is delivered next.</summary>
internal const int ConditionFramesPerValueFrame = 8;
/// <summary>The frame bytes a condition chunk's records must leave free (the sink's frame charge plus wire fields).</summary>
private long ConditionFrameOverhead => 2048L + 4L * (_subscriptionId?.Length ?? 0) + 1024L;
private sealed class ConditionItem(string clientItemId, DataItemHandle handle, ConditionItemAuthority authority,
ConditionItemStream stream, IDisposable reservation) : IDisposable
{
internal readonly string ClientItemId = clientItemId;
internal readonly DataItemHandle Handle = handle;
internal readonly ConditionItemAuthority Authority = authority;
internal readonly ConditionItemStream Stream = stream;
internal volatile bool Active;
private IDisposable? _reservation = reservation;
public void Dispose()
{
if (Interlocked.Exchange(ref _reservation, null) is { } r)
{
Stream.Dispose(); // releases the snapshot memory charge
r.Dispose();
if (Stream.Diagnostics is { } diagnostics) diagnostics.OriginItemClosed(Stream);
else DataConnectionConditionDiagnostics.CountItems(DataConnectionConditionDiagnostics.OriginSide, -1);
}
}
}
private readonly Dictionary<ulong, ConditionItem> _conditionItems = new();
private readonly Dictionary<string, List<ConditionItem>> _conditionActivations = new(StringComparer.Ordinal);
private Channel<PendingDelivery>? _conditionOutboundChannel;
private int _conditionCursor;
private int _conditionStreak;
private Task<bool>? _valuesWait, _conditionsWait;
/// <summary>The bounded condition queue (created lazily on the first condition item; v1 streams never allocate it).</summary>
private Channel<PendingDelivery> ConditionOutbound
{
get
{
if (_conditionOutboundChannel is { } existing) return existing;
var created = Channel.CreateBounded<PendingDelivery>(new BoundedChannelOptions(Math.Max(1, _limits.MaxPendingFrames))
{ SingleReader = true, SingleWriter = true, FullMode = BoundedChannelFullMode.Wait });
return Interlocked.CompareExchange(ref _conditionOutboundChannel, created, null) ?? created;
}
}
/// <summary>Test seam: the condition items' streams, by handle.</summary>
internal IReadOnlyDictionary<ulong, ConditionItemStream> ConditionStreamsForTests
{
get { lock (_gate) return _conditionItems.ToDictionary(x => x.Key, x => x.Value.Stream); }
}
/// <summary>Admits one root-scoped condition item; it starts producing once its ack has been delivered.</summary>
private DataSubscriptionItemAck AddConditionItem(DataSubscriptionItem request, string commandId)
{
var services = _services;
if (services.ConditionHub is not { } hub || services.ConditionSource is not { } source)
return new(request.ClientItemId, DataItemStatus.Unsupported, null, null, null);
DataItemStatus status;
ConditionItemAuthority? authority;
try { status = services.AuthorizeConditionItem(_context, _target, request.View, out authority); }
catch (ArgumentException) { return new(request.ClientItemId, DataItemStatus.InvalidArgument, null, null, null); }
if (status != DataItemStatus.Good || authority is null) return new(request.ClientItemId, status, null, null, null);
if (authority.Serving != _serving) return new(request.ClientItemId, DataItemStatus.Unavailable, null, null, null);
lock (_gate)
{
if (_conditionItems.Values.Any(x => x.ClientItemId == request.ClientItemId) || _itemsByClient.ContainsKey(request.ClientItemId))
return new(request.ClientItemId, DataItemStatus.InvalidArgument, null, null, "Duplicate client item id.");
// A2 review S2: one condition item per (stream, root) — a second would materialise the same listing again.
if (_conditionItems.Values.Any(x => x.Authority.Root.Address == authority.Root.Address && x.Authority.Root.Realm == authority.Root.Realm))
return new(request.ClientItemId, DataItemStatus.InvalidArgument, null, null, "A condition item for this root is already open on this stream.");
// …and at most MaxConditionItems per stream (SubscriptionSessionLimits.DefaultMaxConditionItems).
if (_conditionItems.Count >= _limits.MaxConditionItems)
return new(request.ClientItemId, DataItemStatus.LimitExceeded, null, null,
$"At most {_limits.MaxConditionItems} condition items per stream.");
}
// A2 review S5: a chunk fits both the session's pending bytes and the message limit, after the frame's own overhead.
var chunkBytes = Math.Min(ConditionItemStream.MaxChunkBytes,
Math.Min(_limits.MaxPendingBytes, services.SubscriptionLimits.MaxMessageBytes) - ConditionFrameOverhead);
if (chunkBytes < ConditionItemStream.MinRecordBytes)
return new(request.ClientItemId, DataItemStatus.LimitExceeded, null, null,
"The stream's message limits are too small for condition records.");
var fixedBytes = checked(4096L + 2L * (request.ClientItemId.Length + authority.Root.Subject.Length
+ authority.Root.Address.Identifier.Length + authority.Root.Address.NamespaceUri.Length));
var itemLimit = services.SubscriptionItemLimit(_context);
if (itemLimit <= 0 || !_capacity.TryReserveInterest(_context.PrincipalId, itemLimit, fixedBytes, out var reservation))
return new(request.ClientItemId, DataItemStatus.LimitExceeded, null, null, null);
DataItemHandle handle;
try { handle = _handles!.Add(request.ClientItemId); }
catch (Exception ex) when (ex is InvalidOperationException or OverflowException)
{ reservation!.Dispose(); return new(request.ClientItemId, DataItemStatus.LimitExceeded, null, null, null); }
_ = ConditionOutbound; // exists before the ack is queued, so the delivery loop waits on it from then on
var principal = _context.PrincipalId;
var snapshots = _capacity.Snapshots;
var stream = new ConditionItemStream(hub, source, authority.Scope, request.ConditionScope!.IncludeInfo, services.Clock,
reserveSnapshot: bytes => snapshots.TryAcquire(principal, bytes, out var lease) ? lease : null, chunkBytes: chunkBytes,
diagnostics: services.ConditionDiagnostics);
var item = new ConditionItem(request.ClientItemId, handle, authority, stream, reservation!);
if (stream.Diagnostics is { } itemDiagnostics) itemDiagnostics.OriginItemOpened(stream);
else DataConnectionConditionDiagnostics.CountItems(DataConnectionConditionDiagnostics.OriginSide, 1);
lock (_gate)
{
_conditionItems.Add(handle.Handle, item);
if (!_conditionActivations.TryGetValue(commandId, out var list)) _conditionActivations[commandId] = list = [];
list.Add(item);
}
return new(request.ClientItemId, DataItemStatus.Good, handle, request.Settings, null);
}
/// <summary>The command's ack was delivered: its condition items may now produce (their frames follow their ack).</summary>
private void ActivateConditionItems(string commandId)
{
List<ConditionItem>? list;
lock (_gate) _conditionActivations.Remove(commandId, out list);
if (list is null) return;
foreach (var item in list) item.Active = true;
QueueTick();
}
private bool TryRemoveConditionItem(DataItemHandle handle, out DataSubscriptionItemAck ack)
{
ConditionItem? item;
lock (_gate)
{
if (!_handles!.IsCurrent(handle) || !_conditionItems.Remove(handle.Handle, out item)) { ack = null!; return false; }
_handles.Remove(handle);
}
item.Dispose();
ack = new(item.ClientItemId, DataItemStatus.Good, handle, null, null);
return true;
}
/// <summary>One production round: round-robin over active items while the condition queue has room.</summary>
private Task PumpConditionsAsync()
{
ConditionItem[] items;
lock (_gate)
{
if (_conditionItems.Count == 0) return Task.CompletedTask;
items = _conditionItems.Values.Where(x => x.Active).ToArray();
}
if (items.Length == 0) return Task.CompletedTask;
var queue = ConditionOutbound;
// Review B1: a full queue is back-pressure — produce nothing (the dequeue re-ticks the pump). Never pull a chunk
// that cannot be queued: the stream would then have to reset on every tick while the backlog drains.
var budget = Math.Max(0, _limits.MaxPendingFrames - queue.Reader.Count);
var idle = 0;
while (budget > 0 && idle < items.Length && Volatile.Read(ref _closing) == 0 && Volatile.Read(ref _closed) == 0)
{
var item = items[_conditionCursor++ % items.Length];
lock (_gate) if (!_conditionItems.ContainsKey(item.Handle.Handle)) { idle++; continue; }
if (!item.Authority.CanPublish()) { Stop(); break; }
var chunk = item.Stream.Next();
if (item.Stream.Overflowed) { CloseWithReset("Condition stream overflow; retry later."); break; }
if (item.Stream.Oversized) { CloseWithReset("A condition record exceeds the stream's message limits."); break; }
if (item.Stream.IsRevoked) { Stop(); break; }
if (chunk is null) { idle++; continue; }
idle = 0;
if (!queue.Writer.TryWrite(ConditionDelivery(item, chunk))) { CloseWithReset("Pending condition capacity exhausted."); break; }
budget--;
}
return Task.CompletedTask;
}
private PendingDelivery ConditionDelivery(ConditionItem item, ConditionChunk chunk)
{
var serving = _serving ?? throw new InvalidOperationException("Stream serving identity is unavailable.");
return new PendingDelivery(sequence => new DataSubscriptionConditions(_subscriptionId!, _epoch, sequence, item.Handle,
chunk.IsSnapshot, chunk.Total, chunk.Items, chunk.SnapshotComplete),
() => Volatile.Read(ref _closed) == 0 && Volatile.Read(ref _closing) == 0
&& _services.CanUseSubscription(_context, _target, serving) && IsConditionItemCurrent(item) && item.Authority.CanPublish(),
commit: () => { if (chunk.EndsSnapshot) item.Stream.SnapshotDelivered(chunk.Snapshot); return true; },
obsolete: () => Volatile.Read(ref _closing) != 0 || !IsConditionItemCurrent(item));
}
private bool IsConditionItemCurrent(ConditionItem item)
{
lock (_gate) return _conditionItems.TryGetValue(item.Handle.Handle, out var current) && ReferenceEquals(current, item);
}
/// <summary>
/// The next delivery by priority: a control or ack at the head of the v1 queue first, then a condition frame, then the
/// v1 queue in FIFO order (a v1 control never overtakes a value queued before it: snapshot begin/end ordering depends
/// on that). So conditions overtake queued values, and never a control or ack that is next. Null when the stream's
/// queues are completed and drained.
/// </summary>
private async ValueTask<PendingDelivery?> NextPendingAsync(CancellationToken token)
{
while (true)
{
if (Interlocked.Exchange(ref _coalesced, 0) != 0) return CoalescedControl();
if (_outbound.Reader.TryPeek(out var head) && !head.IsValue)
{
if (_outbound.Reader.TryRead(out var control)) { Dequeued(control); return control; }
continue;
}
// A2 review N1: strict condition priority would starve values and heartbeats during a long snapshot.
if (_conditionStreak >= ConditionFramesPerValueFrame && _outbound.Reader.TryRead(out var fair))
{ _conditionStreak = 0; Dequeued(fair); return fair; }
if (_conditionOutboundChannel is { } conditions && conditions.Reader.TryRead(out var condition))
{
_conditionStreak++;
QueueTick();
return condition;
}
if (_outbound.Reader.TryRead(out var value)) { _conditionStreak = 0; Dequeued(value); return value; }
if (_conditionOutboundChannel is null)
{
if (!await _outbound.Reader.WaitToReadAsync(token).ConfigureAwait(false)) return null;
continue;
}
// A2 review N5: a wait that lost the race stays pending on its channel; reuse it rather than registering a new
// waiter on every pass (values flowing while conditions idle would otherwise pile up condition waiters).
var values = _valuesWait is { IsCompleted: false } pendingValues ? pendingValues : _valuesWait = StartWait(_outbound.Reader, token);
var conditionsReady = _conditionsWait is { IsCompleted: false } pendingConditions
? pendingConditions : _conditionsWait = StartWait(_conditionOutboundChannel.Reader, token);
await Task.WhenAny(values, conditionsReady).ConfigureAwait(false);
token.ThrowIfCancellationRequested();
if (values.IsCompletedSuccessfully && !values.Result && (!conditionsReady.IsCompletedSuccessfully || !conditionsReady.Result)
&& _outbound.Reader.Completion.IsCompleted)
return null;
}
}
private Task<bool> StartWait(ChannelReader<PendingDelivery> reader, CancellationToken token)
{
if (!ReferenceEquals(reader, _outbound.Reader)) Interlocked.Increment(ref _conditionWaitsStarted);
return reader.WaitToReadAsync(token).AsTask();
}
private int _conditionWaitsStarted;
/// <summary>Test seam (N5): how many waits on the CONDITION queue the delivery loop has registered.</summary>
internal int ConditionWaitsStartedForTests => Volatile.Read(ref _conditionWaitsStarted);
/// <summary>Test seam: the stream has processed its Open.</summary>
internal bool IsOpenForTests => Volatile.Read(ref _handles) is not null;
// Test seams (stream priority, fairness, waiters). Internal, reached only through InternalsVisibleTo: they queue empty
// frames directly, bypassing items, so the delivery order can be asserted without a producer.
/// <summary>Test seam: queues an empty value frame on the v1 queue.</summary>
internal Task EnqueueValueProbeForTests() =>
EnqueueAsync(new PendingDelivery(sequence => new DataSubscriptionValues(_subscriptionId!, _epoch, sequence, false, []),
() => true, isValue: true));
/// <summary>Test seam: queues a heartbeat control on the v1 queue.</summary>
internal Task EnqueueHeartbeatProbeForTests()
{
var serving = _serving!;
return EnqueueAsync(new PendingDelivery(sequence => new DataSubscriptionControl(_subscriptionId!, _epoch, sequence,
DataStreamControlKind.Heartbeat, [], serving.CatalogEpoch, serving.AuthorityEpoch, null), () => true));
}
/// <summary>Test seam: queues an empty condition frame for <paramref name="handle"/>; false when the queue is full.</summary>
internal bool TryEnqueueConditionProbeForTests(DataItemHandle handle) =>
ConditionOutbound.Writer.TryWrite(new PendingDelivery(sequence => new DataSubscriptionConditions(_subscriptionId!, _epoch,
sequence, handle, false, null, [], false), () => true));
/// <summary>Called from the worker's teardown: completes and drains the condition queue, releases condition items.</summary>
private void TearDownConditions()
{
if (_conditionOutboundChannel is { } queue)
{
queue.Writer.TryComplete();
while (queue.Reader.TryRead(out var pending)) pending.Dispose();
}
foreach (var item in _conditionItems.Values) item.Dispose();
_conditionItems.Clear();
_conditionActivations.Clear();
}
}