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.
This commit is contained in:
Joseph Doherty
2026-11-23 20:36:02 -05:00
parent 619b0c378d
commit 9d194a7e97
3 changed files with 350 additions and 1 deletions
@@ -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;
/// <summary>What the origin's historian can serve to a remote peer (null from <see cref="IOriginHistoryPort.Serving"/> = nothing).</summary>
/// <param name="Aggregates">The served aggregates (stable <see cref="HistoryAggregateType"/> names).</param>
/// <param name="TimestampResolutionTicks">The backend's timestamp resolution in ticks.</param>
public sealed record OriginHistoryServing(IReadOnlyList<string> Aggregates, long TimestampResolutionTicks);
/// <summary>One node of a peer read, SDK-free.</summary>
/// <param name="Realm">The node's realm.</param>
/// <param name="Identifier">The node's <c>s=</c> identifier (an export view's identifier IS the node identifier).</param>
/// <param name="BindingTag">The peer view's binding tag (a continuation never resumes under another).</param>
/// <param name="AggregateId">Processed: the ns=0 AggregateFunction id.</param>
/// <param name="Continuation">The peer's page token; null = fresh.</param>
public readonly record struct OriginHistoryItem(AddressSpaceRealm Realm, string Identifier, string BindingTag, uint? AggregateId, byte[]? Continuation);
/// <summary>One value of a peer read: a CLR value (as the SDK boundary maps it) and the verbatim status/timestamps.</summary>
public readonly record struct OriginHistorySample(object? Value, uint StatusCode, DateTime? SourceTimestampUtc, DateTime? ServerTimestampUtc);
/// <summary>One node's outcome of a peer read.</summary>
/// <param name="StatusCode">The effective Part 11 status (<see cref="HistoryReadNodeOutcome.Status"/>).</param>
/// <param name="Samples">The values.</param>
/// <param name="Continuation">The next page token, or null when complete.</param>
/// <param name="WiringFault">The continuation scope was miswired (a server fault, answered <c>BadInternalError</c>) — never "unsupported".</param>
public sealed record OriginHistoryOutcome(uint StatusCode, IReadOnlyList<OriginHistorySample> Samples, byte[]? Continuation, bool WiringFault);
/// <summary>
/// The continuation store of ONE (authenticated principal, transport channel) — the public handle over the internal
/// <see cref="PeerHistoryContinuationStore"/> (plan §3.2). The caller keys one per channel and <see cref="Clear"/>s it
/// when the channel closes.
/// </summary>
public sealed class OriginHistoryCursors
{
internal PeerHistoryContinuationStore Store { get; }
/// <summary>Creates the store.</summary>
/// <param name="principal">The owning principal.</param>
/// <param name="channelId">The channel (connection incarnation) id.</param>
/// <param name="capacity">The export's continuation limit (≥ 1).</param>
/// <param name="idleExpiry">Idle expiry; null = 60 s.</param>
/// <param name="clock">Clock (tests).</param>
public OriginHistoryCursors(string principal, string channelId, int capacity, TimeSpan? idleExpiry = null, TimeProvider? clock = null) =>
Store = new PeerHistoryContinuationStore(principal, channelId, capacity, idleExpiry, clock);
/// <summary>The owner.</summary>
public string Principal => Store.Principal;
/// <summary>Live records.</summary>
public int Count => Store.Count;
/// <summary>The idle expiry.</summary>
public TimeSpan IdleExpiry => Store.IdleExpiry;
/// <summary>Releases a token (idempotent).</summary>
public bool Release(byte[]? token) => Store.Release(token);
/// <summary>Drops every record (the channel closed).</summary>
public void Clear() => Store.Clear();
}
/// <summary>
/// The SDK-free facade a remote-history transport (H2) uses over the node manager's override-level history port
/// (<see cref="OtOpcUaNodeManager.ReadHistory"/>, H1). Keeps every SDK type inside OpcUaServer: Runtime and Host see
/// CLR values, uint statuses and byte tokens only.
/// </summary>
public interface IOriginHistoryPort
{
/// <summary>What can be served now; null when no historian backend is configured (or the server is not up).</summary>
OriginHistoryServing? Serving { get; }
/// <summary>Whether <paramref name="identifier"/> in <paramref name="realm"/> is a historized node (registered tagname).</summary>
bool IsHistorized(AddressSpaceRealm realm, string identifier);
/// <summary>
/// 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.
/// </summary>
Task<IReadOnlyList<OriginHistoryOutcome>> ReadAsync(OriginHistoryCursors cursors, string principal, Func<string> servingIncarnation,
DataHistoryDetails details, IReadOnlyList<OriginHistoryItem> items, CancellationToken cancellationToken);
}
/// <summary>The production <see cref="IOriginHistoryPort"/> over one node manager.</summary>
public sealed class OriginHistoryPort(OtOpcUaNodeManager nodeManager) : IOriginHistoryPort
{
private readonly OtOpcUaNodeManager _nm = nodeManager ?? throw new ArgumentNullException(nameof(nodeManager));
/// <inheritdoc />
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));
}
}
/// <inheritdoc />
public bool IsHistorized(AddressSpaceRealm realm, string identifier) =>
!string.IsNullOrEmpty(identifier) && _nm.TryGetHistorizedTagname(identifier, out _, realm);
/// <inheritdoc />
public Task<IReadOnlyList<OriginHistoryOutcome>> ReadAsync(OriginHistoryCursors cursors, string principal, Func<string> servingIncarnation,
DataHistoryDetails details, IReadOnlyList<OriginHistoryItem> 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<IReadOnlyList<OriginHistoryOutcome>>(() =>
{
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));
}
/// <summary>An ABSENT Part 11 bound becomes the port's <see cref="DateTime.MinValue"/> ("unset"), exactly as the SDK adapter hands it.</summary>
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;
/// <summary>Records that the peer scope was miswired, so the outcome can be surfaced distinctly (H1 review note).</summary>
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; }
}
}
}
/// <summary>Resolves the port against the SDK sink bound at server start (null until then / after stop).</summary>
public sealed class DeferredOriginHistoryPort(DeferredAddressSpaceSink deferred) : IOriginHistoryPort
{
private IOriginHistoryPort? Inner => deferred.GetCapability<IOriginHistoryPort>();
/// <inheritdoc />
public OriginHistoryServing? Serving => Inner?.Serving;
/// <inheritdoc />
public bool IsHistorized(AddressSpaceRealm realm, string identifier) => Inner?.IsHistorized(realm, identifier) == true;
/// <inheritdoc />
public Task<IReadOnlyList<OriginHistoryOutcome>> ReadAsync(OriginHistoryCursors cursors, string principal, Func<string> servingIncarnation,
DataHistoryDetails details, IReadOnlyList<OriginHistoryItem> items, CancellationToken cancellationToken) =>
Inner is { } inner ? inner.ReadAsync(cursors, principal, servingIncarnation, details, items, cancellationToken)
: throw new InvalidOperationException("The OPC UA server is not running.");
}
@@ -10,9 +10,26 @@ namespace ZB.MOM.WW.OtOpcUa.OpcUaServer;
/// <see cref="OtOpcUaNodeManager"/>. The host wires this in once the StandardServer has
/// been started (so the node manager exists).
/// </summary>
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);
/// <inheritdoc />
OriginHistoryServing? IOriginHistoryPort.Serving => HistoryPort.Serving;
/// <inheritdoc />
bool IOriginHistoryPort.IsHistorized(AddressSpaceRealm realm, string identifier) => HistoryPort.IsHistorized(realm, identifier);
/// <inheritdoc />
Task<IReadOnlyList<OriginHistoryOutcome>> IOriginHistoryPort.ReadAsync(OriginHistoryCursors cursors, string principal,
Func<string> servingIncarnation, ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections.DataHistoryDetails details,
IReadOnlyList<OriginHistoryItem> items, CancellationToken cancellationToken) =>
HistoryPort.ReadAsync(cursors, principal, servingIncarnation, details, items, cancellationToken);
/// <summary>Initializes a new instance of the SdkAddressSpaceSink class.</summary>
/// <param name="nodeManager">The OPC UA node manager.</param>
@@ -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;
/// <summary>
/// H2: the SDK-free <see cref="OriginHistoryPort"/> 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.
/// </summary>
[Trait("Category", "Unit"), Trait("Feature", "GrpcData"), Trait("Phase", "H2")]
public sealed class OriginHistoryPortTests(HistoryReadPortServerFixture fx) : IClassFixture<HistoryReadPortServerFixture>
{
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<HistoryReadRawVariant>().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<Task> body)
{
await fx.Gate.WaitAsync(TestContext.Current.CancellationToken);
try { await body(); }
finally
{
fx.Nm.HistorianDataSource = NullHistorianDataSource.Instance;
fx.Gate.Release();
}
}
}