fix(grpc-data): H2 review 9 - remote peers cannot starve local HistoryRead

Remote reads hold at most N - max(1, N/4) of the node manager's N process-wide history batch slots
(MaxConcurrentHistoryReadBatches); past that a remote request is BadTooManyOperations unsent, so local OPC UA clients
always keep at least one slot.
This commit is contained in:
Joseph Doherty
2026-11-23 22:09:49 -05:00
parent 6f1faaeb0b
commit 54d49e6cb6
2 changed files with 114 additions and 1 deletions
@@ -89,6 +89,20 @@ public sealed class OriginHistoryPort(OtOpcUaNodeManager nodeManager) : IOriginH
private readonly OtOpcUaNodeManager _nm = nodeManager ?? throw new ArgumentNullException(nameof(nodeManager));
private (IHistorianDataSource Source, OriginHistoryServing? Serving)? _serving;
private SemaphoreSlim? _remoteSlots;
private readonly Lock _slotsGate = new();
/// <summary>
/// The share of the node manager's process-wide history batch limiter (N = <c>MaxConcurrentHistoryReadBatches</c>)
/// remote peers may hold: N - max(1, N/4), at least 1. The rest stays free for local OPC UA HistoryRead.
/// </summary>
public static int RemoteSlots(int batches) => Math.Max(1, batches - Math.Max(1, batches / 4));
private SemaphoreSlim Slots()
{
if (_remoteSlots is { } slots) return slots;
lock (_slotsGate) return _remoteSlots ??= new SemaphoreSlim(RemoteSlots(Math.Max(1, _nm.MaxConcurrentHistoryReadBatches)));
}
/// <inheritdoc />
/// <remarks>Cached per historian source instance: the catalog asks per node, so this is a reference compare, not a rebuild.</remarks>
@@ -124,10 +138,17 @@ public sealed class OriginHistoryPort(OtOpcUaNodeManager nodeManager) : IOriginH
item.AggregateId is { } id ? new NodeId(id, 0) : default, item.BindingTag)).ToArray();
// ONE scope per request: it snapshots the serving incarnation at first use (H1 review note).
var scope = new WiringObservedScope(new PeerHistoryContinuationScope(cursors.Store, principal, servingIncarnation));
// Remote peers never take the slots reserved for local clients (H2 review): full => BadTooManyOperations, unsent.
var slots = Slots();
if (!slots.Wait(0))
return Task.FromResult<IReadOnlyList<OriginHistoryOutcome>>(items
.Select(_ => new OriginHistoryOutcome(StatusCodes.BadTooManyOperations.Code, [], null, false)).ToArray());
// The port block-bridges like the SDK overrides; never run it on the RPC thread.
return Task.Run<IReadOnlyList<OriginHistoryOutcome>>(() =>
{
var outcomes = _nm.ReadHistory(variant, portItems, scope, cancellationToken);
IReadOnlyList<HistoryReadNodeOutcome> outcomes;
try { outcomes = _nm.ReadHistory(variant, portItems, scope, cancellationToken); }
finally { slots.Release(); }
return outcomes.Select(o =>
{
var status = o.Status.Code;