using Microsoft.Extensions.Logging.Abstractions; using Opc.Ua; using Opc.Ua.Client; 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 ZB.MOM.WW.OtOpcUa.OpcUaServer; using ZB.MOM.WW.OtOpcUa.Runtime.DataConnections; using HistorianRead = ZB.MOM.WW.OtOpcUa.Core.Abstractions.HistoryReadResult; using SdkDataValue = Opc.Ua.DataValue; namespace ZB.MOM.WW.OtOpcUa.Runtime.Tests.DataConnections; /// /// H3 — a real consumer OPC UA session HistoryReads a projected node through the real projection stack /// ( + ) and a real in-process origin /// ( over a real history port and its /// PeerHistoryContinuationStore). Replaces the H2 pin that a projected node refused HistoryRead "until H3". /// public sealed partial class GrpcDataConfiguredDiscoveryWireTests { private static readonly DateTime HistoryT0 = new(2026, 11, 20, 10, 0, 0, DateTimeKind.Utc); [Fact(Timeout = 90000)] [Trait("Phase", "H3")] [Trait("Phase", "H2")] // replaces the H2 pin "a projected node refuses HistoryRead until H3" public async Task Granted_projected_HistoryRead_is_served_verbatim_and_pages_to_completion_through_the_origin() { await using var originServer = await HistoryOrigin.StartAsync(7); using var origin = new LocalDataFixture(servingGeneration: 1, history: originServer.Port); var connections = new PersistentConnections(origin); await WithComposedServer(origin, origin.Raw, async (session, _, _, _, _, _, anchor) => { var client = (SessionClient)session; await BrowseAll(client, anchor, 1); var values = new List(); var cp = default(ByteString); var pages = 0; do { var result = await RawHistory(client, anchor, 3, cp); StatusCode.IsGood(result.StatusCode).ShouldBeTrue(result.StatusCode.ToString()); values.AddRange(Values(result)); cp = result.ContinuationPoint; pages++; } while (!cp.IsEmpty && pages < 10); values.Select(v => SdkValueBoundary.ToClr(v.WrappedValue)).ShouldBe(Enumerable.Range(0, 7).Cast()); values.Select(v => v.SourceTimestamp.ToDateTime()).ShouldBe(Enumerable.Range(0, 7).Select(i => HistoryT0.AddSeconds(i))); pages.ShouldBe(3); origin.Services.HistoryOpenContinuations.ShouldBe(0, "a page-through to completion leaves nothing open at the origin"); }, localPermissions: 15, allowHistory: true, connectionSource: connections); } [Fact(Timeout = 90000)] [Trait("Phase", "H3")] [Trait("Phase", "H2")] // replaces the H2 pin "a projected node refuses HistoryRead until H3" public async Task Without_the_local_HistoryRead_grant_on_the_mapping_scope_it_is_BadUserAccessDenied_and_unsent() { await using var originServer = await HistoryOrigin.StartAsync(7); using var origin = new LocalDataFixture(servingGeneration: 1, history: originServer.Port); await WithComposedServer(origin, origin.Raw, async (session, _, _, _, _, _, anchor) => { var client = (SessionClient)session; await BrowseAll(client, anchor, 1); var result = await RawHistory(client, anchor, 3, default); result.StatusCode.Code.ShouldBe(StatusCodes.BadUserAccessDenied.Code); result.ContinuationPoint.IsEmpty.ShouldBeTrue(); originServer.Source.Calls.ShouldBe(0); }, localPermissions: 7, allowHistory: true, connectionSource: new PersistentConnections(origin)); } [Fact(Timeout = 90000)] [Trait("Phase", "H3")] public async Task Consumer_session_close_releases_the_origin_continuations() { await using var originServer = await HistoryOrigin.StartAsync(7); using var origin = new LocalDataFixture(servingGeneration: 1, history: originServer.Port); ProjectedHistoryAccess? history = null; await WithComposedServer(origin, origin.Raw, async (session, _, _, _, _, _, anchor) => { var client = (SessionClient)session; await BrowseAll(client, anchor, 1); var page = await RawHistory(client, anchor, 2, default); page.ContinuationPoint.IsEmpty.ShouldBeFalse(); origin.Services.HistoryOpenContinuations.ShouldBe(1); await session.CloseAsync(TestContext.Current.CancellationToken); await AwaitReleases(history!, () => origin.Services.HistoryOpenContinuations == 0); origin.Services.HistoryOpenContinuations.ShouldBe(0, "the SDK disposed the Remote point and the release reached the origin"); history!.ReleaseCallsForTests.ShouldBe(1); }, localPermissions: 15, allowHistory: true, connectionSource: new PersistentConnections(origin), onHistory: (h, _) => history = h); } [Fact(Timeout = 90000)] [Trait("Phase", "H3")] public async Task ReleaseContinuationPoints_forwards_one_release_and_the_point_is_then_invalid() { await using var originServer = await HistoryOrigin.StartAsync(7); using var origin = new LocalDataFixture(servingGeneration: 1, history: originServer.Port); ProjectedHistoryAccess? history = null; await WithComposedServer(origin, origin.Raw, async (session, _, _, _, _, _, anchor) => { var client = (SessionClient)session; await BrowseAll(client, anchor, 1); var page = await RawHistory(client, anchor, 2, default); origin.Services.HistoryOpenContinuations.ShouldBe(1); var released = await client.HistoryReadAsync(new RequestHeader(), new ExtensionObject(RawDetails(2)), TimestampsToReturn.Both, true, [new HistoryReadValueId { NodeId = anchor, ContinuationPoint = page.ContinuationPoint }], TestContext.Current.CancellationToken); StatusCode.IsGood(released.Results[0].StatusCode).ShouldBeTrue(); await AwaitReleases(history!, () => origin.Services.HistoryOpenContinuations == 0); origin.Services.HistoryOpenContinuations.ShouldBe(0); var resumed = await RawHistory(client, anchor, 2, page.ContinuationPoint); resumed.StatusCode.Code.ShouldBe(StatusCodes.BadContinuationPointInvalid.Code); }, localPermissions: 15, allowHistory: true, connectionSource: new PersistentConnections(origin), onHistory: (h, _) => history = h); } [Fact(Timeout = 90000)] [Trait("Phase", "H3")] public async Task A_resume_after_lease_expiry_or_an_origin_rebuild_epoch_bump_is_invalid_and_a_fresh_read_succeeds() { await using var originServer = await HistoryOrigin.StartAsync(7); using var origin = new LocalDataFixture(servingGeneration: 1, history: originServer.Port); var connections = new PersistentConnections(origin); await WithComposedServer(origin, origin.Raw, async (session, _, _, _, _, _, anchor) => { var client = (SessionClient)session; await BrowseAll(client, anchor, 1); // Lease expiry / redeployment: the deployed connection (route) is replaced — its tokens never resume. var page = await RawHistory(client, anchor, 2, default); connections.Rotate(); (await RawHistory(client, anchor, 2, page.ContinuationPoint)).StatusCode.Code.ShouldBe(StatusCodes.BadContinuationPointInvalid.Code); var fresh = await RawHistory(client, anchor, 2, default); StatusCode.IsGood(fresh.StatusCode).ShouldBeTrue(); // Origin rebuild: its history epoch moves (a removal), so the origin itself refuses the resumed token. originServer.BumpEpoch(); (await RawHistory(client, anchor, 2, fresh.ContinuationPoint)).StatusCode.Code.ShouldBe(StatusCodes.BadContinuationPointInvalid.Code); StatusCode.IsGood((await RawHistory(client, anchor, 2, default)).StatusCode).ShouldBeTrue(); }, localPermissions: 15, allowHistory: true, connectionSource: connections); } [Fact(Timeout = 90000)] [Trait("Phase", "H3")] public async Task Uncapped_raw_returns_the_origin_continuation_and_aggregates_are_refused_both_ways() { await using var originServer = await HistoryOrigin.StartAsync(25, maxRawPerRead: 10); originServer.Source.Aggregates = new HashSet { HistoryAggregateType.Average }; using var origin = new LocalDataFixture(servingGeneration: 1, history: originServer.Port); await WithComposedServer(origin, origin.Raw, async (session, _, _, _, _, _, anchor) => { var client = (SessionClient)session; await BrowseAll(client, anchor, 1); // NumValuesPerNode = 0: the origin pages at its ceiling and the consumer hands back its continuation (Part 11). var uncapped = await RawHistory(client, anchor, 0, default); StatusCode.IsGood(uncapped.StatusCode).ShouldBeTrue(); uncapped.ContinuationPoint.IsEmpty.ShouldBeFalse(); Values(uncapped).Count.ShouldBeLessThan(25); // The origin refuses an aggregate its backend does not serve. var refused = await ProcessedHistory(client, anchor, ObjectIds.AggregateFunction_Count); refused.StatusCode.Code.ShouldBe(StatusCodes.BadAggregateNotSupported.Code); // The consumer refuses an aggregate it cannot name, unsent. var calls = originServer.Source.Calls; var unknown = await ProcessedHistory(client, anchor, new NodeId("no-such-aggregate", 1)); unknown.StatusCode.Code.ShouldBe(StatusCodes.BadAggregateNotSupported.Code); originServer.Source.Calls.ShouldBe(calls); // A served aggregate passes through. var average = await ProcessedHistory(client, anchor, ObjectIds.AggregateFunction_Average); StatusCode.IsGood(average.StatusCode).ShouldBeTrue(average.StatusCode.ToString()); // Found by the H3 live gate (H02): an aggregate's value has ITS OWN type (a Double Average of an Int32 node), // never the node's — it must not be refused BadTypeMismatch against the catalog's value kind. var interval = Values(average).ShouldHaveSingleItem(); StatusCode.IsGood(interval.StatusCode).ShouldBeTrue(interval.StatusCode.ToString()); SdkValueBoundary.ToClr(interval.WrappedValue).ShouldBeOfType().ShouldBe(3.0); }, localPermissions: 15, allowHistory: true, connectionSource: new PersistentConnections(origin)); } [Theory(Timeout = 90000)] [Trait("Phase", "H3")] [InlineData(1_000_000, 3)] [InlineData(25_000, 2)] // ≈ 288 B a value × 40 per node: two nodes fit, the third is refused [InlineData(15_000, 1)] [InlineData(1_200, 0)] public async Task The_per_request_assembly_budget_is_shared_across_the_batch(int budget, int expectedGood) { await using var originServer = await HistoryOrigin.StartAsync(7, extra: 2); using var origin = new LocalDataFixture(additionalRawNodes: 2, servingGeneration: 1, history: originServer.Port); await WithComposedServer(origin, origin.Root, async (session, _, _, _, _, _, anchor) => { var client = (SessionClient)session; var children = (await BrowseAll(client, anchor, 10)) .Select(r => ExpandedNodeId.ToNodeId(r.NodeId, session.NamespaceUris)).ToArray(); children.Length.ShouldBe(3); var details = new ReadAtTimeDetails { ReqTimes = Enumerable.Range(0, 40).Select(i => (DateTimeUtc)HistoryT0.AddSeconds(i)).ToArray() }; var response = await client.HistoryReadAsync(new RequestHeader(), new ExtensionObject(details), TimestampsToReturn.Both, false, children.Select(c => new HistoryReadValueId { NodeId = c }).ToArray(), TestContext.Current.CancellationToken); var results = response.Results.ToArray()!; var statuses = results.Select(r => r.StatusCode.Code).ToArray(); statuses.Count(s => StatusCode.IsGood(s)).ShouldBe(expectedGood, string.Join(",", statuses.Select(x => x.ToString("X8")))); foreach (var r in results.Where(r => !StatusCode.IsGood(r.StatusCode))) { r.StatusCode.Code.ShouldBe(StatusCodes.BadTooManyOperations.Code); Values(r).ShouldBeEmpty("never a partial answer under an error status"); } foreach (var r in results.Where(r => StatusCode.IsGood(r.StatusCode))) Values(r).Count.ShouldBe(40); // The budget is consumed in request order: once a node does not fit, every later node is refused too. statuses.TakeWhile(x => StatusCode.IsGood(x)).Count().ShouldBe(expectedGood); }, localPermissions: 15, allowHistory: true, connectionSource: new PersistentConnections(origin), configureMapping: m => m.MaxHistoryAssemblyBytesPerRequest = budget); } [Theory(Timeout = 90000)] [Trait("Phase", "H3")] [InlineData(false)] [InlineData(true)] public async Task Historizing_and_the_HistoryRead_bit_follow_the_mapping_grant_and_never_HistoryWrite(bool granted) { await using var originServer = await HistoryOrigin.StartAsync(7); using var origin = new LocalDataFixture(servingGeneration: 1, history: originServer.Port); await WithComposedServer(origin, origin.Raw, async (session, _, _, _, _, _, anchor) => { var client = (SessionClient)session; await BrowseAll(client, anchor, 1); var read = await client.ReadAsync(new RequestHeader(), 0, TimestampsToReturn.Neither, [new ReadValueId { NodeId = anchor, AttributeId = Attributes.Historizing }, new ReadValueId { NodeId = anchor, AttributeId = Attributes.AccessLevel }], TestContext.Current.CancellationToken); read.Results[0].WrappedValue.TryGetValue(out bool historizing).ShouldBeTrue(); historizing.ShouldBe(granted); read.Results[1].WrappedValue.TryGetValue(out byte level).ShouldBeTrue(); ((level & AccessLevels.HistoryRead) != 0).ShouldBe(granted); (level & AccessLevels.HistoryWrite).ShouldBe((byte)0); if (granted) return; var result = await RawHistory(client, anchor, 3, default); result.StatusCode.Code.ShouldBe(StatusCodes.BadHistoryOperationUnsupported.Code); originServer.Source.Calls.ShouldBe(0); }, localPermissions: 15, allowHistory: granted, connectionSource: new PersistentConnections(origin)); } // ------------------------------------------------------------------------------------------------------------------ private static ReadRawModifiedDetails RawDetails(uint count) => new() { StartTime = HistoryT0.AddSeconds(-1), EndTime = HistoryT0.AddHours(1), NumValuesPerNode = count, IsReadModified = false, ReturnBounds = false, }; private static async Task RawHistory(SessionClient client, NodeId node, uint count, ByteString cp) { var response = await client.HistoryReadAsync(new RequestHeader(), new ExtensionObject(RawDetails(count)), TimestampsToReturn.Both, false, [new HistoryReadValueId { NodeId = node, ContinuationPoint = cp }], TestContext.Current.CancellationToken); return response.Results.ToArray()!.Single(); } private static async Task ProcessedHistory(SessionClient client, NodeId node, NodeId aggregate) { var details = new ReadProcessedDetails { StartTime = HistoryT0, EndTime = HistoryT0.AddMinutes(1), ProcessingInterval = 10_000, AggregateType = [aggregate], AggregateConfiguration = new AggregateConfiguration { UseServerCapabilitiesDefaults = true }, }; var response = await client.HistoryReadAsync(new RequestHeader(), new ExtensionObject(details), TimestampsToReturn.Both, false, [new HistoryReadValueId { NodeId = node }], TestContext.Current.CancellationToken); return response.Results.ToArray()!.Single(); } private static IReadOnlyList Values(Opc.Ua.HistoryReadResult result) => result.HistoryData.IsNull || ExtensionObject.ToEncodeable(result.HistoryData) is not HistoryData data ? [] : data.DataValues.ToArray() ?? []; private static async Task AwaitReleases(ProjectedHistoryAccess history, Func done) { for (var i = 0; i < 200 && !done(); i++) { await history.FlushReleasesForTestsAsync(); if (!done()) await Task.Delay(10, TestContext.Current.CancellationToken); } } /// One long-lived origin connection, as a deployed gRPC connection is; replaces it (a redeploy). private sealed class PersistentConnections(LocalDataFixture peer) : IGrpcDataAdapterConnectionSource { private (IDataConnection Connection, object Route)? _current; private readonly object _gate = new(); public void Rotate() { lock (_gate) { if (_current is { } old) _ = old.Connection.DisposeAsync(); _current = null; } } public ValueTask AcquireAsync(string connectionId, CancellationToken cancellationToken) { if (connectionId != "link") return ValueTask.FromResult(null); lock (_gate) { _current ??= (peer.Connection(), new object()); return ValueTask.FromResult(new Borrowed(_current.Value.Connection, _current.Value.Route)); } } private sealed class Borrowed(IDataConnection connection, object route) : IGrpcDataAdapterConnectionLease { public IDataConnection Connection => connection; public CancellationToken CancellationToken => CancellationToken.None; public object? RouteIdentity => route; public ValueTask DisposeAsync() => ValueTask.CompletedTask; // non-owning, like a deployment lease } } /// A real origin node manager with a historized raw Plant/Driver/Device/Speed behind a real history port. private sealed class HistoryOrigin : IAsyncDisposable { private readonly OpcUaApplicationHost _host; private readonly string _pki; private readonly OtOpcUaNodeManager _nm; public SeriesSource Source { get; } public OriginHistoryPort Port { get; } private HistoryOrigin(OpcUaApplicationHost host, string pki, OtOpcUaNodeManager nm, SeriesSource source) { _host = host; _pki = pki; _nm = nm; Source = source; Port = new OriginHistoryPort(nm); } public static async Task StartAsync(int samples, int maxRawPerRead = 0, int extra = 0) { var pki = Path.Combine(Path.GetTempPath(), $"h3-origin-{Guid.NewGuid():N}"); var started = await OpcUaHostStart.StartAsync(port => new OpcUaApplicationHost(new OpcUaApplicationHostOptions { ApplicationName = "H3Origin", ApplicationUri = $"urn:h3-origin:{Guid.NewGuid():N}", OpcUaPort = port, PublicHostname = "127.0.0.1", PkiStoreRoot = pki, EnabledSecurityProfiles = [OpcUaSecurityProfile.None], }, NullLogger.Instance), () => new OtOpcUaSdkServer(), TestContext.Current.CancellationToken); var nm = started.Server.NodeManager!; var source = new SeriesSource(Enumerable.Range(0, samples) .Select(i => new DataValueSnapshot(i, 0, HistoryT0.AddSeconds(i), HistoryT0.AddSeconds(i))).ToArray()) { MaxRawValuesPerRead = maxRawPerRead }; nm.HistorianDataSource = source; nm.EnsureVariable("Plant/Driver/Device/Speed", null, "Speed", "Int32", false, AddressSpaceRealm.Raw, historianTagname: "speed"); nm.EnsureVariable("Plant/Driver/Device/Other", null, "Other", "Int32", false, AddressSpaceRealm.Raw); for (var i = 0; i < extra; i++) nm.EnsureVariable("Plant/Driver/Device/Speed" + i, null, "Speed" + i, "Int32", false, AddressSpaceRealm.Raw, historianTagname: "speed" + i); return new HistoryOrigin(started.Host, pki, nm, source); } public void BumpEpoch() => _nm.RemoveVariableNode("Plant/Driver/Device/Other", AddressSpaceRealm.Raw).ShouldBeTrue(); public async ValueTask DisposeAsync() { await _host.DisposeAsync(); if (Directory.Exists(_pki)) try { Directory.Delete(_pki, recursive: true); } catch (IOException) { } } } private sealed class SeriesSource(IReadOnlyList series) : IHistorianDataSource { private int _calls; public int Calls => Volatile.Read(ref _calls); public int MaxRawValuesPerRead { get; init; } public IReadOnlySet Aggregates { get; set; } = HistoryAggregateTypes.All; public IReadOnlySet SupportedAggregates => Aggregates; public bool SupportsReverseRaw => true; public Task ReadRawAsync(string fullReference, DateTime startUtc, DateTime endUtc, uint maxValuesPerNode, CancellationToken cancellationToken) { Interlocked.Increment(ref _calls); IEnumerable window = startUtc <= endUtc ? series.Where(s => s.SourceTimestampUtc >= startUtc && s.SourceTimestampUtc < endUtc) : series.Where(s => s.SourceTimestampUtc <= startUtc && s.SourceTimestampUtc > endUtc).Reverse(); return Task.FromResult(new HistorianRead((maxValuesPerNode == 0 ? window : window.Take((int)maxValuesPerNode)).ToList(), null)); } public Task ReadProcessedAsync(string fullReference, DateTime startUtc, DateTime endUtc, TimeSpan interval, HistoryAggregateType aggregate, CancellationToken cancellationToken) { Interlocked.Increment(ref _calls); return Task.FromResult(new HistorianRead([new DataValueSnapshot(3.0, 0, startUtc, startUtc)], null)); } public Task ReadAtTimeAsync(string fullReference, IReadOnlyList timestampsUtc, CancellationToken cancellationToken) { Interlocked.Increment(ref _calls); return Task.FromResult(new HistorianRead(timestampsUtc.Select(t => new DataValueSnapshot(1, 0, t, t)).ToList(), 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() { } } }