Merge H1: origin history port at override level
v2-ci / unit-tests (push) Has been cancelled

Phase H1 of docs/plans/2026-11-23-grpc-data-connections-history-alarms-plan.md.
HistoryRead (Raw/Processed/AtTime) logic extracted from the SDK overrides into
HistoryReadPort; overrides become adapters; continuation binding re-keyed to
(realm, identifier, namespace tag); unwired PeerHistoryContinuationStore; SDK-free
IDataHistoryService contract. Zero local behaviour change (legacy history suites
unchanged), 10k-seed paging fuzz clean. Three Fable passes.
This commit is contained in:
Joseph Doherty
2026-11-23 20:20:46 -05:00
13 changed files with 2978 additions and 280 deletions
@@ -1083,7 +1083,17 @@ settle windows are calibrated at the A1 exit (L4), before `state_known` ships.
- client: header gating, deadlines, `FailedPrecondition`/`Unimplemented` ⇒ unsupported;
- `LocalDataConnection` history for direct runtime consumers;
- **validator bit + `LocalDataServices.cs:47` `Implemented(target)` + `AddDataConnectionHistory` + artifact projection +
AdminUI checkboxes/limits**.
AdminUI checkboxes/limits**;
- origin over the H1 port (H1 review notes): `ReadHistory` is synchronous (it block-bridges like the SDK overrides), so run
it off the RPC thread; it and `PeerHistoryContinuationStore`/`Scope` are `internal` to OpcUaServer, so add
`InternalsVisibleTo` for the serving project or a public facade implementing `IDataHistoryService`; one store per
(principal, connection incarnation), `Clear()`ed on connection close; ONE `PeerHistoryContinuationScope` per RPC — it
snapshots the serving incarnation (from the connection) at first use, so a later request after an in-process failover
is refused and a request straddling one binds its next token to the incarnation it started under; a miswired scope
(non-owner principal, blank/throwing incarnation source) raises `PeerHistoryContinuationWiringException`, which the
port answers `BadInternalError` — H2 must surface it distinctly (a server fault, never "unsupported" or "denied"); items carry a view `BindingTag` (mapping id/kind);
Processed/AtTime chunking and the consumer's assembly budget live in the transport, not the port; history capabilities
are an additive H2 capabilities field.
- Files: proto/mapper, `Host/Grpc/DataConnectionGrpcService.cs`,
`Runtime/DataConnections/{LocalDataServices,LocalDataConnection,GrpcDataConnection,DataCapabilitiesProvider,LocalExportCatalog.Compilation}.cs`,
`Core/Authorization/DataOperationPolicy.cs`, `Configuration/{Entities/*,Validation/DataConnectionValidator.cs,Migrations/*}`,
@@ -1099,7 +1109,9 @@ settle windows are calibrated at the A1 exit (L4), before `state_known` ships.
**H3 — Consumer OPC UA projection.**
- Tasks: projected `Historizing`/AccessLevel; `IProjectedHistoryAccess` (`ProjectedDataAccess.cs:157` allowlist extended);
overrides split local and projected handles; `HistoryCursorKind.Remote`; release forwarding on `releaseContinuationPoints`
and session close; mapping gate `HistoryRead`; per-request assembly budget.
and session close; mapping gate `HistoryRead`; per-request assembly budget. The Remote cursor stores the ORIGINAL request
details and resends them on resume: a peer continuation binds the details hash (a resume under other details is
`BadContinuationPointInvalid`), whereas local SDK resumes ignore details.
- Files: NM, new `OpcUaServer/IProjectedHistoryAccess.cs`, new `Runtime/DataConnections/ProjectedHistoryAccess.cs`,
`OpcUaServer/Security/DataPlaneAuthorizer.cs`.
- Tests: O for allow/deny with ACLs on and off, resume after mapping revision change / lease expiry / failover / origin rebuild
+42
View File
@@ -0,0 +1,42 @@
# H1 evidence — origin history port at override level
Phase H1 of `docs/plans/2026-11-23-grpc-data-connections-history-alarms-plan.md`, 2026-11-23.
## What changed
- `OpcUaServer/HistoryReadPort.cs`: `ReadHistory(HistoryReadVariant, items, IHistoryContinuationScope, ct)` holds the
aggregate refusals (#897, `SupportsAggregateFor`, `IsServable`), modified+bounds `BadInvalidArgument`, the batch limiter,
deadline, continuation binding and `NormalizeHistoryValues`. The three SDK overrides are `AuthorizeHistoryRead` +
`ServeHistoryReadAdapter`. `ServeNodeAsync` / `ServeRawPagedAsync` / `ServeModifiedPagedAsync` stay in NM. Nothing moved
under `Lock`.
- Continuation binding re-keyed from the NodeId string to `(realm, identifier, binding tag)`; the local tag is the node's
namespace URI, so the binding is as strong as the old NodeId key for every history-served node.
- `OpcUaServer/PeerHistoryContinuationStore.cs` (unwired until H2): 16-byte random tokens, single-use takes (consumed before
any check), idle expiry 60 s, oldest-idle eviction, binds principal, per-request serving-incarnation snapshot, epoch, view,
tag and an invariant details hash. Wiring faults raise `PeerHistoryContinuationWiringException` ⇒ `BadInternalError`.
- `Core.Abstractions/DataConnections/IDataServices.cs`: SDK-free `IDataHistoryService` contract for H2.
## Gates (final HEAD of the H1 branch)
| Gate | Result |
|---|---|
| `dotnet build ZB.MOM.WW.OtOpcUa.slnx` | 0 warnings, 0 errors |
| `run-unit-phase.py H1` | passed (17 Core.Abstractions + 578 OpcUaServer, incl. the 20 legacy history classes) |
| `run-unit-phase.py X0` | passed |
| OpcUaServer unit suite | 1,401 passed, 1 pre-existing skip |
| OpcUaServer.IntegrationTests history classes | 56 passed (4 AVEVA live-gate skips need HistorianGateway + VPN) |
| Core.Abstractions | 852 passed |
| `HistoryReadPortLimiterAndSessionTests` ×20 | 20/20 |
- Paged-vs-unpaged fuzz: 10,000 seeds over SqlServer / QuestDB / Gateway backend shapes, `pageCount <= n` (#736); a
deliberate tie-skip mutation in `ServeRawPagedAsync` failed it at seed 3 (reverted).
- No existing test was edited (`git diff --name-status` over `tests/` shows additions only).
- The tie to pre-H1 behaviour is the pinned literal outcomes in `HistoryReadPortParityTests` plus the unchanged legacy
suites; the parity tests themselves compare the adapter with the port.
- Not run: SqlServer/QuestDB historian integration suites (fixture connection strings) and the AVEVA live gate.
## Review
Three Fable passes: approve-with-changes (GoodNoData status, namespace binding tag, tautological peer binding, hash culture,
log field, fuzz bound, test gaps) → approve-with-changes (token consumed before check, per-request incarnation snapshot,
distinct wiring fault, override-path real-session test) → final fixes checked by the coordinator.
@@ -769,5 +769,49 @@
],
"existing_classes": []
}
],
"H1": [
{
"project": "tests/Core/ZB.MOM.WW.OtOpcUa.Core.Abstractions.Tests/ZB.MOM.WW.OtOpcUa.Core.Abstractions.Tests.csproj",
"filter": "(Feature=GrpcData&Phase=H1)|FullyQualifiedName~.InterfaceIndependenceTests.",
"new_classes": [
"GrpcDataHistoryContractTests"
],
"existing_classes": [
"InterfaceIndependenceTests"
]
},
{
"project": "tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests/ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests.csproj",
"filter": "(Feature=GrpcData&Phase=H1)|FullyQualifiedName~.NodeManagerHistoryReadTests.|FullyQualifiedName~.NodeManagerHistoryReadPagingTests.|FullyQualifiedName~.NodeManagerHistoryReadBoundsTests.|FullyQualifiedName~.NodeManagerHistoryReadPageFillTests.|FullyQualifiedName~.NodeManagerHistoryReadRawCapFuzzTests.|FullyQualifiedName~.NodeManagerHistoryReadModifiedTests.|FullyQualifiedName~.NodeManagerHistoryReadConcurrencyTests.|FullyQualifiedName~.NodeManagerHistoryReadEventsTests.|FullyQualifiedName~.NodeManagerHistoryReadEventsPagingTests.|FullyQualifiedName~.NodeManagerHistoryReadEventsProjectionTests.|FullyQualifiedName~.NodeManagerHistoryReadEventsHorizonTests.|FullyQualifiedName~.HistoryUpdateTests.|FullyQualifiedName~.HistoryPagingTests.|FullyQualifiedName~.SessionHistoryContinuationStoreTests.|FullyQualifiedName~.HistoryServerCapabilitiesAdvertisementTests.|FullyQualifiedName~.NodeManagerMaxReturnDataValuesSyncTests.|FullyQualifiedName~.RawPageLimitTests.|FullyQualifiedName~.ReverseWalkTests.|FullyQualifiedName~.NodeManagerHistorizeTests.|FullyQualifiedName~.NodeManagerAclEnforcementTests.",
"new_classes": [
"HistoryReadPortParityTests",
"HistoryReadPortPagingFuzzTests",
"PeerHistoryContinuationStoreTests",
"HistoryReadPortLimiterAndSessionTests"
],
"existing_classes": [
"NodeManagerHistoryReadTests",
"NodeManagerHistoryReadPagingTests",
"NodeManagerHistoryReadBoundsTests",
"NodeManagerHistoryReadPageFillTests",
"NodeManagerHistoryReadRawCapFuzzTests",
"NodeManagerHistoryReadModifiedTests",
"NodeManagerHistoryReadConcurrencyTests",
"NodeManagerHistoryReadEventsTests",
"NodeManagerHistoryReadEventsPagingTests",
"NodeManagerHistoryReadEventsProjectionTests",
"NodeManagerHistoryReadEventsHorizonTests",
"HistoryUpdateTests",
"HistoryPagingTests",
"SessionHistoryContinuationStoreTests",
"HistoryServerCapabilitiesAdvertisementTests",
"NodeManagerMaxReturnDataValuesSyncTests",
"RawPageLimitTests",
"ReverseWalkTests",
"NodeManagerHistorizeTests",
"NodeManagerAclEnforcementTests"
]
}
]
}
@@ -186,3 +186,86 @@ public interface IDataSubscriptionService
/// <summary>Stream lifetime is independent of unary deadlines; cancellation ends the stream.</summary>
Task<IDataSubscription> SubscribeAsync(CancellationToken cancellationToken);
}
// ---------------------------------------------------------------------------------------------------------------------
// Remote history (gRPC data history plan §2.1, §3.1–§3.3). Declared by H1; the origin implementation over the node
// manager's override-level history port and the wire arrive with H2. SDK-free by construction: aggregates are their
// standard ns=0 numeric ids, statuses the full OPC UA uint32, an unset Part 11 bound is ABSENT (null), never MinValue —
// the origin's end-only / open-end rules depend on the difference.
// ---------------------------------------------------------------------------------------------------------------------
/// <summary>The variable-history request shape. HistoryUpdate and event history are not served remotely.</summary>
public abstract record DataHistoryDetails;
/// <summary>Part 11 ReadRawModifiedDetails without the modified flag (a remote raw read is never a modified read).</summary>
/// <param name="StartUtc">StartTime; null = unset.</param>
/// <param name="EndUtc">EndTime; null = unset.</param>
/// <param name="NumValuesPerNode">Per-page cap; 0 = all (the origin still pages at its ceiling).</param>
/// <param name="ReturnBounds">Part 11 bounding values.</param>
public sealed record DataHistoryRawDetails(DateTimeOffset? StartUtc, DateTimeOffset? EndUtc, uint NumValuesPerNode, bool ReturnBounds)
: DataHistoryDetails;
/// <summary>The Part 13 aggregate configuration a processed read asks for.</summary>
public sealed record DataAggregateConfiguration(
bool UseServerCapabilitiesDefaults, bool TreatUncertainAsBad, byte PercentDataBad, byte PercentDataGood, bool UseSlopedExtrapolation);
/// <summary>Part 11 ReadProcessedDetails. The aggregate is per item (<see cref="DataHistoryReadItem.AggregateId"/>).</summary>
/// <param name="StartUtc">StartTime; null = unset.</param>
/// <param name="EndUtc">EndTime; null = unset.</param>
/// <param name="ProcessingInterval">The interval.</param>
/// <param name="Configuration">The configuration; null = server defaults.</param>
public sealed record DataHistoryProcessedDetails(
DateTimeOffset? StartUtc, DateTimeOffset? EndUtc, TimeSpan ProcessingInterval, DataAggregateConfiguration? Configuration)
: DataHistoryDetails;
/// <summary>Part 11 ReadAtTimeDetails.</summary>
/// <param name="RequestedTimesUtc">The requested times, in order.</param>
public sealed record DataHistoryAtTimeDetails(IReadOnlyList<DateTimeOffset> RequestedTimesUtc) : DataHistoryDetails;
/// <summary>One node of a remote history read.</summary>
/// <param name="CorrelationId">Echoed on the result.</param>
/// <param name="View">The exported view being read.</param>
/// <param name="AggregateId">Processed only: the standard aggregate function's ns=0 numeric NodeId.</param>
/// <param name="Continuation">The origin's opaque continuation token from a previous page; null = a fresh read.</param>
public sealed record DataHistoryReadItem(string CorrelationId, DataView View, uint? AggregateId = null, byte[]? Continuation = null);
/// <summary>A batch of nodes read with one set of details.</summary>
public sealed record DataHistoryReadRequest(DataHistoryDetails Details, IReadOnlyList<DataHistoryReadItem> Items, DataBudget Budget);
/// <summary>
/// One returned history value, verbatim from the origin's Part 11 answer: the full status (Calculated / Interpolated /
/// Partial bits included) and timestamps that stay absent when absent. Owns <see cref="Value"/>.
/// </summary>
public sealed record DataHistorySample(DataValue Value, uint StatusCode, DateTimeOffset? SourceTimestampUtc, DateTimeOffset? ServerTimestampUtc)
: IDisposable
{
public void Dispose() => Value.Dispose();
}
/// <summary>
/// One node's answer: the Part 11 operation status (full uint32 — <c>BadContinuationPointInvalid</c>,
/// <c>BadAggregateNotSupported</c>, <c>GoodNoData</c> …), its samples and the origin's next continuation token (null
/// when the read is complete). Owns its samples.
/// </summary>
public sealed record DataHistoryReadResult(string CorrelationId, uint StatusCode, IReadOnlyList<DataHistorySample> Samples, byte[]? Continuation)
: IDisposable
{
public void Dispose()
{
foreach (var sample in Samples) sample.Dispose();
}
}
/// <summary>
/// Remote HistoryRead (Raw / Processed / AtTime) served by the origin's own historian pipeline. Operations use the
/// authenticated caller bound to the containing connection facade; continuations are bound to that caller, the serving
/// incarnation, the history epoch, the view and the request details, and are single-use.
/// </summary>
public interface IDataHistoryService
{
/// <summary>Reads every item, returning results in request order.</summary>
Task<IReadOnlyList<DataHistoryReadResult>> ReadAsync(DataHistoryReadRequest request, CancellationToken cancellationToken);
/// <summary>Releases continuation tokens without reading (Part 11 <c>releaseContinuationPoints</c>); best effort, idempotent.</summary>
Task ReleaseAsync(IReadOnlyList<byte[]> continuations, CancellationToken cancellationToken);
}
@@ -1,5 +1,6 @@
using Opc.Ua;
using Opc.Ua.Server;
using ZB.MOM.WW.OtOpcUa.Commons.OpcUa;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions;
namespace ZB.MOM.WW.OtOpcUa.OpcUaServer;
@@ -73,7 +74,11 @@ namespace ZB.MOM.WW.OtOpcUa.OpcUaServer;
/// <paramref name="NextStartUtc"/> that still has un-emitted ties — the next page over-fetches the cluster directly
/// instead of first re-reading <c>N + skip + 1</c> rows that are known to be ties.
/// </param>
/// <param name="BoundNodeKey">The exact namespace-qualified node identity; required on every production cursor.</param>
/// <param name="BoundRealm">With <paramref name="BoundIdentifier"/>, the node the cursor was issued for — re-keyed by the H1 history
/// port from the SDK NodeId string to <c>(realm, identifier)</c>, so a cursor never depends on an SDK handle.</param>
/// <param name="BoundIdentifier">The node's identifier in <paramref name="BoundRealm"/>; required on every production cursor.</param>
/// <param name="BoundTag">The node's binding discriminator (<see cref="HistoryReadPortItem.BindingTag"/> — the namespace URI
/// locally, a view tag for a peer); the realm alone folds namespaces, so a cursor is bound to this too.</param>
/// <param name="AddressSpaceEpoch">The topology generation. A removal conservatively invalidates all cursors.</param>
internal sealed record HistoryContinuationState(
string Tagname,
@@ -90,7 +95,9 @@ internal sealed record HistoryContinuationState(
long EmptyToTicks = 0,
HistoryEndBound? PendingEndBound = null,
bool WithinTieCluster = false,
string? BoundNodeKey = null,
AddressSpaceRealm BoundRealm = default,
string? BoundIdentifier = null,
string? BoundTag = null,
long AddressSpaceEpoch = -1)
{
/// <summary>The walk-back hint this cursor carries.</summary>
@@ -0,0 +1,468 @@
using System.Security.Cryptography;
using System.Text;
using Opc.Ua;
using Opc.Ua.Server;
using ZB.MOM.WW.OtOpcUa.Commons.OpcUa;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions;
using SdkHistoryReadResult = Opc.Ua.HistoryReadResult;
namespace ZB.MOM.WW.OtOpcUa.OpcUaServer;
/// <summary>
/// The variable-history request a <see cref="OtOpcUaNodeManager.ReadHistory"/> call serves — Raw (incl. modified),
/// Processed or AtTime. Never HistoryUpdate and never events: those stay on their SDK overrides (plan §2.1.1, §3.1).
/// Timestamps are CLR UTC; an unset Part 11 bound is <see cref="DateTime.MinValue"/>, exactly as the SDK overrides
/// handed it to the node manager before the port existed (the end-only / open-end rules depend on it).
/// </summary>
internal abstract record HistoryReadVariant
{
/// <summary>Maps the SDK's <see cref="HistoryReadDetails"/> onto the port variant the overrides serve.</summary>
/// <param name="details">Raw/modified, Processed or AtTime details.</param>
/// <returns>The equivalent variant.</returns>
/// <exception cref="ArgumentException">Event details (the port serves variable history only).</exception>
public static HistoryReadVariant From(HistoryReadDetails details) => details switch
{
ReadRawModifiedDetails raw => new HistoryReadRawVariant(
SdkValueBoundary.ToClrTimestamp(raw.StartTime), SdkValueBoundary.ToClrTimestamp(raw.EndTime),
raw.NumValuesPerNode, raw.ReturnBounds, raw.IsReadModified),
// OPC UA ProcessingInterval is a Duration in milliseconds — converted once per batch, as the override did.
ReadProcessedDetails processed => new HistoryReadProcessedVariant(
SdkValueBoundary.ToClrTimestamp(processed.StartTime), SdkValueBoundary.ToClrTimestamp(processed.EndTime),
TimeSpan.FromMilliseconds(processed.ProcessingInterval), processed.AggregateConfiguration),
// Snapshot the requested timestamps once — the same list is read for every node.
ReadAtTimeDetails atTime => new HistoryReadAtTimeVariant(
(atTime.ReqTimes.ToArray() ?? []).Select(t => t.ToDateTime()).ToList()),
_ => throw new ArgumentException($"The history port serves Raw, Processed and AtTime details, not {details.GetType().Name}.", nameof(details)),
};
/// <summary>
/// A stable SHA-256 (hex) of the request shape — what a peer continuation binds so a resume under different
/// details is refused (<see cref="PeerHistoryContinuationStore"/>). Local SDK continuation points never use it.
/// </summary>
/// <returns>The lowercase hex digest.</returns>
public string ComputeDetailsHash() =>
Convert.ToHexStringLower(SHA256.HashData(Encoding.UTF8.GetBytes(CanonicalForm())));
/// <summary>The canonical text <see cref="ComputeDetailsHash"/> digests — every field invariant-culture formatted.</summary>
/// <returns>An invariant, field-ordered rendering.</returns>
protected abstract string CanonicalForm();
}
/// <summary>HistoryRead-Raw (or, with <paramref name="IsReadModified"/>, the Part 11 modification trail).</summary>
/// <param name="StartUtc">StartTime (MinValue = unset).</param>
/// <param name="EndUtc">EndTime (MinValue = unset).</param>
/// <param name="NumValuesPerNode">Per-page cap; 0 = all values.</param>
/// <param name="ReturnBounds">Part 11 bounding values requested.</param>
/// <param name="IsReadModified">A modified-value read.</param>
internal sealed record HistoryReadRawVariant(DateTime StartUtc, DateTime EndUtc, uint NumValuesPerNode, bool ReturnBounds, bool IsReadModified = false)
: HistoryReadVariant
{
/// <inheritdoc />
protected override string CanonicalForm() =>
FormattableString.Invariant($"raw|{StartUtc.Ticks}|{EndUtc.Ticks}|{NumValuesPerNode}|{ReturnBounds}|{IsReadModified}");
}
/// <summary>HistoryRead-Processed. The aggregate is per node (<see cref="HistoryReadPortItem.AggregateType"/>).</summary>
/// <param name="StartUtc">StartTime.</param>
/// <param name="EndUtc">EndTime.</param>
/// <param name="ProcessingInterval">The interval.</param>
/// <param name="AggregateConfiguration">The client's configuration; null = server defaults.</param>
internal sealed record HistoryReadProcessedVariant(DateTime StartUtc, DateTime EndUtc, TimeSpan ProcessingInterval, AggregateConfiguration? AggregateConfiguration)
: HistoryReadVariant
{
/// <inheritdoc />
protected override string CanonicalForm()
{
var c = AggregateConfiguration;
var config = c is null ? "null" : FormattableString.Invariant(
$"{c.UseServerCapabilitiesDefaults}|{c.TreatUncertainAsBad}|{c.PercentDataBad}|{c.PercentDataGood}|{c.UseSlopedExtrapolation}");
return FormattableString.Invariant($"processed|{StartUtc.Ticks}|{EndUtc.Ticks}|{ProcessingInterval.Ticks}|{config}");
}
}
/// <summary>HistoryRead-AtTime.</summary>
/// <param name="TimestampsUtc">The requested times, in request order.</param>
internal sealed record HistoryReadAtTimeVariant(IReadOnlyList<DateTime> TimestampsUtc) : HistoryReadVariant
{
/// <inheritdoc />
protected override string CanonicalForm() =>
"attime|" + string.Join(",", TimestampsUtc.Select(t => t.Ticks.ToString(System.Globalization.CultureInfo.InvariantCulture)));
}
/// <summary>One node of a port request, addressed SDK-handle-free by <c>(realm, identifier)</c>.</summary>
/// <param name="Realm">The address-space realm.</param>
/// <param name="Identifier">The node's <c>s=</c> identifier in that realm.</param>
/// <param name="ContinuationPoint">The inbound continuation point; null/empty = a fresh read.</param>
/// <param name="AggregateType">Processed only: the requested aggregate function's NodeId.</param>
/// <param name="BindingTag">
/// An opaque discriminator a continuation is bound to on top of <c>(realm, identifier)</c>, because the realm folds
/// namespaces (mapped/raw → Raw, every other index → Uns): the SDK adapter passes the node's namespace URI
/// (<see cref="OtOpcUaNodeManager.HistoryBindingTag"/>), a peer (H2) its view tag (mapping id / kind). Compared ordinally;
/// a cursor issued under one tag never resumes under another.
/// </param>
/// <param name="NodeId">The local adapter's original NodeId, for log lines only (never used to resolve or bind).</param>
internal readonly record struct HistoryReadPortItem(
AddressSpaceRealm Realm, string Identifier, byte[]? ContinuationPoint = null, NodeId AggregateType = default,
string? BindingTag = null, NodeId NodeId = default)
{
/// <summary>What a log line names the node as: the original NodeId when the SDK adapter supplied it, else <c>Realm:Identifier</c>.</summary>
public object LogNodeId => NodeId.IsNull ? $"{Realm}:{Identifier}" : NodeId;
/// <inheritdoc />
public override string ToString() => LogNodeId.ToString()!;
}
/// <summary>
/// One node's outcome from the port, in the SDK's two-slot shape: <see cref="Error"/> is the service-level operation
/// status (the override's <c>errors[i]</c>) and <see cref="Result"/> the per-node result (<c>results[i]</c>). A slot left
/// <c>null</c> is one the pre-port override never wrote either — the SDK's own pre-seeded value stands (for the operation
/// status that is <c>BadHistoryOperationUnsupported</c>).
/// </summary>
internal sealed class HistoryReadNodeOutcome
{
/// <summary>The operation status, or null when untouched.</summary>
public ServiceResult? Error { get; set; }
/// <summary>The per-node result, or null when untouched.</summary>
public SdkHistoryReadResult? Result { get; set; }
/// <summary>
/// The effective per-node status a non-SDK caller (H2) reports: a non-Good operation status wins; otherwise the
/// result's own status, so <c>GoodNoData</c> passes through verbatim (plan §3.3). An untouched operation slot is the
/// SDK's pre-seeded <c>BadHistoryOperationUnsupported</c>.
/// </summary>
public StatusCode Status
{
get
{
var operation = Error?.StatusCode ?? StatusCodes.BadHistoryOperationUnsupported;
return StatusCode.IsGood(operation) ? Result?.StatusCode ?? StatusCodes.Good : operation;
}
}
/// <summary>The returned samples (HistoryData or HistoryModifiedData values), empty when none.</summary>
public IReadOnlyList<DataValue> Values =>
Result?.HistoryData is { IsNull: false } body && ExtensionObject.ToEncodeable(body) is HistoryData data
? data.DataValues.ToArray() ?? []
: [];
/// <summary>The outbound continuation point, or null when the read is complete.</summary>
public byte[]? ContinuationPoint =>
Result is { } r && !r.ContinuationPoint.IsEmpty ? r.ContinuationPoint.ToArray() : null;
}
/// <summary>What a continuation is bound to, handed to the scope on save and take.</summary>
/// <param name="Realm">The node's realm.</param>
/// <param name="Identifier">The node's identifier.</param>
/// <param name="Epoch">The history (address-space) epoch the cursor was issued under.</param>
/// <param name="Details">The request details (a peer binds their hash; the SDK session store ignores them).</param>
/// <param name="Tag">The item's <see cref="HistoryReadPortItem.BindingTag"/>.</param>
internal readonly record struct HistoryContinuationBinding(
AddressSpaceRealm Realm, string Identifier, long Epoch, HistoryReadVariant? Details, string? Tag = null);
/// <summary>
/// Where the port stores and takes resume state for one caller. The local SDK path binds it to the OPC UA session
/// (<see cref="OtOpcUaNodeManager.SessionHistoryContinuationScope"/>); a remote peer binds it to its authenticated
/// principal and connection incarnation (<see cref="PeerHistoryContinuationScope"/>). The port itself always re-checks
/// the node, realm, epoch, cursor kind and tagname after a take, whatever the scope.
/// </summary>
internal interface IHistoryContinuationScope
{
/// <summary>Stores <paramref name="state"/>; returns the opaque token, or null when nothing can be stored (single-shot).</summary>
byte[]? Save(HistoryContinuationState state, HistoryContinuationBinding binding);
/// <summary>Takes (removes) the state behind <paramref name="continuationPoint"/>; null when unknown/expired/mismatched.</summary>
HistoryContinuationState? TryTake(byte[] continuationPoint, HistoryContinuationBinding binding);
}
/// <summary>
/// H1 — the override-level history port (gRPC data history plan §3.1). Everything the Raw / Processed / AtTime SDK
/// overrides did after authorization now lives here, addressed by <c>(realm, identifier)</c> instead of SDK node
/// handles, so H2 can serve a remote peer's HistoryRead through the exact same pipeline. The overrides are thin
/// adapters (<see cref="ServeHistoryReadAdapter"/>): authorize, map handles to items, call the port, map back.
/// </summary>
public sealed partial class OtOpcUaNodeManager
{
/// <summary>
/// Serves one variable-history batch: aggregate refusals (unknown / not served, the #897 Part 13 data-type rule,
/// the backend's <c>SupportsAggregateFor</c>, a non-default <c>AggregateConfiguration</c>), the modified+bounds
/// <c>Bad_InvalidArgument</c> rule, the process-wide batch limiter, the per-request deadline, continuation binding
/// and value normalisation. Authorization is the caller's (the SDK adapter's ACL gate; H2's ingress).
/// </summary>
/// <param name="details">The request variant.</param>
/// <param name="items">The nodes, in request order.</param>
/// <param name="continuations">Where this caller's continuation points live.</param>
/// <param name="requestCancellation">
/// The request lifetime. It is linked with <see cref="HistoryReadDeadline"/>; a node still in flight when either
/// fires is <c>BadTimeout</c>.
/// </param>
/// <returns>One outcome per item, in item order.</returns>
/// <remarks>
/// Never called under <c>Lock</c> and never takes it for the read itself (the tagname and value-type lookups are
/// lock-free dictionary reads): HistoryRead runs outside the node-manager lock, and must stay there. Synchronous —
/// it block-bridges once at the batch boundary, exactly as the SDK overrides always did.
/// </remarks>
internal IReadOnlyList<HistoryReadNodeOutcome> ReadHistory(
HistoryReadVariant details,
IReadOnlyList<HistoryReadPortItem> items,
IHistoryContinuationScope continuations,
CancellationToken requestCancellation)
{
ArgumentNullException.ThrowIfNull(details);
ArgumentNullException.ThrowIfNull(items);
ArgumentNullException.ThrowIfNull(continuations);
var outcomes = new HistoryReadNodeOutcome[items.Count];
for (var i = 0; i < outcomes.Length; i++) outcomes[i] = new HistoryReadNodeOutcome();
var indices = Enumerable.Range(0, items.Count).ToList();
switch (details)
{
case HistoryReadRawVariant raw:
WithHistoryBatchLimiter(indices, () =>
{
using var deadline = CreateDeadline(requestCancellation);
var ct = deadline?.Token ?? CancellationToken.None;
var work = new List<Func<Task>>(items.Count);
foreach (var i in indices)
{
var item = items[i];
var outcome = outcomes[i];
if (raw.IsReadModified && raw.ReturnBounds && HonorReturnBounds)
{
// Part 11 §6.5.3.3: returnBounds "shall be set to FALSE" for a modified read, "otherwise the Server
// returns a Bad_InvalidArgument". Off with the ServerHistorian:HonorReturnBounds kill switch.
outcome.Error = StatusCodes.BadInvalidArgument;
outcome.Result = new SdkHistoryReadResult { StatusCode = StatusCodes.BadInvalidArgument };
continue;
}
if (raw.IsReadModified)
{
// Part 11 modified-value history: the prior values every HistoryUpdate recorded. Gated by the same
// HistoryRead authorization as a raw read; a backend with no trail ⇒ unsupported.
work.Add(() => ServeModifiedPagedAsync(
item, outcome, continuations, raw, raw.StartUtc, raw.EndUtc, raw.NumValuesPerNode, ct));
continue;
}
work.Add(() => ServeRawPagedAsync(
item, outcome, continuations, raw, raw.StartUtc, raw.EndUtc, raw.NumValuesPerNode,
ct, raw.ReturnBounds && HonorReturnBounds));
}
RunBounded(work, HistoryReadBatchParallelism);
}, i => RejectBatch(outcomes[i]));
NormalizeHistoryValues(items, outcomes);
break;
case HistoryReadProcessedVariant processed:
{
// A client AggregateConfiguration other than the server defaults is refused per node, never silently ignored.
var configurationServable = ServerAggregateConfiguration.IsServable(processed.AggregateConfiguration);
var served = AdvertisedAggregateFunctions.ServedBy(HistorianDataSource);
WithHistoryBatchLimiter(indices, () =>
{
using var deadline = CreateDeadline(requestCancellation);
var ct = deadline?.Token ?? CancellationToken.None;
var work = new List<Func<Task>>(items.Count);
foreach (var i in indices)
{
var item = items[i];
var outcome = outcomes[i];
// One authority — the source's SupportedAggregates (also what HistoryServerCapabilities/
// AggregateFunctions advertises; null ⇒ all, the same rule). An aggregate the server cannot name, or the
// backend does not serve, is refused up front without a backend call.
var aggregate = AggregateFunctionMap.Map(item.AggregateType);
if (aggregate is null || !served.Contains(aggregate.Value))
{
outcome.Error = StatusCodes.BadAggregateNotSupported;
continue;
}
// An aggregate not valid for THIS node's DataType (lmxopcua#897) — Part 11 §6.5.4: "If the Aggregate is
// not valid for the Node then the StatusCode shall be Bad_AggregateNotSupported". The shared Part 13
// Table 50 rule (no numeric aggregate on a String / DateTime node, every backend), then the backend's own
// per-type limit (the Gateway's native TimeAverage / Total on a Boolean node). Unsent, so never a
// backend failure.
var nodeValueType = AtTimeValueType(item.Realm, item.Identifier);
if (!HistoryAggregateDataTypes.AppliesTo(aggregate.Value, nodeValueType)
|| !HistorianDataSource.SupportsAggregateFor(aggregate.Value, nodeValueType))
{
outcome.Error = StatusCodes.BadAggregateNotSupported;
continue;
}
if (!configurationServable)
{
outcome.Error = StatusCodes.BadAggregateConfigurationRejected;
continue;
}
// Processed is SINGLE-SHOT (no continuation point). Unlike Raw, ReadProcessedDetails carries NO client
// count cap (NumValuesPerNode) — the bucket count is deterministic (window / interval) and the
// single-shot backend returns every bucket in one read, so there is no "full page ⇒ maybe more" signal
// to page on. Returning the complete aggregate result with a null CP is spec-conformant (OPC UA Part 11
// lets a server return all available data in one response).
var agg = aggregate.Value;
work.Add(() => ServeNodeAsync(item, outcome, (source, tagname, token) => source.ReadProcessedAsync(
tagname, processed.StartUtc, processed.EndUtc, processed.ProcessingInterval, agg, token), ct));
}
RunBounded(work, HistoryReadBatchParallelism);
}, i => RejectBatch(outcomes[i]));
break;
}
case HistoryReadAtTimeVariant atTime:
WithHistoryBatchLimiter(indices, () =>
{
using var deadline = CreateDeadline(requestCancellation);
var ct = deadline?.Token ?? CancellationToken.None;
var work = new List<Func<Task>>(items.Count);
foreach (var i in indices)
{
var item = items[i];
var outcome = outcomes[i];
// The node's scalar value type, for a backend whose stored values carry none (the Gateway).
var valueType = AtTimeValueType(item.Realm, item.Identifier);
work.Add(() => ServeNodeAsync(item, outcome, (source, tagname, token) => source.ReadAtTimeAsync(
tagname, atTime.TimestampsUtc, valueType, token), ct));
}
RunBounded(work, HistoryReadBatchParallelism);
}, i => RejectBatch(outcomes[i]));
NormalizeHistoryValues(items, outcomes);
break;
default:
throw new ArgumentException($"Unsupported history variant {details.GetType().Name}.", nameof(details));
}
return outcomes;
}
/// <summary>The batch limiter's saturation answer for one node: <c>BadTooManyOperations</c> in both slots.</summary>
private static void RejectBatch(HistoryReadNodeOutcome outcome)
{
outcome.Error = StatusCodes.BadTooManyOperations;
outcome.Result = new SdkHistoryReadResult { StatusCode = StatusCodes.BadTooManyOperations };
}
/// <summary>
/// The SDK-override side of the port: maps the authorized handles to <c>(realm, identifier)</c> items — the same
/// realm-qualified key every node map uses (<see cref="MapKey(NodeId)"/>) — serves them through
/// <see cref="ReadHistory"/> under the session's continuation scope, and writes each outcome back to the handle's
/// slots. A slot the port left unset keeps the SDK's pre-seeded value, as before.
/// </summary>
private void ServeHistoryReadAdapter(
ServerSystemContext context,
HistoryReadDetails details,
ArrayOf<HistoryReadValueId> nodesToRead,
List<NodeHandle> nodesToProcess,
IList<SdkHistoryReadResult> results,
IList<ServiceResult> errors)
{
var variant = HistoryReadVariant.From(details);
var aggregates = details is ReadProcessedDetails processed ? processed.AggregateType : default;
var items = new HistoryReadPortItem[nodesToProcess.Count];
for (var i = 0; i < items.Length; i++)
{
var handle = nodesToProcess[i];
var key = MapKey(handle.NodeId);
var cp = nodesToRead[handle.Index].ContinuationPoint;
// AggregateType is a per-node parallel collection (same length as nodesToRead, enforced by the base
// dispatcher); handle.Index is the node's position in it.
items[i] = new HistoryReadPortItem(key.Realm, key.Id, cp.Length > 0 ? cp.ToArray() : null,
variant is HistoryReadProcessedVariant ? aggregates[handle.Index] : default,
HistoryBindingTag(handle.NodeId), handle.NodeId);
}
var outcomes = ReadHistory(variant, items, SessionHistoryContinuationScope(context.OperationContext?.Session),
context.OperationContext?.CancellationToken ?? CancellationToken.None);
for (var i = 0; i < items.Length; i++)
{
var index = nodesToProcess[i].Index;
if (outcomes[i].Error is { } error) errors[index] = error;
if (outcomes[i].Result is { } result) results[index] = result;
}
}
/// <summary>
/// The continuation binding tag of a local node: its namespace URI. With <c>(realm, identifier)</c> it is the same
/// identity the pre-port cursor bound (the namespace-qualified NodeId string), so a cursor of a raw node never resumes
/// on the same identifier in the mapped/raw namespace, nor the reverse.
/// </summary>
/// <param name="nodeId">The node.</param>
/// <returns>The namespace URI, or <c>ns=&lt;index&gt;</c> for an unregistered index.</returns>
internal string HistoryBindingTag(NodeId nodeId) =>
Server.NamespaceUris.GetString(nodeId.NamespaceIndex)
?? "ns=" + nodeId.NamespaceIndex.ToString(System.Globalization.CultureInfo.InvariantCulture);
/// <summary>The continuation scope of a local OPC UA session — the SDK session store, as before the port.</summary>
/// <param name="session">The request's session; null on the session-less in-process path.</param>
/// <returns>A scope reading <see cref="HistoryContinuationStore"/> at each call.</returns>
internal IHistoryContinuationScope SessionHistoryContinuationScope(ISession? session) => new SessionScope(this, session);
/// <summary>Normalize stored and AtTime history to each scalar node's declared DataType.</summary>
private void NormalizeHistoryValues(IReadOnlyList<HistoryReadPortItem> items, IReadOnlyList<HistoryReadNodeOutcome> outcomes)
{
for (var n = 0; n < items.Count; n++)
{
if (AtTimeValueType(items[n].Realm, items[n].Identifier) is not { } type || outcomes[n].Result?.HistoryData is not { } body) continue;
if (body.IsNull || ExtensionObject.ToEncodeable(body) is not HistoryData data) continue;
var values = data.DataValues.ToArray() ?? [];
for (var i = 0; i < values.Length; i++)
{
var value = values[i];
var payload = SdkValueBoundary.ToClr(value.WrappedValue);
if (payload is null) continue;
try
{
// A gateway number cannot reconstruct a DateTime or a String which was never stored.
if ((type == TypeCode.DateTime && payload is not DateTime)
|| (type == TypeCode.String && payload is not string)) throw new InvalidCastException();
var converted = Convert.ChangeType(payload, type, System.Globalization.CultureInfo.InvariantCulture);
if (converted is float f && float.IsInfinity(f) && payload is double d && double.IsFinite(d))
throw new OverflowException();
values[i] = value.WithWrappedValue(SdkValueBoundary.FromClr(converted));
}
catch (Exception ex) when (ex is InvalidCastException or OverflowException or FormatException)
{
values[i] = value.WithWrappedValue(Variant.Null).WithStatus(StatusCodes.BadTypeMismatch);
}
}
data.DataValues = values;
}
}
/// <summary>
/// Saves a cursor bound to its node (<c>(realm, identifier)</c>, re-keyed from the SDK NodeId string) and the current
/// history epoch. A cursor issued under an epoch that has since moved is not stored — the read degrades to
/// single-shot for that node, as before.
/// </summary>
private byte[]? SaveHistoryContinuation(
IHistoryContinuationScope scope, AddressSpaceRealm realm, string identifier, string? tag, long epoch,
HistoryReadVariant? details, HistoryContinuationState state)
{
if (epoch != Volatile.Read(ref _historyContinuationEpoch)) return null;
return scope.Save(state with { BoundRealm = realm, BoundIdentifier = identifier, BoundTag = tag, AddressSpaceEpoch = epoch },
new HistoryContinuationBinding(realm, identifier, epoch, details, tag));
}
/// <summary>Whether a taken cursor was issued for this node (realm, identifier and binding tag) under this epoch.</summary>
private static bool HistoryContinuationMatches(
HistoryContinuationState state, AddressSpaceRealm realm, string identifier, string? tag, long epoch) =>
state.BoundIdentifier is not null && state.BoundRealm == realm
&& string.Equals(state.BoundIdentifier, identifier, StringComparison.Ordinal)
&& string.Equals(state.BoundTag, tag, StringComparison.Ordinal) && state.AddressSpaceEpoch == epoch;
/// <summary>The SDK session store behind a scope (read per call, so a test's store swap applies to the next call).</summary>
private sealed class SessionScope(OtOpcUaNodeManager nm, ISession? session) : IHistoryContinuationScope
{
public byte[]? Save(HistoryContinuationState state, HistoryContinuationBinding binding) =>
nm._historyContinuationStore.Save(session, state);
public HistoryContinuationState? TryTake(byte[] continuationPoint, HistoryContinuationBinding binding) =>
nm._historyContinuationStore.TryTake(session, continuationPoint);
}
}
@@ -85,7 +85,7 @@ public sealed record ProjectedAnchorDefinition(DataRealm Realm, string LocalIden
// re-implementing the interface is the only way to put an ACL decision on that path. Since #855 condition events no
// longer take it, and since #878 the decision there is a flat deny under enforcement (the SDK memoizes it, so it must
// not depend on grants). Every other member maps to the inherited implementation exactly as before.
public sealed class OtOpcUaNodeManager : CustomNodeManager2, INodeManager3, IProjectedValueSink, IProjectedNamespacePageSink, IProjectedNodeLookup, IProjectedAnchorSink
public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManager3, IProjectedValueSink, IProjectedNamespacePageSink, IProjectedNodeLookup, IProjectedAnchorSink
{
/// <summary>Nonblocking lookup of the current projected parent readiness.</summary>
public Func<NodeId, ProjectedBrowseReadiness>? ProjectedBrowseReadiness { get; set; }
@@ -5491,7 +5491,17 @@ public sealed class OtOpcUaNodeManager : CustomNodeManager2, INodeManager3, IPro
/// <returns>The hint, or null.</returns>
internal TypeCode? AtTimeValueType(NodeId nodeId)
{
if (!_variables.TryGetValue(MapKey(nodeId), out var variable) || variable.ValueRank != ValueRanks.Scalar) return null;
var key = MapKey(nodeId);
return AtTimeValueType(key.Realm, key.Id);
}
/// <summary>The <see cref="AtTimeValueType(NodeId)"/> hint of a node addressed by <c>(realm, identifier)</c> (the history port).</summary>
/// <param name="realm">The node's realm.</param>
/// <param name="identifier">The node's identifier.</param>
/// <returns>The hint, or null.</returns>
internal TypeCode? AtTimeValueType(AddressSpaceRealm realm, string identifier)
{
if (!_variables.TryGetValue(MapKey(realm, identifier), out var variable) || variable.ValueRank != ValueRanks.Scalar) return null;
return TypeInfo.GetBuiltInType(variable.DataType) switch
{
BuiltInType.Boolean => TypeCode.Boolean,
@@ -8788,6 +8798,7 @@ public sealed class OtOpcUaNodeManager : CustomNodeManager2, INodeManager3, IPro
}
/// <inheritdoc />
/// <remarks>A thin adapter over the history port (<see cref="ReadHistory"/>): authorize, then serve.</remarks>
protected override void HistoryReadRawModified(
ServerSystemContext context,
ReadRawModifiedDetails details,
@@ -8798,47 +8809,12 @@ public sealed class OtOpcUaNodeManager : CustomNodeManager2, INodeManager3, IPro
List<NodeHandle> nodesToProcess,
IDictionary<NodeId, NodeState> cache)
{
var session = context.OperationContext?.Session;
nodesToProcess = AuthorizeHistoryRead(context, nodesToProcess, results, errors);
WithHistoryReadBatchLimiter(nodesToProcess, results, errors, () =>
{
using var deadline = CreateDeadline(context);
var ct = deadline?.Token ?? CancellationToken.None;
var work = new List<Func<Task>>(nodesToProcess.Count);
foreach (var handle in nodesToProcess)
{
if (details.IsReadModified && details.ReturnBounds && HonorReturnBounds)
{
// Part 11 §6.5.3.3: returnBounds "shall be set to FALSE" for a modified read, "otherwise the Server returns
// a Bad_InvalidArgument". Off with the ServerHistorian:HonorReturnBounds kill switch.
errors[handle.Index] = StatusCodes.BadInvalidArgument;
results[handle.Index] = new SdkHistoryReadResult { StatusCode = StatusCodes.BadInvalidArgument };
continue;
}
if (details.IsReadModified)
{
// Part 11 modified-value history: the prior values every HistoryUpdate recorded. Gated by the
// same HistoryRead authorization as a raw read (above); a backend with no trail ⇒ unsupported.
work.Add(() => ServeModifiedPagedAsync(
handle, session, nodesToRead, results, errors,
SdkValueBoundary.ToClrTimestamp(details.StartTime), SdkValueBoundary.ToClrTimestamp(details.EndTime), details.NumValuesPerNode,
ct));
continue;
}
work.Add(() => ServeRawPagedAsync(
handle, session, nodesToRead, results, errors,
SdkValueBoundary.ToClrTimestamp(details.StartTime), SdkValueBoundary.ToClrTimestamp(details.EndTime), details.NumValuesPerNode,
ct, details.ReturnBounds && HonorReturnBounds));
}
RunBounded(work, HistoryReadBatchParallelism);
});
NormalizeHistoryValues(nodesToProcess, results);
ServeHistoryReadAdapter(context, details, nodesToRead, nodesToProcess, results, errors);
}
/// <inheritdoc />
/// <remarks>A thin adapter over the history port (<see cref="ReadHistory"/>): authorize, then serve.</remarks>
protected override void HistoryReadProcessed(
ServerSystemContext context,
ReadProcessedDetails details,
@@ -8849,70 +8825,12 @@ public sealed class OtOpcUaNodeManager : CustomNodeManager2, INodeManager3, IPro
List<NodeHandle> nodesToProcess,
IDictionary<NodeId, NodeState> cache)
{
// OPC UA ProcessingInterval is a Duration in milliseconds — convert once per batch.
var interval = TimeSpan.FromMilliseconds(details.ProcessingInterval);
// A client AggregateConfiguration other than the server defaults is refused per node, never silently ignored.
var configurationServable = ServerAggregateConfiguration.IsServable(details.AggregateConfiguration);
nodesToProcess = AuthorizeHistoryRead(context, nodesToProcess, results, errors);
var served = AdvertisedAggregateFunctions.ServedBy(HistorianDataSource);
WithHistoryReadBatchLimiter(nodesToProcess, results, errors, () =>
{
using var deadline = CreateDeadline(context);
var ct = deadline?.Token ?? CancellationToken.None;
var work = new List<Func<Task>>(nodesToProcess.Count);
foreach (var handle in nodesToProcess)
{
// AggregateType is a per-node parallel collection (same length as nodesToRead, enforced by
// the base dispatcher). handle.Index is the node's position in that collection.
var aggregateNodeId = details.AggregateType[handle.Index];
// One authority — the source's SupportedAggregates (also what HistoryServerCapabilities/
// AggregateFunctions advertises; null ⇒ all, the same rule). An aggregate the server cannot name, or the
// backend does not serve, is refused up front without a backend call.
var aggregate = AggregateFunctionMap.Map(aggregateNodeId);
if (aggregate is null || !served.Contains(aggregate.Value))
{
errors[handle.Index] = StatusCodes.BadAggregateNotSupported;
continue;
}
// An aggregate not valid for THIS node's DataType (lmxopcua#897) — Part 11 §6.5.4: "If the Aggregate is not
// valid for the Node then the StatusCode shall be Bad_AggregateNotSupported". The shared Part 13 Table 50
// rule (no numeric aggregate on a String / DateTime node, every backend), then the backend's own per-type
// limit (the Gateway's native TimeAverage / Total on a Boolean node). Unsent, so never a backend failure.
var nodeValueType = AtTimeValueType(handle.NodeId);
if (!HistoryAggregateDataTypes.AppliesTo(aggregate.Value, nodeValueType)
|| !HistorianDataSource.SupportsAggregateFor(aggregate.Value, nodeValueType))
{
errors[handle.Index] = StatusCodes.BadAggregateNotSupported;
continue;
}
if (!configurationServable)
{
errors[handle.Index] = StatusCodes.BadAggregateConfigurationRejected;
continue;
}
// Processed is SINGLE-SHOT (no continuation point). Unlike Raw, ReadProcessedDetails carries
// NO client count cap (NumValuesPerNode) — the bucket count is deterministic (window / interval)
// and the single-shot backend returns every bucket in one read, so there is no "full page ⇒
// maybe more" signal to page on. Returning the complete aggregate result with a null CP is
// spec-conformant (OPC UA Part 11 lets a server return all available data in one response).
var agg = aggregate.Value;
work.Add(() => ServeNodeAsync(handle, results, errors, (source, tagname, token) => source.ReadProcessedAsync(
tagname,
SdkValueBoundary.ToClrTimestamp(details.StartTime),
SdkValueBoundary.ToClrTimestamp(details.EndTime),
interval,
agg,
token), ct));
}
RunBounded(work, HistoryReadBatchParallelism);
});
ServeHistoryReadAdapter(context, details, nodesToRead, nodesToProcess, results, errors);
}
/// <inheritdoc />
/// <remarks>A thin adapter over the history port (<see cref="ReadHistory"/>): authorize, then serve.</remarks>
protected override void HistoryReadAtTime(
ServerSystemContext context,
ReadAtTimeDetails details,
@@ -8923,28 +8841,8 @@ public sealed class OtOpcUaNodeManager : CustomNodeManager2, INodeManager3, IPro
List<NodeHandle> nodesToProcess,
IDictionary<NodeId, NodeState> cache)
{
// Snapshot the requested timestamps once — the same list is read for every node.
var timestamps = (details.ReqTimes.ToArray() ?? []).Select(t => t.ToDateTime()).ToList();
nodesToProcess = AuthorizeHistoryRead(context, nodesToProcess, results, errors);
WithHistoryReadBatchLimiter(nodesToProcess, results, errors, () =>
{
using var deadline = CreateDeadline(context);
var ct = deadline?.Token ?? CancellationToken.None;
var work = new List<Func<Task>>(nodesToProcess.Count);
foreach (var handle in nodesToProcess)
{
// The node's scalar value type, for a backend whose stored values carry none (the Gateway).
var valueType = AtTimeValueType(handle.NodeId);
work.Add(() => ServeNodeAsync(handle, results, errors, (source, tagname, token) => source.ReadAtTimeAsync(
tagname,
timestamps,
valueType,
token), ct));
}
RunBounded(work, HistoryReadBatchParallelism);
});
NormalizeHistoryValues(nodesToProcess, results);
ServeHistoryReadAdapter(context, details, nodesToRead, nodesToProcess, results, errors);
}
/// <inheritdoc />
@@ -9137,7 +9035,8 @@ public sealed class OtOpcUaNodeManager : CustomNodeManager2, INodeManager3, IPro
// for THIS node only.
var state = _historyContinuationStore.TryTake(session, inboundCp.ToArray());
// A point is bound to the node that issued it: another node's source name is a miss too.
if (state is null || !HistoryContinuationMatches(state, handle.NodeId, historyEpoch) || state.Kind != HistoryCursorKind.Events || state.Tagname != sourceName)
var boundKey = MapKey(handle.NodeId);
if (state is null || !HistoryContinuationMatches(state, boundKey.Realm, boundKey.Id, HistoryBindingTag(handle.NodeId), historyEpoch) || state.Kind != HistoryCursorKind.Events || state.Tagname != sourceName)
{
errors[handle.Index] = StatusCodes.BadContinuationPointInvalid;
results[handle.Index] = new SdkHistoryReadResult { StatusCode = StatusCodes.BadContinuationPointInvalid };
@@ -9313,7 +9212,10 @@ public sealed class OtOpcUaNodeManager : CustomNodeManager2, INodeManager3, IPro
// ConditionName, as the live event does. Rewritten after paging: EventId and time are untouched.
events = scope.ResolveConditions(events);
var historyEvent = ProjectEvents(events, selectClauses, where, filterContext);
var outboundCp = pendingCursor is null ? null : SaveHistoryContinuation(session, handle.NodeId, historyEpoch, pendingCursor);
var eventsKey = MapKey(handle.NodeId);
var outboundCp = pendingCursor is null ? null : SaveHistoryContinuation(
SessionHistoryContinuationScope(session), eventsKey.Realm, eventsKey.Id, HistoryBindingTag(handle.NodeId), historyEpoch,
details: null, pendingCursor);
results[handle.Index] = new SdkHistoryReadResult
{
// No events ⇒ GoodNoData (the notifier is historized, the window just held no events — or none matched).
@@ -9923,9 +9825,8 @@ public sealed class OtOpcUaNodeManager : CustomNodeManager2, INodeManager3, IPro
/// tagname and is wrapped in try/catch so a backend throw / timeout becomes a Bad status for
/// THIS node without throwing out of the batch.
/// </summary>
/// <param name="handle">The pre-filtered node handle to serve; <c>handle.Index</c> indexes results/errors.</param>
/// <param name="results">The service-level results list to fill at <c>handle.Index</c>.</param>
/// <param name="errors">The service-level errors list to fill at <c>handle.Index</c>.</param>
/// <param name="handle">The history-port item to serve, addressed by <c>(realm, identifier)</c>.</param>
/// <param name="outcome">The item's outcome to fill (operation status + result).</param>
/// <param name="read">Invokes the resolved data-source read with the resolved tagname; only called
/// once the tagname is confirmed present.</param>
/// <summary>
@@ -9976,8 +9877,11 @@ public sealed class OtOpcUaNodeManager : CustomNodeManager2, INodeManager3, IPro
IList<SdkHistoryReadResult> results,
IList<ServiceResult> errors,
Action serve) =>
WithHistoryBatchLimiter(nodesToProcess, errors, serve, handle =>
results[handle.Index] = new SdkHistoryReadResult { StatusCode = StatusCodes.BadTooManyOperations });
WithHistoryBatchLimiter(nodesToProcess, serve, handle =>
{
errors[handle.Index] = StatusCodes.BadTooManyOperations;
results[handle.Index] = new SdkHistoryReadResult { StatusCode = StatusCodes.BadTooManyOperations };
});
/// <summary>
/// HistoryUpdate counterpart of <see cref="WithHistoryReadBatchLimiter(List{NodeHandle}, IList{SdkHistoryReadResult}, IList{ServiceResult}, Action)"/>:
@@ -9993,19 +9897,20 @@ public sealed class OtOpcUaNodeManager : CustomNodeManager2, INodeManager3, IPro
IList<HistoryUpdateResult> results,
IList<ServiceResult> errors,
Action serve) =>
WithHistoryBatchLimiter(nodesToProcess, errors, serve, handle =>
results[handle.Index] = new HistoryUpdateResult { StatusCode = StatusCodes.BadTooManyOperations });
WithHistoryBatchLimiter(nodesToProcess, serve, handle =>
{
errors[handle.Index] = StatusCodes.BadTooManyOperations;
results[handle.Index] = new HistoryUpdateResult { StatusCode = StatusCodes.BadTooManyOperations };
});
/// <summary>Shared body of the HistoryRead / HistoryUpdate batch limiter.</summary>
/// <param name="nodesToProcess">The batch's handles.</param>
/// <param name="errors">The service-level errors list.</param>
/// <summary>Shared body of the HistoryRead / HistoryUpdate batch limiter (SDK handles, or the port's item indices).</summary>
/// <param name="nodesToProcess">The batch's nodes.</param>
/// <param name="serve">The arm body.</param>
/// <param name="rejectResult">Fills the per-node result slot when the batch is rejected.</param>
private void WithHistoryBatchLimiter(
List<NodeHandle> nodesToProcess,
IList<ServiceResult> errors,
/// <param name="rejectResult">Fills the node's operation and result slots when the batch is rejected.</param>
private void WithHistoryBatchLimiter<T>(
IReadOnlyList<T> nodesToProcess,
Action serve,
Action<NodeHandle> rejectResult)
Action<T> rejectResult)
{
var gate = GetHistoryReadBatchLimiter();
@@ -10017,10 +9922,7 @@ public sealed class OtOpcUaNodeManager : CustomNodeManager2, INodeManager3, IPro
if (!gate.Wait(TimeSpan.FromMilliseconds(waitMs)))
{
foreach (var handle in nodesToProcess)
{
errors[handle.Index] = StatusCodes.BadTooManyOperations;
rejectResult(handle);
}
return;
}
@@ -10053,9 +9955,14 @@ public sealed class OtOpcUaNodeManager : CustomNodeManager2, INodeManager3, IPro
/// <summary>Link the SDK request lifetime to the application's per-batch history deadline.</summary>
/// <param name="context">The request's server context.</param>
/// <returns>The linked deadline source, or null when neither request nor application can cancel.</returns>
private CancellationTokenSource? CreateDeadline(ServerSystemContext context)
private CancellationTokenSource? CreateDeadline(ServerSystemContext context) =>
CreateDeadline(context.OperationContext?.CancellationToken ?? CancellationToken.None);
/// <summary>Link a request lifetime to the application's per-batch history deadline.</summary>
/// <param name="request">The request lifetime (the SDK request, or a peer's call).</param>
/// <returns>The linked deadline source, or null when neither request nor application can cancel.</returns>
private CancellationTokenSource? CreateDeadline(CancellationToken request)
{
var request = context.OperationContext?.CancellationToken ?? CancellationToken.None;
if (!request.CanBeCanceled && HistoryReadDeadline <= TimeSpan.Zero) return null;
var deadline = request.CanBeCanceled
? CancellationTokenSource.CreateLinkedTokenSource(request)
@@ -10081,17 +9988,16 @@ public sealed class OtOpcUaNodeManager : CustomNodeManager2, INodeManager3, IPro
}
private async Task ServeNodeAsync(
NodeHandle handle,
IList<SdkHistoryReadResult> results,
IList<ServiceResult> errors,
HistoryReadPortItem handle,
HistoryReadNodeOutcome outcome,
Func<IHistorianDataSource, string, CancellationToken, Task<HistorianRead>> read,
CancellationToken ct)
{
if (!TryGetHistorizedTagname(handle.NodeId, out var tagname))
if (!TryGetHistorizedTagname(handle.Identifier, out var tagname, handle.Realm))
{
// Not a historized node we own a tagname for — unsupported. (The base pre-seeds this same
// status, but set it explicitly so the contract is local + obvious.)
errors[handle.Index] = StatusCodes.BadHistoryOperationUnsupported;
outcome.Error = StatusCodes.BadHistoryOperationUnsupported;
return;
}
@@ -10102,7 +10008,7 @@ public sealed class OtOpcUaNodeManager : CustomNodeManager2, INodeManager3, IPro
var sourceResult = await read(HistorianDataSource, tagname!, ct).ConfigureAwait(false);
var historyData = ToHistoryData(sourceResult);
results[handle.Index] = new SdkHistoryReadResult
outcome.Result = new SdkHistoryReadResult
{
// No source samples ⇒ GoodNoData (the node is historized, the window just held no data).
StatusCode = historyData.DataValues.Count == 0 ? StatusCodes.GoodNoData : StatusCodes.Good,
@@ -10112,39 +10018,39 @@ public sealed class OtOpcUaNodeManager : CustomNodeManager2, INodeManager3, IPro
// continuation point. Raw pages via ServeRawPaged, not this helper.
ContinuationPoint = default,
};
errors[handle.Index] = ServiceResult.Good;
outcome.Error = ServiceResult.Good;
}
catch (OperationCanceledException)
{
// The per-request deadline elapsed while this node was in flight — surface BadTimeout for
// THIS node only (a spec-conformant history-read status), ahead of the generic catch.
errors[handle.Index] = StatusCodes.BadTimeout;
results[handle.Index] = new SdkHistoryReadResult { StatusCode = StatusCodes.BadTimeout };
outcome.Error = StatusCodes.BadTimeout;
outcome.Result = new SdkHistoryReadResult { StatusCode = StatusCodes.BadTimeout };
}
catch (HistoryAggregateNotSupportedException ex)
{
// The backend cannot serve this Part 13 aggregate — the spec status for THIS node,
// not a logged server fault.
_logger.LogDebug(ex, "OtOpcUaNodeManager: backend does not support aggregate for node {NodeId}", handle.NodeId);
errors[handle.Index] = StatusCodes.BadAggregateNotSupported;
results[handle.Index] = new SdkHistoryReadResult { StatusCode = StatusCodes.BadAggregateNotSupported };
_logger.LogDebug(ex, "OtOpcUaNodeManager: backend does not support aggregate for node {NodeId}", handle.LogNodeId);
outcome.Error = StatusCodes.BadAggregateNotSupported;
outcome.Result = new SdkHistoryReadResult { StatusCode = StatusCodes.BadAggregateNotSupported };
}
catch (HistoryReadLimitExceededException ex)
{
// The read would exceed a backend size limit (the time-weighted raw-row cap) — refuse THIS node
// explicitly instead of a generic fault or a deadline-elapsed BadTimeout.
_logger.LogWarning("OtOpcUaNodeManager: HistoryRead limit exceeded for node {NodeId}: {Message}", handle.NodeId, ex.Message);
errors[handle.Index] = StatusCodes.BadTooManyOperations;
results[handle.Index] = new SdkHistoryReadResult { StatusCode = StatusCodes.BadTooManyOperations };
_logger.LogWarning("OtOpcUaNodeManager: HistoryRead limit exceeded for node {NodeId}: {Message}", handle.LogNodeId, ex.Message);
outcome.Error = StatusCodes.BadTooManyOperations;
outcome.Result = new SdkHistoryReadResult { StatusCode = StatusCodes.BadTooManyOperations };
}
catch (Exception ex)
{
// One node's backend failure (throw / timeout) must not throw out of the batch — surface a
// Bad status for THIS node only. Logged through the injected ILogger
// rather than swallowed silently.
_logger.LogError(ex, "OtOpcUaNodeManager: HistoryRead failed for node {NodeId}", handle.NodeId);
errors[handle.Index] = HistoryReadFailureStatus(ex);
results[handle.Index] = new SdkHistoryReadResult { StatusCode = HistoryReadFailureStatus(ex) };
_logger.LogError(ex, "OtOpcUaNodeManager: HistoryRead failed for node {NodeId}", handle.LogNodeId);
outcome.Error = HistoryReadFailureStatus(ex);
outcome.Result = new SdkHistoryReadResult { StatusCode = HistoryReadFailureStatus(ex) };
}
}
@@ -10174,12 +10080,11 @@ public sealed class OtOpcUaNodeManager : CustomNodeManager2, INodeManager3, IPro
/// isolation matches <see cref="ServeNode"/>: a backend throw / an unknown continuation point
/// becomes a Bad status for THIS node only and never throws out of the batch.
/// </summary>
/// <param name="handle">The pre-filtered node handle; <c>handle.Index</c> indexes results/errors.</param>
/// <param name="session">The session the read runs under (null on the session-less in-process path).</param>
/// <param name="nodesToRead">The per-node read list; <c>nodesToRead[handle.Index].ContinuationPoint</c>
/// carries the inbound continuation point (non-null ⇒ a resume read).</param>
/// <param name="results">The service-level results list to fill at <c>handle.Index</c>.</param>
/// <param name="errors">The service-level errors list to fill at <c>handle.Index</c>.</param>
/// <param name="handle">The history-port item, addressed by <c>(realm, identifier)</c>; its
/// <see cref="HistoryReadPortItem.ContinuationPoint"/> (non-empty ⇒ a resume read) is the inbound point.</param>
/// <param name="outcome">The item's outcome to fill (operation status + result).</param>
/// <param name="continuations">The caller's continuation scope (the SDK session, or a remote peer's store).</param>
/// <param name="details">The request details, bound into a peer continuation.</param>
/// <param name="startTimeUtc">The request window's (inclusive) lower bound, used for a fresh read.</param>
/// <param name="endUtc">The (inclusive) upper bound of the read window; unchanged across pages.</param>
/// <param name="numValuesPerNode">The client's per-page cap; <c>0</c> means "all values, no paging".</param>
@@ -10189,11 +10094,10 @@ public sealed class OtOpcUaNodeManager : CustomNodeManager2, INodeManager3, IPro
/// ends the last, and both count toward <paramref name="numValuesPerNode"/>. A resumed read takes it from the cursor.
/// </param>
private async Task ServeRawPagedAsync(
NodeHandle handle,
ISession? session,
ArrayOf<HistoryReadValueId> nodesToRead,
IList<SdkHistoryReadResult> results,
IList<ServiceResult> errors,
HistoryReadPortItem handle,
HistoryReadNodeOutcome outcome,
IHistoryContinuationScope continuations,
HistoryReadVariant details,
DateTime startTimeUtc,
DateTime endUtc,
uint numValuesPerNode,
@@ -10201,7 +10105,7 @@ public sealed class OtOpcUaNodeManager : CustomNodeManager2, INodeManager3, IPro
bool returnBounds = false)
{
var historyEpoch = Volatile.Read(ref _historyContinuationEpoch);
var inboundCp = nodesToRead[handle.Index].ContinuationPoint;
var inboundCp = handle.ContinuationPoint;
try
{
@@ -10216,12 +10120,12 @@ public sealed class OtOpcUaNodeManager : CustomNodeManager2, INodeManager3, IPro
{
// Resume read: take the stored cursor. A miss (unknown / evicted / malformed point) ⇒
// BadContinuationPointInvalid for THIS node.
var state = _historyContinuationStore.TryTake(session, inboundCp.ToArray());
if (state is null || !HistoryContinuationMatches(state, handle.NodeId, historyEpoch) || state.Kind != HistoryCursorKind.Raw
|| !TryGetHistorizedTagname(handle.NodeId, out var boundTag) || boundTag != state.Tagname)
var state = continuations.TryTake(inboundCp, new HistoryContinuationBinding(handle.Realm, handle.Identifier, historyEpoch, details, handle.BindingTag));
if (state is null || !HistoryContinuationMatches(state, handle.Realm, handle.Identifier, handle.BindingTag, historyEpoch) || state.Kind != HistoryCursorKind.Raw
|| !TryGetHistorizedTagname(handle.Identifier, out var boundTag, handle.Realm) || boundTag != state.Tagname)
{
errors[handle.Index] = StatusCodes.BadContinuationPointInvalid;
results[handle.Index] = new SdkHistoryReadResult { StatusCode = StatusCodes.BadContinuationPointInvalid };
outcome.Error = StatusCodes.BadContinuationPointInvalid;
outcome.Result = new SdkHistoryReadResult { StatusCode = StatusCodes.BadContinuationPointInvalid };
return;
}
@@ -10237,9 +10141,9 @@ public sealed class OtOpcUaNodeManager : CustomNodeManager2, INodeManager3, IPro
else
{
// Fresh read: resolve the node's historian tagname (as ServeNode does).
if (!TryGetHistorizedTagname(handle.NodeId, out var resolved) || resolved is null)
if (!TryGetHistorizedTagname(handle.Identifier, out var resolved, handle.Realm) || resolved is null)
{
errors[handle.Index] = StatusCodes.BadHistoryOperationUnsupported;
outcome.Error = StatusCodes.BadHistoryOperationUnsupported;
return;
}
@@ -10284,7 +10188,7 @@ public sealed class OtOpcUaNodeManager : CustomNodeManager2, INodeManager3, IPro
return null;
}
return SaveHistoryContinuation(session, handle.NodeId, historyEpoch, new HistoryContinuationState(
return SaveHistoryContinuation(continuations, handle.Realm, handle.Identifier, handle.BindingTag, historyEpoch, details, new HistoryContinuationState(
tagname, previous, endUtc, 0, numValuesPerNode, SegmentWidthTicks: walkHint.WidthTicks,
EmptyFromTicks: walkHint.EmptyFromTicks, EmptyToTicks: walkHint.EmptyToTicks,
PendingEndBound: HistoryBounds.Carry(endBound!, page)! with { DataExhausted = true }));
@@ -10323,13 +10227,13 @@ public sealed class OtOpcUaNodeManager : CustomNodeManager2, INodeManager3, IPro
{
var onlyBound = new List<DataValueSnapshot>(1);
var afterCp = await AppendEndBoundAsync(onlyBound, startUtc, numValuesPerNode).ConfigureAwait(false);
results[handle.Index] = new SdkHistoryReadResult
outcome.Result = new SdkHistoryReadResult
{
StatusCode = StatusCodes.Good,
HistoryData = new ExtensionObject(ToHistoryDataFromSamples(onlyBound)),
ContinuationPoint = afterCp is null ? default : ByteString.From(afterCp),
};
errors[handle.Index] = ServiceResult.Good;
outcome.Error = ServiceResult.Good;
return;
}
@@ -10350,30 +10254,30 @@ public sealed class OtOpcUaNodeManager : CustomNodeManager2, INodeManager3, IPro
if (startBound is not null && numValuesPerNode == 1 && anything)
{
// The page is the start bound alone; the data starts at StartTime on the next page.
var boundOnlyCp = SaveHistoryContinuation(session, handle.NodeId, historyEpoch, new HistoryContinuationState(
var boundOnlyCp = SaveHistoryContinuation(continuations, handle.Realm, handle.Identifier, handle.BindingTag, historyEpoch, details, new HistoryContinuationState(
tagname, startUtc, endUtc, 0, numValuesPerNode, SegmentWidthTicks: walkHint.WidthTicks,
EmptyFromTicks: walkHint.EmptyFromTicks, EmptyToTicks: walkHint.EmptyToTicks,
PendingEndBound: HistoryBounds.Carry(pending, [startBound])));
results[handle.Index] = new SdkHistoryReadResult
outcome.Result = new SdkHistoryReadResult
{
StatusCode = StatusCodes.Good,
HistoryData = new ExtensionObject(ToHistoryDataFromSamples([startBound])),
ContinuationPoint = boundOnlyCp is null ? default : ByteString.From(boundOnlyCp),
};
errors[handle.Index] = ServiceResult.Good;
outcome.Error = ServiceResult.Good;
return;
}
if (startBound is not null && numValuesPerNode == 1)
{
// Nothing at all — no data and no bound found: the pre-bounds GoodNoData answer.
results[handle.Index] = new SdkHistoryReadResult
outcome.Result = new SdkHistoryReadResult
{
StatusCode = StatusCodes.GoodNoData,
HistoryData = new ExtensionObject(ToHistoryDataFromSamples([])),
ContinuationPoint = default,
};
errors[handle.Index] = ServiceResult.Good;
outcome.Error = ServiceResult.Good;
return;
}
@@ -10504,8 +10408,8 @@ public sealed class OtOpcUaNodeManager : CustomNodeManager2, INodeManager3, IPro
"exceeding {Max} (MaxTieClusterOverfetch, or the backend's row ceiling less one); cannot page within it. " +
"Increase MaxTieClusterOverfetch (or the HistorianGateway MaxValuesCeiling).",
startUtc, tagname, cluster.Count, overfetchBound);
errors[handle.Index] = StatusCodes.BadTooManyOperations;
results[handle.Index] = new SdkHistoryReadResult { StatusCode = StatusCodes.BadTooManyOperations };
outcome.Error = StatusCodes.BadTooManyOperations;
outcome.Result = new SdkHistoryReadResult { StatusCode = StatusCodes.BadTooManyOperations };
return;
}
@@ -10537,7 +10441,7 @@ public sealed class OtOpcUaNodeManager : CustomNodeManager2, INodeManager3, IPro
EmptyFromTicks: walkHint.EmptyFromTicks, EmptyToTicks: walkHint.EmptyToTicks,
PendingEndBound: HistoryBounds.Carry(endBound, slice),
WithinTieCluster: resumeAt == startUtc);
clusterCp = SaveHistoryContinuation(session, handle.NodeId, historyEpoch, clusterState);
clusterCp = SaveHistoryContinuation(continuations, handle.Realm, handle.Identifier, handle.BindingTag, historyEpoch, details, clusterState);
}
else if (endBound is not null)
{
@@ -10549,13 +10453,13 @@ public sealed class OtOpcUaNodeManager : CustomNodeManager2, INodeManager3, IPro
clusterCp = await AppendEndBoundAsync(slice, startUtc, clusterAllowance).ConfigureAwait(false);
}
results[handle.Index] = new SdkHistoryReadResult
outcome.Result = new SdkHistoryReadResult
{
StatusCode = slice.Count == 0 ? StatusCodes.GoodNoData : StatusCodes.Good,
HistoryData = new ExtensionObject(ToHistoryDataFromSamples(slice)),
ContinuationPoint = clusterCp is null ? default : ByteString.From(clusterCp),
};
errors[handle.Index] = ServiceResult.Good;
outcome.Error = ServiceResult.Good;
return;
}
@@ -10592,7 +10496,7 @@ public sealed class OtOpcUaNodeManager : CustomNodeManager2, INodeManager3, IPro
{
// Save may return null (no session on this request) ⇒ degrade to single-shot for this node.
// Built AFTER historyData so a failure projecting samples can never orphan a stored cursor.
outboundCp = SaveHistoryContinuation(session, handle.NodeId, historyEpoch, nextState);
outboundCp = SaveHistoryContinuation(continuations, handle.Realm, handle.Identifier, handle.BindingTag, historyEpoch, details, nextState);
}
else if (endBound is not null)
{
@@ -10615,7 +10519,7 @@ public sealed class OtOpcUaNodeManager : CustomNodeManager2, INodeManager3, IPro
historyData = ToHistoryDataFromSamples(samples);
}
results[handle.Index] = new SdkHistoryReadResult
outcome.Result = new SdkHistoryReadResult
{
// No samples ⇒ GoodNoData (the node is historized, the window just held no data). With the
// degenerate-cluster guard above, a resumed empty page now only means the window/cluster is
@@ -10624,28 +10528,28 @@ public sealed class OtOpcUaNodeManager : CustomNodeManager2, INodeManager3, IPro
HistoryData = new ExtensionObject(historyData),
ContinuationPoint = outboundCp is null ? default : ByteString.From(outboundCp),
};
errors[handle.Index] = ServiceResult.Good;
outcome.Error = ServiceResult.Good;
}
catch (OperationCanceledException)
{
// The per-request deadline elapsed while paging this node — BadTimeout for THIS node only.
errors[handle.Index] = StatusCodes.BadTimeout;
results[handle.Index] = new SdkHistoryReadResult { StatusCode = StatusCodes.BadTimeout };
outcome.Error = StatusCodes.BadTimeout;
outcome.Result = new SdkHistoryReadResult { StatusCode = StatusCodes.BadTimeout };
}
catch (HistoryReadLimitExceededException ex)
{
// A request limit (a reverse read walked back from forward reads met a tie cluster over the row
// budget) — BadTooManyOperations for THIS node, as on the processed path; not a backend fault.
_logger.LogWarning("OtOpcUaNodeManager: HistoryReadRaw limit exceeded for node {NodeId}: {Message}", handle.NodeId, ex.Message);
errors[handle.Index] = StatusCodes.BadTooManyOperations;
results[handle.Index] = new SdkHistoryReadResult { StatusCode = StatusCodes.BadTooManyOperations };
_logger.LogWarning("OtOpcUaNodeManager: HistoryReadRaw limit exceeded for node {NodeId}: {Message}", handle.LogNodeId, ex.Message);
outcome.Error = StatusCodes.BadTooManyOperations;
outcome.Result = new SdkHistoryReadResult { StatusCode = StatusCodes.BadTooManyOperations };
}
catch (Exception ex)
{
// One node's backend failure must not throw out of the batch — Bad for THIS node only.
_logger.LogError(ex, "OtOpcUaNodeManager: HistoryReadRaw (paged) failed for node {NodeId}", handle.NodeId);
errors[handle.Index] = HistoryReadFailureStatus(ex);
results[handle.Index] = new SdkHistoryReadResult { StatusCode = HistoryReadFailureStatus(ex) };
_logger.LogError(ex, "OtOpcUaNodeManager: HistoryReadRaw (paged) failed for node {NodeId}", handle.LogNodeId);
outcome.Error = HistoryReadFailureStatus(ex);
outcome.Result = new SdkHistoryReadResult { StatusCode = HistoryReadFailureStatus(ex) };
}
}
@@ -10659,34 +10563,32 @@ public sealed class OtOpcUaNodeManager : CustomNodeManager2, INodeManager3, IPro
/// point is <c>BadContinuationPointInvalid</c>. A backend that keeps no trail (Gateway, Null) throws
/// <see cref="NotSupportedException"/> ⇒ <c>BadHistoryOperationUnsupported</c> for this node.
/// </summary>
/// <param name="handle">The node handle; <c>handle.Index</c> indexes results/errors.</param>
/// <param name="session">The session (null on the session-less in-process path ⇒ single-shot).</param>
/// <param name="nodesToRead">The per-node read list (inbound continuation points).</param>
/// <param name="results">The service-level results list.</param>
/// <param name="errors">The service-level errors list.</param>
/// <param name="handle">The history-port item (inbound continuation point included).</param>
/// <param name="outcome">The item's outcome to fill.</param>
/// <param name="continuations">The caller's continuation scope (a session-less scope ⇒ single-shot).</param>
/// <param name="details">The request details, bound into a peer continuation.</param>
/// <param name="startTimeUtc">Request StartTime.</param>
/// <param name="endUtc">Request EndTime.</param>
/// <param name="numValuesPerNode">Per-page cap; <c>0</c> = all.</param>
/// <param name="ct">Request deadline.</param>
private async Task ServeModifiedPagedAsync(
NodeHandle handle,
ISession? session,
ArrayOf<HistoryReadValueId> nodesToRead,
IList<SdkHistoryReadResult> results,
IList<ServiceResult> errors,
HistoryReadPortItem handle,
HistoryReadNodeOutcome outcome,
IHistoryContinuationScope continuations,
HistoryReadVariant details,
DateTime startTimeUtc,
DateTime endUtc,
uint numValuesPerNode,
CancellationToken ct)
{
var historyEpoch = Volatile.Read(ref _historyContinuationEpoch);
var inboundCp = nodesToRead[handle.Index].ContinuationPoint;
var inboundCp = handle.ContinuationPoint;
try
{
if (!TryGetHistorizedTagname(handle.NodeId, out var tagname) || tagname is null)
if (!TryGetHistorizedTagname(handle.Identifier, out var tagname, handle.Realm) || tagname is null)
{
errors[handle.Index] = StatusCodes.BadHistoryOperationUnsupported;
results[handle.Index] = new SdkHistoryReadResult { StatusCode = StatusCodes.BadHistoryOperationUnsupported };
outcome.Error = StatusCodes.BadHistoryOperationUnsupported;
outcome.Result = new SdkHistoryReadResult { StatusCode = StatusCodes.BadHistoryOperationUnsupported };
return;
}
@@ -10694,11 +10596,11 @@ public sealed class OtOpcUaNodeManager : CustomNodeManager2, INodeManager3, IPro
HistoryModifiedCursor? resumeAfter = null;
if (inboundCp is { Length: > 0 })
{
var state = _historyContinuationStore.TryTake(session, inboundCp.ToArray());
if (state is null || !HistoryContinuationMatches(state, handle.NodeId, historyEpoch) || state.Kind != HistoryCursorKind.Modified || state.Tagname != tagname)
var state = continuations.TryTake(inboundCp, new HistoryContinuationBinding(handle.Realm, handle.Identifier, historyEpoch, details, handle.BindingTag));
if (state is null || !HistoryContinuationMatches(state, handle.Realm, handle.Identifier, handle.BindingTag, historyEpoch) || state.Kind != HistoryCursorKind.Modified || state.Tagname != tagname)
{
errors[handle.Index] = StatusCodes.BadContinuationPointInvalid;
results[handle.Index] = new SdkHistoryReadResult { StatusCode = StatusCodes.BadContinuationPointInvalid };
outcome.Error = StatusCodes.BadContinuationPointInvalid;
outcome.Result = new SdkHistoryReadResult { StatusCode = StatusCodes.BadContinuationPointInvalid };
return;
}
@@ -10725,36 +10627,36 @@ public sealed class OtOpcUaNodeManager : CustomNodeManager2, INodeManager3, IPro
if (page.HasMore && numValuesPerNode > 0 && page.Values.Count > 0)
{
var last = page.Values[^1];
outboundCp = SaveHistoryContinuation(session, handle.NodeId, historyEpoch, new HistoryContinuationState(
outboundCp = SaveHistoryContinuation(continuations, handle.Realm, handle.Identifier, handle.BindingTag, historyEpoch, details, new HistoryContinuationState(
tagname, last.SourceTimeUtc, endUtc, 0, numValuesPerNode,
HistoryCursorKind.Modified, last.ModifiedId, startUtc));
}
results[handle.Index] = new SdkHistoryReadResult
outcome.Result = new SdkHistoryReadResult
{
StatusCode = page.Values.Count == 0 ? StatusCodes.GoodNoData : StatusCodes.Good,
HistoryData = new ExtensionObject(data),
ContinuationPoint = outboundCp is null ? default : ByteString.From(outboundCp),
};
errors[handle.Index] = ServiceResult.Good;
outcome.Error = ServiceResult.Good;
}
catch (OperationCanceledException)
{
errors[handle.Index] = StatusCodes.BadTimeout;
results[handle.Index] = new SdkHistoryReadResult { StatusCode = StatusCodes.BadTimeout };
outcome.Error = StatusCodes.BadTimeout;
outcome.Result = new SdkHistoryReadResult { StatusCode = StatusCodes.BadTimeout };
}
catch (NotSupportedException ex)
{
// The backend keeps no modification trail (Gateway / Null) — the spec status, not a server fault.
_logger.LogDebug(ex, "OtOpcUaNodeManager: backend serves no modified-value history for node {NodeId}", handle.NodeId);
errors[handle.Index] = StatusCodes.BadHistoryOperationUnsupported;
results[handle.Index] = new SdkHistoryReadResult { StatusCode = StatusCodes.BadHistoryOperationUnsupported };
_logger.LogDebug(ex, "OtOpcUaNodeManager: backend serves no modified-value history for node {NodeId}", handle.LogNodeId);
outcome.Error = StatusCodes.BadHistoryOperationUnsupported;
outcome.Result = new SdkHistoryReadResult { StatusCode = StatusCodes.BadHistoryOperationUnsupported };
}
catch (Exception ex)
{
_logger.LogError(ex, "OtOpcUaNodeManager: HistoryRead (modified) failed for node {NodeId}", handle.NodeId);
errors[handle.Index] = HistoryReadFailureStatus(ex);
results[handle.Index] = new SdkHistoryReadResult { StatusCode = HistoryReadFailureStatus(ex) };
_logger.LogError(ex, "OtOpcUaNodeManager: HistoryRead (modified) failed for node {NodeId}", handle.LogNodeId);
outcome.Error = HistoryReadFailureStatus(ex);
outcome.Result = new SdkHistoryReadResult { StatusCode = HistoryReadFailureStatus(ex) };
}
}
@@ -10803,59 +10705,17 @@ public sealed class OtOpcUaNodeManager : CustomNodeManager2, INodeManager3, IPro
}
}
private byte[]? SaveHistoryContinuation(ISession? session, NodeId nodeId, long epoch, HistoryContinuationState state)
{
if (epoch != Volatile.Read(ref _historyContinuationEpoch)) return null;
return _historyContinuationStore.Save(session, state with
{
BoundNodeKey = nodeId.ToString(), AddressSpaceEpoch = epoch,
});
}
private static bool HistoryContinuationMatches(HistoryContinuationState state, NodeId nodeId, long epoch) =>
state.BoundNodeKey == nodeId.ToString() && state.AddressSpaceEpoch == epoch;
/// <summary>Transport failures are retryable; unsupported operations retain their distinct status.</summary>
private static StatusCode HistoryReadFailureStatus(Exception error)
{
// A miswired peer continuation scope (H1/H2) is a server fault, never "this node has no history".
if (error is PeerHistoryContinuationWiringException) return StatusCodes.BadInternalError;
for (Exception? ex = error; ex is not null; ex = ex.InnerException)
if (ex is System.IO.IOException or System.Net.Sockets.SocketException or System.Net.Http.HttpRequestException or TimeoutException)
return StatusCodes.BadNoCommunication;
return StatusCodes.BadHistoryOperationUnsupported;
}
/// <summary>Normalize stored and AtTime history to each scalar node's declared DataType.</summary>
private void NormalizeHistoryValues(List<NodeHandle> handles, IList<SdkHistoryReadResult> results)
{
foreach (var handle in handles)
{
if (AtTimeValueType(handle.NodeId) is not { } type || results[handle.Index]?.HistoryData is not { } body) continue;
if (body.IsNull || ExtensionObject.ToEncodeable(body) is not HistoryData data) continue;
var values = data.DataValues.ToArray() ?? [];
for (var i = 0; i < values.Length; i++)
{
var value = values[i];
var payload = SdkValueBoundary.ToClr(value.WrappedValue);
if (payload is null) continue;
try
{
// A gateway number cannot reconstruct a DateTime or a String which was never stored.
if ((type == TypeCode.DateTime && payload is not DateTime)
|| (type == TypeCode.String && payload is not string)) throw new InvalidCastException();
var converted = Convert.ChangeType(payload, type, System.Globalization.CultureInfo.InvariantCulture);
if (converted is float f && float.IsInfinity(f) && payload is double d && double.IsFinite(d))
throw new OverflowException();
values[i] = value.WithWrappedValue(SdkValueBoundary.FromClr(converted));
}
catch (Exception ex) when (ex is InvalidCastException or OverflowException or FormatException)
{
values[i] = value.WithWrappedValue(Variant.Null).WithStatus(StatusCodes.BadTypeMismatch);
}
}
data.DataValues = values;
}
}
/// <summary>Project a plain sample list into an SDK <see cref="HistoryData"/> (the paged Raw path
/// works on a trimmed <see cref="IReadOnlyList{T}"/> rather than a whole <see cref="HistorianRead"/>).</summary>
/// <param name="samples">The samples to project (already trimmed of boundary duplicates).</param>
@@ -0,0 +1,286 @@
using System.Security.Cryptography;
using ZB.MOM.WW.OtOpcUa.Commons.OpcUa;
namespace ZB.MOM.WW.OtOpcUa.OpcUaServer;
/// <summary>
/// Everything a peer continuation is bound to (plan §3.2): the authenticated principal, the serving incarnation
/// (an origin restart or failover changes it), the history epoch (a rebuild/removal bumps it), the view
/// <c>(realm, identifier)</c> and the hash of the request details.
/// </summary>
/// <param name="Principal">The authenticated principal of the connection.</param>
/// <param name="ServingIncarnation">The serving incarnation CURRENT when the cursor was issued (or, on a take, now).</param>
/// <param name="Epoch">The history (address-space) epoch.</param>
/// <param name="Realm">The view's realm.</param>
/// <param name="Identifier">The view's identifier.</param>
/// <param name="BindingTag">The view's binding tag (<see cref="HistoryReadPortItem.BindingTag"/>).</param>
/// <param name="DetailsHash">The <see cref="HistoryReadVariant.ComputeDetailsHash"/> of the request.</param>
internal readonly record struct PeerHistoryContinuationKey(
string Principal, string ServingIncarnation, long Epoch, AddressSpaceRealm Realm, string Identifier, string? BindingTag, string DetailsHash);
/// <summary>
/// The ORIGIN-side store for remote peers' HistoryRead continuation points (gRPC data history plan §3.2, phase H1;
/// wired to the RPC by H2). One instance per (authenticated principal, connection incarnation), so no peer can ever
/// reach another's cursors (H2 must <see cref="Clear"/> it when the connection closes); unlike the SDK session store (<see cref="SessionHistoryContinuationStore"/>) there is no
/// session to own the points, so this store owns lifetime itself.
/// <list type="bullet">
/// <item><b>Token:</b> a fresh random 16-byte id (<see cref="RandomNumberGenerator"/>). Unguessable, so no MAC is needed; it
/// carries nothing — the state stays here.</item>
/// <item><b>Binding:</b> each record binds the CALLER's principal and the serving incarnation current at save (both
/// supplied by the caller — <see cref="PeerHistoryContinuationScope"/> reads the incarnation live, so an in-process
/// failover or role change on a still-open connection invalidates its tokens), the history epoch, the view and the
/// details hash; a take whose expected <see cref="PeerHistoryContinuationKey"/> differs in ANY of them is a miss
/// (<c>BadContinuationPointInvalid</c> at the port). A save for a principal other than the owner is refused.</item>
/// <item><b>Single-use:</b> a take removes the record whether or not it matches, so a page lost in transit makes the
/// client's resume fail rather than silently skipping a page, and a token can never be replayed.</item>
/// <item><b>Idle expiry:</b> a record not taken within <see cref="IdleExpiry"/> (default 60 s, matching v1 browse
/// continuations) is gone — the backstop for a consumer that never resumes or releases.</item>
/// <item><b>Capacity:</b> at most <see cref="Capacity"/> live records (the export limit). Saving past it evicts the
/// <b>oldest-idle</b> record — the one saved longest ago, since a record is never touched between its save and its
/// (single-use) take — after expired ones are swept. Eviction is silent; the evicted token's resume is a miss.</item>
/// </list>
/// Thread-safe; every operation is O(1) amortised under one short lock, and no I/O ever runs under it.
/// </summary>
internal sealed class PeerHistoryContinuationStore
{
/// <summary>The default idle expiry (60 s, as v1 browse continuations).</summary>
public static readonly TimeSpan DefaultIdleExpiry = TimeSpan.FromSeconds(60);
/// <summary>The token length in bytes.</summary>
public const int TokenLength = 16;
private readonly Lock _gate = new();
private readonly Dictionary<Guid, LinkedListNode<Entry>> _entries = new();
private readonly LinkedList<Entry> _byAge = new(); // oldest save first == oldest idle first
private readonly TimeProvider _clock;
/// <summary>Creates the store of one (principal, connection incarnation).</summary>
/// <param name="principal">The authenticated principal that owns the connection.</param>
/// <param name="connectionIncarnation">The connection's own incarnation (identity only; never a binding).</param>
/// <param name="capacity">The export limit on concurrent continuations (≥ 1).</param>
/// <param name="idleExpiry">Idle expiry; null = <see cref="DefaultIdleExpiry"/>. Must be positive.</param>
/// <param name="clock">Clock (tests inject a fake); null = system.</param>
public PeerHistoryContinuationStore(
string principal, string connectionIncarnation, int capacity, TimeSpan? idleExpiry = null, TimeProvider? clock = null)
{
ArgumentException.ThrowIfNullOrWhiteSpace(principal);
ArgumentException.ThrowIfNullOrWhiteSpace(connectionIncarnation);
ArgumentOutOfRangeException.ThrowIfLessThan(capacity, 1);
var idle = idleExpiry ?? DefaultIdleExpiry;
ArgumentOutOfRangeException.ThrowIfLessThanOrEqual(idle, TimeSpan.Zero, nameof(idleExpiry));
Principal = principal;
ConnectionIncarnation = connectionIncarnation;
Capacity = capacity;
IdleExpiry = idle;
_clock = clock ?? TimeProvider.System;
}
/// <summary>The principal this instance serves.</summary>
public string Principal { get; }
/// <summary>
/// The connection's incarnation — IDENTITY ONLY (which connection this store belongs to, for diagnostics and H2's
/// per-connection bookkeeping). It is never part of a binding: the serving incarnation a cursor binds is supplied per
/// request by <see cref="PeerHistoryContinuationScope"/>.
/// </summary>
public string ConnectionIncarnation { get; }
/// <summary>The most live records.</summary>
public int Capacity { get; }
/// <summary>How long an untaken record lives.</summary>
public TimeSpan IdleExpiry { get; }
/// <summary>Live (unexpired) records — H3's "origin store count returns to 0" check reads it.</summary>
public int Count
{
get
{
lock (_gate)
{
Sweep(_clock.GetTimestamp());
return _entries.Count;
}
}
}
/// <summary>
/// Stores <paramref name="state"/> under a fresh token, bound to the calling <paramref name="principal"/>, the
/// <paramref name="servingIncarnation"/> current now, the state's own epoch and view
/// (<see cref="HistoryContinuationState.BoundRealm"/> / <see cref="HistoryContinuationState.BoundIdentifier"/>, set by
/// the port) and <paramref name="detailsHash"/>.
/// </summary>
/// <param name="state">The bound resume state.</param>
/// <param name="principal">The caller's authenticated principal; must be this store's owner.</param>
/// <param name="servingIncarnation">The serving incarnation current at save.</param>
/// <param name="detailsHash">The request's details hash.</param>
/// <returns>The 16-byte token.</returns>
/// <exception cref="ArgumentException">An unbound state.</exception>
/// <exception cref="PeerHistoryContinuationWiringException">A principal other than the owner, or a blank incarnation.</exception>
public byte[] Save(HistoryContinuationState state, string principal, string servingIncarnation, string detailsHash)
{
ArgumentNullException.ThrowIfNull(state);
ArgumentNullException.ThrowIfNull(detailsHash);
if (state.BoundIdentifier is null)
throw new ArgumentException("A peer continuation must be bound to its view.", nameof(state));
if (string.IsNullOrWhiteSpace(servingIncarnation))
throw new PeerHistoryContinuationWiringException("A peer continuation needs the serving incarnation it is issued under.");
if (!string.Equals(principal, Principal, StringComparison.Ordinal))
throw new PeerHistoryContinuationWiringException("A peer continuation store holds only its owning principal's cursors.");
var token = RandomNumberGenerator.GetBytes(TokenLength);
var key = new PeerHistoryContinuationKey(
principal, servingIncarnation, state.AddressSpaceEpoch, state.BoundRealm, state.BoundIdentifier, state.BoundTag, detailsHash);
lock (_gate)
{
var now = _clock.GetTimestamp();
Sweep(now);
while (_entries.Count >= Capacity && _byAge.First is { } oldest) Remove(oldest);
var id = new Guid(token);
_entries[id] = _byAge.AddLast(new Entry(id, key, state, now));
}
return token;
}
/// <summary>
/// Takes (removes) the record behind <paramref name="token"/> and returns its state when it is live and every bound
/// field equals <paramref name="expected"/>; otherwise null. The record is consumed either way.
/// </summary>
/// <param name="token">The token the peer handed back.</param>
/// <param name="expected">What the resume must match.</param>
/// <returns>The state, or null (unknown, expired, evicted, malformed or mismatched).</returns>
public HistoryContinuationState? TryTake(byte[]? token, PeerHistoryContinuationKey expected) =>
TryTake(token, () => expected);
/// <summary>
/// <see cref="TryTake(byte[], PeerHistoryContinuationKey)"/> with the expectation computed only AFTER the record is
/// consumed: if <paramref name="expected"/> throws (the incarnation source is down), the token is already gone and the
/// take is a miss — never a token left replayable.
/// </summary>
/// <param name="token">The token the peer handed back.</param>
/// <param name="expected">Computes what the resume must match.</param>
/// <returns>The state, or null.</returns>
public HistoryContinuationState? TryTake(byte[]? token, Func<PeerHistoryContinuationKey> expected)
{
ArgumentNullException.ThrowIfNull(expected);
if (token is not { Length: TokenLength }) return null;
Entry taken;
lock (_gate)
{
var now = _clock.GetTimestamp();
Sweep(now);
if (!_entries.TryGetValue(new Guid(token), out var node)) return null;
Remove(node);
taken = node.Value;
}
try
{
return taken.Key == expected() ? taken.State : null;
}
catch (Exception)
{
return null; // consumed, unverifiable ⇒ a miss (BadContinuationPointInvalid at the port)
}
}
/// <summary>Drops a record without reading it (<c>release_continuations</c>). Idempotent.</summary>
/// <param name="token">The token to release.</param>
/// <returns>Whether a live record was dropped.</returns>
public bool Release(byte[]? token)
{
if (token is not { Length: TokenLength }) return false;
lock (_gate)
{
if (!_entries.TryGetValue(new Guid(token), out var node)) return false;
Remove(node);
return true;
}
}
/// <summary>Drops every record (the connection closed).</summary>
public void Clear()
{
lock (_gate)
{
_entries.Clear();
_byAge.Clear();
}
}
private void Sweep(long now)
{
while (_byAge.First is { } oldest && _clock.GetElapsedTime(oldest.Value.SavedAt, now) >= IdleExpiry) Remove(oldest);
}
private void Remove(LinkedListNode<Entry> node)
{
_entries.Remove(node.Value.Id);
_byAge.Remove(node);
}
private sealed record Entry(Guid Id, PeerHistoryContinuationKey Key, HistoryContinuationState State, long SavedAt);
}
/// <summary>
/// A peer continuation store or scope was wired wrongly — a scope for a principal the store does not belong to, or a
/// serving-incarnation source that is blank or throws. A server fault, not a property of the request: the port answers
/// <c>BadInternalError</c> for the node (never <c>BadHistoryOperationUnsupported</c>), and H2 must surface it distinctly.
/// </summary>
internal sealed class PeerHistoryContinuationWiringException : InvalidOperationException
{
/// <summary>Creates the exception.</summary>
/// <param name="message">What is miswired.</param>
/// <param name="inner">The incarnation source's own failure, if any.</param>
public PeerHistoryContinuationWiringException(string message, Exception? inner = null) : base(message, inner) { }
}
/// <summary>
/// The port's continuation scope for one remote peer's ONE request (create a new scope per <c>ReadHistory</c> call):
/// saves and takes through that peer's <see cref="PeerHistoryContinuationStore"/>, binding the caller's principal, the
/// request's details hash and the serving incarnation, on top of the view and epoch the port itself re-checks.
/// <para>
/// The serving incarnation is read from <paramref name="currentServingIncarnation"/> ONCE, at the scope's first use,
/// and that snapshot is used for every take and save of the request: a request resumed under incarnation A binds its
/// next token to A even when a failover lands mid-request (the resume under B then fails
/// <c>BadContinuationPointInvalid</c>), and a later request reads the then-current incarnation, so an in-process
/// failover or role change on a still-open connection invalidates the connection's tokens. A take whose snapshot
/// cannot be read (blank / throwing source) is a miss with the token consumed; a save is a
/// <see cref="PeerHistoryContinuationWiringException"/>. Save never answers <c>null</c> (that would read as a
/// complete read and truncate).
/// </para>
/// </summary>
/// <param name="store">The (principal, connection) store.</param>
/// <param name="principal">The caller's authenticated principal.</param>
/// <param name="currentServingIncarnation">Reads this server's serving incarnation now.</param>
internal sealed class PeerHistoryContinuationScope(
PeerHistoryContinuationStore store, string principal, Func<string> currentServingIncarnation) : IHistoryContinuationScope
{
private readonly Lazy<string> _incarnation = new(() =>
{
string value;
try
{
value = currentServingIncarnation();
}
catch (Exception ex)
{
throw new PeerHistoryContinuationWiringException("The serving-incarnation source failed.", ex);
}
return string.IsNullOrWhiteSpace(value)
? throw new PeerHistoryContinuationWiringException("The serving-incarnation source answered a blank incarnation.")
: value;
}, LazyThreadSafetyMode.ExecutionAndPublication);
/// <inheritdoc />
public byte[]? Save(HistoryContinuationState state, HistoryContinuationBinding binding) =>
store.Save(state, principal, _incarnation.Value, binding.Details?.ComputeDetailsHash() ?? string.Empty);
/// <inheritdoc />
public HistoryContinuationState? TryTake(byte[] continuationPoint, HistoryContinuationBinding binding) =>
store.TryTake(continuationPoint, () => new PeerHistoryContinuationKey(
principal, _incarnation.Value, binding.Epoch, binding.Realm, binding.Identifier, binding.Tag,
binding.Details?.ComputeDetailsHash() ?? string.Empty));
}
@@ -0,0 +1,59 @@
using Shouldly;
using Xunit;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections;
namespace ZB.MOM.WW.OtOpcUa.Core.Abstractions.Tests.DataConnections;
/// <summary>H1: the SDK-free remote-history contract H2 implements on the origin side.</summary>
[Trait("Category", "Unit"), Trait("Feature", "GrpcData"), Trait("Phase", "H1")]
public sealed class GrpcDataHistoryContractTests
{
[Fact]
public void The_contract_lives_in_the_data_connection_namespace_and_names_no_sdk_type()
{
var types = new[]
{
typeof(IDataHistoryService), typeof(DataHistoryDetails), typeof(DataHistoryRawDetails), typeof(DataHistoryProcessedDetails),
typeof(DataHistoryAtTimeDetails), typeof(DataAggregateConfiguration), typeof(DataHistoryReadItem),
typeof(DataHistoryReadRequest), typeof(DataHistorySample), typeof(DataHistoryReadResult),
};
foreach (var type in types)
{
type.Namespace.ShouldBe("ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections");
type.IsPublic.ShouldBeTrue(type.Name);
var referenced = type.GetProperties().Select(p => p.PropertyType)
.Concat(type.GetMethods().SelectMany(m => m.GetParameters().Select(p => p.ParameterType).Append(m.ReturnType)));
referenced.ShouldAllBe(t => t.Namespace == null || !t.Namespace.StartsWith("Opc.", StringComparison.Ordinal), type.Name);
}
typeof(DataHistoryDetails).IsAbstract.ShouldBeTrue();
typeof(DataHistoryRawDetails).BaseType.ShouldBe(typeof(DataHistoryDetails));
typeof(DataHistoryProcessedDetails).BaseType.ShouldBe(typeof(DataHistoryDetails));
typeof(DataHistoryAtTimeDetails).BaseType.ShouldBe(typeof(DataHistoryDetails));
}
[Fact]
public void Unset_bounds_are_absent_not_MinValue_and_statuses_are_full_uint32()
{
// §3.3: the origin's end-only / open-end rules depend on "absent", so the contract cannot spell it MinValue.
typeof(DataHistoryRawDetails).GetProperty(nameof(DataHistoryRawDetails.StartUtc))!.PropertyType.ShouldBe(typeof(DateTimeOffset?));
typeof(DataHistoryRawDetails).GetProperty(nameof(DataHistoryRawDetails.EndUtc))!.PropertyType.ShouldBe(typeof(DateTimeOffset?));
typeof(DataHistoryProcessedDetails).GetProperty(nameof(DataHistoryProcessedDetails.StartUtc))!.PropertyType.ShouldBe(typeof(DateTimeOffset?));
typeof(DataHistorySample).GetProperty(nameof(DataHistorySample.SourceTimestampUtc))!.PropertyType.ShouldBe(typeof(DateTimeOffset?));
typeof(DataHistoryReadResult).GetProperty(nameof(DataHistoryReadResult.StatusCode))!.PropertyType.ShouldBe(typeof(uint));
typeof(DataHistorySample).GetProperty(nameof(DataHistorySample.StatusCode))!.PropertyType.ShouldBe(typeof(uint));
var endOnly = new DataHistoryRawDetails(null, DateTimeOffset.UnixEpoch, 5, ReturnBounds: false);
endOnly.StartUtc.ShouldBeNull();
}
[Fact]
public void A_result_owns_and_disposes_its_samples()
{
var value = DataValue.FromScalar(DataValueKind.Double, 1.5);
var result = new DataHistoryReadResult("c1", 0x00A50000u,
[new DataHistorySample(value, 0x00000000u, DateTimeOffset.UnixEpoch, null)], Continuation: null);
result.Dispose();
Should.Throw<ObjectDisposedException>(() => value.GetScalar());
}
}
@@ -0,0 +1,309 @@
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using Microsoft.Extensions.Logging.Abstractions;
using Opc.Ua;
using Opc.Ua.Security.Certificates;
using Opc.Ua.Server;
using Shouldly;
using Xunit;
using ZB.MOM.WW.OtOpcUa.Commons.OpcUa;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions;
using HistorianRead = ZB.MOM.WW.OtOpcUa.Core.Abstractions.HistoryReadResult;
using SdkHistoryReadResult = Opc.Ua.HistoryReadResult;
namespace ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests;
/// <summary>
/// H1 (review 7): the port's process-wide batch limiter, its per-request deadline and request cancellation, and paging
/// against the REAL SDK session-backed continuation store. Each case boots its own server, because the batch limiter is
/// sized once per node manager at first use.
/// </summary>
[Trait("Feature", "GrpcData")]
[Trait("Phase", "H1")]
public sealed class HistoryReadPortLimiterAndSessionTests : IAsyncDisposable
{
private static readonly DateTime T0 = new(2026, 3, 1, 10, 0, 0, DateTimeKind.Utc);
private readonly string _pki = Path.Combine(Path.GetTempPath(), $"otopcua-histport-limit-{Guid.NewGuid():N}");
private OpcUaApplicationHost? _host;
[Fact]
public async Task A_saturated_limiter_fails_every_node_of_the_waiting_batch_on_both_paths()
{
var (server, nm) = await BootAsync();
nm.MaxConcurrentHistoryReadBatches = 1;
// The holder runs with NO deadline (it is captured when its batch starts), so it holds the slot until released,
// whatever the machine's speed; the waiting batches then get a short deadline, so their admission wait is short.
nm.HistoryReadDeadline = TimeSpan.Zero;
var source = new GatedSource();
nm.HistorianDataSource = source;
var nodeId = Add(nm, "lim/a", "P.a");
Add(nm, "lim/b", "P.b");
var details = new HistoryReadRawVariant(T0, T0.AddHours(1), 5, ReturnBounds: false);
var scope = nm.SessionHistoryContinuationScope(session: null);
// Batch A holds the only slot inside the backend.
var holder = Task.Run(() => nm.ReadHistory(details, [new HistoryReadPortItem(AddressSpaceRealm.Uns, "lim/a")], scope, CancellationToken.None));
await source.Entered.Task.WaitAsync(TimeSpan.FromSeconds(10), TestContext.Current.CancellationToken);
nm.HistoryReadDeadline = TimeSpan.FromMilliseconds(300); // admission waits min(deadline, 5 s)
var waiting = nm.ReadHistory(details,
[new HistoryReadPortItem(AddressSpaceRealm.Uns, "lim/a"), new HistoryReadPortItem(AddressSpaceRealm.Uns, "lim/b")],
scope, CancellationToken.None);
waiting.ShouldAllBe(o => o.Error!.StatusCode == StatusCodes.BadTooManyOperations
&& o.Result!.StatusCode == StatusCodes.BadTooManyOperations);
source.Calls.ShouldBe(1, "the rejected batch never reached the backend");
// The SDK override path shares the same limiter.
var context = new OperationContext(new RequestHeader(), secureChannelContext: null, RequestType.HistoryRead,
requestLifetime: RequestLifetime.None, identity: null);
var results = new List<SdkHistoryReadResult> { null! };
var errors = new List<ServiceResult> { null! };
nm.HistoryRead(context, new ReadRawModifiedDetails { StartTime = T0, EndTime = T0.AddHours(1), NumValuesPerNode = 5, ReturnBounds = false, IsReadModified = false },
TimestampsToReturn.Both, false, new List<HistoryReadValueId> { new() { NodeId = nodeId } }, results, errors);
errors[0].StatusCode.Code.ShouldBe(StatusCodes.BadTooManyOperations.Code);
results[0].StatusCode.Code.ShouldBe(StatusCodes.BadTooManyOperations.Code);
source.Release.SetResult();
var held = await holder.WaitAsync(TimeSpan.FromSeconds(10), TestContext.Current.CancellationToken);
held.Single().Error!.StatusCode.Code.ShouldBe(StatusCodes.Good.Code, "the slot holder completes normally");
}
[Fact]
public async Task The_deadline_and_request_cancellation_time_out_each_in_flight_node()
{
var (_, nm) = await BootAsync();
nm.HistorianDataSource = new GatedSource { HonourCancellation = true };
Add(nm, "dl/a", "P.a");
var scope = nm.SessionHistoryContinuationScope(session: null);
HistoryReadVariant[] variants =
[
new HistoryReadRawVariant(T0, T0.AddHours(1), 5, ReturnBounds: false),
new HistoryReadAtTimeVariant([T0]),
new HistoryReadProcessedVariant(T0, T0.AddHours(1), TimeSpan.FromMinutes(10), null),
];
var item = new HistoryReadPortItem(AddressSpaceRealm.Uns, "dl/a",
AggregateType: ObjectIds.AggregateFunction_Average);
// The application deadline.
nm.HistoryReadDeadline = TimeSpan.FromMilliseconds(200);
foreach (var variant in variants)
{
var o = nm.ReadHistory(variant, [item], scope, CancellationToken.None).Single();
o.Error!.StatusCode.Code.ShouldBe(StatusCodes.BadTimeout.Code, variant.GetType().Name);
o.Result!.StatusCode.Code.ShouldBe(StatusCodes.BadTimeout.Code);
}
// The caller's own cancellation (H2's per-node deadline rides it), with no application deadline.
nm.HistoryReadDeadline = TimeSpan.Zero;
foreach (var variant in variants)
{
using var cts = new CancellationTokenSource(TimeSpan.FromMilliseconds(200));
var o = nm.ReadHistory(variant, [item], scope, cts.Token).Single();
o.Error!.StatusCode.Code.ShouldBe(StatusCodes.BadTimeout.Code, variant.GetType().Name);
o.Result!.StatusCode.Code.ShouldBe(StatusCodes.BadTimeout.Code, variant.GetType().Name);
}
}
[Fact]
public async Task The_port_pages_through_the_real_session_backed_store()
{
var (server, nm) = await BootAsync();
nm.HistoryContinuationStore = new SessionHistoryContinuationStore();
var source = new GatedSource { Opened = true };
source.Series.AddRange(Enumerable.Range(0, 7).Select(i => new DataValueSnapshot((double)i, 0, T0.AddSeconds(i), T0.AddSeconds(i))));
nm.HistorianDataSource = source;
Add(nm, "sess/a", "P.a");
var details = new HistoryReadRawVariant(T0, T0.AddHours(1), 2, ReturnBounds: false);
var item = new HistoryReadPortItem(AddressSpaceRealm.Uns, "sess/a");
using var certificateKey = RSA.Create(2048);
using var certificate = Certificate.From(new CertificateRequest("CN=H1.Port.Session", certificateKey, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1)
.CreateSelfSigned(DateTimeOffset.UtcNow.AddDays(-1), DateTimeOffset.UtcNow.AddDays(1)));
using var nonce = Nonce.CreateNonce(32);
using var session = NewSession(server, certificate, nonce);
using var other = NewSession(server, certificate, nonce);
var scope = nm.SessionHistoryContinuationScope(session);
var values = new List<double>();
byte[]? cp = null;
byte[]? firstCp = null;
do
{
var o = nm.ReadHistory(details, [item with { ContinuationPoint = cp }], scope, CancellationToken.None).Single();
o.Error!.StatusCode.Code.ShouldBe(StatusCodes.Good.Code);
values.AddRange(o.Values.Select(v => (double)SdkValueBoundary.ToClr(v.WrappedValue)!));
cp = o.ContinuationPoint;
firstCp ??= cp;
}
while (cp is not null);
values.ShouldBe([0, 1, 2, 3, 4, 5, 6]);
// Session-store semantics: single-use, and a point is never visible to another session.
nm.ReadHistory(details, [item with { ContinuationPoint = firstCp }], scope, CancellationToken.None).Single()
.Status.Code.ShouldBe(StatusCodes.BadContinuationPointInvalid.Code);
var fresh = nm.ReadHistory(details, [item], scope, CancellationToken.None).Single().ContinuationPoint!;
nm.ReadHistory(details, [item with { ContinuationPoint = fresh }], nm.SessionHistoryContinuationScope(other), CancellationToken.None).Single()
.Status.Code.ShouldBe(StatusCodes.BadContinuationPointInvalid.Code);
// With no session there is nowhere to keep a cursor: the read degrades to single-shot, as before.
nm.ReadHistory(details, [item], nm.SessionHistoryContinuationScope(session: null), CancellationToken.None).Single()
.ContinuationPoint.ShouldBeNull();
}
[Fact]
public async Task The_override_pages_and_resumes_through_the_real_session_store_with_a_real_session()
{
var (server, nm) = await BootAsync();
nm.HistoryContinuationStore = new SessionHistoryContinuationStore();
var source = new GatedSource { Opened = true };
source.Series.AddRange(Enumerable.Range(0, 7).Select(i => new DataValueSnapshot((double)i, 0, T0.AddSeconds(i), T0.AddSeconds(i))));
nm.HistorianDataSource = source;
var nodeId = Add(nm, "sess/o", "P.o");
using var certificateKey = RSA.Create(2048);
using var certificate = Certificate.From(new CertificateRequest("CN=H1.Override.Session", certificateKey, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1)
.CreateSelfSigned(DateTimeOffset.UtcNow.AddDays(-1), DateTimeOffset.UtcNow.AddDays(1)));
using var nonce = Nonce.CreateNonce(32);
using var session = NewSession(server, certificate, nonce);
using var other = NewSession(server, certificate, nonce);
(uint Error, List<double> Values, byte[]? Cp) Read(ISession s, byte[]? cp)
{
var context = new OperationContext(new RequestHeader(), null!, RequestType.HistoryRead, RequestLifetime.None, s);
var results = new List<SdkHistoryReadResult> { null! };
var errors = new List<ServiceResult> { null! };
nm.HistoryRead(context,
new ReadRawModifiedDetails { StartTime = T0, EndTime = T0.AddHours(1), NumValuesPerNode = 2, ReturnBounds = false, IsReadModified = false },
TimestampsToReturn.Both, false, new List<HistoryReadValueId> { new() { NodeId = nodeId, ContinuationPoint = ByteString.From(cp) } },
results, errors);
var values = results[0]?.HistoryData is { IsNull: false } body && ExtensionObject.ToEncodeable(body) is HistoryData data
? (data.DataValues.ToArray() ?? []).Select(v => (double)SdkValueBoundary.ToClr(v.WrappedValue)!).ToList()
: [];
return (errors[0].StatusCode.Code, values, results[0]?.ContinuationPoint.ToNullableArray());
}
var collected = new List<double>();
byte[]? cp = null;
var pages = 0;
do
{
var (error, values, next) = Read(session, cp);
error.ShouldBe(StatusCodes.Good.Code);
collected.AddRange(values);
cp = next;
pages++;
}
while (cp is not null && pages < 20);
collected.ShouldBe([0, 1, 2, 3, 4, 5, 6]);
pages.ShouldBe(4, "N = 2 over 7 values: four pages, the session store holding each cursor in between");
// An override-issued cursor lives in the SDK session: another session cannot resume it, a reuse is a miss, and the
// port resumes it through the same session with the adapter's binding tag.
var first = Read(session, null).Cp!;
Read(other, first).Error.ShouldBe(StatusCodes.BadContinuationPointInvalid.Code);
var second = Read(session, null).Cp!;
var viaPort = nm.ReadHistory(new HistoryReadRawVariant(T0, T0.AddHours(1), 2, ReturnBounds: false),
[new HistoryReadPortItem(AddressSpaceRealm.Uns, "sess/o", second, BindingTag: nm.HistoryBindingTag(nodeId))],
nm.SessionHistoryContinuationScope(session), CancellationToken.None).Single();
viaPort.Error!.StatusCode.Code.ShouldBe(StatusCodes.Good.Code);
viaPort.Values.Select(v => (double)SdkValueBoundary.ToClr(v.WrappedValue)!).ShouldBe([2, 3]);
Read(session, second).Error.ShouldBe(StatusCodes.BadContinuationPointInvalid.Code, "single use");
}
private static Session NewSession(OtOpcUaSdkServer server, Certificate certificate, Nonce nonce)
{
var endpoint = new EndpointDescription { EndpointUrl = "opc.tcp://localhost:4840", SecurityMode = MessageSecurityMode.None };
using var context = new OperationContext(new RequestHeader(),
new SecureChannelContext(Guid.NewGuid().ToString(), endpoint, RequestEncoding.Binary),
RequestType.CreateSession, RequestLifetime.None);
return new Session(context, server.CurrentInstance, certificate, new NodeId(Guid.NewGuid()), default,
nonce, "H1 port session", new ApplicationDescription(), endpoint.EndpointUrl, null!, null!, 60_000, 10, 10);
}
private static NodeId Add(OtOpcUaNodeManager nm, string id, string tag)
{
nm.EnsureVariable(id, parentFolderNodeId: null, displayName: id, dataType: "Double", writable: false,
realm: AddressSpaceRealm.Uns, historianTagname: tag);
return nm.TryGetVariable(id)!.NodeId;
}
private async Task<(OtOpcUaSdkServer Server, OtOpcUaNodeManager Nm)> BootAsync()
{
var started = await OpcUaHostStart.StartAsync(
port => new OpcUaApplicationHost(new OpcUaApplicationHostOptions
{
ApplicationName = "OtOpcUa.HistoryPortLimit", ApplicationUri = $"urn:OtOpcUa.HistoryPortLimit:{Guid.NewGuid():N}",
OpcUaPort = port, PublicHostname = "localhost", PkiStoreRoot = _pki,
}, NullLogger<OpcUaApplicationHost>.Instance),
() => new OtOpcUaSdkServer(), TestContext.Current.CancellationToken);
_host = started.Host;
var nm = started.Server.NodeManager!;
nm.HistoryContinuationStore = new InMemoryHistoryContinuationStore();
return (started.Server, nm);
}
public async ValueTask DisposeAsync()
{
if (_host is not null) await _host.DisposeAsync();
if (Directory.Exists(_pki))
{
try { Directory.Delete(_pki, recursive: true); }
catch { /* best-effort */ }
}
}
/// <summary>
/// A backend whose reads block until <see cref="Release"/> (ignoring cancellation, so a slot stays held) — or, with
/// <see cref="HonourCancellation"/>, until the read's token fires; <see cref="Opened"/> answers from
/// <see cref="Series"/> straight away.
/// </summary>
private sealed class GatedSource : IHistorianDataSource
{
private int _calls;
public TaskCompletionSource Entered { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously);
public TaskCompletionSource Release { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously);
public bool HonourCancellation { get; init; }
public bool Opened { get; init; }
public List<DataValueSnapshot> Series { get; } = [];
public int Calls => Volatile.Read(ref _calls);
public bool SupportsReverseRaw => true;
private async Task<HistorianRead> Gate(Func<IReadOnlyList<DataValueSnapshot>> answer, CancellationToken ct)
{
Interlocked.Increment(ref _calls);
if (!Opened)
{
Entered.TrySetResult();
if (HonourCancellation) await Task.Delay(Timeout.Infinite, ct).ConfigureAwait(false);
else await Release.Task.ConfigureAwait(false);
}
await Task.Delay(1, CancellationToken.None).ConfigureAwait(false);
return new HistorianRead(answer(), null);
}
public Task<HistorianRead> ReadRawAsync(
string fullReference, DateTime startUtc, DateTime endUtc, uint maxValuesPerNode, CancellationToken cancellationToken) =>
Gate(() =>
{
var window = Series.Where(s => s.SourceTimestampUtc >= startUtc && s.SourceTimestampUtc < endUtc);
return (maxValuesPerNode == 0 ? window : window.Take((int)maxValuesPerNode)).ToList();
}, cancellationToken);
public Task<HistorianRead> ReadProcessedAsync(
string fullReference, DateTime startUtc, DateTime endUtc, TimeSpan interval,
HistoryAggregateType aggregate, CancellationToken cancellationToken) => Gate(() => [], cancellationToken);
public Task<HistorianRead> ReadAtTimeAsync(
string fullReference, IReadOnlyList<DateTime> timestampsUtc, CancellationToken cancellationToken) =>
Gate(() => [], cancellationToken);
public Task<HistoricalEventsResult> ReadEventsAsync(
string? sourceName, DateTime startUtc, DateTime endUtc, int maxEvents, CancellationToken cancellationToken) =>
Task.FromResult(new HistoricalEventsResult(Array.Empty<HistoricalEvent>(), null));
public HistorianHealthSnapshot GetHealthSnapshot() => NullHistorianDataSource.Instance.GetHealthSnapshot();
public void Dispose() { }
}
}
@@ -0,0 +1,317 @@
using Opc.Ua;
using Opc.Ua.Server;
using Shouldly;
using Xunit;
using ZB.MOM.WW.OtOpcUa.Commons.OpcUa;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions;
using HistorianRead = ZB.MOM.WW.OtOpcUa.Core.Abstractions.HistoryReadResult;
using SdkHistoryReadResult = Opc.Ua.HistoryReadResult;
namespace ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests;
/// <summary>
/// H1: paged-vs-unpaged fuzz THROUGH THE HISTORY PORT (plan §9 H1). Random tie-heavy series (sub-resolution stamps,
/// bursts, gaps, tie clusters), random windows (on a tie, a step past one, between samples; forward, reverse and
/// end-only; with and without bounds), random <c>NumValuesPerNode</c> and an optional backend row ceiling, over three
/// backend shapes (SqlServer: ticks, native reverse; QuestDB: µs truncation, native reverse; Gateway: forward-only,
/// walked back). The concatenated pages must equal the one-shot read, which for a plain read must also equal the
/// series itself; paging must terminate; and on every tenth seed the SDK override path must return the SAME pages,
/// page for page, as the port — the override is an adapter over the port, so any divergence is an adapter defect.
/// <para>
/// Seeds are deterministic (0 … N−1), so a failure names a reproducible seed. Iterations:
/// <c>OTOPCUA_PORT_FUZZ_ITERATIONS</c> (default 10 000, the H1 gate minimum).
/// </para>
/// </summary>
[Trait("Feature", "GrpcData")]
[Trait("Phase", "H1")]
public sealed class HistoryReadPortPagingFuzzTests(HistoryReadPortServerFixture fx) : IClassFixture<HistoryReadPortServerFixture>
{
private static readonly DateTime T0 = new(2026, 10, 22, 12, 0, 0, DateTimeKind.Utc);
private enum Shape { SqlServer, QuestDb, Gateway }
private enum Direction { Forward, Reverse, EndOnly }
private static int Iterations =>
int.TryParse(Environment.GetEnvironmentVariable("OTOPCUA_PORT_FUZZ_ITERATIONS"), out var n) && n > 0 ? n : 10_000;
[Fact]
public async Task Paged_equals_unpaged_through_the_port_on_random_tie_series()
{
var iterations = Iterations;
iterations.ShouldBeGreaterThanOrEqualTo(1);
var counts = new Dictionary<string, int>();
void Count(string key) => counts[key] = counts.GetValueOrDefault(key) + 1;
var (realm, id, nodeId) = fx.Nodes["dbl"];
await fx.Gate.WaitAsync(TestContext.Current.CancellationToken);
try
{
fx.Nm.MaxTieClusterOverfetch = 65536;
for (var seed = 0; seed < iterations; seed++)
{
var rng = new Random(seed);
var shape = (Shape)(seed % 3);
var resolution = shape == Shape.QuestDb ? 10L : 1L;
var series = RandomSeries(rng, resolution);
var n = rng.Next(6) switch { 0 => 1u, 1 => 2u, 2 => 3u, 3 => (uint)rng.Next(4, 12), 4 => 0u, _ => (uint)rng.Next(12, 60) };
var direction = rng.Next(5) switch { 0 => Direction.Reverse, 1 => Direction.EndOnly, _ => Direction.Forward };
if (direction == Direction.EndOnly && n == 0) direction = Direction.Forward; // Part 11: one bound only with a cap
var bounds = direction != Direction.EndOnly && rng.Next(4) == 0;
// A strict row ceiling only on the native shapes (the walk-back's own budget is the raw-cap fuzz's subject).
var ceiling = shape != Shape.Gateway && rng.Next(4) == 0 ? rng.Next(3, 12) : 0;
var a = PickBoundary(rng, series, resolution);
var b = PickBoundary(rng, series, resolution);
var (lo, hi) = a <= b ? (a, b) : (b, a);
var (start, end) = direction switch
{
Direction.Forward => (lo, hi),
Direction.Reverse => (hi, lo),
_ => (DateTime.MinValue, hi),
};
var tag = $"seed {seed} {shape} N {n} ceiling {ceiling} {direction} bounds {bounds} [{start:O} .. {end:O}]";
// The oracle: the port's one-shot answer with no cap and no ceiling (end-only: the explicit reverse to 1970).
fx.Nm.HistoryContinuationStore = new InMemoryHistoryContinuationStore();
fx.Nm.HistorianDataSource = new FuzzSource(series, shape, ceiling: 0);
var oracleDetails = direction == Direction.EndOnly
? new HistoryReadRawVariant(hi, DateTime.UnixEpoch, 0, false)
: new HistoryReadRawVariant(start, end, 0, bounds);
var truth = PortRead(oracleDetails, realm, id, null);
truth.Status.ShouldBe(StatusCodes.Good.Code, $"oracle: {tag}");
truth.Cp.ShouldBeNull($"oracle is one page: {tag}");
if (!bounds) truth.Values.ShouldBe(SeriesOracle(series, start, end, direction, resolution), $"oracle vs series: {tag}");
// The read under test, through the port.
var source = new FuzzSource(series, shape, ceiling);
fx.Nm.HistorianDataSource = source;
var details = new HistoryReadRawVariant(start, end, n, bounds);
var portPages = Page(cp => PortRead(details, realm, id, cp), truth.Values.Count, tag, out var portStatus);
source.ReverseOnForwardOnly.ShouldBe(0, $"a reverse window reached a forward-only backend: {tag}");
if (portStatus == StatusCodes.BadTooManyOperations)
{
// Legitimate only when a tie cluster is too large for the page a ceiling leaves.
(ceiling > 0 && LargestTieCluster(series, resolution) >= ceiling - 1).ShouldBeTrue($"refused without an oversized tie cluster: {tag}");
Count("refused");
}
else
{
portStatus.ShouldBe(StatusCodes.Good.Code, tag);
string.Join(" | ", portPages.SelectMany(p => p)).ShouldBe(string.Join(" | ", truth.Values), $"paged ≠ unpaged: {tag}");
if (n > 0) portPages.ShouldAllBe(p => p.Count <= n, $"a page over N (bounds count toward it, #736): {tag}");
Count("exact");
}
// Every tenth seed: the SDK override path returns the same pages as the port.
if (seed % 10 == 0)
{
fx.Nm.HistoryContinuationStore = new InMemoryHistoryContinuationStore();
fx.Nm.HistorianDataSource = new FuzzSource(series, shape, ceiling);
var sdkDetails = new ReadRawModifiedDetails
{
StartTime = start, EndTime = end, NumValuesPerNode = n, ReturnBounds = bounds, IsReadModified = false,
};
var overridePages = Page(cp => OverrideRead(sdkDetails, nodeId, cp), truth.Values.Count, tag, out var overrideStatus);
overrideStatus.ShouldBe(portStatus, $"override vs port status: {tag}");
overridePages.Select(p => string.Join(" | ", p)).ShouldBe(portPages.Select(p => string.Join(" | ", p)), $"override vs port pages: {tag}");
Count("override compared");
}
if (truth.Values.Count == 0) Count("empty");
if (portPages.Count > 1) Count("paged");
if (direction != Direction.Forward) Count(direction.ToString());
if (bounds) Count("bounds");
if (ceiling > 0) Count("ceiling");
if (n == 0) Count("N=0");
if (n == 1) Count("N=1");
Count(shape.ToString());
}
}
finally
{
fx.Nm.HistorianDataSource = NullHistorianDataSource.Instance;
fx.Nm.HistoryContinuationStore = new InMemoryHistoryContinuationStore();
fx.Gate.Release();
}
var summary = string.Join(", ", counts.OrderBy(kv => kv.Key).Select(kv => $"{kv.Key}={kv.Value}"));
foreach (var required in new[] { "empty", "paged", "Reverse", "EndOnly", "bounds", "ceiling", "N=0", "N=1", "SqlServer", "QuestDb", "Gateway", "override compared" })
counts.GetValueOrDefault(required).ShouldBeGreaterThan(iterations / 200, $"{required} under-represented: {summary}");
counts.GetValueOrDefault("exact").ShouldBeGreaterThan(iterations * 9 / 10, summary);
TestContext.Current.TestOutputHelper?.WriteLine($"port paging fuzz: {iterations} iterations — {summary}");
}
private static List<List<string>> Page(
Func<byte[]?, (uint Status, List<string> Values, byte[]? Cp)> read, int truthCount, string tag, out uint status)
{
var pages = new List<List<string>>();
byte[]? cp = null;
do
{
var (s, values, next) = read(cp);
status = s;
if ((s & 0x80000000u) != 0) return pages;
pages.Add(values);
cp = next;
pages.Count.ShouldBeLessThanOrEqualTo(2 * truthCount + 4, $"paging must terminate: {tag}");
}
while (cp is not null);
return pages;
}
private (uint Status, List<string> Values, byte[]? Cp) PortRead(HistoryReadRawVariant details, AddressSpaceRealm realm, string id, byte[]? cp)
{
// The binding tag the SDK adapter would pass for THIS node: derived from the node read, not a fixed key.
var nodeId = fx.Nodes.Values.Single(n => n.Realm == realm && n.Id == id).NodeId;
var outcome = fx.Nm.ReadHistory(details, [new HistoryReadPortItem(realm, id, cp, BindingTag: fx.Nm.HistoryBindingTag(nodeId))],
fx.Nm.SessionHistoryContinuationScope(session: null), CancellationToken.None)[0];
// The operation slot, as the override's errors[i] (Status folds GoodNoData in; pinned by the parity tests).
return (outcome.Error?.StatusCode.Code ?? StatusCodes.BadHistoryOperationUnsupported.Code,
outcome.Values.Select(Render).ToList(), outcome.ContinuationPoint);
}
private (uint Status, List<string> Values, byte[]? Cp) OverrideRead(ReadRawModifiedDetails details, NodeId nodeId, byte[]? cp)
{
var context = new OperationContext(new RequestHeader(), secureChannelContext: null, RequestType.HistoryRead,
requestLifetime: RequestLifetime.None, identity: null);
var nodesToRead = new List<HistoryReadValueId> { new() { NodeId = nodeId, ContinuationPoint = ByteString.From(cp) } };
var results = new List<SdkHistoryReadResult> { null! };
var errors = new List<ServiceResult> { null! };
fx.Nm.HistoryRead(context, details, TimestampsToReturn.Both, releaseContinuationPoints: false, nodesToRead, results, errors);
var values = results[0]?.HistoryData is { IsNull: false } body && ExtensionObject.ToEncodeable(body) is HistoryData data
? (data.DataValues.ToArray() ?? []).Select(Render).ToList()
: [];
return (errors[0].StatusCode.Code, values, results[0]?.ContinuationPoint.ToNullableArray());
}
private static string Render(DataValue v) =>
$"{v.SourceTimestamp.ToDateTime().Ticks}={SdkValueBoundary.ToClr(v.WrappedValue) ?? "null"}/{v.StatusCode.Code:X8}";
private static string Render(DataValueSnapshot s) =>
$"{Ts(s).Ticks}={s.Value ?? "null"}/{s.StatusCode:X8}";
private static DateTime Ts(DataValueSnapshot s) => s.SourceTimestampUtc ?? DateTime.MinValue;
private static DateTime Trunc(DateTime t, long resolution) => new(t.Ticks - t.Ticks % resolution, DateTimeKind.Utc);
private static List<DataValueSnapshot> RandomSeries(Random rng, long resolution)
{
var list = new List<DataValueSnapshot>();
var t = T0.Ticks - rng.Next(0, 3) * TimeSpan.TicksPerHour;
var count = rng.Next(0, 60);
var v = 0;
while (list.Count < count)
{
t += rng.Next(6) switch
{
0 => rng.Next(1, 10),
1 => rng.Next(1, 5) * TimeSpan.TicksPerMillisecond,
2 => rng.Next(1, 3) * TimeSpan.TicksPerSecond,
3 => rng.Next(1, 30) * TimeSpan.TicksPerMinute,
_ => rng.Next(1, 1000) * TimeSpan.TicksPerMillisecond,
};
var ties = rng.Next(5) == 0 ? rng.Next(2, 9) : 1;
for (var k = 0; k < ties; k++)
{
var ts = Trunc(new DateTime(t, DateTimeKind.Utc), resolution);
var bad = rng.Next(12) == 0;
list.Add(new DataValueSnapshot(bad ? null : (double)v, bad ? StatusCodes.Bad.Code : StatusCodes.Good.Code, ts, ts));
v++;
}
}
return list;
}
private static DateTime PickBoundary(Random rng, List<DataValueSnapshot> series, long resolution)
{
if (series.Count == 0) return T0.AddSeconds(rng.Next(-100, 100));
var i = rng.Next(series.Count);
var t = Ts(series[i]);
switch (rng.Next(9))
{
case 0: return Ts(series[0]).AddSeconds(-rng.Next(1, 100));
case 1: return Ts(series[^1]).AddSeconds(rng.Next(1, 100));
case 2:
case 3: return t;
case 4: return t.AddTicks(resolution);
case 5: return t.AddTicks(-1);
case 6: return t.AddMilliseconds(1);
default:
var next = i + 1 < series.Count ? Ts(series[i + 1]) : t.AddSeconds(10);
return new DateTime(t.Ticks + (long)((next.Ticks - t.Ticks) * rng.NextDouble()), DateTimeKind.Utc);
}
}
private static List<string> SeriesOracle(List<DataValueSnapshot> series, DateTime start, DateTime end, Direction direction, long resolution)
{
var s = Trunc(start, resolution);
var e = Trunc(end, resolution);
IEnumerable<DataValueSnapshot> window = direction switch
{
Direction.Forward or Direction.Reverse when s == e => series.Where(x => Ts(x) == s),
Direction.Forward => series.Where(x => Ts(x) >= s && Ts(x) < e),
Direction.Reverse => series.Where(x => Ts(x) > e && Ts(x) <= s).Reverse(),
_ => series.Where(x => Ts(x) <= e).Reverse(),
};
return window.Select(Render).ToList();
}
private static int LargestTieCluster(List<DataValueSnapshot> series, long resolution) =>
series.GroupBy(x => Trunc(Ts(x), resolution).Ticks).Select(g => g.Count()).DefaultIfEmpty(0).Max();
/// <summary>A series-backed backend of one shape; a non-zero <c>ceiling</c> is a strict row ceiling (refused above it).</summary>
private sealed class FuzzSource(IReadOnlyList<DataValueSnapshot> series, Shape shape, int ceiling) : IHistorianDataSource
{
public int ReverseOnForwardOnly;
public bool SupportsReverseRaw => shape != Shape.Gateway;
public long TimestampResolutionTicks => shape == Shape.QuestDb ? 10 : 1;
public int MaxRawValuesPerRead => ceiling;
public Task<HistorianRead> ReadRawAsync(
string fullReference, DateTime startUtc, DateTime endUtc, uint maxValuesPerNode, CancellationToken cancellationToken)
{
if (shape == Shape.Gateway && startUtc > endUtc)
{
Interlocked.Increment(ref ReverseOnForwardOnly);
throw new InvalidOperationException("start_time must be less than or equal to end_time.");
}
startUtc = Trunc(startUtc, TimestampResolutionTicks);
endUtc = Trunc(endUtc, TimestampResolutionTicks);
List<DataValueSnapshot> window;
if (startUtc > endUtc) window = series.Where(x => Ts(x) > endUtc && Ts(x) <= startUtc).Reverse().ToList();
else if (startUtc == endUtc) window = series.Where(x => Ts(x) == startUtc).ToList();
else window = series.Where(x => Ts(x) >= startUtc && Ts(x) < endUtc).ToList();
var probe = ceiling > 0 && (maxValuesPerNode == 0 || maxValuesPerNode > (uint)ceiling);
if (probe && window.Count > ceiling)
throw new HistoryReadLimitExceededException(ceiling, $"more than {ceiling} rows");
var page = maxValuesPerNode == 0 ? window : window.Take((int)Math.Min(maxValuesPerNode, int.MaxValue)).ToList();
return Task.FromResult(new HistorianRead(page, null));
}
public Task<HistorianRead> ReadProcessedAsync(
string fullReference, DateTime startUtc, DateTime endUtc, TimeSpan interval,
HistoryAggregateType aggregate, CancellationToken cancellationToken) =>
Task.FromResult(new HistorianRead(Array.Empty<DataValueSnapshot>(), null));
public Task<HistorianRead> ReadAtTimeAsync(
string fullReference, IReadOnlyList<DateTime> timestampsUtc, CancellationToken cancellationToken) =>
Task.FromResult(new HistorianRead(Array.Empty<DataValueSnapshot>(), null));
public Task<HistoricalEventsResult> ReadEventsAsync(
string? sourceName, DateTime startUtc, DateTime endUtc, int maxEvents, CancellationToken cancellationToken) =>
Task.FromResult(new HistoricalEventsResult(Array.Empty<HistoricalEvent>(), null));
public HistorianHealthSnapshot GetHealthSnapshot() => NullHistorianDataSource.Instance.GetHealthSnapshot();
public void Dispose() { }
}
}
@@ -0,0 +1,851 @@
using Microsoft.Extensions.Logging.Abstractions;
using Opc.Ua;
using Opc.Ua.Server;
using Shouldly;
using Xunit;
using ZB.MOM.WW.OtOpcUa.Commons.OpcUa;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions;
using HistorianRead = ZB.MOM.WW.OtOpcUa.Core.Abstractions.HistoryReadResult;
using SdkHistoryReadResult = Opc.Ua.HistoryReadResult;
namespace ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests;
/// <summary>Boots one SDK server with the historized nodes the port parity cases read.</summary>
public sealed class HistoryReadPortServerFixture : IAsyncLifetime
{
private readonly string _pkiRoot = Path.Combine(Path.GetTempPath(), $"otopcua-histport-{Guid.NewGuid():N}");
private OpcUaApplicationHost? _host;
/// <summary>The node manager under test.</summary>
public OtOpcUaNodeManager Nm { get; private set; } = null!;
/// <summary>Every node-manager log entry's structured properties.</summary>
public CapturingLogger Log { get; } = new();
/// <summary>Serialises the cases (they share the node manager's source and continuation store).</summary>
public SemaphoreSlim Gate { get; } = new(1, 1);
/// <summary>The historized nodes: (realm, identifier) → NodeId.</summary>
public Dictionary<string, (AddressSpaceRealm Realm, string Id, NodeId NodeId)> Nodes { get; } = new();
public async ValueTask InitializeAsync()
{
var started = await OpcUaHostStart.StartAsync(
port => new OpcUaApplicationHost(
new OpcUaApplicationHostOptions
{
ApplicationName = "OtOpcUa.HistoryPortTest",
ApplicationUri = $"urn:OtOpcUa.HistoryPortTest:{Guid.NewGuid():N}",
OpcUaPort = port,
PublicHostname = "localhost",
PkiStoreRoot = _pkiRoot,
},
NullLogger<OpcUaApplicationHost>.Instance),
() => new OtOpcUaSdkServer(Log), CancellationToken.None);
_host = started.Host;
Nm = started.Server.NodeManager!;
Nm.HistoryContinuationStore = new InMemoryHistoryContinuationStore();
Add("dbl", "port/dbl", "Double", AddressSpaceRealm.Uns);
Add("str", "port/str", "String", AddressSpaceRealm.Uns);
Add("bool", "port/bool", "Boolean", AddressSpaceRealm.Uns);
Add("int", "port/int", "Int32", AddressSpaceRealm.Uns);
Add("raw", "Plant/dev/raw1", "Double", AddressSpaceRealm.Raw);
Add("plain", "port/plain", "Double", AddressSpaceRealm.Uns, historized: false);
}
/// <summary>Adds one more historized node (the epoch-bump case removes one).</summary>
public NodeId Add(string key, string id, string dataType, AddressSpaceRealm realm, bool historized = true)
{
Nm.EnsureVariable(id, parentFolderNodeId: null, displayName: key, dataType: dataType, writable: false,
realm: realm, historianTagname: historized ? "P." + key : null);
var nodeId = Nm.TryGetVariable(id, realm)!.NodeId;
Nodes[key] = (realm, id, nodeId);
return nodeId;
}
public async ValueTask DisposeAsync()
{
if (_host is not null) await _host.DisposeAsync();
if (Directory.Exists(_pkiRoot))
{
try { Directory.Delete(_pkiRoot, recursive: true); }
catch { /* best-effort */ }
}
}
}
/// <summary>Records each log entry's level and structured properties.</summary>
public sealed class CapturingLogger : Microsoft.Extensions.Logging.ILogger<OtOpcUaNodeManager>
{
private readonly System.Collections.Concurrent.ConcurrentQueue<(Microsoft.Extensions.Logging.LogLevel Level, IReadOnlyList<KeyValuePair<string, object?>> Properties)> _entries = new();
public IReadOnlyList<(Microsoft.Extensions.Logging.LogLevel Level, IReadOnlyList<KeyValuePair<string, object?>> Properties)> Entries => _entries.ToArray();
public void Clear() => _entries.Clear();
public IDisposable? BeginScope<TState>(TState state) where TState : notnull => null;
public bool IsEnabled(Microsoft.Extensions.Logging.LogLevel logLevel) => true;
public void Log<TState>(Microsoft.Extensions.Logging.LogLevel logLevel, Microsoft.Extensions.Logging.EventId eventId, TState state,
Exception? exception, Func<TState, Exception?, string> formatter) =>
_entries.Enqueue((logLevel, state as IReadOnlyList<KeyValuePair<string, object?>> ?? []));
}
/// <summary>
/// H1 (gRPC data history plan §3.1): the override-level history port is the ONE pipeline the SDK overrides and a remote
/// peer's HistoryRead (H2) are served through. Every case runs the same request two ways against the same fake backend —
/// the SDK override path (<c>HistoryRead</c> on the node manager, the path every local OPC UA client takes) and the port
/// directly with <c>(realm, identifier)</c> items — and requires identical per-node outcomes.
/// <para>
/// What this class proves is port ≡ adapter. Since H1 the override IS an adapter over the port, so that equality
/// alone cannot detect a behaviour change the port introduced. The tie to PRE-H1 behaviour is (a) the pinned literal
/// outcomes in these cases, which were recorded and run green against the pre-port node manager (the port calls then
/// stubbed onto the override), and (b) the legacy history suites (<c>NodeManagerHistoryRead*Tests</c>,
/// <c>HistoryUpdateTests</c>, the raw-cap fuzz …), unchanged and re-run by the H1 gate.
/// </para>
/// </summary>
[Trait("Feature", "GrpcData")]
[Trait("Phase", "H1")]
public sealed class HistoryReadPortParityTests(HistoryReadPortServerFixture fx) : IClassFixture<HistoryReadPortServerFixture>
{
private static readonly DateTime T0 = new(2026, 3, 1, 10, 0, 0, DateTimeKind.Utc);
private static DateTime T(int seconds) => T0.AddSeconds(seconds);
private static DataValueSnapshot S(object? value, int seconds, uint status = 0) =>
new(value, status, T(seconds), T(seconds));
// ---------------------------------------------------------------------------------------------------------
// Processed refusals
// ---------------------------------------------------------------------------------------------------------
[Fact]
public async Task Aggregate_refused_for_the_nodes_data_type_897_and_by_SupportsAggregateFor_and_unknown_aggregates()
{
await RunAsync(async () =>
{
var source = new ParitySource { ProcessedResult = [S(1.5, 0, StatusCodes.Good.Code)] };
fx.Nm.HistorianDataSource = source;
var details = Processed(ObjectIds.AggregateFunction_Average);
var nodes = new[] { "dbl", "str", "bool", "dbl", "bool" };
var aggregates = new[]
{
ObjectIds.AggregateFunction_Average,
ObjectIds.AggregateFunction_Average, // #897: numeric aggregate on a String node
ObjectIds.AggregateFunction_TimeAverage, // the backend's own SupportsAggregateFor refusal
new NodeId(987654u), // an aggregate the server cannot name
ObjectIds.AggregateFunction_Average, // Boolean is served
};
details.AggregateType = aggregates;
var viaOverride = Override(details, nodes);
var callsAfterOverride = source.ProcessedCalls;
var viaPort = Port(details, nodes);
viaOverride.Select(o => o.Error).ShouldBe(new[]
{
StatusCodes.Good.Code, StatusCodes.BadAggregateNotSupported.Code, StatusCodes.BadAggregateNotSupported.Code,
StatusCodes.BadAggregateNotSupported.Code, StatusCodes.Good.Code,
});
viaOverride[0].Values.ShouldBe("T0+0=1.5:Double/00000000");
viaOverride[0].ResultStatus.ShouldBe(StatusCodes.Good.Code);
viaOverride[1].ResultStatus.ShouldBe(StatusCodes.Good.Code, "a refusal sets only the operation status (the SDK seeds the result slot)");
viaOverride[1].Values.ShouldBe("");
callsAfterOverride.ShouldBe(2, "refused nodes are never sent to the backend");
source.RefusedAggregateAsked.ShouldBeTrue();
viaPort.ShouldBe(viaOverride);
source.ProcessedCalls.ShouldBe(4);
});
}
[Fact]
public async Task Non_default_aggregate_configuration_is_rejected_per_node_and_the_defaults_are_served()
{
await RunAsync(async () =>
{
var source = new ParitySource { ProcessedResult = [S(2.0, 0)] };
fx.Nm.HistorianDataSource = source;
var rejected = Processed(ObjectIds.AggregateFunction_Average);
rejected.AggregateConfiguration = new AggregateConfiguration
{
UseServerCapabilitiesDefaults = false, TreatUncertainAsBad = true, PercentDataBad = 100, PercentDataGood = 100,
};
var spelled = Processed(ObjectIds.AggregateFunction_Average);
spelled.AggregateConfiguration = new AggregateConfiguration
{
UseServerCapabilitiesDefaults = false, TreatUncertainAsBad = false, PercentDataBad = 100, PercentDataGood = 100,
UseSlopedExtrapolation = false,
};
var r1 = Override(rejected, "dbl");
r1.Single().Error.ShouldBe(StatusCodes.BadAggregateConfigurationRejected.Code);
Port(rejected, "dbl").ShouldBe(r1);
var r2 = Override(spelled, "dbl");
r2.Single().Error.ShouldBe(StatusCodes.Good.Code);
Port(spelled, "dbl").ShouldBe(r2);
source.ProcessedCalls.ShouldBe(2);
await Task.CompletedTask;
});
}
// ---------------------------------------------------------------------------------------------------------
// Raw
// ---------------------------------------------------------------------------------------------------------
[Fact]
public async Task Modified_read_with_bounds_is_BadInvalidArgument_on_both_slots()
{
await RunAsync(async () =>
{
fx.Nm.HistorianDataSource = new ParitySource();
var details = Raw(T(0), T(10), 10, bounds: true);
details.IsReadModified = true;
var viaOverride = Override(details, "dbl", "str");
viaOverride.ShouldAllBe(o => o.Error == StatusCodes.BadInvalidArgument.Code && o.ResultStatus == StatusCodes.BadInvalidArgument.Code);
Port(details, "dbl", "str").ShouldBe(viaOverride);
await Task.CompletedTask;
});
}
[Fact]
public async Task Modified_read_without_bounds_on_a_trail_less_backend_is_unsupported_on_both_paths()
{
await RunAsync(async () =>
{
fx.Nm.HistorianDataSource = new ParitySource();
var details = Raw(T(0), T(10), 10, bounds: false);
details.IsReadModified = true;
var viaOverride = Override(details, "dbl");
viaOverride.Single().Error.ShouldBe(StatusCodes.BadHistoryOperationUnsupported.Code);
Port(details, "dbl").ShouldBe(viaOverride);
await Task.CompletedTask;
});
}
[Fact]
public async Task Stored_and_AtTime_values_are_normalised_to_the_nodes_data_type()
{
await RunAsync(async () =>
{
var source = new ParitySource();
source.Series["P.int"] = [S(7.0, 0), S("x", 1), S(41.0, 2)];
source.AtTimeResult = [S(7.0, 0), S("not a number", 1)];
fx.Nm.HistorianDataSource = source;
var raw = Override(Raw(T(0), T(10), 0, bounds: false), "int");
raw.Single().Values.ShouldBe("T0+0=7:Int32/00000000 | T0+1=null/80740000 | T0+2=41:Int32/00000000");
Port(Raw(T(0), T(10), 0, bounds: false), "int").ShouldBe(raw);
var atTime = new ReadAtTimeDetails { ReqTimes = new[] { (DateTimeUtc)T(0), (DateTimeUtc)T(1) } };
var viaOverride = Override(atTime, "int");
viaOverride.Single().Values.ShouldBe("T0+0=7:Int32/00000000 | T0+1=null/80740000");
source.LastAtTimeType.ShouldBe(TypeCode.Int32, "the node's scalar type rides to the backend");
Port(atTime, "int").ShouldBe(viaOverride);
await Task.CompletedTask;
});
}
[Fact]
public async Task End_only_and_reverse_raw_page_newest_first()
{
await RunAsync(async () =>
{
foreach (var native in new[] { true, false })
{
var source = new ParitySource { NativeReverse = native };
source.Series["P.dbl"] = Enumerable.Range(0, 7).Select(i => S((double)i, i)).ToList();
fx.Nm.HistorianDataSource = source;
var endOnly = Raw(DateTime.MinValue, T(5), 2, bounds: false);
var o = DrainOverride(endOnly, "dbl");
o.ShouldBe("T0+5=5:Double/00000000 | T0+4=4:Double/00000000 | T0+3=3:Double/00000000 | T0+2=2:Double/00000000 | T0+1=1:Double/00000000 | T0+0=0:Double/00000000");
DrainPort(endOnly, "dbl").ShouldBe(o);
var reverse = Raw(T(6), T(1), 3, bounds: false);
var r = DrainOverride(reverse, "dbl");
r.ShouldBe("T0+6=6:Double/00000000 | T0+5=5:Double/00000000 | T0+4=4:Double/00000000 | T0+3=3:Double/00000000 | T0+2=2:Double/00000000");
DrainPort(reverse, "dbl").ShouldBe(r);
source.ReverseOnForwardOnly.ShouldBe(0);
}
await Task.CompletedTask;
});
}
[Fact]
public async Task Bounds_placeholders_lead_and_end_a_bounded_read()
{
await RunAsync(async () =>
{
var source = new ParitySource();
source.Series["P.dbl"] = [S(1.0, 2), S(2.0, 3)];
fx.Nm.HistorianDataSource = source;
// Nothing at or before StartTime and nothing at or after EndTime: both bounds are placeholders.
var details = Raw(T(0), T(5), 0, bounds: true);
var viaOverride = Override(details, "dbl");
viaOverride.Single().Values.ShouldBe(
"T0+0=null/80D70000 | T0+2=1:Double/00000000 | T0+3=2:Double/00000000 | T0+5=null/80D70000");
Port(details, "dbl").ShouldBe(viaOverride);
// Paged at N = 1: the start bound alone, then the data, then the end bound.
var paged = Raw(T(0), T(5), 1, bounds: true);
var drained = DrainOverride(paged, "dbl");
drained.ShouldBe(viaOverride.Single().Values);
DrainPort(paged, "dbl").ShouldBe(drained);
// No data and no bound at all (a tag with no history) ⇒ GoodNoData with no values (the pre-bounds answer).
var empty = Raw(T(100), T(200), 0, bounds: true);
var none = Override(empty, "str");
none.Single().ResultStatus.ShouldBe(StatusCodes.GoodNoData.Code);
none.Single().Values.ShouldBe("");
Port(empty, "str").ShouldBe(none);
await Task.CompletedTask;
});
}
[Fact]
public async Task Uncapped_raw_pages_at_the_backend_ceiling_with_a_continuation_point()
{
await RunAsync(async () =>
{
var source = new ParitySource { Ceiling = 4 };
source.Series["P.raw"] = Enumerable.Range(0, 11).Select(i => S((double)i, i)).ToList();
fx.Nm.HistorianDataSource = source;
var details = Raw(T(0), T(100), 0, bounds: false);
var first = Override(details, "raw").Single();
first.HasContinuation.ShouldBeTrue("an uncapped read above the ceiling returns a page and a continuation point");
Port(details, "raw").ShouldBe([first]);
var all = string.Join(" | ", Enumerable.Range(0, 11).Select(i => $"T0+{i}={i}:Double/00000000"));
DrainOverride(details, "raw").ShouldBe(all);
DrainPort(details, "raw").ShouldBe(all);
await Task.CompletedTask;
});
}
[Fact]
public async Task An_epoch_bump_invalidates_a_continuation_point_on_both_paths()
{
await RunAsync(async () =>
{
var source = new ParitySource();
source.Series["P.dbl"] = Enumerable.Range(0, 5).Select(i => S((double)i, i)).ToList();
fx.Nm.HistorianDataSource = source;
var details = Raw(T(0), T(100), 2, bounds: false);
var (_, overrideCp) = ReadOverrideRaw(details, "dbl", cp: null);
var portCp = ReadPortRaw(details, "dbl", cp: null).Cp;
overrideCp.ShouldNotBeNull();
portCp.ShouldNotBeNull();
// Removing ANY node bumps the history epoch: every outstanding cursor is conservatively invalid.
fx.Add("victim", "port/victim-" + Guid.NewGuid().ToString("N"), "Double", AddressSpaceRealm.Uns);
fx.Nm.RemoveVariableNode(fx.Nodes["victim"].Id, AddressSpaceRealm.Uns).ShouldBeTrue();
var afterOverride = ReadOverrideRaw(details, "dbl", overrideCp).Outcome;
afterOverride.Error.ShouldBe(StatusCodes.BadContinuationPointInvalid.Code);
afterOverride.ResultStatus.ShouldBe(StatusCodes.BadContinuationPointInvalid.Code);
ReadPortRaw(details, "dbl", portCp).Outcome.ShouldBe(afterOverride);
await Task.CompletedTask;
});
}
[Fact]
public async Task A_continuation_point_is_bound_to_its_node_and_realm()
{
await RunAsync(async () =>
{
var source = new ParitySource();
source.Series["P.dbl"] = Enumerable.Range(0, 5).Select(i => S((double)i, i)).ToList();
source.Series["P.raw"] = Enumerable.Range(0, 5).Select(i => S((double)i, i)).ToList();
fx.Nm.HistorianDataSource = source;
var details = Raw(T(0), T(100), 2, bounds: false);
var overrideCp = ReadOverrideRaw(details, "dbl", cp: null).Cp;
var crossed = ReadOverrideRaw(details, "raw", overrideCp).Outcome;
crossed.Error.ShouldBe(StatusCodes.BadContinuationPointInvalid.Code);
var portCp = ReadPortRaw(details, "dbl", cp: null).Cp;
ReadPortRaw(details, "raw", portCp).Outcome.ShouldBe(crossed);
await Task.CompletedTask;
});
}
[Fact]
public async Task A_peer_scope_pages_like_the_session_scope_and_binds_details_principal_incarnation_and_epoch()
{
await RunAsync(async () =>
{
var source = new ParitySource();
source.Series["P.raw"] = Enumerable.Range(0, 9).Select(i => S((double)i, i)).ToList();
fx.Nm.HistorianDataSource = source;
var (realm, id, _) = fx.Nodes["raw"];
var details = new HistoryReadRawVariant(T(0), T(100), 2, ReturnBounds: false);
var store = new PeerHistoryContinuationStore("svc-consumer", "conn-1", capacity: 4);
var incarnation = "inc-1";
// One scope per request (it snapshots the serving incarnation at first use), as H2 creates per RPC.
IHistoryContinuationScope Peer() => new PeerHistoryContinuationScope(store, "svc-consumer", () => incarnation);
HistoryReadNodeOutcome Read(IHistoryContinuationScope scope, HistoryReadVariant d, byte[]? cp) =>
fx.Nm.ReadHistory(d, [new HistoryReadPortItem(realm, id, cp)], scope, CancellationToken.None)[0];
string DrainWith(Func<IHistoryContinuationScope> scope)
{
var parts = new List<string>();
byte[]? cp = null;
do
{
var o = Read(scope(), details, cp);
o.Status.Code.ShouldBe(StatusCodes.Good.Code);
parts.AddRange(o.Values.Select(Render));
cp = o.ContinuationPoint;
}
while (cp is not null);
return string.Join(" | ", parts);
}
DrainWith(Peer).ShouldBe(DrainWith(() => fx.Nm.SessionHistoryContinuationScope(session: null)));
store.Count.ShouldBe(0, "every page's token was taken");
// A resume under other details, by another incarnation, or after an epoch bump is refused.
var cp1 = Read(Peer(), details, null).ContinuationPoint!;
Read(Peer(), details with { NumValuesPerNode = 3 }, cp1).Status.Code.ShouldBe(StatusCodes.BadContinuationPointInvalid.Code);
// A serving-incarnation change on the SAME live connection (in-process failover) is a key mismatch in one store.
var cp2 = Read(Peer(), details, null).ContinuationPoint!;
incarnation = "inc-2";
Read(Peer(), details, cp2).Status.Code.ShouldBe(StatusCodes.BadContinuationPointInvalid.Code);
// Another principal's scope over the store cannot resume the owner's cursor.
var cpOther = Read(Peer(), details, null).ContinuationPoint!;
var intruder = new PeerHistoryContinuationScope(store, "someone-else", () => incarnation);
Read(intruder, details, cpOther).Status.Code.ShouldBe(StatusCodes.BadContinuationPointInvalid.Code);
var cp3 = Read(Peer(), details, null).ContinuationPoint!;
fx.Add("victim2", "port/victim-" + Guid.NewGuid().ToString("N"), "Double", AddressSpaceRealm.Uns);
fx.Nm.RemoveVariableNode(fx.Nodes["victim2"].Id, AddressSpaceRealm.Uns).ShouldBeTrue();
Read(Peer(), details, cp3).Status.Code.ShouldBe(StatusCodes.BadContinuationPointInvalid.Code);
// The take was single-use: the same token again is still a miss, and nothing is left behind.
Read(Peer(), details, cp1).Status.Code.ShouldBe(StatusCodes.BadContinuationPointInvalid.Code);
store.Count.ShouldBe(0, "every presented token was consumed, matched or not");
// A wiring fault (a scope for a principal the store does not belong to) is its own status, never "unsupported".
var miswired = Read(new PeerHistoryContinuationScope(store, "someone-else", () => incarnation), details, null);
miswired.Status.Code.ShouldBe(StatusCodes.BadInternalError.Code);
miswired.Error!.StatusCode.Code.ShouldBe(StatusCodes.BadInternalError.Code);
await Task.CompletedTask;
});
}
[Fact]
public async Task A_cursor_is_bound_to_its_namespace_not_only_realm_and_identifier()
{
await RunAsync(async () =>
{
var source = new ParitySource();
source.Series["P.raw"] = Enumerable.Range(0, 6).Select(i => S((double)i, i)).ToList();
fx.Nm.HistorianDataSource = source;
var (realm, id, nodeId) = fx.Nodes["raw"];
var details = new HistoryReadRawVariant(T(0), T(100), 2, ReturnBounds: false);
var local = fx.Nm.HistoryBindingTag(nodeId);
// mapped/raw folds into the Raw realm: the same (Raw, identifier) in the projected namespace is ANOTHER node.
var mapped = ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections.ProjectedDataIds.RawNamespaceUri;
local.ShouldNotBe(mapped);
var scope = fx.Nm.SessionHistoryContinuationScope(session: null);
HistoryReadNodeOutcome Read(string tag, byte[]? cp) =>
fx.Nm.ReadHistory(details, [new HistoryReadPortItem(realm, id, cp, BindingTag: tag)], scope, CancellationToken.None)[0];
Read(mapped, Read(local, null).ContinuationPoint).Status.Code.ShouldBe(StatusCodes.BadContinuationPointInvalid.Code);
Read(local, Read(mapped, null).ContinuationPoint).Status.Code.ShouldBe(StatusCodes.BadContinuationPointInvalid.Code);
Read(local, Read(local, null).ContinuationPoint).Status.Code.ShouldBe(StatusCodes.Good.Code);
// The SDK adapter tags with the same value: an override-issued cursor resumes through the port with the local
// tag and is refused with the mapped one.
var sdk = Raw(T(0), T(100), 2, bounds: false);
Read(local, ReadOverrideRaw(sdk, "raw", null).Cp).Status.Code.ShouldBe(StatusCodes.Good.Code);
Read(mapped, ReadOverrideRaw(sdk, "raw", null).Cp).Status.Code.ShouldBe(StatusCodes.BadContinuationPointInvalid.Code);
await Task.CompletedTask;
});
}
[Fact]
public async Task A_backend_failure_logs_the_original_NodeId_on_the_local_path()
{
await RunAsync(async () =>
{
fx.Nm.HistorianDataSource = new ParitySource { Throw = true };
var nodeId = fx.Nodes["dbl"].NodeId;
static object? NodeIdProperty(CapturingLogger log) => log.Entries
.Where(e => e.Level == Microsoft.Extensions.Logging.LogLevel.Error)
.SelectMany(e => e.Properties).Single(p => p.Key == "NodeId").Value;
foreach (var details in new HistoryReadDetails[]
{
Raw(T(0), T(10), 5, bounds: false),
new ReadAtTimeDetails { ReqTimes = new[] { (DateTimeUtc)T(0) } },
})
{
fx.Log.Clear();
Override(details, "dbl").Single().Error.ShouldBe(StatusCodes.BadHistoryOperationUnsupported.Code);
NodeIdProperty(fx.Log).ShouldBe(nodeId, "the {NodeId} property keeps meaning a NodeId");
// A peer item carries no SDK NodeId: it logs as Realm:Identifier.
fx.Log.Clear();
fx.Nm.ReadHistory(HistoryReadVariant.From(details), [new HistoryReadPortItem(AddressSpaceRealm.Uns, "port/dbl")],
fx.Nm.SessionHistoryContinuationScope(session: null), CancellationToken.None);
NodeIdProperty(fx.Log).ShouldBe("Uns:port/dbl");
}
await Task.CompletedTask;
});
}
[Fact]
public async Task A_mixed_batch_maps_every_outcome_back_to_its_own_handle_index()
{
await RunAsync(async () =>
{
var source = new ParitySource { ProcessedResult = [S(1.0, 0)] };
source.Series["P.dbl"] = Enumerable.Range(0, 5).Select(i => S((double)i, i)).ToList();
source.Series["P.raw"] = Enumerable.Range(0, 5).Select(i => S(10.0 + i, i)).ToList();
fx.Nm.HistorianDataSource = source;
// "plain" has no HistoryRead access bit: the SDK drops it before the override, so every later handle's Index
// differs from its position in the port's item list.
var processed = Processed(ObjectIds.AggregateFunction_Average);
processed.AggregateType = new[]
{
ObjectIds.AggregateFunction_Minimum, ObjectIds.AggregateFunction_Maximum,
ObjectIds.AggregateFunction_Average, ObjectIds.AggregateFunction_Count,
};
var nodes = new[] { "plain", "dbl", "str", "raw" };
var viaOverride = Override(processed, nodes);
viaOverride.Select(o => o.Error).ShouldBe(new[]
{
StatusCodes.BadHistoryOperationUnsupported.Code, StatusCodes.Good.Code,
StatusCodes.BadAggregateNotSupported.Code, StatusCodes.Good.Code,
});
source.ProcessedAsked.OrderBy(kv => kv.Key).Select(kv => $"{kv.Key}:{kv.Value}")
.ShouldBe(new[] { "P.dbl:Maximum", "P.raw:Count" }, "each node reached the backend with ITS aggregate");
Port(processed, nodes).ShouldBe(viaOverride);
// Raw: per-node continuation points route to their own node.
var raw = Raw(T(0), T(100), 2, bounds: false);
var first = InvokeOverride(raw, [("plain", null), ("dbl", null), ("raw", null)]);
var cpDbl = first.Results[1]!.ContinuationPoint.ToNullableArray();
var cpRaw = first.Results[2]!.ContinuationPoint.ToNullableArray();
cpDbl.ShouldNotBeNull();
cpRaw.ShouldNotBeNull();
var second = InvokeOverride(raw, [("plain", null), ("raw", cpRaw), ("dbl", cpDbl)]);
ToOutcome(second.Errors[1], second.Results[1]).Values.ShouldStartWith("T0+2=12:Double");
ToOutcome(second.Errors[2], second.Results[2]).Values.ShouldStartWith("T0+2=2:Double");
var portFirst = PortRead(raw, [("plain", null), ("dbl", null), ("raw", null)]);
portFirst.Select(o => o.Outcome).ShouldBe(Enumerable.Range(0, 3).Select(i => ToOutcome(first.Errors[i], first.Results[i])));
var portSecond = PortRead(raw, [("plain", null), ("raw", portFirst[2].Cp), ("dbl", portFirst[1].Cp)]);
portSecond[1].Outcome.ShouldBe(ToOutcome(second.Errors[1], second.Results[1]));
portSecond[2].Outcome.ShouldBe(ToOutcome(second.Errors[2], second.Results[2]));
await Task.CompletedTask;
});
}
[Fact]
public async Task Modified_reads_page_and_resume_through_the_port_as_through_the_override()
{
await RunAsync(async () =>
{
var source = new ParitySource();
source.Trail["P.dbl"] = Enumerable.Range(0, 7)
.Select(i => new HistoryModifiedValue(S((double)i, i / 2), T(1000 + i), HistoryModificationType.Replace, "alice", i + 1, T(i / 2)))
.ToList();
fx.Nm.HistorianDataSource = source;
var details = Raw(T(0), T(100), 3, bounds: false);
details.IsReadModified = true;
var expected = "T0+0=0:Double/00000000 | T0+0=1:Double/00000000 | T0+1=2:Double/00000000 | T0+1=3:Double/00000000 | " +
"T0+2=4:Double/00000000 | T0+2=5:Double/00000000 | T0+3=6:Double/00000000";
DrainOverride(details, "dbl").ShouldBe(expected);
DrainPort(details, "dbl").ShouldBe(expected);
// A modified cursor is bound to the modified kind: a plain raw resume is refused (and the reverse) — on the
// override path and on the port alike.
var plain = Raw(T(0), T(100), 3, bounds: false);
source.Series["P.dbl"] = Enumerable.Range(0, 7).Select(i => S((double)i, i)).ToList();
foreach (var (name, read) in new (string, Func<HistoryReadDetails, byte[]?, (Outcome Outcome, byte[]? Cp)>)[]
{
("override", (d, cp) => ReadOverrideRaw(d, "dbl", cp)),
("port", (d, cp) => ReadPortRaw(d, "dbl", cp)),
})
{
var modifiedCp = read(details, null).Cp!;
var crossed = read(plain, modifiedCp).Outcome;
crossed.Error.ShouldBe(StatusCodes.BadContinuationPointInvalid.Code, name);
crossed.ResultStatus.ShouldBe(StatusCodes.BadContinuationPointInvalid.Code, name);
var rawCp = read(plain, null).Cp!;
read(details, rawCp).Outcome.Error.ShouldBe(StatusCodes.BadContinuationPointInvalid.Code, name);
}
await Task.CompletedTask;
});
}
[Fact]
public async Task The_outcome_status_carries_GoodNoData_and_Bad_operation_statuses_verbatim()
{
await RunAsync(async () =>
{
fx.Nm.HistorianDataSource = new ParitySource();
HistoryReadNodeOutcome Read(HistoryReadVariant d, string key) =>
fx.Nm.ReadHistory(d, [new HistoryReadPortItem(fx.Nodes[key].Realm, fx.Nodes[key].Id)],
fx.Nm.SessionHistoryContinuationScope(session: null), CancellationToken.None)[0];
// §3.3: an empty window is GoodNoData (the result slot), not the Good operation status.
Read(new HistoryReadRawVariant(T(0), T(10), 5, ReturnBounds: false), "dbl").Status.Code.ShouldBe(StatusCodes.GoodNoData.Code);
Read(new HistoryReadAtTimeVariant([]), "dbl").Status.Code.ShouldBe(StatusCodes.GoodNoData.Code);
// A Bad operation status wins, with or without a result slot.
Read(new HistoryReadRawVariant(T(0), T(10), 5, ReturnBounds: true, IsReadModified: true), "dbl")
.Status.Code.ShouldBe(StatusCodes.BadInvalidArgument.Code);
Read(new HistoryReadRawVariant(T(0), T(10), 5, ReturnBounds: false), "plain")
.Status.Code.ShouldBe(StatusCodes.BadHistoryOperationUnsupported.Code);
await Task.CompletedTask;
});
}
[Fact]
public async Task A_node_with_no_historian_tagname_is_unsupported_on_both_paths()
{
await RunAsync(async () =>
{
fx.Nm.HistorianDataSource = new ParitySource();
// The SDK filters nodes without the HistoryRead access bit before the override; the port sees every item.
var viaPort = Port(Raw(T(0), T(10), 0, bounds: false), "plain");
viaPort.Single().Error.ShouldBe(StatusCodes.BadHistoryOperationUnsupported.Code);
var atTime = Port(new ReadAtTimeDetails { ReqTimes = new[] { (DateTimeUtc)T(0) } }, "plain");
atTime.Single().Error.ShouldBe(StatusCodes.BadHistoryOperationUnsupported.Code);
await Task.CompletedTask;
});
}
// ---------------------------------------------------------------------------------------------------------
// Harness
// ---------------------------------------------------------------------------------------------------------
/// <summary>One node's observable outcome: the operation (errors) slot, the result slot, values and the CP presence.</summary>
public sealed record Outcome(uint Error, uint? ResultStatus, string Values, bool HasContinuation);
private async Task RunAsync(Func<Task> body)
{
await fx.Gate.WaitAsync(TestContext.Current.CancellationToken);
try
{
fx.Nm.HistoryContinuationStore = new InMemoryHistoryContinuationStore();
fx.Nm.MaxTieClusterOverfetch = 65536;
await body();
}
finally
{
fx.Nm.HistorianDataSource = NullHistorianDataSource.Instance;
fx.Gate.Release();
}
}
private static ReadRawModifiedDetails Raw(DateTime start, DateTime end, uint n, bool bounds) => new()
{
StartTime = start, EndTime = end, NumValuesPerNode = n, ReturnBounds = bounds, IsReadModified = false,
};
private static ReadProcessedDetails Processed(NodeId aggregate) => new()
{
StartTime = T(0), EndTime = T(60), ProcessingInterval = 10_000, AggregateType = new[] { aggregate },
AggregateConfiguration = new AggregateConfiguration { UseServerCapabilitiesDefaults = true },
};
private Outcome[] Override(HistoryReadDetails details, params string[] nodes)
{
var (results, errors) = InvokeOverride(details, nodes.Select(k => (k, (byte[]?)null)).ToArray());
return nodes.Select((_, i) => ToOutcome(errors[i], results[i])).ToArray();
}
private (SdkHistoryReadResult?[] Results, ServiceResult?[] Errors) InvokeOverride(
HistoryReadDetails details, (string Key, byte[]? Cp)[] nodes)
{
var context = new OperationContext(new RequestHeader(), secureChannelContext: null, RequestType.HistoryRead,
requestLifetime: RequestLifetime.None, identity: null);
var nodesToRead = nodes.Select(n => new HistoryReadValueId
{
NodeId = fx.Nodes[n.Key].NodeId, ContinuationPoint = ByteString.From(n.Cp),
}).ToList();
var results = new List<SdkHistoryReadResult>(nodes.Select(_ => (SdkHistoryReadResult)null!));
var errors = new List<ServiceResult>(nodes.Select(_ => (ServiceResult)null!));
fx.Nm.HistoryRead(context, details, TimestampsToReturn.Both, releaseContinuationPoints: false, nodesToRead, results, errors);
return (results.ToArray(), errors.ToArray());
}
private Outcome[] Port(HistoryReadDetails details, params string[] nodes) =>
PortRead(details, nodes.Select(k => (k, (byte[]?)null)).ToArray()).Select(o => o.Outcome).ToArray();
private (Outcome Outcome, byte[]? Cp)[] PortRead(HistoryReadDetails details, (string Key, byte[]? Cp)[] nodes)
{
var items = nodes.Select((n, i) => new HistoryReadPortItem(
fx.Nodes[n.Key].Realm, fx.Nodes[n.Key].Id, n.Cp,
details is ReadProcessedDetails p ? p.AggregateType[i] : default,
BindingTag: fx.Nm.HistoryBindingTag(fx.Nodes[n.Key].NodeId), NodeId: fx.Nodes[n.Key].NodeId)).ToArray();
var outcomes = fx.Nm.ReadHistory(HistoryReadVariant.From(details), items,
fx.Nm.SessionHistoryContinuationScope(session: null), CancellationToken.None);
// A slot the port leaves unset is the one the SDK seeded before the override ran (an empty, Good result).
return outcomes.Select(o => (ToOutcome(o.Error, o.Result ?? new SdkHistoryReadResult()), o.ContinuationPoint)).ToArray();
}
private (Outcome Outcome, byte[]? Cp) ReadOverrideRaw(HistoryReadDetails details, string node, byte[]? cp)
{
var (results, errors) = InvokeOverride(details, [(node, cp)]);
return (ToOutcome(errors[0], results[0]), results[0]?.ContinuationPoint.ToNullableArray());
}
private (Outcome Outcome, byte[]? Cp) ReadPortRaw(HistoryReadDetails details, string node, byte[]? cp) =>
PortRead(details, [(node, cp)])[0];
private string DrainOverride(HistoryReadDetails details, string node) =>
Drain(cp => ReadOverrideRaw(details, node, cp));
private string DrainPort(HistoryReadDetails details, string node) =>
Drain(cp => ReadPortRaw(details, node, cp));
private static string Drain(Func<byte[]?, (Outcome Outcome, byte[]? Cp)> read)
{
var parts = new List<string>();
byte[]? cp = null;
for (var page = 0; page < 100; page++)
{
var (outcome, next) = read(cp);
outcome.Error.ShouldBe(StatusCodes.Good.Code, $"page {page}");
if (outcome.Values.Length > 0) parts.Add(outcome.Values);
cp = next;
if (cp is null) return string.Join(" | ", parts);
}
throw new InvalidOperationException("paging did not terminate");
}
private static Outcome ToOutcome(ServiceResult? error, SdkHistoryReadResult? result)
{
var values = "";
if (result?.HistoryData is { IsNull: false } body && ExtensionObject.ToEncodeable(body) is HistoryData data)
values = string.Join(" | ", (data.DataValues.ToArray() ?? []).Select(Render));
return new Outcome(error?.StatusCode.Code ?? uint.MaxValue, result?.StatusCode.Code, values, result?.ContinuationPoint.ToNullableArray() is not null);
}
private static string Render(DataValue v)
{
var clr = SdkValueBoundary.ToClr(v.WrappedValue);
var when = v.SourceTimestamp.ToDateTime();
var stamp = when == DateTime.MinValue ? "none" : $"T0+{(when - T0).TotalSeconds:0.#######}";
return $"{stamp}={(clr is null ? "null" : $"{clr}:{clr.GetType().Name}")}/{v.StatusCode.Code:X8}";
}
/// <summary>A series-backed fake with scripted processed / AtTime answers and the Gateway's Boolean TimeAverage refusal.</summary>
internal sealed class ParitySource : IHistorianDataSource
{
public Dictionary<string, List<DataValueSnapshot>> Series { get; } = new();
public Dictionary<string, List<HistoryModifiedValue>> Trail { get; } = new();
public System.Collections.Concurrent.ConcurrentDictionary<string, HistoryAggregateType> ProcessedAsked { get; } = new();
public IReadOnlyList<DataValueSnapshot> ProcessedResult { get; init; } = [];
public IReadOnlyList<DataValueSnapshot> AtTimeResult { get; set; } = [];
public bool NativeReverse { get; init; } = true;
public int Ceiling { get; init; }
public bool Throw { get; init; }
public int ProcessedCalls;
public int ReverseOnForwardOnly;
public bool RefusedAggregateAsked { get; private set; }
public TypeCode? LastAtTimeType { get; private set; }
public bool SupportsReverseRaw => NativeReverse;
public int MaxRawValuesPerRead => Ceiling;
public bool SupportsAggregateFor(HistoryAggregateType aggregate, TypeCode? valueType)
{
if (aggregate == HistoryAggregateType.TimeAverage && valueType == TypeCode.Boolean)
{
RefusedAggregateAsked = true;
return false;
}
return true;
}
public Task<HistorianRead> ReadRawAsync(
string fullReference, DateTime startUtc, DateTime endUtc, uint maxValuesPerNode, CancellationToken cancellationToken)
{
static DateTime Ts(DataValueSnapshot s) => s.SourceTimestampUtc ?? DateTime.MinValue;
if (Throw) throw new InvalidOperationException("backend down");
var series = Series.TryGetValue(fullReference, out var s) ? s : [];
List<DataValueSnapshot> window;
if (startUtc > endUtc)
{
if (!NativeReverse)
{
Interlocked.Increment(ref ReverseOnForwardOnly);
throw new InvalidOperationException("start_time must be less than or equal to end_time.");
}
window = series.Where(x => Ts(x) > endUtc && Ts(x) <= startUtc).Reverse().ToList();
}
else if (startUtc == endUtc) window = series.Where(x => Ts(x) == startUtc).ToList();
else window = series.Where(x => Ts(x) >= startUtc && Ts(x) < endUtc).ToList();
if (Ceiling > 0 && (maxValuesPerNode == 0 || maxValuesPerNode > Ceiling) && window.Count > Ceiling)
throw new HistoryReadLimitExceededException(Ceiling, "over the ceiling");
var page = maxValuesPerNode == 0 ? window : window.Take((int)maxValuesPerNode).ToList();
return Task.FromResult(new HistorianRead(page, null));
}
public Task<HistorianRead> ReadProcessedAsync(
string fullReference, DateTime startUtc, DateTime endUtc, TimeSpan interval,
HistoryAggregateType aggregate, CancellationToken cancellationToken)
{
Interlocked.Increment(ref ProcessedCalls);
ProcessedAsked[fullReference] = aggregate;
return Task.FromResult(new HistorianRead(ProcessedResult, null));
}
public Task<HistoryModifiedReadResult> ReadModifiedAsync(
string fullReference, DateTime startUtc, DateTime endUtc, uint maxValues, HistoryModifiedCursor? resumeAfter,
CancellationToken cancellationToken)
{
if (!Trail.TryGetValue(fullReference, out var trail)) throw new NotSupportedException("no trail");
var window = trail.Where(m => m.SourceTimeUtc >= startUtc && m.SourceTimeUtc < endUtc)
.OrderBy(m => m.SourceTimeUtc).ThenBy(m => m.ModifiedId)
.Where(m => resumeAfter is null || m.SourceTimeUtc > resumeAfter.SourceTimeUtc
|| (m.SourceTimeUtc == resumeAfter.SourceTimeUtc && m.ModifiedId > resumeAfter.ModifiedId))
.ToList();
var page = maxValues == 0 ? window : window.Take((int)maxValues).ToList();
return Task.FromResult(new HistoryModifiedReadResult(page, page.Count < window.Count));
}
public Task<HistorianRead> ReadAtTimeAsync(
string fullReference, IReadOnlyList<DateTime> timestampsUtc, CancellationToken cancellationToken) =>
Task.FromResult(new HistorianRead(AtTimeResult, null));
public Task<HistorianRead> ReadAtTimeAsync(
string fullReference, IReadOnlyList<DateTime> timestampsUtc, TypeCode? valueType, CancellationToken cancellationToken)
{
LastAtTimeType = valueType;
if (Throw) throw new InvalidOperationException("backend down");
return Task.FromResult(new HistorianRead(AtTimeResult, null));
}
public Task<HistoricalEventsResult> ReadEventsAsync(
string? sourceName, DateTime startUtc, DateTime endUtc, int maxEvents, CancellationToken cancellationToken) =>
Task.FromResult(new HistoricalEventsResult(Array.Empty<HistoricalEvent>(), null));
public HistorianHealthSnapshot GetHealthSnapshot() => NullHistorianDataSource.Instance.GetHealthSnapshot();
public void Dispose() { }
}
}
@@ -0,0 +1,360 @@
using Shouldly;
using Xunit;
using ZB.MOM.WW.OtOpcUa.Commons.OpcUa;
namespace ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests;
/// <summary>
/// H1 (plan §3.2): the origin's per-(principal, incarnation) store for remote HistoryRead continuations — idle expiry,
/// capacity eviction (oldest-idle), every binding field (principal, incarnation, epoch, view, details hash), single-use
/// takes and the token's shape.
/// </summary>
[Trait("Feature", "GrpcData")]
[Trait("Phase", "H1")]
public sealed class PeerHistoryContinuationStoreTests
{
private const string Principal = "svc-consumer";
private const string Incarnation = "inc-1";
private const string Hash = "hash-a";
private static HistoryContinuationState State(string identifier = "Plant/dev/t1", long epoch = 3, AddressSpaceRealm realm = AddressSpaceRealm.Raw) =>
new("WW.T1", DateTime.UnixEpoch, DateTime.UnixEpoch.AddDays(1), 0, 10)
{
BoundRealm = realm, BoundIdentifier = identifier, BoundTag = "view-1", AddressSpaceEpoch = epoch,
};
private static PeerHistoryContinuationKey Key(
string principal = Principal, string incarnation = Incarnation, long epoch = 3,
AddressSpaceRealm realm = AddressSpaceRealm.Raw, string identifier = "Plant/dev/t1", string hash = Hash,
string? tag = "view-1") =>
new(principal, incarnation, epoch, realm, identifier, tag, hash);
private static PeerHistoryContinuationStore Store(int capacity = 8, ManualClock? clock = null, TimeSpan? idle = null) =>
new(Principal, Incarnation, capacity, idle, clock ?? new ManualClock());
[Fact]
public void A_matching_take_returns_the_state_once()
{
var store = Store();
var state = State();
var token = store.Save(state, Principal, Incarnation, Hash);
store.Count.ShouldBe(1);
store.TryTake(token, Key()).ShouldBe(state);
store.TryTake(token, Key()).ShouldBeNull("takes are single-use");
store.Count.ShouldBe(0);
}
[Fact]
public void A_mismatched_take_consumes_the_record_too()
{
var store = Store();
var token = store.Save(State(), Principal, Incarnation, Hash);
store.TryTake(token, Key(hash: "other")).ShouldBeNull();
store.TryTake(token, Key()).ShouldBeNull("a failed take never leaves the token replayable");
}
[Fact]
public void Every_bound_field_must_match()
{
var cases = new (string Name, PeerHistoryContinuationKey Key)[]
{
("principal", Key(principal: "someone-else")),
("incarnation", Key(incarnation: "inc-2")),
("epoch bump", Key(epoch: 4)),
("realm", Key(realm: AddressSpaceRealm.Uns)),
("identifier", Key(identifier: "Plant/dev/t2")),
("binding tag", Key(tag: "view-2")),
("no binding tag", Key(tag: null)),
("details hash", Key(hash: "hash-b")),
};
foreach (var (name, key) in cases)
{
var store = Store();
var token = store.Save(State(), Principal, Incarnation, Hash);
store.TryTake(token, key).ShouldBeNull(name);
}
}
[Fact]
public void An_idle_record_expires()
{
var clock = new ManualClock();
var store = Store(clock: clock);
var fresh = store.Save(State(), Principal, Incarnation, Hash);
clock.Advance(TimeSpan.FromSeconds(59));
store.TryTake(fresh, Key()).ShouldNotBeNull("59 s is inside the default 60 s idle expiry");
var stale = store.Save(State(), Principal, Incarnation, Hash);
clock.Advance(TimeSpan.FromSeconds(60));
store.Count.ShouldBe(0);
store.TryTake(stale, Key()).ShouldBeNull();
PeerHistoryContinuationStore.DefaultIdleExpiry.ShouldBe(TimeSpan.FromSeconds(60));
}
[Fact]
public void A_custom_idle_expiry_applies()
{
var clock = new ManualClock();
var store = Store(clock: clock, idle: TimeSpan.FromSeconds(5));
var token = store.Save(State(), Principal, Incarnation, Hash);
clock.Advance(TimeSpan.FromSeconds(5));
store.TryTake(token, Key()).ShouldBeNull();
}
[Fact]
public void Capacity_evicts_the_oldest_idle_record()
{
var clock = new ManualClock();
var store = Store(capacity: 3, clock: clock);
var tokens = new List<byte[]>();
for (var i = 0; i < 3; i++)
{
tokens.Add(store.Save(State(), Principal, Incarnation, Hash));
clock.Advance(TimeSpan.FromSeconds(1));
}
// Take the middle one: the oldest-idle survivor is still tokens[0].
store.TryTake(tokens[1], Key()).ShouldNotBeNull();
tokens.Add(store.Save(State(), Principal, Incarnation, Hash)); // 3 live: 0, 2, 3 — at capacity, nothing evicted yet
store.Count.ShouldBe(3);
tokens.Add(store.Save(State(), Principal, Incarnation, Hash)); // over capacity ⇒ evicts tokens[0]
store.Count.ShouldBe(3);
store.TryTake(tokens[0], Key()).ShouldBeNull("the oldest-idle record was evicted");
store.TryTake(tokens[2], Key()).ShouldNotBeNull();
store.TryTake(tokens[3], Key()).ShouldNotBeNull();
store.TryTake(tokens[4], Key()).ShouldNotBeNull();
}
[Fact]
public void Expired_records_are_swept_before_capacity_evicts_a_live_one()
{
var clock = new ManualClock();
var store = Store(capacity: 2, clock: clock);
store.Save(State(), Principal, Incarnation, Hash);
clock.Advance(TimeSpan.FromSeconds(61));
var live = store.Save(State(), Principal, Incarnation, Hash);
var newest = store.Save(State(), Principal, Incarnation, Hash);
store.TryTake(live, Key()).ShouldNotBeNull();
store.TryTake(newest, Key()).ShouldNotBeNull();
}
[Fact]
public void Release_drops_a_record_and_is_idempotent()
{
var store = Store();
var token = store.Save(State(), Principal, Incarnation, Hash);
store.Release(token).ShouldBeTrue();
store.Release(token).ShouldBeFalse();
store.TryTake(token, Key()).ShouldBeNull();
store.Release(null).ShouldBeFalse();
store.Release([1, 2, 3]).ShouldBeFalse();
}
[Fact]
public void Clear_drops_everything()
{
var store = Store();
var token = store.Save(State(), Principal, Incarnation, Hash);
store.Save(State(), Principal, Incarnation, Hash);
store.Clear();
store.Count.ShouldBe(0);
store.TryTake(token, Key()).ShouldBeNull();
}
[Fact]
public void Tokens_are_random_16_byte_ids()
{
var store = Store(capacity: 2000);
var seen = new HashSet<string>();
for (var i = 0; i < 1000; i++)
{
var token = store.Save(State(), Principal, Incarnation, Hash);
token.Length.ShouldBe(PeerHistoryContinuationStore.TokenLength);
PeerHistoryContinuationStore.TokenLength.ShouldBe(16);
seen.Add(Convert.ToHexString(token)).ShouldBeTrue("tokens never repeat");
}
// Random, not sequential: across 1000 tokens every byte position takes many values.
var tokens = seen.Select(Convert.FromHexString).ToList();
for (var position = 0; position < 16; position++)
tokens.Select(t => t[position]).Distinct().Count().ShouldBeGreaterThan(100, $"byte {position}");
}
[Fact]
public void Malformed_tokens_are_misses()
{
var store = Store();
store.Save(State(), Principal, Incarnation, Hash);
store.TryTake(null, Key()).ShouldBeNull();
store.TryTake([], Key()).ShouldBeNull();
store.TryTake(new byte[15], Key()).ShouldBeNull();
store.TryTake(new byte[17], Key()).ShouldBeNull();
store.TryTake(new byte[16], Key()).ShouldBeNull();
store.Count.ShouldBe(1);
}
[Fact]
public void A_record_must_be_bound_to_a_view_and_arguments_are_validated()
{
var store = Store();
Should.Throw<ArgumentException>(() => store.Save(State() with { BoundIdentifier = null }, Principal, Incarnation, Hash));
Should.Throw<ArgumentOutOfRangeException>(() => new PeerHistoryContinuationStore(Principal, Incarnation, 0));
Should.Throw<ArgumentException>(() => new PeerHistoryContinuationStore(" ", Incarnation, 1));
Should.Throw<ArgumentException>(() => new PeerHistoryContinuationStore(Principal, "", 1));
Should.Throw<ArgumentOutOfRangeException>(() => new PeerHistoryContinuationStore(Principal, Incarnation, 1, TimeSpan.Zero));
}
[Fact]
public void The_scope_binds_the_request_details_hash()
{
var store = Store();
var scope = new PeerHistoryContinuationScope(store, Principal, () => Incarnation);
var details = new HistoryReadRawVariant(DateTime.UnixEpoch, DateTime.UnixEpoch.AddHours(1), 10, ReturnBounds: false);
var binding = new HistoryContinuationBinding(AddressSpaceRealm.Raw, "Plant/dev/t1", 3, details, Tag: "view-1");
var token = scope.Save(State(), binding)!;
scope.TryTake(token, binding with { Details = details with { NumValuesPerNode = 11 } }).ShouldBeNull("other details");
token = scope.Save(State(), binding)!;
scope.TryTake(token, binding with { Details = details with { } }).ShouldNotBeNull("equal details hash equal");
token = scope.Save(State(), binding)!;
scope.TryTake(token, binding with { Epoch = 4 }).ShouldBeNull("epoch bump");
store.Count.ShouldBe(0);
}
[Fact]
public void A_serving_incarnation_change_on_a_live_connection_invalidates_its_tokens()
{
// In-process failover / role change: the connection (and so the store) survives, the serving incarnation does not.
var store = Store();
var incarnation = Incarnation;
var scope = new PeerHistoryContinuationScope(store, Principal, () => incarnation);
var binding = new HistoryContinuationBinding(AddressSpaceRealm.Raw, "Plant/dev/t1", 3,
new HistoryReadRawVariant(DateTime.UnixEpoch, DateTime.UnixEpoch.AddHours(1), 10, ReturnBounds: false), Tag: "view-1");
var token = scope.Save(State(), binding)!;
incarnation = "inc-2";
// A scope is per request: the resume is a NEW request, so it reads inc-2.
var resume = new PeerHistoryContinuationScope(store, Principal, () => incarnation);
resume.TryTake(token, binding).ShouldBeNull("issued under inc-1, resumed under inc-2");
token = new PeerHistoryContinuationScope(store, Principal, () => incarnation).Save(State(), binding)!;
new PeerHistoryContinuationScope(store, Principal, () => incarnation).TryTake(token, binding)
.ShouldNotBeNull("issued and resumed under inc-2");
}
[Fact]
public void Only_the_owning_principal_can_save_or_take()
{
var store = Store();
var owner = new PeerHistoryContinuationScope(store, Principal, () => Incarnation);
var other = new PeerHistoryContinuationScope(store, "someone-else", () => Incarnation);
var binding = new HistoryContinuationBinding(AddressSpaceRealm.Raw, "Plant/dev/t1", 3, null, Tag: "view-1");
Should.Throw<PeerHistoryContinuationWiringException>(() => other.Save(State(), binding), "a store never holds another principal's cursor");
var token = owner.Save(State(), binding)!;
other.TryTake(token, binding).ShouldBeNull();
owner.TryTake(token, binding).ShouldBeNull("the foreign take consumed it");
}
[Fact]
public void A_take_whose_expectation_throws_still_consumes_the_token()
{
var store = Store();
var token = store.Save(State(), Principal, Incarnation, Hash);
store.TryTake(token, () => throw new InvalidOperationException("incarnation source down")).ShouldBeNull();
store.Count.ShouldBe(0);
store.TryTake(token, Key()).ShouldBeNull("the token is gone");
}
[Fact]
public void A_scope_whose_incarnation_source_throws_or_is_blank_takes_nothing_and_fails_wiring_on_save()
{
var binding = new HistoryContinuationBinding(AddressSpaceRealm.Raw, "Plant/dev/t1", 3, null, Tag: "view-1");
foreach (var (name, source) in new (string, Func<string>)[]
{
("throws", () => throw new InvalidOperationException("incarnation source down")),
("blank", () => " "),
})
{
var store = Store();
var token = store.Save(State(), Principal, Incarnation, Hash);
var broken = new PeerHistoryContinuationScope(store, Principal, source);
broken.TryTake(token, binding).ShouldBeNull(name);
store.Count.ShouldBe(0, $"{name}: the take consumed the token");
Should.Throw<PeerHistoryContinuationWiringException>(
() => new PeerHistoryContinuationScope(store, Principal, source).Save(State(), binding), name);
}
}
[Fact]
public void Wiring_errors_have_their_own_exception_type()
{
var store = Store();
Should.Throw<PeerHistoryContinuationWiringException>(() => store.Save(State(), "someone-else", Incarnation, Hash));
Should.Throw<PeerHistoryContinuationWiringException>(() => store.Save(State(), Principal, "", Hash));
}
[Fact]
public void A_request_that_straddles_an_incarnation_change_binds_the_incarnation_it_started_under()
{
// One scope per request: the incarnation is snapshotted at its first use, so a failover that lands between the
// request's take and its save cannot re-bind the next token to the NEW incarnation.
var store = Store();
var incarnation = Incarnation;
var binding = new HistoryContinuationBinding(AddressSpaceRealm.Raw, "Plant/dev/t1", 3, null, Tag: "view-1");
var first = new PeerHistoryContinuationScope(store, Principal, () => incarnation).Save(State(), binding)!;
var request = new PeerHistoryContinuationScope(store, Principal, () => incarnation);
request.TryTake(first, binding).ShouldNotBeNull();
incarnation = "inc-2"; // failover mid-request
var next = request.Save(State(), binding);
next.ShouldNotBeNull("a save never answers null (that would read as a complete read)");
new PeerHistoryContinuationScope(store, Principal, () => incarnation).TryTake(next!, binding)
.ShouldBeNull("the next token is bound to inc-1, so the resume under inc-2 is refused");
}
[Fact]
public void The_details_hash_is_culture_invariant()
{
var variants = new HistoryReadVariant[]
{
new HistoryReadRawVariant(DateTime.UnixEpoch, DateTime.UnixEpoch.AddHours(1), 10, ReturnBounds: true),
new HistoryReadProcessedVariant(DateTime.UnixEpoch, DateTime.UnixEpoch.AddHours(1), TimeSpan.FromTicks(-5),
new Opc.Ua.AggregateConfiguration { PercentDataBad = 100, PercentDataGood = 100 }),
new HistoryReadAtTimeVariant([DateTime.UnixEpoch, DateTime.UnixEpoch.AddSeconds(1)]),
};
var invariant = variants.Select(v => v.ComputeDetailsHash()).ToArray();
var odd = (System.Globalization.CultureInfo)System.Globalization.CultureInfo.InvariantCulture.Clone();
odd.NumberFormat.NegativeSign = "~";
odd.NumberFormat.NumberGroupSeparator = "'";
odd.TextInfo.ListSeparator = "#";
var previous = System.Globalization.CultureInfo.CurrentCulture;
try
{
System.Globalization.CultureInfo.CurrentCulture = odd;
variants.Select(v => v.ComputeDetailsHash()).ToArray().ShouldBe(invariant);
}
finally
{
System.Globalization.CultureInfo.CurrentCulture = previous;
}
}
/// <summary>A monotonic test clock.</summary>
private sealed class ManualClock : TimeProvider
{
private long _ticks = 1_000_000;
public override long TimestampFrequency => TimeSpan.TicksPerSecond;
public override long GetTimestamp() => Interlocked.Read(ref _ticks);
public void Advance(TimeSpan by) => Interlocked.Add(ref _ticks, by.Ticks);
}
}