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
{
// The limiter is sized ONCE per node manager, at first use: with the shared fixture another test may have sized it
// already (H3 review round 2: the non-local share is now one node-manager semaphore), so saturate what exists.
fx.Nm.MaxConcurrentHistoryReadBatches = 4;
fx.Nm.HistorianDataSource = source;
var port = new OriginHistoryPort(fx.Nm);
OriginHistoryPort.RemoteSlots(4).ShouldBe(3);
var slots = port.AvailableRemoteSlots;
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, slots).Select(i => port.ReadAsync(new OriginHistoryCursors("peer", "c" + i, 4), "peer", () => "inc",
details, [item], CancellationToken.None)).ToArray();
await source.WaitForCalls(slots);
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(slots + 1);
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();
}
}
[Fact]
public async Task A_pre_cancelled_read_returns_its_remote_slot()
{
await fx.Gate.WaitAsync(TestContext.Current.CancellationToken);
var source = new BlockingSource();
source.Release.TrySetResult(); // reads complete at once
try
{
fx.Nm.HistorianDataSource = source;
var port = new OriginHistoryPort(fx.Nm);
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 slots = port.AvailableRemoteSlots; // the node manager's non-local share, sized once at first use
using var cancelled = new CancellationTokenSource();
await cancelled.CancelAsync();
for (var i = 0; i < slots + 3; i++)
await Should.ThrowAsync(() => port.ReadAsync(new OriginHistoryCursors("peer", "c" + i, 4), "peer",
() => "inc", details, [item], cancelled.Token));
port.AvailableRemoteSlots.ShouldBe(slots, "every cancelled dispatch gave its slot back");
var served = (await port.ReadAsync(new OriginHistoryCursors("peer", "ok", 4), "peer", () => "inc", details, [item],
CancellationToken.None)).Single();
served.StatusCode.ShouldNotBe(StatusCodes.BadTooManyOperations.Code);
}
finally
{
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() { }
}
}