using Opc.Ua; using Opc.Ua.Client; using Shouldly; using Xunit; using ZB.MOM.WW.OtOpcUa.Commons.OpcUa; using ZB.MOM.WW.OtOpcUa.Configuration.Entities; using ZB.MOM.WW.OtOpcUa.Configuration.Enums; using ZB.MOM.WW.OtOpcUa.Core.Abstractions; using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections; using ZB.MOM.WW.OtOpcUa.Core.Authorization; using ZB.MOM.WW.OtOpcUa.OpcUaServer.Security; using HistorianRead = ZB.MOM.WW.OtOpcUa.Core.Abstractions.HistoryReadResult; using SdkDataValue = Opc.Ua.DataValue; using static ZB.MOM.WW.OtOpcUa.OpcUaServer.IntegrationTests.ServerEventRig; using static ZB.MOM.WW.OtOpcUa.OpcUaServer.IntegrationTests.WarmRedundancyWireTests; namespace ZB.MOM.WW.OtOpcUa.OpcUaServer.IntegrationTests; /// /// H3 end to end over the wire: a real consumer OPC UA session HistoryReads a projected variable on a real consumer SDK /// server, whose projected half is forwarded to a real in-process ORIGIN node manager through its real history port /// (, PeerHistoryContinuationStore). Proves the Remote cursor in the real SDK /// session store (resume, single use, session close ⇒ the origin store count returns to 0), the mapped HistoryRead gate /// with ACLs on and off, and that a mixed local + projected batch keeps every slot. /// [Trait("Category", "Integration"), Trait("Feature", "GrpcData"), Trait("Phase", "H3")] public sealed class GrpcDataProjectedHistoryWireTests { private static readonly DateTime T0 = new(2026, 11, 20, 10, 0, 0, DateTimeKind.Utc); [Theory(Timeout = 90000)] [InlineData(false)] [InlineData(true)] public async Task Projected_history_pages_through_the_origin_and_a_mixed_batch_keeps_its_slots(bool aclEnabled) { var ct = Deadline(); await using var origin = await StartModeAsync("H3Origin", "None", ct); origin.Nm.HistorianDataSource = new Series(7, offset: 100); origin.Nm.EnsureVariable("Plant/Speed", null, "Speed", "Int32", false, AddressSpaceRealm.Raw, historianTagname: "speed"); await using var consumer = await StartModeAsync("H3Consumer", "None", ct); consumer.Nm.HistorianDataSource = new Series(3, offset: 0); var mapped = Setup(consumer, aclEnabled, NodePermissions.Browse | NodePermissions.Read | NodePermissions.HistoryRead); var bridge = new OriginBridge(origin.Nm, mapped.Identifier, "Plant/Speed"); consumer.Nm.ProjectedHistoryAccess = bridge; consumer.Nm.EnsureVariable("Plant/Local", "Plant", "Local", "Int32", false, AddressSpaceRealm.Raw, historianTagname: "local"); var local = consumer.Nm.TryGetVariable("Plant/Local", AddressSpaceRealm.Raw)!.NodeId; using var session = await consumer.ConnectAsync(anonymous: true, ct); var client = (SessionClient)session; // A mixed batch [projected, local]: each slot holds its own source's answer. var mixed = await Raw(client, [mapped.Node, local], 3, [default, default], ct); IntValues(mixed[0]).ShouldBe([100, 101, 102]); IntValues(mixed[1]).ShouldBe([0, 1, 2]); mixed[0].ContinuationPoint.IsEmpty.ShouldBeFalse(); bridge.Cursors.Count.ShouldBe(1); // Resume the projected node to completion through the real SDK session store. var all = IntValues(mixed[0]).ToList(); var cp = mixed[0].ContinuationPoint; while (!cp.IsEmpty) { var page = (await Raw(client, [mapped.Node], 3, [cp], ct))[0]; StatusCode.IsGood(page.StatusCode).ShouldBeTrue(); all.AddRange(IntValues(page)); cp = page.ContinuationPoint; } all.ShouldBe([100, 101, 102, 103, 104, 105, 106]); bridge.Cursors.Count.ShouldBe(0); // Single use: the first page's point is gone. (await Raw(client, [mapped.Node], 3, [mixed[0].ContinuationPoint], ct))[0].StatusCode.Code .ShouldBe(StatusCodes.BadContinuationPointInvalid.Code); } [Fact(Timeout = 90000)] public async Task Closing_the_consumer_session_releases_the_origin_continuations() { var ct = Deadline(); await using var origin = await StartModeAsync("H3OriginClose", "None", ct); origin.Nm.HistorianDataSource = new Series(7, offset: 0); origin.Nm.EnsureVariable("Plant/Speed", null, "Speed", "Int32", false, AddressSpaceRealm.Raw, historianTagname: "speed"); await using var consumer = await StartModeAsync("H3ConsumerClose", "None", ct); var mapped = Setup(consumer, aclEnabled: true, NodePermissions.Browse | NodePermissions.Read | NodePermissions.HistoryRead); var bridge = new OriginBridge(origin.Nm, mapped.Identifier, "Plant/Speed"); consumer.Nm.ProjectedHistoryAccess = bridge; var session = await consumer.ConnectAsync(anonymous: true, ct); var page = (await Raw((SessionClient)session, [mapped.Node], 2, [default], ct))[0]; page.ContinuationPoint.IsEmpty.ShouldBeFalse(); bridge.Cursors.Count.ShouldBe(1, "the origin holds the page cursor"); await session.CloseAsync(ct); session.Dispose(); for (var i = 0; i < 200 && bridge.Cursors.Count != 0; i++) await Task.Delay(10, ct); bridge.Cursors.Count.ShouldBe(0, "the SDK disposed the Remote point on session close and the release reached the origin"); bridge.Releases.ShouldBe(1); } [Theory(Timeout = 90000)] [InlineData(false)] [InlineData(true)] public async Task Without_a_local_HistoryRead_grant_on_the_mapping_scope_it_is_BadUserAccessDenied_unsent(bool aclEnabled) { var ct = Deadline(); await using var origin = await StartModeAsync("H3OriginDeny", "None", ct); origin.Nm.HistorianDataSource = new Series(7, offset: 0); origin.Nm.EnsureVariable("Plant/Speed", null, "Speed", "Int32", false, AddressSpaceRealm.Raw, historianTagname: "speed"); await using var consumer = await StartModeAsync("H3ConsumerDeny", "None", ct); var mapped = Setup(consumer, aclEnabled, NodePermissions.Browse | NodePermissions.Read); var bridge = new OriginBridge(origin.Nm, mapped.Identifier, "Plant/Speed"); consumer.Nm.ProjectedHistoryAccess = bridge; using var session = await consumer.ConnectAsync(anonymous: true, ct); var result = (await Raw((SessionClient)session, [mapped.Node], 2, [default], ct))[0]; result.StatusCode.Code.ShouldBe(StatusCodes.BadUserAccessDenied.Code); bridge.Calls.ShouldBe(0); } [Fact(Timeout = 90000)] public async Task The_shared_client_aggregate_read_asks_for_server_defaults_and_is_served() { // Found by the H3 live gate (H02): Client.Shared sent the SDK's default AggregateConfiguration (all false / 0), a // NON-default configuration this server refuses BadAggregateConfigurationRejected (#677) — on local and projected // nodes alike, so the CLI's --aggregate never worked against it. var ct = Deadline(); await using var rig = await StartModeAsync("H3ClientAggregate", "None", ct); rig.Nm.HistorianDataSource = new Series(3, offset: 0); rig.Nm.EnsureVariable("Plant/Speed", null, "Speed", "Int32", false, AddressSpaceRealm.Raw, historianTagname: "speed"); rig.Enforce(false, [Key()]); using var client = new ZB.MOM.WW.OtOpcUa.Client.Shared.OpcUaClientService(); await client.ConnectAsync(new ZB.MOM.WW.OtOpcUa.Client.Shared.Models.ConnectionSettings { EndpointUrl = rig.EndpointUrl, CertificateStorePath = Path.Combine(Path.GetTempPath(), $"otopcua-clientpki-{Guid.NewGuid():N}"), }, ct); var node = rig.Nm.TryGetVariable("Plant/Speed", AddressSpaceRealm.Raw)!.NodeId; var values = await client.HistoryReadAggregateAsync(node, T0, T0.AddMinutes(1), ZB.MOM.WW.OtOpcUa.Client.Shared.Models.AggregateType.Average, 60_000, ct); values.Count.ShouldBe(1); // The hand-paging API returns the server's page verbatim (status, values, continuation). var page = await client.HistoryReadPageAsync(new ReadRawModifiedDetails { StartTime = T0.AddSeconds(-1), EndTime = T0.AddHours(1), NumValuesPerNode = 2, IsReadModified = false, ReturnBounds = false, }, node, null, false, ct); StatusCode.IsGood(page.Status).ShouldBeTrue(); page.Values.Count.ShouldBe(2); page.ContinuationPoint.ShouldNotBeNull(); var released = await client.HistoryReadPageAsync(new ReadRawModifiedDetails { IsReadModified = false, ReturnBounds = false }, node, page.ContinuationPoint, true, ct); StatusCode.IsGood(released.Status).ShouldBeTrue(); await client.DisconnectAsync(ct); } // ------------------------------------------------------------------------------------------------------------------ private static (NodeId Node, string Identifier) Setup(ServerEventRig consumer, bool aclEnabled, NodePermissions permissions) { consumer.Nm.EnsureFolder("Plant", null, "Plant", AddressSpaceRealm.Raw); var parent = consumer.Nm.TryGetFolder("Plant", AddressSpaceRealm.Raw)!.NodeId; var scopePaths = new Dictionary> { [new(NodeAclScopeKind.RawFolder, "plant")] = [new([NodeAclRealms.Raw, "Plant"])], }; var grant = new NodeAcl { NodeAclId = "h3", ClusterId = ServerEventRig.Cluster, Principal = OpcUaPrincipals.Anonymous, ScopeKind = NodeAclScopeKind.RawFolder, ScopeId = "plant", PermissionFlags = permissions }; var state = consumer.Enforce(aclEnabled, [Key()], scopePaths, grant); var origin = new DataAddress("origin", "urn:raw", "string", "Plant/Speed"); var view = new DataView(origin, DataRealm.Raw, "mapping", 1, "Plant/Speed"); var metadata = new DataMetadata(view, "Speed", "Tag", DataValueKind.Int32, -1, [], false, DataOperations.Browse | DataOperations.Read | DataOperations.HistoryRead, 1, null, null, false, History: new DataHistoryInfo(true)); var identifier = ProjectedDataIds.Identifier("mapping", origin); consumer.Nm.TryEnsureProjectedVariable(new ProjectedVariableDefinition(DataRealm.Raw, identifier, parent, metadata, 1, () => true) { Historizing = true }, out var node).ShouldBeTrue(); var lease = new Lease(); var subject = new MappedNamespaceSubject(view, new NodeScope { ClusterId = ServerEventRig.Cluster, Kind = NodeHierarchyKind.Raw, Segments = ["Plant", "Speed"] }, ["plant", "mapping"], lease.Serving, DataOperations.Browse | DataOperations.Read | DataOperations.HistoryRead, WriteThrough: false); var resolver = new MappedSubjectResolver([subject], catalogEpoch: 7, new Catalog(state)); consumer.Nm.MappedSubjectResolver = (realm, id) => realm == AddressSpaceRealm.Raw && id == identifier ? MappedNodeResolution.Mapped(view, subject, resolver, lease) : MappedNodeResolution.Local; return (node!.Value, identifier); } private static async Task Raw(SessionClient client, NodeId[] nodes, uint count, ByteString[] cps, CancellationToken ct) { var details = new ReadRawModifiedDetails { StartTime = T0.AddSeconds(-1), EndTime = T0.AddHours(1), NumValuesPerNode = count, IsReadModified = false, ReturnBounds = false, }; var response = await client.HistoryReadAsync(H(), new ExtensionObject(details), TimestampsToReturn.Both, false, nodes.Select((n, i) => new HistoryReadValueId { NodeId = n, ContinuationPoint = cps[i] }).ToArray(), ct); return response.Results.ToArray()!; } private static int[] IntValues(Opc.Ua.HistoryReadResult result) => (result.HistoryData.IsNull || ExtensionObject.ToEncodeable(result.HistoryData) is not HistoryData data ? [] : data.DataValues.ToArray() ?? []) .Select(v => (int)SdkValueBoundary.ToClr(v.WrappedValue)!).ToArray(); /// /// The consumer's projected half wired straight onto a real origin's history port: one peer cursor store, as one /// authenticated principal on one connection; a release drops the origin token. /// private sealed class OriginBridge(OtOpcUaNodeManager origin, string projectedIdentifier, string originIdentifier) : IProjectedHistoryAccess { private readonly OriginHistoryPort _port = new(origin); private int _calls, _releases; public OriginHistoryCursors Cursors { get; } = new("peer", "channel-1", 16); public int Calls => Volatile.Read(ref _calls); public int Releases => Volatile.Read(ref _releases); public async Task> ReadAsync(RoleCarryingUserIdentity caller, DataHistoryDetails details, IReadOnlyList nodes, TimeSpan deadline, CancellationToken cancellationToken) { Interlocked.Increment(ref _calls); var items = nodes.Select(n => new OriginHistoryItem(AddressSpaceRealm.Raw, originIdentifier, "export-view", n.AggregateId, (n.Resume as Cursor)?.Token)).ToArray(); // A resume resends the ORIGINAL details (the peer store binds their hash), as ProjectedHistoryAccess does. var sent = nodes.Select(n => n.Resume).OfType().FirstOrDefault()?.Details ?? details; var outcomes = await _port.ReadAsync(Cursors, "peer", () => "serving-1", sent, items, cancellationToken); details = sent; return outcomes.Select(o => new ProjectedHistoryOutcome(o.StatusCode, o.Samples, o.Continuation is { } token ? new Cursor(this, projectedIdentifier, token, details) : null)).ToArray(); } private sealed class Cursor(OriginBridge owner, string identifier, byte[] token, DataHistoryDetails details) : ProjectedHistoryContinuation(DataRealm.Raw, identifier) { public byte[] Token => token; public DataHistoryDetails Details => details; protected override void OnRelease() { Interlocked.Increment(ref owner._releases); owner.Cursors.Release(token); } } } private sealed class Series(int count, int offset) : IHistorianDataSource { private readonly DataValueSnapshot[] _series = Enumerable.Range(0, count) .Select(i => new DataValueSnapshot(offset + i, 0, T0.AddSeconds(i), T0.AddSeconds(i))).ToArray(); public bool SupportsReverseRaw => true; public Task ReadRawAsync(string fullReference, DateTime startUtc, DateTime endUtc, uint maxValuesPerNode, CancellationToken ct) { var window = _series.Where(s => s.SourceTimestampUtc >= startUtc && s.SourceTimestampUtc < endUtc); 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 ct) => Task.FromResult(new HistorianRead([new DataValueSnapshot(42.0, 0, startUtc, startUtc)], null)); public Task ReadAtTimeAsync(string fullReference, IReadOnlyList timestampsUtc, CancellationToken ct) => Task.FromResult(new HistorianRead([], null)); public Task ReadEventsAsync(string? sourceName, DateTime startUtc, DateTime endUtc, int maxEvents, CancellationToken ct) => Task.FromResult(new HistoricalEventsResult(Array.Empty(), null)); public HistorianHealthSnapshot GetHealthSnapshot() => NullHistorianDataSource.Instance.GetHealthSnapshot(); public void Dispose() { } } private sealed class Catalog(DataPlaneAuthorityState state) : IDataMappedCatalogAuthority { public long CatalogEpoch => 1; public long AuthorityEpoch => state.Current.GenerationId; public bool IsActive => true; } private sealed class Lease : IDataAuthorizationLease { public ServingIdentity Serving { get; } = new("node-a", "incarnation-a", "Primary", 7, 1); public bool IsValid => true; } }