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>