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;
@@ -0,0 +1,92 @@
using Opc.Ua;
using Shouldly;
using Xunit;
using ZB.MOM.WW.OtOpcUa.Commons.OpcUa;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections;
using HistorianRead = ZB.MOM.WW.OtOpcUa.Core.Abstractions.HistoryReadResult;
namespace ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests;
/// <summary>
/// H2 review 9: remote peers share the node manager's process-wide history batch limiter with local OPC UA clients,
/// so they may hold at most N − max(1, N/4) of its N slots — a remote flood can never starve local HistoryRead.
/// </summary>
[Trait("Category", "Unit"), Trait("Feature", "GrpcData"), Trait("Phase", "H2")]
public sealed class OriginHistoryLimiterTests(HistoryReadPortServerFixture fx) : IClassFixture<HistoryReadPortServerFixture>
{
private static readonly DateTime T0 = new(2026, 3, 1, 10, 0, 0, DateTimeKind.Utc);
[Fact]
public async Task Remote_reads_leave_local_slots_free()
{
await fx.Gate.WaitAsync(TestContext.Current.CancellationToken);
var source = new BlockingSource();
try
{
fx.Nm.MaxConcurrentHistoryReadBatches = 4; // the limiter is sized at first use; this fixture is fresh
fx.Nm.HistorianDataSource = source;
var port = new OriginHistoryPort(fx.Nm);
OriginHistoryPort.RemoteSlots(4).ShouldBe(3);
var details = new DataHistoryRawDetails(new DateTimeOffset(T0), new DateTimeOffset(T0.AddSeconds(5)), 1, false);
var item = new OriginHistoryItem(AddressSpaceRealm.Uns, "port/dbl", "peer:uns", null, null);
var remote = Enumerable.Range(0, 3).Select(i => port.ReadAsync(new OriginHistoryCursors("peer", "c" + i, 4), "peer", () => "inc",
details, [item], CancellationToken.None)).ToArray();
await source.WaitForCalls(3);
var refused = (await port.ReadAsync(new OriginHistoryCursors("peer", "c9", 4), "peer", () => "inc", details, [item], CancellationToken.None)).Single();
refused.StatusCode.ShouldBe(StatusCodes.BadTooManyOperations.Code, "the remote share is full");
// A local (SDK-path) read still gets the reserved slot.
var local = Task.Run(() => fx.Nm.ReadHistory(OriginHistoryPort.ToVariant(details),
[new HistoryReadPortItem(AddressSpaceRealm.Uns, "port/dbl", null, default, "urn:local")],
fx.Nm.SessionHistoryContinuationScope(null), CancellationToken.None));
await source.WaitForCalls(4);
source.Release.TrySetResult();
(await local).Single().Status.Code.ShouldNotBe(StatusCodes.BadTooManyOperations.Code);
foreach (var r in await Task.WhenAll(remote)) r.Single().StatusCode.ShouldNotBe(StatusCodes.BadTooManyOperations.Code);
}
finally
{
source.Release.TrySetResult();
fx.Nm.HistorianDataSource = NullHistorianDataSource.Instance;
fx.Gate.Release();
}
}
private sealed class BlockingSource : IHistorianDataSource
{
private int _calls;
public TaskCompletionSource Release { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously);
public bool SupportsReverseRaw => true;
public async Task WaitForCalls(int count)
{
var until = DateTime.UtcNow.AddSeconds(20);
while (Volatile.Read(ref _calls) < count)
{
if (DateTime.UtcNow > until) throw new TimeoutException($"only {_calls} backend calls");
await Task.Delay(10, TestContext.Current.CancellationToken);
}
}
public async Task<HistorianRead> ReadRawAsync(string fullReference, DateTime startUtc, DateTime endUtc, uint maxValuesPerNode,
CancellationToken cancellationToken)
{
Interlocked.Increment(ref _calls);
await Release.Task.ConfigureAwait(false);
return new HistorianRead([], null);
}
public Task<HistorianRead> ReadProcessedAsync(string fullReference, DateTime startUtc, DateTime endUtc, TimeSpan interval,
HistoryAggregateType aggregate, CancellationToken cancellationToken) => Task.FromResult(new HistorianRead([], null));
public Task<HistorianRead> ReadAtTimeAsync(string fullReference, IReadOnlyList<DateTime> timestampsUtc, CancellationToken cancellationToken) =>
Task.FromResult(new HistorianRead([], null));
public Task<HistoricalEventsResult> ReadEventsAsync(string? sourceName, DateTime startUtc, DateTime endUtc, int maxEvents,
CancellationToken cancellationToken) => Task.FromResult(new HistoricalEventsResult(Array.Empty<HistoricalEvent>(), null));
public HistorianHealthSnapshot GetHealthSnapshot() => NullHistorianDataSource.Instance.GetHealthSnapshot();
public void Dispose() { }
}
}