diff --git a/scripts/validation/grpc-data/unit-phases.json b/scripts/validation/grpc-data/unit-phases.json index d9e7d4423..9dc13d469 100644 --- a/scripts/validation/grpc-data/unit-phases.json +++ b/scripts/validation/grpc-data/unit-phases.json @@ -888,5 +888,36 @@ "GrpcDataEditorValidationTests" ] } + ], + "H3": [ + { + "project": "tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests/ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests.csproj", + "filter": "(Feature=GrpcData&Phase=H3)|FullyQualifiedName~.HistoryReadPortParityTests.|FullyQualifiedName~.SessionHistoryContinuationStoreTests.|FullyQualifiedName~.NodeManagerHistoryReadTests.|FullyQualifiedName~.NodeManagerHistoryReadPagingTests.|FullyQualifiedName~.NodeManagerAclEnforcementTests.|FullyQualifiedName~.GrpcDataMappedSubjectTests.|FullyQualifiedName~.GrpcDataSdkProjectionTests.", + "new_classes": [ + "ProjectedHistoryReadTests" + ], + "existing_classes": [ + "HistoryReadPortParityTests", + "SessionHistoryContinuationStoreTests", + "NodeManagerHistoryReadTests", + "NodeManagerHistoryReadPagingTests", + "NodeManagerAclEnforcementTests", + "GrpcDataMappedSubjectTests", + "GrpcDataSdkProjectionTests" + ] + }, + { + "project": "tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/ZB.MOM.WW.OtOpcUa.Runtime.Tests.csproj", + "filter": "(Feature=GrpcData&Phase=H3)|FullyQualifiedName~.GrpcDataHistoryLeaseTests.|FullyQualifiedName~.GrpcDataHistoryClientTests.|FullyQualifiedName~.GrpcDataProjectedAccessTests.", + "new_classes": [ + "GrpcDataProjectedHistoryCursorTests", + "GrpcDataConfiguredDiscoveryWireTests" + ], + "existing_classes": [ + "GrpcDataHistoryLeaseTests", + "GrpcDataHistoryClientTests", + "GrpcDataProjectedAccessTests" + ] + } ] } diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.IntegrationTests/GrpcDataProjectedHistoryWireTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.IntegrationTests/GrpcDataProjectedHistoryWireTests.cs new file mode 100644 index 000000000..f92e669a7 --- /dev/null +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.IntegrationTests/GrpcDataProjectedHistoryWireTests.cs @@ -0,0 +1,236 @@ +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); + } + + // ------------------------------------------------------------------------------------------------------------------ + + 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([], 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; + } +}