feat(grpc-data): A2a — origin condition streaming: root-scoped items over the A1 hub, priority queue, host negotiation, consumer decode

This commit is contained in:
Joseph Doherty
2026-11-24 12:08:08 -05:00
parent 73142e52d4
commit 5b03c8a26e
17 changed files with 809 additions and 43 deletions
@@ -0,0 +1,210 @@
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).
/// 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
{
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)
{
r.Dispose();
OtOpcUaTelemetry.DataConnConditionItems.Add(-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;
/// <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.");
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 stream = new ConditionItemStream(hub, source, authority.Scope, authority.Limit,
request.ConditionScope!.IncludeInfo, services.Clock);
var item = new ConditionItem(request.ClientItemId, handle, authority, stream, reservation!);
OtOpcUaTelemetry.DataConnConditionItems.Add(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;
var budget = Math.Max(1, _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.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(),
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 queued control or ack first, then a condition frame, then the queued value. 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;
}
if (_conditionOutboundChannel is { } conditions && conditions.Reader.TryRead(out var condition))
{
QueueTick();
return condition;
}
if (_outbound.Reader.TryRead(out var value)) { Dequeued(value); return value; }
if (_conditionOutboundChannel is null)
{
if (!await _outbound.Reader.WaitToReadAsync(token).ConfigureAwait(false)) return null;
continue;
}
var values = _outbound.Reader.WaitToReadAsync(token).AsTask();
var conditionsReady = _conditionOutboundChannel.Reader.WaitToReadAsync(token).AsTask();
await Task.WhenAny(values, conditionsReady).ConfigureAwait(false);
token.ThrowIfCancellationRequested();
if (values.IsCompletedSuccessfully && !values.Result && (!conditionsReady.IsCompletedSuccessfully || !conditionsReady.Result)
&& _outbound.Reader.Completion.IsCompleted)
return null;
}
}
/// <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();
}
}