feat(grpc-data): H1 override-level history port; SDK HistoryRead overrides become adapters
Raw/modified, Processed and AtTime serving (aggregate refusals incl. #897 and SupportsAggregateFor, non-default AggregateConfiguration, modified+bounds BadInvalidArgument, batch limiter, deadline, continuation binding, value normalisation) now runs through OtOpcUaNodeManager.ReadHistory, addressed by (realm, identifier) instead of SDK node handles. Continuation cursors are re-keyed from the NodeId string to (realm, identifier). Adds the production PeerHistoryContinuationStore (per principal + incarnation, random 16-byte single-use tokens, 60 s idle expiry, oldest-idle eviction) for H2.
This commit is contained in:
@@ -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,9 @@ 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="AddressSpaceEpoch">The topology generation. A removal conservatively invalidates all cursors.</param>
|
||||
internal sealed record HistoryContinuationState(
|
||||
string Tagname,
|
||||
@@ -90,7 +93,8 @@ internal sealed record HistoryContinuationState(
|
||||
long EmptyToTicks = 0,
|
||||
HistoryEndBound? PendingEndBound = null,
|
||||
bool WithinTieCluster = false,
|
||||
string? BoundNodeKey = null,
|
||||
AddressSpaceRealm BoundRealm = default,
|
||||
string? BoundIdentifier = null,
|
||||
long AddressSpaceEpoch = -1)
|
||||
{
|
||||
/// <summary>The walk-back hint this cursor carries.</summary>
|
||||
|
||||
@@ -0,0 +1,429 @@
|
||||
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.</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() =>
|
||||
$"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" : $"{c.UseServerCapabilitiesDefaults}|{c.TreatUncertainAsBad}|{c.PercentDataBad}|{c.PercentDataGood}|{c.UseSlopedExtrapolation}";
|
||||
return $"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));
|
||||
}
|
||||
|
||||
/// <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>
|
||||
internal readonly record struct HistoryReadPortItem(
|
||||
AddressSpaceRealm Realm, string Identifier, byte[]? ContinuationPoint = null, NodeId AggregateType = default)
|
||||
{
|
||||
/// <summary>The node, for log lines (<c>Realm:Identifier</c>).</summary>
|
||||
public override string ToString() => $"{Realm}:{Identifier}";
|
||||
}
|
||||
|
||||
/// <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 operation status a non-SDK caller (H2) reports.</summary>
|
||||
public StatusCode Status => Error?.StatusCode ?? StatusCodes.BadHistoryOperationUnsupported;
|
||||
|
||||
/// <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>
|
||||
internal readonly record struct HistoryContinuationBinding(
|
||||
AddressSpaceRealm Realm, string Identifier, long Epoch, HistoryReadVariant? Details);
|
||||
|
||||
/// <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);
|
||||
}
|
||||
|
||||
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 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, long epoch,
|
||||
HistoryReadVariant? details, HistoryContinuationState state)
|
||||
{
|
||||
if (epoch != Volatile.Read(ref _historyContinuationEpoch)) return null;
|
||||
return scope.Save(state with { BoundRealm = realm, BoundIdentifier = identifier, AddressSpaceEpoch = epoch },
|
||||
new HistoryContinuationBinding(realm, identifier, epoch, details));
|
||||
}
|
||||
|
||||
/// <summary>Whether a taken cursor was issued for this node, in this realm, under this epoch.</summary>
|
||||
private static bool HistoryContinuationMatches(HistoryContinuationState state, AddressSpaceRealm realm, string identifier, long epoch) =>
|
||||
state.BoundIdentifier is not null && state.BoundRealm == realm
|
||||
&& string.Equals(state.BoundIdentifier, identifier, 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, historyEpoch) || state.Kind != HistoryCursorKind.Events || state.Tagname != sourceName)
|
||||
{
|
||||
errors[handle.Index] = StatusCodes.BadContinuationPointInvalid;
|
||||
results[handle.Index] = new SdkHistoryReadResult { StatusCode = StatusCodes.BadContinuationPointInvalid };
|
||||
@@ -9313,7 +9212,9 @@ 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, 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 +9824,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 +9876,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 +9896,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 +9921,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 +9954,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 +9987,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 +10007,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 +10017,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);
|
||||
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, 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);
|
||||
outcome.Error = HistoryReadFailureStatus(ex);
|
||||
outcome.Result = new SdkHistoryReadResult { StatusCode = HistoryReadFailureStatus(ex) };
|
||||
}
|
||||
}
|
||||
|
||||
@@ -10174,12 +10079,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 +10093,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 +10104,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 +10119,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));
|
||||
if (state is null || !HistoryContinuationMatches(state, handle.Realm, handle.Identifier, 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 +10140,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 +10187,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, 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 +10226,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 +10253,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, 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 +10407,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 +10440,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, historyEpoch, details, clusterState);
|
||||
}
|
||||
else if (endBound is not null)
|
||||
{
|
||||
@@ -10549,13 +10452,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 +10495,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, historyEpoch, details, nextState);
|
||||
}
|
||||
else if (endBound is not null)
|
||||
{
|
||||
@@ -10615,7 +10518,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 +10527,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, 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);
|
||||
outcome.Error = HistoryReadFailureStatus(ex);
|
||||
outcome.Result = new SdkHistoryReadResult { StatusCode = HistoryReadFailureStatus(ex) };
|
||||
}
|
||||
}
|
||||
|
||||
@@ -10659,34 +10562,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 +10595,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));
|
||||
if (state is null || !HistoryContinuationMatches(state, handle.Realm, handle.Identifier, 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 +10626,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, 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);
|
||||
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);
|
||||
outcome.Error = HistoryReadFailureStatus(ex);
|
||||
outcome.Result = new SdkHistoryReadResult { StatusCode = HistoryReadFailureStatus(ex) };
|
||||
}
|
||||
}
|
||||
|
||||
@@ -10803,18 +10704,6 @@ 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)
|
||||
{
|
||||
@@ -10824,38 +10713,6 @@ public sealed class OtOpcUaNodeManager : CustomNodeManager2, INodeManager3, IPro
|
||||
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,205 @@
|
||||
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 the cursor was issued under.</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="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 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; 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 principal, serving incarnation, history epoch, view and details hash; a
|
||||
/// take whose expected <see cref="PeerHistoryContinuationKey"/> differs in ANY of them is a miss
|
||||
/// (<c>BadContinuationPointInvalid</c> at the port).</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.</param>
|
||||
/// <param name="servingIncarnation">This server's serving incarnation at connection time.</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 servingIncarnation, int capacity, TimeSpan? idleExpiry = null, TimeProvider? clock = null)
|
||||
{
|
||||
ArgumentException.ThrowIfNullOrWhiteSpace(principal);
|
||||
ArgumentException.ThrowIfNullOrWhiteSpace(servingIncarnation);
|
||||
ArgumentOutOfRangeException.ThrowIfLessThan(capacity, 1);
|
||||
var idle = idleExpiry ?? DefaultIdleExpiry;
|
||||
ArgumentOutOfRangeException.ThrowIfLessThanOrEqual(idle, TimeSpan.Zero, nameof(idleExpiry));
|
||||
Principal = principal;
|
||||
ServingIncarnation = servingIncarnation;
|
||||
Capacity = capacity;
|
||||
IdleExpiry = idle;
|
||||
_clock = clock ?? TimeProvider.System;
|
||||
}
|
||||
|
||||
/// <summary>The principal this instance serves.</summary>
|
||||
public string Principal { get; }
|
||||
|
||||
/// <summary>The connection's serving incarnation.</summary>
|
||||
public string ServingIncarnation { 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 this instance's principal and incarnation, 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="detailsHash">The request's details hash.</param>
|
||||
/// <returns>The 16-byte token.</returns>
|
||||
public byte[] Save(HistoryContinuationState state, 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));
|
||||
|
||||
var token = RandomNumberGenerator.GetBytes(TokenLength);
|
||||
var key = new PeerHistoryContinuationKey(
|
||||
Principal, ServingIncarnation, state.AddressSpaceEpoch, state.BoundRealm, state.BoundIdentifier, 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)
|
||||
{
|
||||
if (token is not { Length: TokenLength }) return null;
|
||||
lock (_gate)
|
||||
{
|
||||
var now = _clock.GetTimestamp();
|
||||
Sweep(now);
|
||||
if (!_entries.TryGetValue(new Guid(token), out var node)) return null;
|
||||
Remove(node);
|
||||
return node.Value.Key == expected ? node.Value.State : null;
|
||||
}
|
||||
}
|
||||
|
||||
/// <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>
|
||||
/// The port's continuation scope for one remote peer: saves and takes through that peer's
|
||||
/// <see cref="PeerHistoryContinuationStore"/>, binding the request's details hash and this instance's principal and
|
||||
/// incarnation on top of the view and epoch the port itself re-checks.
|
||||
/// </summary>
|
||||
/// <param name="store">The (principal, incarnation) store.</param>
|
||||
internal sealed class PeerHistoryContinuationScope(PeerHistoryContinuationStore store) : IHistoryContinuationScope
|
||||
{
|
||||
/// <inheritdoc />
|
||||
public byte[]? Save(HistoryContinuationState state, HistoryContinuationBinding binding) =>
|
||||
store.Save(state, binding.Details?.ComputeDetailsHash() ?? string.Empty);
|
||||
|
||||
/// <inheritdoc />
|
||||
public HistoryContinuationState? TryTake(byte[] continuationPoint, HistoryContinuationBinding binding) =>
|
||||
store.TryTake(continuationPoint, new PeerHistoryContinuationKey(
|
||||
store.Principal, store.ServingIncarnation, binding.Epoch, binding.Realm, binding.Identifier,
|
||||
binding.Details?.ComputeDetailsHash() ?? string.Empty));
|
||||
}
|
||||
Reference in New Issue
Block a user