From 9d194a7e971cfa7a686466c0169b1786c70c54b4 Mon Sep 17 00:00:00 2001 From: Joseph Doherty Date: Mon, 23 Nov 2026 20:36:02 -0500 Subject: [PATCH] feat(grpc-data): H2 SDK-free origin history facade over the H1 port OriginHistoryPort (public, implements IOriginHistoryPort) keeps SDK types inside OpcUaServer instead of an InternalsVisibleTo: runs the synchronous ReadHistory off the caller's thread, one PeerHistoryContinuationScope per request, absent bounds -> port MinValue, miswired scope surfaced as WiringFault. Exposed through the SDK sink so DeferredOriginHistoryPort resolves it after server start; aggregate wire table pinned to AggregateFunctionMap. --- .../OriginHistoryPort.cs | 192 ++++++++++++++++++ .../SdkAddressSpaceSink.cs | 19 +- .../OriginHistoryPortTests.cs | 140 +++++++++++++ 3 files changed, 350 insertions(+), 1 deletion(-) create mode 100644 src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/OriginHistoryPort.cs create mode 100644 tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests/OriginHistoryPortTests.cs diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/OriginHistoryPort.cs b/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/OriginHistoryPort.cs new file mode 100644 index 000000000..bdac9f01b --- /dev/null +++ b/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/OriginHistoryPort.cs @@ -0,0 +1,192 @@ +using Opc.Ua; +using ZB.MOM.WW.OtOpcUa.Commons.OpcUa; +using ZB.MOM.WW.OtOpcUa.Core.Abstractions; +using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections; + +namespace ZB.MOM.WW.OtOpcUa.OpcUaServer; + +/// What the origin's historian can serve to a remote peer (null from = nothing). +/// The served aggregates (stable names). +/// The backend's timestamp resolution in ticks. +public sealed record OriginHistoryServing(IReadOnlyList Aggregates, long TimestampResolutionTicks); + +/// One node of a peer read, SDK-free. +/// The node's realm. +/// The node's s= identifier (an export view's identifier IS the node identifier). +/// The peer view's binding tag (a continuation never resumes under another). +/// Processed: the ns=0 AggregateFunction id. +/// The peer's page token; null = fresh. +public readonly record struct OriginHistoryItem(AddressSpaceRealm Realm, string Identifier, string BindingTag, uint? AggregateId, byte[]? Continuation); + +/// One value of a peer read: a CLR value (as the SDK boundary maps it) and the verbatim status/timestamps. +public readonly record struct OriginHistorySample(object? Value, uint StatusCode, DateTime? SourceTimestampUtc, DateTime? ServerTimestampUtc); + +/// One node's outcome of a peer read. +/// The effective Part 11 status (). +/// The values. +/// The next page token, or null when complete. +/// The continuation scope was miswired (a server fault, answered BadInternalError) — never "unsupported". +public sealed record OriginHistoryOutcome(uint StatusCode, IReadOnlyList Samples, byte[]? Continuation, bool WiringFault); + +/// +/// The continuation store of ONE (authenticated principal, transport channel) — the public handle over the internal +/// (plan §3.2). The caller keys one per channel and s it +/// when the channel closes. +/// +public sealed class OriginHistoryCursors +{ + internal PeerHistoryContinuationStore Store { get; } + + /// Creates the store. + /// The owning principal. + /// The channel (connection incarnation) id. + /// The export's continuation limit (≥ 1). + /// Idle expiry; null = 60 s. + /// Clock (tests). + public OriginHistoryCursors(string principal, string channelId, int capacity, TimeSpan? idleExpiry = null, TimeProvider? clock = null) => + Store = new PeerHistoryContinuationStore(principal, channelId, capacity, idleExpiry, clock); + + /// The owner. + public string Principal => Store.Principal; + + /// Live records. + public int Count => Store.Count; + + /// The idle expiry. + public TimeSpan IdleExpiry => Store.IdleExpiry; + + /// Releases a token (idempotent). + public bool Release(byte[]? token) => Store.Release(token); + + /// Drops every record (the channel closed). + public void Clear() => Store.Clear(); +} + +/// +/// The SDK-free facade a remote-history transport (H2) uses over the node manager's override-level history port +/// (, H1). Keeps every SDK type inside OpcUaServer: Runtime and Host see +/// CLR values, uint statuses and byte tokens only. +/// +public interface IOriginHistoryPort +{ + /// What can be served now; null when no historian backend is configured (or the server is not up). + OriginHistoryServing? Serving { get; } + + /// Whether in is a historized node (registered tagname). + bool IsHistorized(AddressSpaceRealm realm, string identifier); + + /// + /// Serves one batch through the history port, OFF the caller's thread (the port is synchronous and block-bridges), + /// with ONE continuation scope for the whole request that snapshots the serving incarnation at first use. + /// + Task> ReadAsync(OriginHistoryCursors cursors, string principal, Func servingIncarnation, + DataHistoryDetails details, IReadOnlyList items, CancellationToken cancellationToken); +} + +/// The production over one node manager. +public sealed class OriginHistoryPort(OtOpcUaNodeManager nodeManager) : IOriginHistoryPort +{ + private readonly OtOpcUaNodeManager _nm = nodeManager ?? throw new ArgumentNullException(nameof(nodeManager)); + + /// + public OriginHistoryServing? Serving + { + get + { + var source = _nm.HistorianDataSource; + if (source is NullHistorianDataSource) return null; + var served = AdvertisedAggregateFunctions.ServedBy(source).Select(x => x.ToString()).Order(StringComparer.Ordinal).ToArray(); + return new OriginHistoryServing(served, Math.Max(1, source.TimestampResolutionTicks)); + } + } + + /// + public bool IsHistorized(AddressSpaceRealm realm, string identifier) => + !string.IsNullOrEmpty(identifier) && _nm.TryGetHistorizedTagname(identifier, out _, realm); + + /// + public Task> ReadAsync(OriginHistoryCursors cursors, string principal, Func servingIncarnation, + DataHistoryDetails details, IReadOnlyList items, CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(cursors); ArgumentNullException.ThrowIfNull(servingIncarnation); + ArgumentNullException.ThrowIfNull(details); ArgumentNullException.ThrowIfNull(items); + var variant = ToVariant(details); + var portItems = items.Select(item => new HistoryReadPortItem(item.Realm, item.Identifier, item.Continuation, + item.AggregateId is { } id ? new NodeId(id, 0) : default, item.BindingTag)).ToArray(); + // ONE scope per request: it snapshots the serving incarnation at first use (H1 review note). + var scope = new WiringObservedScope(new PeerHistoryContinuationScope(cursors.Store, principal, servingIncarnation)); + // The port block-bridges like the SDK overrides; never run it on the RPC thread. + return Task.Run>(() => + { + var outcomes = _nm.ReadHistory(variant, portItems, scope, cancellationToken); + return outcomes.Select(o => + { + var status = o.Status.Code; + return new OriginHistoryOutcome(status, o.Values.Select(Sample).ToArray(), o.ContinuationPoint, + scope.Faulted && status == StatusCodes.BadInternalError); + }).ToArray(); + }, cancellationToken); + } + + private static OriginHistorySample Sample(Opc.Ua.DataValue value) + { + var source = SdkValueBoundary.ToClrTimestamp(value.SourceTimestamp); + var server = SdkValueBoundary.ToClrTimestamp(value.ServerTimestamp); + return new OriginHistorySample(SdkValueBoundary.ToClr(value.WrappedValue), value.StatusCode.Code, + source == DateTime.MinValue ? null : DateTime.SpecifyKind(source, DateTimeKind.Utc), + server == DateTime.MinValue ? null : DateTime.SpecifyKind(server, DateTimeKind.Utc)); + } + + /// An ABSENT Part 11 bound becomes the port's ("unset"), exactly as the SDK adapter hands it. + internal static HistoryReadVariant ToVariant(DataHistoryDetails details) => details switch + { + DataHistoryRawDetails raw => new HistoryReadRawVariant(Clr(raw.StartUtc), Clr(raw.EndUtc), raw.NumValuesPerNode, raw.ReturnBounds), + DataHistoryProcessedDetails processed => new HistoryReadProcessedVariant(Clr(processed.StartUtc), Clr(processed.EndUtc), + processed.ProcessingInterval, processed.Configuration is { } c ? new AggregateConfiguration + { + UseServerCapabilitiesDefaults = c.UseServerCapabilitiesDefaults, TreatUncertainAsBad = c.TreatUncertainAsBad, + PercentDataBad = c.PercentDataBad, PercentDataGood = c.PercentDataGood, UseSlopedExtrapolation = c.UseSlopedExtrapolation, + } : null), + DataHistoryAtTimeDetails atTime => new HistoryReadAtTimeVariant(atTime.RequestedTimesUtc.Select(t => t.UtcDateTime).ToArray()), + _ => throw new ArgumentException("Unsupported history details.", nameof(details)), + }; + + private static DateTime Clr(DateTimeOffset? value) => value is { } v ? v.UtcDateTime : DateTime.MinValue; + + /// Records that the peer scope was miswired, so the outcome can be surfaced distinctly (H1 review note). + private sealed class WiringObservedScope(IHistoryContinuationScope inner) : IHistoryContinuationScope + { + private volatile bool _faulted; + public bool Faulted => _faulted; + + public byte[]? Save(HistoryContinuationState state, HistoryContinuationBinding binding) + { + try { return inner.Save(state, binding); } + catch (PeerHistoryContinuationWiringException) { _faulted = true; throw; } + } + + public HistoryContinuationState? TryTake(byte[] continuationPoint, HistoryContinuationBinding binding) + { + try { return inner.TryTake(continuationPoint, binding); } + catch (PeerHistoryContinuationWiringException) { _faulted = true; throw; } + } + } +} + +/// Resolves the port against the SDK sink bound at server start (null until then / after stop). +public sealed class DeferredOriginHistoryPort(DeferredAddressSpaceSink deferred) : IOriginHistoryPort +{ + private IOriginHistoryPort? Inner => deferred.GetCapability(); + + /// + public OriginHistoryServing? Serving => Inner?.Serving; + + /// + public bool IsHistorized(AddressSpaceRealm realm, string identifier) => Inner?.IsHistorized(realm, identifier) == true; + + /// + public Task> ReadAsync(OriginHistoryCursors cursors, string principal, Func servingIncarnation, + DataHistoryDetails details, IReadOnlyList items, CancellationToken cancellationToken) => + Inner is { } inner ? inner.ReadAsync(cursors, principal, servingIncarnation, details, items, cancellationToken) + : throw new InvalidOperationException("The OPC UA server is not running."); +} diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/SdkAddressSpaceSink.cs b/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/SdkAddressSpaceSink.cs index f09f23333..42965bce1 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/SdkAddressSpaceSink.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/SdkAddressSpaceSink.cs @@ -10,9 +10,26 @@ namespace ZB.MOM.WW.OtOpcUa.OpcUaServer; /// . The host wires this in once the StandardServer has /// been started (so the node manager exists). /// -public sealed class SdkAddressSpaceSink : IOpcUaAddressSpaceSink, ISurgicalAddressSpaceSink, IProjectedValueSink, IProjectedNamespacePageSink, IProjectedNodeLookup, IProjectedAnchorSink +public sealed class SdkAddressSpaceSink : IOpcUaAddressSpaceSink, ISurgicalAddressSpaceSink, IProjectedValueSink, IProjectedNamespacePageSink, IProjectedNodeLookup, IProjectedAnchorSink, + IOriginHistoryPort { private readonly OtOpcUaNodeManager _nodeManager; + private OriginHistoryPort? _historyPort; + + // H2: the remote-history facade over this node manager, resolved through DeferredAddressSpaceSink.GetCapability. + private OriginHistoryPort HistoryPort => _historyPort ??= new OriginHistoryPort(_nodeManager); + + /// + OriginHistoryServing? IOriginHistoryPort.Serving => HistoryPort.Serving; + + /// + bool IOriginHistoryPort.IsHistorized(AddressSpaceRealm realm, string identifier) => HistoryPort.IsHistorized(realm, identifier); + + /// + Task> IOriginHistoryPort.ReadAsync(OriginHistoryCursors cursors, string principal, + Func servingIncarnation, ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections.DataHistoryDetails details, + IReadOnlyList items, CancellationToken cancellationToken) => + HistoryPort.ReadAsync(cursors, principal, servingIncarnation, details, items, cancellationToken); /// Initializes a new instance of the SdkAddressSpaceSink class. /// The OPC UA node manager. diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests/OriginHistoryPortTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests/OriginHistoryPortTests.cs new file mode 100644 index 000000000..db7e5979e --- /dev/null +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests/OriginHistoryPortTests.cs @@ -0,0 +1,140 @@ +using Opc.Ua; +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; + +namespace ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests; + +/// +/// H2: the SDK-free facade a remote-history transport uses over the H1 port — served off +/// the caller's thread, one continuation scope per request, absent bounds mapped to the port's "unset", a miswired scope +/// surfaced distinctly, and the aggregate wire-name table pinned to the SDK's AggregateFunction ids. +/// +[Trait("Category", "Unit"), Trait("Feature", "GrpcData"), Trait("Phase", "H2")] +public sealed class OriginHistoryPortTests(HistoryReadPortServerFixture fx) : IClassFixture +{ + private static readonly DateTime T0 = new(2026, 3, 1, 10, 0, 0, DateTimeKind.Utc); + + [Fact] + public void The_aggregate_wire_table_matches_the_servers_aggregate_function_map_exactly() + { + DataHistoryAggregates.IdByName.Count.ShouldBe(AggregateFunctionMap.ByNodeId.Count); + foreach (var (nodeId, aggregate) in AggregateFunctionMap.ByNodeId) + { + nodeId.NamespaceIndex.ShouldBe((ushort)0); + nodeId.TryGetValue(out uint id).ShouldBeTrue(); + DataHistoryAggregates.IdByName[aggregate.ToString()].ShouldBe(id, aggregate.ToString()); + } + } + + [Fact] + public async Task Serving_is_null_without_a_historian_and_names_the_backends_aggregates_with_one() + { + await Run(async () => + { + var port = new OriginHistoryPort(fx.Nm); + port.Serving.ShouldBeNull("the Null source serves nothing remotely"); + fx.Nm.HistorianDataSource = new HistoryReadPortParityTests.ParitySource(); + var serving = port.Serving.ShouldNotBeNull(); + serving.Aggregates.ShouldContain("Average"); + serving.TimestampResolutionTicks.ShouldBe(1); + port.IsHistorized(AddressSpaceRealm.Uns, "port/dbl").ShouldBeTrue(); + port.IsHistorized(AddressSpaceRealm.Uns, "port/plain").ShouldBeFalse(); + port.IsHistorized(AddressSpaceRealm.Raw, "port/dbl").ShouldBeFalse("realm-qualified"); + await Task.CompletedTask; + }); + } + + [Fact] + public async Task Raw_pages_resume_once_through_the_cursor_store_and_a_resume_under_other_details_is_invalid() + { + await Run(async () => + { + var source = new HistoryReadPortParityTests.ParitySource(); + source.Series["P.dbl"] = Enumerable.Range(0, 5).Select(i => new DataValueSnapshot((double)i, 0, T0.AddSeconds(i), T0.AddSeconds(i))).ToList(); + fx.Nm.HistorianDataSource = source; + var port = new OriginHistoryPort(fx.Nm); + var cursors = new OriginHistoryCursors("peer", "chan-1", 8); + var details = new DataHistoryRawDetails(new DateTimeOffset(T0), new DateTimeOffset(T0.AddSeconds(10)), 2, false); + var item = new OriginHistoryItem(AddressSpaceRealm.Uns, "port/dbl", "peer:uns", null, null); + + var first = (await port.ReadAsync(cursors, "peer", () => "inc-A", details, [item], CancellationToken.None)).Single(); + first.StatusCode.ShouldBe(StatusCodes.Good.Code); + first.Samples.Select(s => s.Value).ShouldBe(new object?[] { 0.0, 1.0 }); + first.Samples[0].SourceTimestampUtc.ShouldBe(T0); + first.Continuation.ShouldNotBeNull().Length.ShouldBe(16); + cursors.Count.ShouldBe(1); + + var second = (await port.ReadAsync(cursors, "peer", () => "inc-A", details, [item with { Continuation = first.Continuation }], + CancellationToken.None)).Single(); + second.Samples.Select(s => s.Value).ShouldBe(new object?[] { 2.0, 3.0 }); + + // Single-use: the consumed token replays as invalid (a lost page is never silently skipped). + var replay = (await port.ReadAsync(cursors, "peer", () => "inc-A", details, [item with { Continuation = first.Continuation }], + CancellationToken.None)).Single(); + replay.StatusCode.ShouldBe(StatusCodes.BadContinuationPointInvalid.Code); + + // Another incarnation (failover) or other details ⇒ invalid. + var moved = (await port.ReadAsync(cursors, "peer", () => "inc-B", details, [item with { Continuation = second.Continuation }], + CancellationToken.None)).Single(); + moved.StatusCode.ShouldBe(StatusCodes.BadContinuationPointInvalid.Code); + var third = (await port.ReadAsync(cursors, "peer", () => "inc-A", details, [item], CancellationToken.None)).Single(); + var other = (await port.ReadAsync(cursors, "peer", () => "inc-A", details with { NumValuesPerNode = 3 }, + [item with { Continuation = third.Continuation }], CancellationToken.None)).Single(); + other.StatusCode.ShouldBe(StatusCodes.BadContinuationPointInvalid.Code); + }); + } + + [Fact] + public async Task Absent_bounds_are_the_ports_unset_so_an_end_only_read_returns_the_latest_values_newest_first() + { + await Run(async () => + { + var source = new HistoryReadPortParityTests.ParitySource(); + source.Series["P.dbl"] = Enumerable.Range(0, 5).Select(i => new DataValueSnapshot((double)i, 0, T0.AddSeconds(i), T0.AddSeconds(i))).ToList(); + fx.Nm.HistorianDataSource = source; + var port = new OriginHistoryPort(fx.Nm); + var cursors = new OriginHistoryCursors("peer", "chan-1", 8); + var endOnly = new DataHistoryRawDetails(null, new DateTimeOffset(T0.AddSeconds(10)), 2, false); + var outcome = (await port.ReadAsync(cursors, "peer", () => "inc-A", endOnly, + [new OriginHistoryItem(AddressSpaceRealm.Uns, "port/dbl", "peer:uns", null, null)], CancellationToken.None)).Single(); + outcome.Samples.Select(s => s.Value).ShouldBe(new object?[] { 4.0, 3.0 }); + OriginHistoryPort.ToVariant(endOnly).ShouldBeOfType().StartUtc.ShouldBe(DateTime.MinValue); + }); + } + + [Fact] + public async Task A_miswired_scope_is_a_distinct_wiring_fault_never_unsupported_or_denied() + { + await Run(async () => + { + var source = new HistoryReadPortParityTests.ParitySource(); + source.Series["P.dbl"] = Enumerable.Range(0, 5).Select(i => new DataValueSnapshot((double)i, 0, T0.AddSeconds(i), T0.AddSeconds(i))).ToList(); + fx.Nm.HistorianDataSource = source; + var port = new OriginHistoryPort(fx.Nm); + var cursors = new OriginHistoryCursors("peer", "chan-1", 8); + var details = new DataHistoryRawDetails(new DateTimeOffset(T0), new DateTimeOffset(T0.AddSeconds(10)), 2, false); + var item = new OriginHistoryItem(AddressSpaceRealm.Uns, "port/dbl", "peer:uns", null, null); + var blank = (await port.ReadAsync(cursors, "peer", () => "", details, [item], CancellationToken.None)).Single(); + blank.WiringFault.ShouldBeTrue(); + blank.StatusCode.ShouldBe(StatusCodes.BadInternalError.Code); + var stranger = (await port.ReadAsync(cursors, "someone-else", () => "inc-A", details, [item], CancellationToken.None)).Single(); + stranger.WiringFault.ShouldBeTrue("a scope for a principal the store does not belong to"); + var fine = (await port.ReadAsync(cursors, "peer", () => "inc-A", details, [item], CancellationToken.None)).Single(); + fine.WiringFault.ShouldBeFalse(); + }); + } + + private async Task Run(Func body) + { + await fx.Gate.WaitAsync(TestContext.Current.CancellationToken); + try { await body(); } + finally + { + fx.Nm.HistorianDataSource = NullHistorianDataSource.Instance; + fx.Gate.Release(); + } + } +}