using System.Security.Cryptography; using System.Security.Cryptography.X509Certificates; using Microsoft.Extensions.Logging.Abstractions; using Opc.Ua; using Opc.Ua.Security.Certificates; using Opc.Ua.Server; using Shouldly; using Xunit; using ZB.MOM.WW.OtOpcUa.Commons.OpcUa; using ZB.MOM.WW.OtOpcUa.Core.Abstractions; using HistorianRead = ZB.MOM.WW.OtOpcUa.Core.Abstractions.HistoryReadResult; using SdkHistoryReadResult = Opc.Ua.HistoryReadResult; namespace ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests; /// /// H1 (review 7): the port's process-wide batch limiter, its per-request deadline and request cancellation, and paging /// against the REAL SDK session-backed continuation store. Each case boots its own server, because the batch limiter is /// sized once per node manager at first use. /// [Trait("Feature", "GrpcData")] [Trait("Phase", "H1")] public sealed class HistoryReadPortLimiterAndSessionTests : IAsyncDisposable { private static readonly DateTime T0 = new(2026, 3, 1, 10, 0, 0, DateTimeKind.Utc); private readonly string _pki = Path.Combine(Path.GetTempPath(), $"otopcua-histport-limit-{Guid.NewGuid():N}"); private OpcUaApplicationHost? _host; [Fact] public async Task A_saturated_limiter_fails_every_node_of_the_waiting_batch_on_both_paths() { var (server, nm) = await BootAsync(); nm.MaxConcurrentHistoryReadBatches = 1; // The holder runs with NO deadline (it is captured when its batch starts), so it holds the slot until released, // whatever the machine's speed; the waiting batches then get a short deadline, so their admission wait is short. nm.HistoryReadDeadline = TimeSpan.Zero; var source = new GatedSource(); nm.HistorianDataSource = source; var nodeId = Add(nm, "lim/a", "P.a"); Add(nm, "lim/b", "P.b"); var details = new HistoryReadRawVariant(T0, T0.AddHours(1), 5, ReturnBounds: false); var scope = nm.SessionHistoryContinuationScope(session: null); // Batch A holds the only slot inside the backend. var holder = Task.Run(() => nm.ReadHistory(details, [new HistoryReadPortItem(AddressSpaceRealm.Uns, "lim/a")], scope, CancellationToken.None)); await source.Entered.Task.WaitAsync(TimeSpan.FromSeconds(10), TestContext.Current.CancellationToken); nm.HistoryReadDeadline = TimeSpan.FromMilliseconds(300); // admission waits min(deadline, 5 s) var waiting = nm.ReadHistory(details, [new HistoryReadPortItem(AddressSpaceRealm.Uns, "lim/a"), new HistoryReadPortItem(AddressSpaceRealm.Uns, "lim/b")], scope, CancellationToken.None); waiting.ShouldAllBe(o => o.Error!.StatusCode == StatusCodes.BadTooManyOperations && o.Result!.StatusCode == StatusCodes.BadTooManyOperations); source.Calls.ShouldBe(1, "the rejected batch never reached the backend"); // The SDK override path shares the same limiter. var context = new OperationContext(new RequestHeader(), secureChannelContext: null, RequestType.HistoryRead, requestLifetime: RequestLifetime.None, identity: null); var results = new List { null! }; var errors = new List { null! }; nm.HistoryRead(context, new ReadRawModifiedDetails { StartTime = T0, EndTime = T0.AddHours(1), NumValuesPerNode = 5, ReturnBounds = false, IsReadModified = false }, TimestampsToReturn.Both, false, new List { new() { NodeId = nodeId } }, results, errors); errors[0].StatusCode.Code.ShouldBe(StatusCodes.BadTooManyOperations.Code); results[0].StatusCode.Code.ShouldBe(StatusCodes.BadTooManyOperations.Code); source.Release.SetResult(); var held = await holder.WaitAsync(TimeSpan.FromSeconds(10), TestContext.Current.CancellationToken); held.Single().Error!.StatusCode.Code.ShouldBe(StatusCodes.Good.Code, "the slot holder completes normally"); } [Fact] public async Task The_deadline_and_request_cancellation_time_out_each_in_flight_node() { var (_, nm) = await BootAsync(); nm.HistorianDataSource = new GatedSource { HonourCancellation = true }; Add(nm, "dl/a", "P.a"); var scope = nm.SessionHistoryContinuationScope(session: null); HistoryReadVariant[] variants = [ new HistoryReadRawVariant(T0, T0.AddHours(1), 5, ReturnBounds: false), new HistoryReadAtTimeVariant([T0]), new HistoryReadProcessedVariant(T0, T0.AddHours(1), TimeSpan.FromMinutes(10), null), ]; var item = new HistoryReadPortItem(AddressSpaceRealm.Uns, "dl/a", AggregateType: ObjectIds.AggregateFunction_Average); // The application deadline. nm.HistoryReadDeadline = TimeSpan.FromMilliseconds(200); foreach (var variant in variants) { var o = nm.ReadHistory(variant, [item], scope, CancellationToken.None).Single(); o.Error!.StatusCode.Code.ShouldBe(StatusCodes.BadTimeout.Code, variant.GetType().Name); o.Result!.StatusCode.Code.ShouldBe(StatusCodes.BadTimeout.Code); } // The caller's own cancellation (H2's per-node deadline rides it), with no application deadline. nm.HistoryReadDeadline = TimeSpan.Zero; foreach (var variant in variants) { using var cts = new CancellationTokenSource(TimeSpan.FromMilliseconds(200)); var o = nm.ReadHistory(variant, [item], scope, cts.Token).Single(); o.Error!.StatusCode.Code.ShouldBe(StatusCodes.BadTimeout.Code, variant.GetType().Name); o.Result!.StatusCode.Code.ShouldBe(StatusCodes.BadTimeout.Code, variant.GetType().Name); } } [Fact] public async Task The_port_pages_through_the_real_session_backed_store() { var (server, nm) = await BootAsync(); nm.HistoryContinuationStore = new SessionHistoryContinuationStore(); var source = new GatedSource { Opened = true }; source.Series.AddRange(Enumerable.Range(0, 7).Select(i => new DataValueSnapshot((double)i, 0, T0.AddSeconds(i), T0.AddSeconds(i)))); nm.HistorianDataSource = source; Add(nm, "sess/a", "P.a"); var details = new HistoryReadRawVariant(T0, T0.AddHours(1), 2, ReturnBounds: false); var item = new HistoryReadPortItem(AddressSpaceRealm.Uns, "sess/a"); using var certificateKey = RSA.Create(2048); using var certificate = Certificate.From(new CertificateRequest("CN=H1.Port.Session", certificateKey, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1) .CreateSelfSigned(DateTimeOffset.UtcNow.AddDays(-1), DateTimeOffset.UtcNow.AddDays(1))); using var nonce = Nonce.CreateNonce(32); using var session = NewSession(server, certificate, nonce); using var other = NewSession(server, certificate, nonce); var scope = nm.SessionHistoryContinuationScope(session); var values = new List(); byte[]? cp = null; byte[]? firstCp = null; do { var o = nm.ReadHistory(details, [item with { ContinuationPoint = cp }], scope, CancellationToken.None).Single(); o.Error!.StatusCode.Code.ShouldBe(StatusCodes.Good.Code); values.AddRange(o.Values.Select(v => (double)SdkValueBoundary.ToClr(v.WrappedValue)!)); cp = o.ContinuationPoint; firstCp ??= cp; } while (cp is not null); values.ShouldBe([0, 1, 2, 3, 4, 5, 6]); // Session-store semantics: single-use, and a point is never visible to another session. nm.ReadHistory(details, [item with { ContinuationPoint = firstCp }], scope, CancellationToken.None).Single() .Status.Code.ShouldBe(StatusCodes.BadContinuationPointInvalid.Code); var fresh = nm.ReadHistory(details, [item], scope, CancellationToken.None).Single().ContinuationPoint!; nm.ReadHistory(details, [item with { ContinuationPoint = fresh }], nm.SessionHistoryContinuationScope(other), CancellationToken.None).Single() .Status.Code.ShouldBe(StatusCodes.BadContinuationPointInvalid.Code); // With no session there is nowhere to keep a cursor: the read degrades to single-shot, as before. nm.ReadHistory(details, [item], nm.SessionHistoryContinuationScope(session: null), CancellationToken.None).Single() .ContinuationPoint.ShouldBeNull(); } [Fact] public async Task The_override_pages_and_resumes_through_the_real_session_store_with_a_real_session() { var (server, nm) = await BootAsync(); nm.HistoryContinuationStore = new SessionHistoryContinuationStore(); var source = new GatedSource { Opened = true }; source.Series.AddRange(Enumerable.Range(0, 7).Select(i => new DataValueSnapshot((double)i, 0, T0.AddSeconds(i), T0.AddSeconds(i)))); nm.HistorianDataSource = source; var nodeId = Add(nm, "sess/o", "P.o"); using var certificateKey = RSA.Create(2048); using var certificate = Certificate.From(new CertificateRequest("CN=H1.Override.Session", certificateKey, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1) .CreateSelfSigned(DateTimeOffset.UtcNow.AddDays(-1), DateTimeOffset.UtcNow.AddDays(1))); using var nonce = Nonce.CreateNonce(32); using var session = NewSession(server, certificate, nonce); using var other = NewSession(server, certificate, nonce); (uint Error, List Values, byte[]? Cp) Read(ISession s, byte[]? cp) { var context = new OperationContext(new RequestHeader(), null!, RequestType.HistoryRead, RequestLifetime.None, s); var results = new List { null! }; var errors = new List { null! }; nm.HistoryRead(context, new ReadRawModifiedDetails { StartTime = T0, EndTime = T0.AddHours(1), NumValuesPerNode = 2, ReturnBounds = false, IsReadModified = false }, TimestampsToReturn.Both, false, new List { new() { NodeId = nodeId, ContinuationPoint = ByteString.From(cp) } }, results, errors); var values = results[0]?.HistoryData is { IsNull: false } body && ExtensionObject.ToEncodeable(body) is HistoryData data ? (data.DataValues.ToArray() ?? []).Select(v => (double)SdkValueBoundary.ToClr(v.WrappedValue)!).ToList() : []; return (errors[0].StatusCode.Code, values, results[0]?.ContinuationPoint.ToNullableArray()); } var collected = new List(); byte[]? cp = null; var pages = 0; do { var (error, values, next) = Read(session, cp); error.ShouldBe(StatusCodes.Good.Code); collected.AddRange(values); cp = next; pages++; } while (cp is not null && pages < 20); collected.ShouldBe([0, 1, 2, 3, 4, 5, 6]); pages.ShouldBe(4, "N = 2 over 7 values: four pages, the session store holding each cursor in between"); // An override-issued cursor lives in the SDK session: another session cannot resume it, a reuse is a miss, and the // port resumes it through the same session with the adapter's binding tag. var first = Read(session, null).Cp!; Read(other, first).Error.ShouldBe(StatusCodes.BadContinuationPointInvalid.Code); var second = Read(session, null).Cp!; var viaPort = nm.ReadHistory(new HistoryReadRawVariant(T0, T0.AddHours(1), 2, ReturnBounds: false), [new HistoryReadPortItem(AddressSpaceRealm.Uns, "sess/o", second, BindingTag: nm.HistoryBindingTag(nodeId))], nm.SessionHistoryContinuationScope(session), CancellationToken.None).Single(); viaPort.Error!.StatusCode.Code.ShouldBe(StatusCodes.Good.Code); viaPort.Values.Select(v => (double)SdkValueBoundary.ToClr(v.WrappedValue)!).ShouldBe([2, 3]); Read(session, second).Error.ShouldBe(StatusCodes.BadContinuationPointInvalid.Code, "single use"); } private static Session NewSession(OtOpcUaSdkServer server, Certificate certificate, Nonce nonce) { var endpoint = new EndpointDescription { EndpointUrl = "opc.tcp://localhost:4840", SecurityMode = MessageSecurityMode.None }; using var context = new OperationContext(new RequestHeader(), new SecureChannelContext(Guid.NewGuid().ToString(), endpoint, RequestEncoding.Binary), RequestType.CreateSession, RequestLifetime.None); return new Session(context, server.CurrentInstance, certificate, new NodeId(Guid.NewGuid()), default, nonce, "H1 port session", new ApplicationDescription(), endpoint.EndpointUrl, null!, null!, 60_000, 10, 10); } private static NodeId Add(OtOpcUaNodeManager nm, string id, string tag) { nm.EnsureVariable(id, parentFolderNodeId: null, displayName: id, dataType: "Double", writable: false, realm: AddressSpaceRealm.Uns, historianTagname: tag); return nm.TryGetVariable(id)!.NodeId; } private async Task<(OtOpcUaSdkServer Server, OtOpcUaNodeManager Nm)> BootAsync() { var started = await OpcUaHostStart.StartAsync( port => new OpcUaApplicationHost(new OpcUaApplicationHostOptions { ApplicationName = "OtOpcUa.HistoryPortLimit", ApplicationUri = $"urn:OtOpcUa.HistoryPortLimit:{Guid.NewGuid():N}", OpcUaPort = port, PublicHostname = "localhost", PkiStoreRoot = _pki, }, NullLogger.Instance), () => new OtOpcUaSdkServer(), TestContext.Current.CancellationToken); _host = started.Host; var nm = started.Server.NodeManager!; nm.HistoryContinuationStore = new InMemoryHistoryContinuationStore(); return (started.Server, nm); } public async ValueTask DisposeAsync() { if (_host is not null) await _host.DisposeAsync(); if (Directory.Exists(_pki)) { try { Directory.Delete(_pki, recursive: true); } catch { /* best-effort */ } } } /// /// A backend whose reads block until (ignoring cancellation, so a slot stays held) — or, with /// , until the read's token fires; answers from /// straight away. /// private sealed class GatedSource : IHistorianDataSource { private int _calls; public TaskCompletionSource Entered { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously); public TaskCompletionSource Release { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously); public bool HonourCancellation { get; init; } public bool Opened { get; init; } public List Series { get; } = []; public int Calls => Volatile.Read(ref _calls); public bool SupportsReverseRaw => true; private async Task Gate(Func> answer, CancellationToken ct) { Interlocked.Increment(ref _calls); if (!Opened) { Entered.TrySetResult(); if (HonourCancellation) await Task.Delay(Timeout.Infinite, ct).ConfigureAwait(false); else await Release.Task.ConfigureAwait(false); } await Task.Delay(1, CancellationToken.None).ConfigureAwait(false); return new HistorianRead(answer(), null); } public Task ReadRawAsync( string fullReference, DateTime startUtc, DateTime endUtc, uint maxValuesPerNode, CancellationToken cancellationToken) => Gate(() => { var window = Series.Where(s => s.SourceTimestampUtc >= startUtc && s.SourceTimestampUtc < endUtc); return (maxValuesPerNode == 0 ? window : window.Take((int)maxValuesPerNode)).ToList(); }, cancellationToken); public Task ReadProcessedAsync( string fullReference, DateTime startUtc, DateTime endUtc, TimeSpan interval, HistoryAggregateType aggregate, CancellationToken cancellationToken) => Gate(() => [], cancellationToken); public Task ReadAtTimeAsync( string fullReference, IReadOnlyList timestampsUtc, CancellationToken cancellationToken) => Gate(() => [], cancellationToken); 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() { } } }