diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Host/Configuration/DataConnectionEndpoints.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Host/Configuration/DataConnectionEndpoints.cs index adfd9fc29..487feb26d 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Host/Configuration/DataConnectionEndpoints.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Host/Configuration/DataConnectionEndpoints.cs @@ -7,7 +7,7 @@ namespace ZB.MOM.WW.OtOpcUa.Host.Configuration; public static class DataConnectionEndpoints { public const string ServicePrefix = "/data_connection.v1.DataConnectionService/"; - private static readonly HashSet Methods = ["GetCapabilities", "Browse", "GetMetadata", "Read", "Write", "Subscribe"]; + private static readonly HashSet Methods = ["GetCapabilities", "Browse", "GetMetadata", "Read", "Write", "Subscribe", "HistoryRead"]; public static bool IsDataRequest(HttpContext context, DataConnectionOptions options) => options.Enabled && context.Connection.LocalPort == options.ListenPort diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Host/Grpc/DataConnectionGrpcService.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Host/Grpc/DataConnectionGrpcService.cs index a14db50f9..863d36da2 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Host/Grpc/DataConnectionGrpcService.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Host/Grpc/DataConnectionGrpcService.cs @@ -122,6 +122,7 @@ public sealed class DataConnectionGrpcService(IDataConnectionFactory factory, IO Execute(context, async (connection, caller, token) => { var caps = await Ready(connection, DataOperations.Read, token).ConfigureAwait(false); + HistoryNegotiated(context, caps); // records the effective set; Read carries no history shape var decoded = DataProtoMapper.DecodeReadRequest(request, DecodeLimits(caps)); var results = await connection.ReadAsync(decoded with { Budget = Clamp(decoded.Budget) }, token).ConfigureAwait(false); foreach (var result in results) context.GetHttpContext().Response.RegisterForDispose(result); @@ -138,6 +139,7 @@ public sealed class DataConnectionGrpcService(IDataConnectionFactory factory, IO Execute(context, async (connection, caller, token) => { var caps = await connection.GetCapabilitiesAsync(DiscoveryBudget, token).ConfigureAwait(false); + HistoryNegotiated(context, caps); // records the effective set; Write carries no history shape var limits = DecodeLimits(caps); var decoded = DataProtoMapper.DecodeWriteRequest(request, limits.MaxItems, limits.MaxBytes, limits.MaxValueElements); try @@ -250,6 +252,7 @@ public sealed class DataConnectionGrpcService(IDataConnectionFactory factory, IO initial.CancelAfter(_options.UnaryTimeout); caps = await Ready(connection, DataOperations.Subscribe, initial.Token).ConfigureAwait(false); } + HistoryNegotiated(context, caps); // records the effective set; no stream frame carries history in H2 var codecHeaders = context.RequestHeaders.Where(entry => string.Equals(entry.Key, DataConnectionProtoContract.CompactCodecHeader, StringComparison.OrdinalIgnoreCase)).ToArray(); if (codecHeaders.Length > 1 || codecHeaders.Length == 1 && (codecHeaders[0].IsBinary || codecHeaders[0].Value != "1")) diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.Host.Tests/DataConnections/GrpcDataHistoryWireTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.Host.Tests/DataConnections/GrpcDataHistoryWireTests.cs new file mode 100644 index 000000000..f54674c0b --- /dev/null +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Host.Tests/DataConnections/GrpcDataHistoryWireTests.cs @@ -0,0 +1,315 @@ +using System.Collections.Concurrent; +using Google.Protobuf; +using Grpc.Core; +using Shouldly; +using Xunit; +using ZB.MOM.WW.OtOpcUa.Commons.DataConnections; +using ZB.MOM.WW.OtOpcUa.Commons.OpcUa; +using ZB.MOM.WW.OtOpcUa.Configuration.Enums; +using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections; +using ZB.MOM.WW.OtOpcUa.Host.Grpc; +using ZB.MOM.WW.OtOpcUa.OpcUaServer; +using W = ZB.MOM.WW.OtOpcUa.Commons.Protos.DataConnection.V1; + +namespace ZB.MOM.WW.OtOpcUa.Host.Tests.DataConnections; + +/// +/// H2 wire: the real over the REAL origin stack (: +/// LocalDataServices, LocalExportCatalog, the data-plane ACL), with only the node manager's history port faked +/// (; the port itself is covered by OpcUaServer OriginHistoryPortTests). +/// +[Trait("Category", "Unit"), Trait("Feature", "GrpcData"), Trait("Phase", "H2")] +public sealed class GrpcDataHistoryWireTests +{ + private static Metadata History => new() { { "x-otopcua-data-features", "history" } }; + private static readonly DataBudget Budget = new(TimeSpan.FromSeconds(5), 16, 1 << 20); + private static readonly DateTimeOffset T0 = new(2026, 11, 23, 0, 0, 0, TimeSpan.Zero); + + private static DataHistoryReadItem I(string id, DataView view) => new(id, view); + + private static W.HistoryReadRequest Raw(params DataHistoryReadItem[] items) => DataHistoryProtoMapper.EncodeRequest( + new DataHistoryReadRequest(new DataHistoryRawDetails(T0, T0.AddHours(1), 0, false), items, Budget)); + + [Fact] + public async Task Probe_with_history_on_a_history_capable_origin_advertises_field_16_and_bit_32() + { + await using var origin = new RealOrigin(); + var bytes = await origin.DriveAsync("GetCapabilities", History); + var response = W.CapabilitiesResponse.Parser.ParseFrom(Convert.FromHexString(bytes)); + response.History.ShouldNotBeNull(); + response.History.Raw.ShouldBeTrue(); response.History.AtTime.ShouldBeTrue(); response.History.Processed.ShouldBeTrue(); + response.History.Aggregates.ShouldBe(["Average", "Count"]); + response.History.MaxValuesPerPage.ShouldBe(10_000); response.History.MaxConcurrentReads.ShouldBe(4); + response.History.TimestampResolutionTicks.ShouldBe(10); + (response.Operations & (uint)DataOperations.HistoryRead).ShouldBe((uint)DataOperations.HistoryRead); + // Without the header the same origin answers the v1 golden (also pinned by the real-origin gate). + (await origin.DriveAsync("GetCapabilities", new Metadata())).ShouldBe(GrpcDataV1RealOriginGoldens.Responses["GetCapabilities"]); + } + + [Fact] + public async Task Probe_with_history_on_an_origin_without_a_historian_advertises_neither() + { + await using var origin = new RealOrigin(historian: false); + var response = W.CapabilitiesResponse.Parser.ParseFrom(Convert.FromHexString(await origin.DriveAsync("GetCapabilities", History))); + response.History.ShouldBeNull(); + (response.Operations & (uint)DataOperations.HistoryRead).ShouldBe(0u); + } + + [Fact] + public async Task Negotiated_metadata_carries_history_info_only_for_historized_and_granted_nodes() + { + await using var origin = new RealOrigin(); + var response = W.MetadataResponse.Parser.ParseFrom(Convert.FromHexString(await origin.DriveAsync("GetMetadata", History))); + var byId = response.Items.Where(x => x.Value is not null).ToDictionary(x => x.Value.View.Address.Identifier, x => x.Value); + byId["Plant/Modbus/dev1/Flow"].History.Historizing.ShouldBeTrue(); + (byId["Plant/Modbus/dev1/Flow"].AllowedOperations & 32u).ShouldBe(32u); + byId["Area1/Line1/Filler/FlowRate"].History.Historizing.ShouldBeTrue(); + byId["Plant/Modbus/dev1/Speed"].History.Historizing.ShouldBeFalse(); + (byId["Plant/Modbus/dev1/Speed"].AllowedOperations & 32u).ShouldBe(0u); + // Header-less: the golden (no Metadata.history, no bit 32). + (await origin.DriveAsync("GetMetadata", new Metadata())).ShouldBe(GrpcDataV1RealOriginGoldens.Responses["GetMetadata"]); + // A caller whose ACL lacks HistoryRead sees historizing=false on Flow: the same as an unhistorized node. + await using var denied = new RealOrigin(permissions: NodePermissions.Operator & ~NodePermissions.HistoryRead); + var deniedMeta = W.MetadataResponse.Parser.ParseFrom(Convert.FromHexString(await denied.DriveAsync("GetMetadata", History))); + var flow = deniedMeta.Items.Single(x => x.Value?.View.Address.Identifier == "Plant/Modbus/dev1/Flow").Value; + flow.History.Historizing.ShouldBeFalse(); + (flow.AllowedOperations & 32u).ShouldBe(0u); + } + + [Fact] + public async Task HistoryRead_without_the_negotiated_feature_is_failed_precondition() + { + await using var origin = new RealOrigin(); + var headerless = await Should.ThrowAsync(() => origin.HistoryAsync(Raw(I("a", RealOriginRequests.Flow)), new Metadata())); + headerless.StatusCode.ShouldBe(StatusCode.FailedPrecondition); + headerless.Status.Detail.ShouldBe("feature not negotiated"); + var conditions = await Should.ThrowAsync(() => + origin.HistoryAsync(Raw(I("a", RealOriginRequests.Flow)), new Metadata { { "x-otopcua-data-features", "conditions" } })); + conditions.StatusCode.ShouldBe(StatusCode.FailedPrecondition); + await using var noHistorian = new RealOrigin(historian: false); + var unservable = await Should.ThrowAsync(() => noHistorian.HistoryAsync(Raw(I("a", RealOriginRequests.Flow)), History)); + unservable.StatusCode.ShouldBe(StatusCode.FailedPrecondition); + origin.History!.Calls.ShouldBe(0); + } + + [Fact] + public async Task Denied_and_unhistorized_and_unknown_are_byte_identical_and_never_reach_the_backend() + { + await using var origin = new RealOrigin(); + await using var denied = new RealOrigin(permissions: NodePermissions.Operator & ~NodePermissions.HistoryRead); + var unhistorized = await origin.HistoryAsync(Raw(I("x", RealOriginRequests.Speed)), History); + var aclDenied = await denied.HistoryAsync(Raw(I("x", RealOriginRequests.Flow)), History); + var unknown = await origin.HistoryAsync(Raw(I("x", RealOriginRequests.Missing)), History); + var folder = await origin.HistoryAsync(Raw(I("x", RealOriginRequests.Device)), History); + var foreign = await origin.HistoryAsync(Raw(I("x", RealOriginRequests.Flow with { Subject = "elsewhere" })), History); + var expected = unhistorized.Items.Single().ToByteArray(); + foreach (var other in new[] { aclDenied, unknown, folder, foreign }) + other.Items.Single().ToByteArray().ShouldBe(expected); + unhistorized.Items.Single().StatusCode.ShouldBe(0x80720000u); // Bad_HistoryOperationUnsupported + unhistorized.Items.Single().HasDiagnostic.ShouldBeFalse(); + origin.History!.Calls.ShouldBe(0); + denied.History!.Calls.ShouldBe(0, "the ACL refusal happens before the tagname lookup and the backend"); + denied.History.HistorizedLookups.ShouldBe(0, "ingress order: export grant, ACL, then the tagname"); + } + + [Fact] + public async Task A_granted_historized_read_serves_values_verbatim_through_the_port() + { + await using var origin = new RealOrigin(); + origin.History!.Samples = [new(1.5, 0x00000400u, T0.UtcDateTime, null), new(null, 0x80000000u, null, T0.AddSeconds(1).UtcDateTime)]; + var response = await origin.HistoryAsync(Raw(I("flow", RealOriginRequests.Flow), I("ref", RealOriginRequests.UnsFlow)), History); + response.Serving.ShouldNotBeNull(); + foreach (var item in response.Items) + { + item.StatusCode.ShouldBe(0u); + item.Samples.Count.ShouldBe(2); + item.Samples[0].Value.DoubleValue.ShouldBe(1.5); + item.Samples[0].StatusCode.ShouldBe(0x400u); + item.Samples[0].ServerTimestamp.ShouldBeNull(); + item.Samples[1].SourceTimestamp.ShouldBeNull(); + item.Samples[1].StatusCode.ShouldBe(0x80000000u); + } + origin.History.LastItems.Select(x => (x.Realm, x.Identifier)).ShouldBe( + [(AddressSpaceRealm.Raw, "Plant/Modbus/dev1/Flow"), (AddressSpaceRealm.Uns, "Area1/Line1/Filler/FlowRate")]); + var raw = origin.History.LastDetails.ShouldBeOfType(); + raw.NumValuesPerNode.ShouldBe(10_000u, "an uncapped read pages at the export's per-page ceiling"); + raw.StartUtc.ShouldBe(T0); + } + + [Fact] + public async Task A_value_kind_disagreeing_with_the_catalog_is_BadTypeMismatch() + { + await using var origin = new RealOrigin(); + origin.History!.Samples = [new("not a double", 0, T0.UtcDateTime, null), new(2.0, 0, T0.UtcDateTime, null)]; + var item = (await origin.HistoryAsync(Raw(I("flow", RealOriginRequests.Flow)), History)).Items.Single(); + item.Samples[0].StatusCode.ShouldBe(DataHistoryProtoMapper.BadTypeMismatch); + item.Samples[0].Value.Kind.ShouldBe(W.ValueKind.Null); + item.Samples[1].Value.DoubleValue.ShouldBe(2.0); + } + + [Fact] + public async Task Admission_past_MaxConcurrentHistoryReads_is_BadTooManyOperations_for_the_principal() + { + await using var origin = new RealOrigin(concurrentReads: 1); + var gate = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + origin.History!.Hold = gate.Task; + var first = origin.HistoryAsync(Raw(I("a", RealOriginRequests.Flow)), History); + await origin.History.Entered.WaitAsync(TimeSpan.FromSeconds(10), TestContext.Current.CancellationToken); + var second = await origin.HistoryAsync(Raw(I("b", RealOriginRequests.Flow), I("c", RealOriginRequests.Speed)), History, "conn-2"); + second.Items.Select(x => x.StatusCode).ShouldBe([0x80100000u, 0x80100000u]); + gate.SetResult(); + (await first).Items.Single().StatusCode.ShouldBe(0u); + // Admission is released: the next read is served. + (await origin.HistoryAsync(Raw(I("d", RealOriginRequests.Flow)), History)).Items.Single().StatusCode.ShouldBe(0u); + } + + [Fact] + public async Task A_caller_cancel_is_Cancelled_never_a_backend_outcome_and_releases_admission() + { + await using var origin = new RealOrigin(concurrentReads: 1); + origin.History!.Hold = new TaskCompletionSource().Task; // never completes on its own; the token ends it + using var cancel = new CancellationTokenSource(); + var read = origin.HistoryAsync(Raw(I("a", RealOriginRequests.Flow)), History, cancel: cancel); + await origin.History.Entered.WaitAsync(TimeSpan.FromSeconds(10), TestContext.Current.CancellationToken); + await cancel.CancelAsync(); + var failure = await Should.ThrowAsync(() => read); + failure.StatusCode.ShouldBe(StatusCode.Cancelled); + origin.History.Hold = null; + (await origin.HistoryAsync(Raw(I("b", RealOriginRequests.Flow)), History)).Items.Single().StatusCode.ShouldBe(0u); + } + + [Fact] + public async Task A_wiring_fault_is_BadInternalError_with_a_distinct_diagnostic() + { + await using var origin = new RealOrigin(); + origin.History!.WiringFault = true; + var item = (await origin.HistoryAsync(Raw(I("a", RealOriginRequests.Flow)), History)).Items.Single(); + item.StatusCode.ShouldBe(0x80020000u); + item.Diagnostic.ShouldContain("wiring"); + item.StatusCode.ShouldNotBe(0x80720000u); + } + + [Fact] + public async Task An_answer_larger_than_the_response_cap_is_chunked_and_a_lost_chunk_is_ContinuationPointInvalid() + { + await using var origin = new RealOrigin(responseBytes: 1); + origin.History!.Samples = Enumerable.Range(0, 2000).Select(i => new OriginHistorySample((double)i, 0, T0.AddSeconds(i).UtcDateTime, null)).ToArray(); + origin.History.Continuation = Enumerable.Repeat((byte)7, 16).ToArray(); + var request = Raw(I("a", RealOriginRequests.Flow)); + var all = new List(); + var page = (await origin.HistoryAsync(request, History)).Items.Single(); + var chunks = 1; + page.ChunkContinues.ShouldBeTrue(); + var firstToken = page.Continuation.ToByteArray(); + while (page.ChunkContinues) + { + all.AddRange(page.Samples.Select(s => s.Value.DoubleValue)); + var next = request.Clone(); next.Items[0].Continuation = page.Continuation; + page = (await origin.HistoryAsync(next, History)).Items.Single(); + chunks++; + } + all.AddRange(page.Samples.Select(s => s.Value.DoubleValue)); + chunks.ShouldBeGreaterThan(1); + all.ShouldBe(Enumerable.Range(0, 2000).Select(i => (double)i)); + page.Continuation.ToByteArray().ShouldBe(origin.History.Continuation, "the last chunk carries the page continuation"); + origin.History.Calls.ShouldBe(1, "chunks are served from the transport remainder, not re-read"); + // The first chunk token was consumed: replaying it (a page lost in transit) is invalid, never a skipped page. + var replay = request.Clone(); replay.Items[0].Continuation = ByteString.CopyFrom(firstToken); + (await origin.HistoryAsync(replay, History)).Items.Single().StatusCode.ShouldBe(0x804A0000u); + // Another HTTP/2 connection cannot use this connection's tokens. + var fresh = (await origin.HistoryAsync(request, History, "conn-a")).Items.Single(); + var stolen = request.Clone(); stolen.Items[0].Continuation = fresh.Continuation; + (await origin.HistoryAsync(stolen, History, "conn-b")).Items.Single().StatusCode.ShouldBe(0x804A0000u); + } + + [Fact] + public async Task Release_continuations_drops_the_tokens_without_reading() + { + await using var origin = new RealOrigin(responseBytes: 1); + origin.History!.Samples = Enumerable.Range(0, 2000).Select(i => new OriginHistorySample((double)i, 0, T0.AddSeconds(i).UtcDateTime, null)).ToArray(); + var request = Raw(I("a", RealOriginRequests.Flow)); + var chunk = (await origin.HistoryAsync(request, History)).Items.Single(); + chunk.ChunkContinues.ShouldBeTrue(); + var release = request.Clone(); release.Items[0].Continuation = chunk.Continuation; release.ReleaseContinuations = true; + var released = (await origin.HistoryAsync(release, History)).Items.Single(); + released.StatusCode.ShouldBe(0u); released.Samples.ShouldBeEmpty(); + origin.History.Calls.ShouldBe(1); + var resume = request.Clone(); resume.Items[0].Continuation = chunk.Continuation; + (await origin.HistoryAsync(resume, History)).Items.Single().StatusCode.ShouldBe(0x804A0000u); + } + + [Fact] + public async Task Direct_runtime_consumer_reads_history_through_the_local_connection_unchunked() + { + await using var origin = new RealOrigin(responseBytes: 1); + origin.History!.Samples = Enumerable.Range(0, 500).Select(i => new OriginHistorySample((double)i, 0, T0.AddSeconds(i).UtcDateTime, null)).ToArray(); + await using var connection = origin.Connect(); + var history = connection.ShouldBeAssignableTo()!; + var results = await history.ReadAsync(new DataHistoryReadRequest(new DataHistoryRawDetails(null, T0.AddHours(1), 0, false), + [I("a", RealOriginRequests.Flow), I("b", RealOriginRequests.Speed)], Budget), TestContext.Current.CancellationToken); + results[0].ChunkContinues.ShouldBeFalse("a direct consumer is never handed transport chunks"); + results[0].Samples.Count.ShouldBe(500); + results[0].Samples[0].SourceTimestampUtc.ShouldBe(T0); + results[1].StatusCode.ShouldBe(0x80720000u); + origin.History.LastDetails.ShouldBeOfType().StartUtc.ShouldBeNull("absent stays absent end to end"); + foreach (var result in results) result.Dispose(); + } + + [Fact] + public async Task Every_rpc_records_history_effective_only_when_the_origin_can_serve_it() + { + await using var origin = new RealOrigin(); + var context = RealOrigin.NewContext("HistoryRead", History, TestContext.Current.CancellationToken); + await origin.HistoryAsync(Raw(I("a", RealOriginRequests.Flow)), History, existing: context); + DataConnectionGrpcService.CallFeatures(context).ShouldBe(new DataCallFeatures(DataFeatures.History, DataFeatures.History)); + await using var none = new RealOrigin(historian: false); + var refused = RealOrigin.NewContext("HistoryRead", History, TestContext.Current.CancellationToken); + await Should.ThrowAsync(() => none.HistoryAsync(Raw(I("a", RealOriginRequests.Flow)), History, existing: refused)); + DataConnectionGrpcService.CallFeatures(refused).ShouldBe(new DataCallFeatures(DataFeatures.History, DataFeatures.None)); + } +} + +/// A scripted node-manager history port: Flow (raw) and FlowRate (UNS) are historized. +internal sealed class FakeHistoryPort : IOriginHistoryPort +{ + private int _calls, _lookups; + private readonly TaskCompletionSource _entered = new(TaskCreationOptions.RunContinuationsAsynchronously); + private readonly ConcurrentDictionary _issued = new(); + + public OriginHistoryServing? Serving { get; set; } = new(["Average", "Count"], 10); + public IReadOnlyList Samples { get; set; } = []; + public byte[]? Continuation { get; set; } + public bool WiringFault { get; set; } + public Task? Hold { get; set; } + public Task Entered => _entered.Task; + public int Calls => Volatile.Read(ref _calls); + public int HistorizedLookups => Volatile.Read(ref _lookups); + public IReadOnlyList LastItems { get; private set; } = []; + public DataHistoryDetails? LastDetails { get; private set; } + + public bool IsHistorized(AddressSpaceRealm realm, string identifier) + { + Interlocked.Increment(ref _lookups); + return (realm == AddressSpaceRealm.Raw && identifier == "Plant/Modbus/dev1/Flow") + || (realm == AddressSpaceRealm.Uns && identifier == "Area1/Line1/Filler/FlowRate"); + } + + public async Task> ReadAsync(OriginHistoryCursors cursors, string principal, Func servingIncarnation, + DataHistoryDetails details, IReadOnlyList items, CancellationToken cancellationToken) + { + Interlocked.Increment(ref _calls); + LastItems = items; LastDetails = details; + _entered.TrySetResult(); + if (Hold is { } hold) await hold.WaitAsync(cancellationToken); + await Task.Yield(); + // Emulates the real port's single-use store: an unknown/consumed token is BadContinuationPointInvalid. + return items.Select(item => + { + if (WiringFault) return new OriginHistoryOutcome(0x80020000u, [], null, true); + if (item.Continuation is { } token && !_issued.TryRemove(Convert.ToHexString(token), out _)) + return new OriginHistoryOutcome(0x804A0000u, [], null, false); + if (Continuation is { } next) _issued[Convert.ToHexString(next)] = true; + return new OriginHistoryOutcome(0, Samples, Continuation, false); + }).ToArray(); + } +} diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.Host.Tests/DataConnections/GrpcDataV1CompatibilityTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.Host.Tests/DataConnections/GrpcDataV1CompatibilityTests.cs index ae4e40bc7..f1c3dadaa 100644 --- a/tests/Server/ZB.MOM.WW.OtOpcUa.Host.Tests/DataConnections/GrpcDataV1CompatibilityTests.cs +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Host.Tests/DataConnections/GrpcDataV1CompatibilityTests.cs @@ -51,11 +51,28 @@ public sealed class GrpcDataV1CompatibilityTests [Theory] [MemberData(nameof(Rpcs))] - public async Task Feature_header_changes_nothing_while_the_server_supports_no_feature(string rpc) + public async Task Feature_header_changes_nothing_while_no_requested_feature_is_servable(string rpc) { + // H2 supports history, but this origin advertises none (and conditions are A2): the effective set is empty. var headers = new Metadata { { "x-otopcua-data-features", "history,conditions" } }; - var actual = await V1CompatibilityHarness.DriveAsync(rpc, headers); - actual.ShouldBe(GrpcDataV1Goldens.Responses[rpc], $"{rpc} response must not change in X0 when features are requested"); + var actual = await V1CompatibilityHarness.DriveAsync(rpc, headers, history: false); + actual.ShouldBe(GrpcDataV1Goldens.Responses[rpc], $"{rpc} response must not change when nothing requested is servable"); + (await V1CompatibilityHarness.DriveAsync(rpc, new Metadata { { "x-otopcua-data-features", "conditions" } })) + .ShouldBe(GrpcDataV1Goldens.Responses[rpc], $"{rpc}: conditions are not supported before A2"); + } + + [Fact] + public async Task H2_a_history_capable_origin_shows_history_shapes_only_with_the_header() + { + var headers = new Metadata { { "x-otopcua-data-features", "history" } }; + var caps = W.CapabilitiesResponse.Parser.ParseFrom(Convert.FromHexString(await V1CompatibilityHarness.DriveAsync("GetCapabilities", headers))); + caps.History.ShouldNotBeNull(); + (caps.Operations & 32u).ShouldBe(32u); + var metadata = W.MetadataResponse.Parser.ParseFrom(Convert.FromHexString(await V1CompatibilityHarness.DriveAsync("GetMetadata", headers))); + metadata.Items[0].Value.History.Historizing.ShouldBeTrue(); + (metadata.Items[0].Value.AllowedOperations & 32u).ShouldBe(32u); + var browse = W.BrowseResponse.Parser.ParseFrom(Convert.FromHexString(await V1CompatibilityHarness.DriveAsync("Browse", headers))); + browse.Items[0].History.ShouldNotBeNull(); } [Theory] @@ -68,9 +85,12 @@ public sealed class GrpcDataV1CompatibilityTests var (_, requested) = await V1CompatibilityHarness.DriveWithContextAsync(rpc, new Metadata { { "x-otopcua-data-features", "history" }, { "x-otopcua-data-features", " conditions, future" } }); - // X0: the server supports no feature, so whatever is asked for, nothing is effective. - DataConnectionGrpcService.CallFeatures(requested).ShouldBe(new DataCallFeatures(DataFeatures.History | DataFeatures.Conditions, DataFeatures.None)); - DataConnectionGrpcService.SupportedFeatures.ShouldBe(DataFeatures.None); + // H2: history is effective on a history-capable origin; conditions are not supported before A2. + DataConnectionGrpcService.CallFeatures(requested).ShouldBe(new DataCallFeatures(DataFeatures.History | DataFeatures.Conditions, DataFeatures.History)); + DataConnectionGrpcService.SupportedFeatures.ShouldBe(DataFeatures.History); + var (_, unservable) = await V1CompatibilityHarness.DriveWithContextAsync(rpc, + new Metadata { { "x-otopcua-data-features", "history" } }, history: false); + DataConnectionGrpcService.CallFeatures(unservable).ShouldBe(new DataCallFeatures(DataFeatures.History, DataFeatures.None)); } public static TheoryData MalformedHeaders() @@ -201,13 +221,17 @@ internal static class V1CompatibilityHarness { /// The fake origin's granted operations (default: the full v1 set). /// Request bytes; default is the recorded golden request for . + /// + /// H2 new-shape data (default ON): the fake origin also grants HistoryRead, advertises history capabilities and + /// marks its scalar historized; a header-less caller must still get the golden bytes. + /// internal static async Task DriveAsync(string rpc, Metadata headers, DataOperations operations = DataOperationSets.V1, - byte[]? request = null) => (await DriveWithContextAsync(rpc, headers, operations, request)).Bytes; + byte[]? request = null, bool history = true) => (await DriveWithContextAsync(rpc, headers, operations, request, history)).Bytes; internal static async Task<(string Bytes, ServerCallContext Context)> DriveWithContextAsync(string rpc, Metadata headers, - DataOperations operations = DataOperationSets.V1, byte[]? request = null) + DataOperations operations = DataOperationSets.V1, byte[]? request = null, bool history = true) { - var (service, context) = Create(rpc, headers, operations); + var (service, context) = Create(rpc, headers, operations, history); return (await DriveAsync(service, context, rpc, request ?? Convert.FromHexString(GrpcDataV1Goldens.Requests[rpc])), context); } @@ -231,7 +255,7 @@ internal static class V1CompatibilityHarness } internal static (DataConnectionGrpcService Service, CallContext Context) Create(string rpc, Metadata headers, - DataOperations operations = DataOperationSets.V1) + DataOperations operations = DataOperationSets.V1, bool history = true) { var (bearer, id, hash) = ApiKeySecret.Generate("pepper"); var authority = new DataPlaneAuthorityState(); @@ -246,18 +270,19 @@ internal static class V1CompatibilityHarness http.Items[typeof(DataAuthenticatedContext)] = authenticator.Authenticate(bearer); http.Items[typeof(DataTarget)] = new DataTarget(DataTargetMode.Node, "cluster", "node"); context.UserState["__HttpContext"] = http; - return (new DataConnectionGrpcService(new Factory(operations), Options.Create(options), authenticator), context); + return (new DataConnectionGrpcService(new Factory(operations, history), Options.Create(options), authenticator), context); } internal static HttpContext Http(ServerCallContext context) => (HttpContext)context.UserState["__HttpContext"]; - private sealed class Factory(DataOperations operations) : IDataConnectionFactory + private sealed class Factory(DataOperations operations, bool history) : IDataConnectionFactory { - public IDataConnection Create(DataAuthenticatedContext context, DataTarget target) => new Origin(target, operations); + public IDataConnection Create(DataAuthenticatedContext context, DataTarget target) => + new Origin(target, history ? operations | DataOperations.HistoryRead : operations, history); } /// A deterministic v1 origin exercising every optional v1 field the encoders emit. - private sealed class Origin(DataTarget target, DataOperations operations) : IDataConnection, IDataConnectionPublicationGate, IDataConnectionDiscoveryGate + private sealed class Origin(DataTarget target, DataOperations operations, bool history) : IDataConnection, IDataConnectionPublicationGate, IDataConnectionDiscoveryGate { internal static readonly ServingIdentity Serving = new("node", "boot", "Primary", 1, 1, 1); private static readonly DateTimeOffset Source = new(2026, 11, 23, 12, 0, 0, TimeSpan.Zero); @@ -271,13 +296,17 @@ internal static class V1CompatibilityHarness 1, 3, Serving, DataReadiness.Ready, operations, new HashSet { DataValueKind.Int32, DataValueKind.String, DataValueKind.Array }, new(16, 16, 65_536, 16, 4, 65_536, TimeSpan.FromSeconds(30), TimeSpan.FromMinutes(10), TimeSpan.FromSeconds(5), 1000), - false, 0, "cluster", true, true, true, true, true)); + false, 0, "cluster", true, true, true, true, true, + history ? new DataHistoryCapabilities(true, true, true, ["Average"], 1, 10_000, 4, TimeSpan.FromSeconds(60)) : null)); - private static DataMetadata Scalar => new(V1Requests.Raw, "Speed", "Variable", DataValueKind.Int32, -1, [], true, - DataOperations.Browse | DataOperations.Metadata | DataOperations.Read | DataOperations.Write | DataOperations.Subscribe, - 1, "src-1", "rpm", false); - private static DataMetadata ArrayItem => new(V1Requests.Array, "Array", "Variable", DataValueKind.Array, 1, [3], false, - DataOperations.Browse | DataOperations.Metadata | DataOperations.Read, 1, null, null, true, DataValueKind.UInt8); + // H2 new-shape data: HistoryRead granted, HistoryInfo present (the service strips both from a header-less call). + private DataMetadata Scalar => new(V1Requests.Raw, "Speed", "Variable", DataValueKind.Int32, -1, [], true, + DataOperations.Browse | DataOperations.Metadata | DataOperations.Read | DataOperations.Write | DataOperations.Subscribe + | (history ? DataOperations.HistoryRead : DataOperations.None), + 1, "src-1", "rpm", false, History: history ? new DataHistoryInfo(true) : null); + private DataMetadata ArrayItem => new(V1Requests.Array, "Array", "Variable", DataValueKind.Array, 1, [3], false, + DataOperations.Browse | DataOperations.Metadata | DataOperations.Read, 1, null, null, true, DataValueKind.UInt8, + History: history ? new DataHistoryInfo(false) : null); public Task BrowseAsync(BrowseRequest request, CancellationToken token) => Task.FromResult(new DataBrowseBranch( request.Parent, DataItemStatus.Good, [Scalar, ArrayItem], false, "next-page", new MetadataLease(1, 1, TimeSpan.FromSeconds(30)))); diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.Host.Tests/DataConnections/GrpcDataV1RealOriginCompatibilityTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.Host.Tests/DataConnections/GrpcDataV1RealOriginCompatibilityTests.cs index 70ede2d9c..224c4d746 100644 --- a/tests/Server/ZB.MOM.WW.OtOpcUa.Host.Tests/DataConnections/GrpcDataV1RealOriginCompatibilityTests.cs +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Host.Tests/DataConnections/GrpcDataV1RealOriginCompatibilityTests.cs @@ -47,6 +47,11 @@ namespace ZB.MOM.WW.OtOpcUa.Host.Tests.DataConnections; /// RULE for H2/A2/A3: extend 's snapshot with that phase's new-shape data (historized tags /// with HistoryInfo, conditions, the new operation bits on the exports), then these tests must still see the same /// golden bytes WITHOUT the header. +/// H2 extension: every export also grants HistoryRead, the origin has a historian +/// (: Flow and the FlowRate reference are historized, aggregates served), so a +/// header-requesting caller WOULD see CapabilitiesResponse.history, the bit 32 and Metadata.history — +/// and the header-less replay must still be byte-identical. Asserted in GrpcDataHistoryWireTests that the +/// history-shaped data really is there with the header. /// [Trait("Category", "Unit"), Trait("Feature", "GrpcData"), Trait("Phase", "X0")] public sealed class GrpcDataV1RealOriginCompatibilityTests @@ -72,11 +77,16 @@ public sealed class GrpcDataV1RealOriginCompatibilityTests [Theory] [MemberData(nameof(Scenarios))] - public async Task Feature_header_changes_nothing_while_the_server_supports_no_feature(string scenario) + public async Task Feature_header_changes_nothing_while_no_requested_feature_is_servable(string scenario) { - await using var origin = new RealOrigin(); + // H2: history is supported, but an origin WITHOUT a historian cannot serve it (and conditions are A2), so the + // effective set is empty and the bytes are v1. + await using var origin = new RealOrigin(historian: false); var actual = await origin.DriveAsync(scenario, new Metadata { { "x-otopcua-data-features", "history,conditions" } }); - actual.ShouldBe(GrpcDataV1RealOriginGoldens.Responses[scenario], $"{scenario} response must not change in X0 when features are requested"); + actual.ShouldBe(GrpcDataV1RealOriginGoldens.Responses[scenario], $"{scenario} response must not change when nothing requested is servable"); + await using var conditionsOnly = new RealOrigin(); + (await conditionsOnly.DriveAsync(scenario, new Metadata { { "x-otopcua-data-features", "conditions" } })) + .ShouldBe(GrpcDataV1RealOriginGoldens.Responses[scenario], $"{scenario}: conditions are not supported before A2"); } public static TheoryData V1Rejections() @@ -237,22 +247,29 @@ internal sealed class RealOrigin : IAsyncDisposable private readonly LocalDataServices _services; internal ServingIdentity Serving { get; } - internal RealOrigin(DataOperations exportOperations = DataOperationSets.V1) + /// The fake historian behind the origin's history port (H2), or null when constructed without one. + internal FakeHistoryPort? History { get; } + + internal RealOrigin(DataOperations exportOperations = DataOperationSets.V1, bool historian = true, int concurrentReads = 4, + int responseBytes = 4 * 1024 * 1024, NodePermissions permissions = NodePermissions.Operator) { + History = historian ? new FakeHistoryPort() : null; var fence = new DataWriteDispatchFence(); var authority = new DataPlaneAuthorityState(fence); var activation = new CatalogActivation(fence); var key = new ApiKey { ApiKeyId = KeyId, Name = "peer", Principal = "peer", SecretHash = ApiKeySecret.ComputeHash(Secret, Pepper), Enabled = true }; authority.Apply("cluster", "rev-1", [key], [new NodeAcl { NodeAclId = "grant", ClusterId = "cluster", Principal = "peer", ScopeKind = NodeAclScopeKind.Cluster, - PermissionFlags = NodePermissions.Operator }], + PermissionFlags = permissions }], new Dictionary>()); var epoch = activation.Begin("rev-1"); activation.AuthorityInstalled(epoch, authority.Current.GenerationId); activation.Complete(epoch, true); Serving = new ServingIdentity("node-a", Incarnation, "Primary", epoch, authority.Current.GenerationId, 1); if (Serving.CatalogEpoch != CatalogEpoch) throw new InvalidOperationException("Catalog epoch is no longer deterministic."); - var catalog = LocalExportCatalog.Compile(Snapshot(exportOperations), Serving, activation.CaptureAuthority()); + // H2 new-shape data: every export also grants HistoryRead (header-less callers must never see it). + var catalog = LocalExportCatalog.Compile(Snapshot(exportOperations | DataOperations.HistoryRead, concurrentReads, responseBytes), + Serving, activation.CaptureAuthority()); _hub = new PartitionedSampleHub(new DataResourceLimits { @@ -280,14 +297,15 @@ internal sealed class RealOrigin : IAsyncDisposable LocalDataServices? services = null; services = new LocalDataServices(() => catalog, _hub, policy, capabilities, _clock, writes: context => new DataWriteExecutor(context, () => catalog, policy, capabilities, _route, registry, values, _clock, bounds), - targetSubscriptions: (context, target) => new LocalSubscriptionService(services!, context, target, new Demand(), sessionLimits, transport)); + targetSubscriptions: (context, target) => new LocalSubscriptionService(services!, context, target, new Demand(), sessionLimits, transport), + history: History); _services = services; _authenticator = new DataConnectionAuthenticator(authority, Options.Create(new ApiKeyOptions { Pepper = Pepper }), _clock); } internal IReadOnlyList Dispatched => _route.Dispatched; - private static DraftSnapshot Snapshot(DataOperations operations) + private static DraftSnapshot Snapshot(DataOperations operations, int concurrentReads, int responseBytes) { Tag Tag(string id, string name, string type, TagAccessLevel access = TagAccessLevel.Read, string config = "{}") => new() { TagId = id, DeviceId = "device-1", Name = name, DataType = type, AccessLevel = access, TagConfig = config }; @@ -320,9 +338,11 @@ internal sealed class RealOrigin : IAsyncDisposable DataExports = [ new() { DataExportId = "export-raw", ClusterId = "cluster", Enabled = true, Realm = DataRealm.Raw, - RootKind = "Cluster", RootEntityId = "cluster", PrincipalId = "peer", AllowedOperations = operations }, + RootKind = "Cluster", RootEntityId = "cluster", PrincipalId = "peer", AllowedOperations = operations, + MaxConcurrentHistoryReads = concurrentReads, MaxHistoryResponseBytes = responseBytes }, new() { DataExportId = "export-uns", ClusterId = "cluster", Enabled = true, Realm = DataRealm.Uns, - RootKind = "Cluster", RootEntityId = "cluster", PrincipalId = "peer", AllowedOperations = operations }, + RootKind = "Cluster", RootEntityId = "cluster", PrincipalId = "peer", AllowedOperations = operations, + MaxConcurrentHistoryReads = concurrentReads, MaxHistoryResponseBytes = responseBytes }, ], }; } @@ -343,6 +363,32 @@ internal sealed class RealOrigin : IAsyncDisposable } } + /// Drives one HistoryRead through the real service (H2); is the HTTP/2 connection. + internal async Task HistoryAsync(W.HistoryReadRequest request, Metadata headers, string connectionId = "conn-1", + CancellationTokenSource? cancel = null, ServerCallContext? existing = null) + { + var options = new DataConnectionOptions { Enabled = true, ListenPort = 9443, AllowedHosts = ["source.local"], CertificatePath = "server.pem" }; + using var linked = CancellationTokenSource.CreateLinkedTokenSource(cancel?.Token ?? CancellationToken.None, TestContext.Current.CancellationToken); + var context = existing ?? new Context("HistoryRead", headers, linked.Token); + var http = new DefaultHttpContext(); + http.Connection.Id = connectionId; + http.Connection.LocalPort = 9443; http.Request.Protocol = "HTTP/2"; http.Request.Scheme = "https"; http.Request.Method = "POST"; + http.Request.Host = new HostString("source.local", 9443); http.Request.Path = context.Method; + http.Items[typeof(DataAuthenticatedContext)] = _authenticator.Authenticate($"{ApiKeySecret.Prefix}_{KeyId}_{Secret}"); + http.Items[typeof(DataTarget)] = new DataTarget(DataTargetMode.Node, "cluster", "node-a"); + context.UserState["__HttpContext"] = http; + var service = new DataConnectionGrpcService(_services, Options.Create(options), _authenticator); + return await service.HistoryRead(request, context); + } + + /// The origin facade, for direct runtime-consumer history (H2). + internal IDataConnection Connect() => _services.Create(_authenticator.Authenticate($"{ApiKeySecret.Prefix}_{KeyId}_{Secret}"), + new DataTarget(DataTargetMode.Node, "cluster", "node-a")); + + internal LocalDataServices Services => _services; + + internal static Context NewContext(string rpc, Metadata headers, CancellationToken token) => new(rpc, headers, token); + internal async Task DriveAsync(string scenario, Metadata headers, byte[]? request = null) { var rpc = scenario.Split('/')[0]; @@ -437,7 +483,7 @@ internal sealed class RealOrigin : IAsyncDisposable public Task WriteAsync(W.SubscriptionFrame frame, CancellationToken cancellationToken) => WriteAsync(frame); } - private sealed class Context(string rpc, Metadata headers, CancellationToken token) : ServerCallContext + internal sealed class Context(string rpc, Metadata headers, CancellationToken token) : ServerCallContext { protected override string MethodCore => DataConnectionEndpoints.ServicePrefix + rpc; protected override string HostCore => "source.local";