From 54d49e6cb61ccac42c740cb9b16906c3cb57f124 Mon Sep 17 00:00:00 2001 From: Joseph Doherty Date: Mon, 23 Nov 2026 22:09:49 -0500 Subject: [PATCH] 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. --- .../OriginHistoryPort.cs | 23 ++++- .../OriginHistoryLimiterTests.cs | 92 +++++++++++++++++++ 2 files changed, 114 insertions(+), 1 deletion(-) create mode 100644 tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests/OriginHistoryLimiterTests.cs diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/OriginHistoryPort.cs b/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/OriginHistoryPort.cs index 1baff2b39..6d16046e0 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/OriginHistoryPort.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/OriginHistoryPort.cs @@ -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(); + + /// + /// The share of the node manager's process-wide history batch limiter (N = MaxConcurrentHistoryReadBatches) + /// remote peers may hold: N - max(1, N/4), at least 1. The rest stays free for local OPC UA HistoryRead. + /// + 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))); + } /// /// Cached per historian source instance: the catalog asks per node, so this is a reference compare, not a rebuild. @@ -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>(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>(() => { - var outcomes = _nm.ReadHistory(variant, portItems, scope, cancellationToken); + IReadOnlyList outcomes; + try { outcomes = _nm.ReadHistory(variant, portItems, scope, cancellationToken); } + finally { slots.Release(); } return outcomes.Select(o => { var status = o.Status.Code; diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests/OriginHistoryLimiterTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests/OriginHistoryLimiterTests.cs new file mode 100644 index 000000000..ac39a5aa1 --- /dev/null +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests/OriginHistoryLimiterTests.cs @@ -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; + +/// +/// 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. +/// +[Trait("Category", "Unit"), Trait("Feature", "GrpcData"), Trait("Phase", "H2")] +public sealed class OriginHistoryLimiterTests(HistoryReadPortServerFixture fx) : IClassFixture +{ + 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 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 ReadProcessedAsync(string fullReference, DateTime startUtc, DateTime endUtc, TimeSpan interval, + HistoryAggregateType aggregate, CancellationToken cancellationToken) => Task.FromResult(new HistorianRead([], null)); + + public Task ReadAtTimeAsync(string fullReference, IReadOnlyList timestampsUtc, CancellationToken cancellationToken) => + Task.FromResult(new HistorianRead([], null)); + + public Task ReadEventsAsync(string? sourceName, DateTime startUtc, DateTime endUtc, int maxEvents, + CancellationToken cancellationToken) => Task.FromResult(new HistoricalEventsResult(Array.Empty(), null)); + + public HistorianHealthSnapshot GetHealthSnapshot() => NullHistorianDataSource.Instance.GetHealthSnapshot(); + + public void Dispose() { } + } +}