fix(grpc-data): H1 cursors bind an opaque namespace/view tag besides (realm, identifier) (review 2)

The realm folds mapped/raw into Raw (and every other index into Uns), so
(realm, identifier) alone could resume a raw node's cursor on the same
identifier in a mapped namespace. Items and cursor state now carry a
binding tag: the SDK adapter (and the events path) passes the node's
namespace URI, restoring the pre-port namespace-qualified binding; a peer
passes its view tag. The peer key binds it too.
This commit is contained in:
Joseph Doherty
2026-11-23 19:49:59 -05:00
parent 1bacabb24f
commit 19a7c7af01
7 changed files with 100 additions and 33 deletions
@@ -77,6 +77,8 @@ namespace ZB.MOM.WW.OtOpcUa.OpcUaServer;
/// <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,
@@ -95,6 +97,7 @@ internal sealed record HistoryContinuationState(
bool WithinTieCluster = false,
AddressSpaceRealm BoundRealm = default,
string? BoundIdentifier = null,
string? BoundTag = null,
long AddressSpaceEpoch = -1)
{
/// <summary>The walk-back hint this cursor carries.</summary>
@@ -94,11 +94,22 @@ internal sealed record HistoryReadAtTimeVariant(IReadOnlyList<DateTime> Timestam
/// <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)
AddressSpaceRealm Realm, string Identifier, byte[]? ContinuationPoint = null, NodeId AggregateType = default,
string? BindingTag = null, NodeId NodeId = default)
{
/// <summary>The node, for log lines (<c>Realm:Identifier</c>).</summary>
public override string ToString() => $"{Realm}:{Identifier}";
/// <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>
@@ -145,8 +156,9 @@ internal sealed class HistoryReadNodeOutcome
/// <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);
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
@@ -361,7 +373,8 @@ public sealed partial class OtOpcUaNodeManager
// 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);
variant is HistoryReadProcessedVariant ? aggregates[handle.Index] : default,
HistoryBindingTag(handle.NodeId), handle.NodeId);
}
var outcomes = ReadHistory(variant, items, SessionHistoryContinuationScope(context.OperationContext?.Session),
@@ -374,6 +387,17 @@ public sealed partial class OtOpcUaNodeManager
}
}
/// <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>
@@ -417,18 +441,20 @@ public sealed partial class OtOpcUaNodeManager
/// single-shot for that node, as before.
/// </summary>
private byte[]? SaveHistoryContinuation(
IHistoryContinuationScope scope, AddressSpaceRealm realm, string identifier, long epoch,
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, AddressSpaceEpoch = epoch },
new HistoryContinuationBinding(realm, identifier, epoch, details));
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, in this realm, under this epoch.</summary>
private static bool HistoryContinuationMatches(HistoryContinuationState state, AddressSpaceRealm realm, string identifier, long epoch) =>
/// <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) && state.AddressSpaceEpoch == epoch;
&& 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
@@ -9036,7 +9036,7 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage
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.
var boundKey = MapKey(handle.NodeId);
if (state is null || !HistoryContinuationMatches(state, boundKey.Realm, boundKey.Id, historyEpoch) || state.Kind != HistoryCursorKind.Events || state.Tagname != sourceName)
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 };
@@ -9214,7 +9214,8 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage
var historyEvent = ProjectEvents(events, selectClauses, where, filterContext);
var eventsKey = MapKey(handle.NodeId);
var outboundCp = pendingCursor is null ? null : SaveHistoryContinuation(
SessionHistoryContinuationScope(session), eventsKey.Realm, eventsKey.Id, historyEpoch, details: null, pendingCursor);
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).
@@ -10119,8 +10120,8 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage
{
// Resume read: take the stored cursor. A miss (unknown / evicted / malformed point) ⇒
// BadContinuationPointInvalid for THIS node.
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
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)
{
outcome.Error = StatusCodes.BadContinuationPointInvalid;
@@ -10187,7 +10188,7 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage
return null;
}
return SaveHistoryContinuation(continuations, handle.Realm, handle.Identifier, historyEpoch, details, 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 }));
@@ -10253,7 +10254,7 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage
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(continuations, handle.Realm, handle.Identifier, historyEpoch, details, 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])));
@@ -10440,7 +10441,7 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage
EmptyFromTicks: walkHint.EmptyFromTicks, EmptyToTicks: walkHint.EmptyToTicks,
PendingEndBound: HistoryBounds.Carry(endBound, slice),
WithinTieCluster: resumeAt == startUtc);
clusterCp = SaveHistoryContinuation(continuations, handle.Realm, handle.Identifier, historyEpoch, details, clusterState);
clusterCp = SaveHistoryContinuation(continuations, handle.Realm, handle.Identifier, handle.BindingTag, historyEpoch, details, clusterState);
}
else if (endBound is not null)
{
@@ -10495,7 +10496,7 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage
{
// 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(continuations, handle.Realm, handle.Identifier, historyEpoch, details, nextState);
outboundCp = SaveHistoryContinuation(continuations, handle.Realm, handle.Identifier, handle.BindingTag, historyEpoch, details, nextState);
}
else if (endBound is not null)
{
@@ -10595,8 +10596,8 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage
HistoryModifiedCursor? resumeAfter = null;
if (inboundCp is { Length: > 0 })
{
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)
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)
{
outcome.Error = StatusCodes.BadContinuationPointInvalid;
outcome.Result = new SdkHistoryReadResult { StatusCode = StatusCodes.BadContinuationPointInvalid };
@@ -10626,7 +10627,7 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage
if (page.HasMore && numValuesPerNode > 0 && page.Values.Count > 0)
{
var last = page.Values[^1];
outboundCp = SaveHistoryContinuation(continuations, handle.Realm, handle.Identifier, historyEpoch, details, 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));
}
@@ -13,9 +13,10 @@ namespace ZB.MOM.WW.OtOpcUa.OpcUaServer;
/// <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 DetailsHash);
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;
@@ -123,7 +124,7 @@ internal sealed class PeerHistoryContinuationStore
var token = RandomNumberGenerator.GetBytes(TokenLength);
var key = new PeerHistoryContinuationKey(
principal, servingIncarnation, state.AddressSpaceEpoch, state.BoundRealm, state.BoundIdentifier, detailsHash);
principal, servingIncarnation, state.AddressSpaceEpoch, state.BoundRealm, state.BoundIdentifier, state.BoundTag, detailsHash);
lock (_gate)
{
var now = _clock.GetTimestamp();
@@ -214,6 +215,6 @@ internal sealed class PeerHistoryContinuationScope(
/// <inheritdoc />
public HistoryContinuationState? TryTake(byte[] continuationPoint, HistoryContinuationBinding binding) =>
store.TryTake(continuationPoint, new PeerHistoryContinuationKey(
principal, currentServingIncarnation(), binding.Epoch, binding.Realm, binding.Identifier,
principal, currentServingIncarnation(), binding.Epoch, binding.Realm, binding.Identifier, binding.Tag,
binding.Details?.ComputeDetailsHash() ?? string.Empty));
}