Files
lmxopcua/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ProjectedHistoryAccess.cs
T
Joseph Doherty 7aaa98751a fix(grpc-data): H3 review round 2 — no batch probe; budget stop; orphan tokens; lease-retired status
1: the separate capability probe is gone (through the unary path a cancelled
probe recorded an endpoint failure and put the connection into discovery
backoff). Projected calls split at the deployed connection's batch size;
GrpcDataConnection splits again at the origin's advertised MaxBatchItems from
the capabilities the history call already negotiated, sharing the assembly
budget across sub-batches. 3: once the connection reports the assembly budget
spent, no further origin call is made. 4: an answer that never became an
outcome (mismatch, exception mid-answer) releases its new origin token. 5: a
cancel that is neither the caller's nor the deadline (a lease retired by a
redeploy) is BadNoCommunication / BadContinuationPointInvalid, not BadTimeout.
Flush delay on the access's clock. Docs: the request deadline covers the local
half too; shared non-local slots; split. Red/green for each by mutation.
2026-11-24 06:25:19 -05:00

546 lines
30 KiB
C#

using Opc.Ua;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections;
using ZB.MOM.WW.OtOpcUa.OpcUaServer;
using ZB.MOM.WW.OtOpcUa.OpcUaServer.Security;
namespace ZB.MOM.WW.OtOpcUa.Runtime.DataConnections;
/// <summary>A connection's own history batch size (the deployed connection row's batch); a larger request is refused.</summary>
internal interface IHistoryBatchLimit
{
int MaxHistoryBatchItems { get; }
}
/// <summary>What a projected HistoryRead demand is bound to (H3).</summary>
/// <param name="MappingId">The mapping.</param>
/// <param name="MappingRevision">The deployed mapping revision.</param>
/// <param name="ConnectionId">The deployed connection the mapping reads through.</param>
/// <param name="OriginMetadata">The origin's metadata (origin view, value kind).</param>
/// <param name="Serving">The origin serving identity the projection was built under.</param>
/// <param name="ProjectionGeneration">The projection generation.</param>
internal sealed record ProjectedHistoryTarget(string MappingId, long MappingRevision, string ConnectionId, DataMetadata OriginMetadata,
ServingIdentity Serving, long ProjectionGeneration);
/// <summary>
/// H3 — consumer OPC UA projection of remote history (gRPC data history plan §2.1, §3.2, §3.3). For each projected node:
/// resolve + authorize + pin it through <see cref="ProjectedDataAccess"/> (a <see cref="DataOperations.HistoryRead"/>
/// demand: the mapping's HistoryRead bit and a local HistoryRead grant on the mapping scope, ACLs on or off), group the
/// batch per deployed connection and per details, and forward through <see cref="IDataHistoryService"/>.
/// <list type="bullet">
/// <item>A fresh read may move endpoint within its deadline (the connection decides); a RESUMED read never moves —
/// its origin token pins the issuing endpoint and serving incarnation, and its cursor re-checks the caller, the
/// mapping revision, the projection generation, the serving identity and the connection lease (route) before any
/// call. Any mismatch ⇒ <c>BadContinuationPointInvalid</c> and the origin token is released.</item>
/// <item>A resume resends the ORIGINAL details verbatim (the origin binds their hash); local SDK resumes ignore details,
/// so the consumer does too.</item>
/// <item>The per-request assembly budget (min <c>MaxHistoryAssemblyBytesPerRequest</c> of the batch's mappings) is shared
/// across the batch; once spent, the remaining nodes are <c>BadTooManyOperations</c>.</item>
/// <item>Deadline per call = min(the consumer's remaining <c>HistoryReadDeadline</c>, the connection's
/// <c>HistoryTimeoutMilliseconds</c>) ⇒ <c>BadTimeout</c>; a cancelled read is never an origin fault.</item>
/// <item>Releases (<c>releaseContinuationPoints</c>, session close, eviction) are coalesced per connection into one
/// best-effort <c>ReleaseHistoryAsync</c>; the origin's idle expiry is the backstop.</item>
/// </list>
/// </summary>
public sealed class ProjectedHistoryAccess : IProjectedHistoryAccess, IDisposable
{
internal const uint Good = 0, BadContinuationPointInvalid = 0x804A0000u, BadTooManyOperations = 0x80100000u, BadTimeout = 0x800A0000u,
BadNoCommunication = 0x80310000u, BadTypeMismatch = 0x80740000u, BadHistoryOperationUnsupported = 0x80720000u;
internal const long DefaultAssemblyBudget = 16L * 1024 * 1024;
private readonly ProjectedDataAccess _access;
private readonly IGrpcDataAdapterConnectionSource _connections;
private readonly Func<string, long?> _assemblyBudget;
private readonly TimeProvider _clock;
private readonly object _releaseGate = new();
private readonly Dictionary<string, List<byte[]>> _pendingReleases = new(StringComparer.OrdinalIgnoreCase);
private readonly CancellationTokenSource _stop = new();
private Task _releaseFlush = Task.CompletedTask;
private bool _flushScheduled;
private int _disposed;
/// <summary>Creates the gateway.</summary>
/// <param name="access">The projected data access that resolves, authorizes and pins projected nodes.</param>
/// <param name="connections">The deployed connection registry.</param>
/// <param name="assemblyBudget">A mapping's <c>MaxHistoryAssemblyBytesPerRequest</c>; null = not deployed.</param>
/// <param name="clock">The clock.</param>
public ProjectedHistoryAccess(ProjectedDataAccess access, IGrpcDataAdapterConnectionSource connections,
Func<string, long?> assemblyBudget, TimeProvider clock)
{
_access = access ?? throw new ArgumentNullException(nameof(access));
_connections = connections ?? throw new ArgumentNullException(nameof(connections));
_assemblyBudget = assemblyBudget ?? throw new ArgumentNullException(nameof(assemblyBudget));
_clock = clock ?? throw new ArgumentNullException(nameof(clock));
}
/// <summary>How long a release waits to coalesce with others for the same connection (a session close disposes one by one).</summary>
internal TimeSpan ReleaseCoalesce { get; init; } = TimeSpan.FromMilliseconds(25);
/// <summary>Releases queued and not yet sent (tests).</summary>
internal int PendingReleasesForTests { get { lock (_releaseGate) return _pendingReleases.Values.Sum(x => x.Count); } }
/// <summary>Release calls sent (tests): one per connection per coalesced flush.</summary>
internal int ReleaseCallsForTests => Volatile.Read(ref _releaseCalls);
private int _releaseCalls;
/// <summary>Waits for the queued releases to be sent (tests).</summary>
internal async Task FlushReleasesForTestsAsync()
{
Task flush;
lock (_releaseGate) flush = _releaseFlush;
await flush.ConfigureAwait(false);
lock (_releaseGate) flush = _releaseFlush;
await flush.ConfigureAwait(false);
}
/// <summary>
/// Whether a projected node is advertised as historizing: the mapping (masked by the export) grants HistoryRead AND the
/// origin's negotiated metadata (<c>HistoryInfo</c>, bit 32) says historizing.
/// </summary>
public static bool Advertises(ProjectedNodeProof proof) =>
proof is not null && (proof.Subject.AllowedOperations & DataOperations.HistoryRead) != 0
&& (proof.OriginMetadata.AllowedOperations & DataOperations.HistoryRead) != 0
&& proof.OriginMetadata.History is { Historizing: true } && proof.OriginMetadata.NodeKind is "Variable" or "Tag";
/// <inheritdoc />
public async Task<IReadOnlyList<ProjectedHistoryOutcome>> ReadAsync(RoleCarryingUserIdentity caller, DataHistoryDetails details,
IReadOnlyList<ProjectedHistoryNode> nodes, TimeSpan deadline, CancellationToken cancellationToken)
{
ArgumentNullException.ThrowIfNull(caller); ArgumentNullException.ThrowIfNull(details); ArgumentNullException.ThrowIfNull(nodes);
var started = _clock.GetTimestamp();
var outcomes = new ProjectedHistoryOutcome?[nodes.Count];
var demands = new IProjectedDemandLease?[nodes.Count];
var targets = new ProjectedHistoryTarget?[nodes.Count];
var assembled = new long[nodes.Count];
var assemblyRefused = new bool[nodes.Count];
var callerKey = CallerKey(caller);
long budget = DefaultAssemblyBudget, received = 0;
var budgetExhausted = false;
try
{
// 1. Resolve, authorize and pin every node; check each resumed cursor against what it was issued under.
for (var i = 0; i < nodes.Count; i++)
{
var node = nodes[i];
var cursor = node.Resume as RemoteCursor;
if (node.Resume is not null && (cursor is null || !ReferenceEquals(cursor.Owner, this)))
{
node.Resume.ReleaseEvenIfClaimed();
outcomes[i] = Fail(BadContinuationPointInvalid);
continue;
}
if (!_access.TryAcquire(node.NodeId, caller, DataOperations.HistoryRead, out var demand) || demand is null
|| !_access.TryDescribeHistoryDemand(demand, out var target) || target is null)
{
demand?.Dispose();
cursor?.ReleaseOrigin();
// The node manager already authorized the node: a projection that cannot be pinned now is not servable.
outcomes[i] = Fail(cursor is null ? BadNoCommunication : BadContinuationPointInvalid);
continue;
}
demands[i] = demand;
targets[i] = target;
if (cursor is not null && !cursor.StillMatches(callerKey, target, demand))
{
// Mapping revision change, failover, projection rebuild, another caller: the cursor never resumes.
cursor.ReleaseOrigin();
outcomes[i] = Fail(BadContinuationPointInvalid);
}
}
// 2. The per-request assembly budget, shared across the batch: the tightest mapping's.
budget = long.MaxValue;
foreach (var target in targets)
if (target is not null) budget = Math.Min(budget, _assemblyBudget(target.MappingId) is { } b and > 0 ? b : DefaultAssemblyBudget);
if (budget == long.MaxValue) budget = DefaultAssemblyBudget;
// 3. Calls per (connection, details, resumed endpoint): a resumed item pins its issuing endpoint, so cursors of
// different endpoints, and fresh items (which may move), never share a call. Calls are RUNS of consecutive
// request positions with one key, read in request order (H3 review D7), so the assembly budget is consumed in
// request order and a budget shortfall only ever refuses nodes later in the request. Each run is sub-batched.
var runs = new List<(GroupKey Key, List<int> Indices)>();
for (var i = 0; i < nodes.Count; i++)
{
if (outcomes[i] is not null) continue;
var key = new GroupKey(targets[i]!.ConnectionId, DetailsOf(nodes[i], details), ResumeKey(nodes[i]));
if (runs.Count > 0 && runs[^1].Key == key) runs[^1].Indices.Add(i);
else runs.Add((key, [i]));
}
foreach (var (key, list) in runs)
{
var indices = list.ToArray();
if (cancellationToken.IsCancellationRequested || Remaining() <= TimeSpan.Zero) { FailAll(indices, BadTimeout); continue; }
if (received >= budget || budgetExhausted) { FailAll(indices, BadTooManyOperations); continue; }
await ReadGroupAsync(key, indices, cancellationToken).ConfigureAwait(false);
}
// 4. Charge the assembly budget in REQUEST order (H3 review D7): the first node that does not fit, and every later
// node with data, is BadTooManyOperations; its next origin cursor is released.
var left = budget;
var exhausted = false;
for (var i = 0; i < nodes.Count; i++)
{
if (assemblyRefused[i]) { exhausted = true; continue; }
if (outcomes[i] is not { } outcome || assembled[i] == 0 && !exhausted) continue;
if (exhausted || assembled[i] > left)
{
exhausted = true;
(outcome.Continuation as RemoteCursor)?.ReleaseOrigin();
outcomes[i] = Fail(BadTooManyOperations);
continue;
}
left -= assembled[i];
}
return outcomes.Select(o => o ?? Fail(BadNoCommunication)).ToArray();
}
catch (Exception ex) when (ex is not OutOfMemoryException)
{
// Last resort (H3 review D1): whatever escaped, fail per node — a timeout when the deadline fired — and release every
// origin cursor this request still owns. Nothing escapes to the SDK override.
var timedOut = cancellationToken.IsCancellationRequested || Remaining() <= TimeSpan.Zero || ex is OperationCanceledException;
for (var i = 0; i < nodes.Count; i++)
{
if (outcomes[i] is not null) continue;
nodes[i].Resume?.ReleaseEvenIfClaimed();
outcomes[i] = Fail(timedOut ? BadTimeout : BadNoCommunication);
}
return outcomes.Select(o => o!).ToArray();
}
finally
{
foreach (var demand in demands) demand?.Dispose();
}
TimeSpan Remaining() => deadline > TimeSpan.Zero
? deadline - _clock.GetElapsedTime(started)
: TimeSpan.FromHours(1); // unbounded locally: the connection's HistoryTimeout still caps each call
async Task ReadGroupAsync(GroupKey key, int[] indices, CancellationToken ct)
{
IGrpcDataAdapterConnectionLease? lease = null;
try
{
var remaining = Remaining();
using var timeout = new CancellationTokenSource(remaining, _clock);
using var linked = CancellationTokenSource.CreateLinkedTokenSource(ct, timeout.Token);
lease = await _connections.AcquireAsync(key.ConnectionId, linked.Token).ConfigureAwait(false);
if (lease is null || lease.Connection is not IDataHistoryService history || lease.CancellationToken.IsCancellationRequested)
{
foreach (var i in indices)
{
if (nodes[i].Resume is RemoteCursor c) { c.ReleaseOrigin(); outcomes[i] = Fail(BadContinuationPointInvalid); }
else outcomes[i] = Fail(BadNoCommunication);
}
return;
}
var route = lease.RouteIdentity;
var sendable = new List<int>(indices.Length);
foreach (var i in indices)
{
// The connection lease moved (expiry, redeployment, credential change): its tokens are gone.
if (nodes[i].Resume is RemoteCursor cursor && !Equals(cursor.RouteIdentity, route))
{
cursor.ReleaseOrigin();
outcomes[i] = Fail(BadContinuationPointInvalid);
continue;
}
sendable.Add(i);
}
if (sendable.Count == 0) return;
var batch = BatchSize(lease.Connection);
for (var offset = 0; offset < sendable.Count;)
{
var now = Remaining();
if (ct.IsCancellationRequested || now <= TimeSpan.Zero) { FailAll(sendable.Skip(offset).ToArray(), BadTimeout); return; }
// A budget shortfall refuses the remaining nodes unsent — never an endpoint failure (H3 review D4). A call may
// carry at most one item per MinimumBytesPerItem of its byte budget (the origin's admission rule).
var fitting = budgetExhausted ? 0 : (int)Math.Min(int.MaxValue, (budget - received) / MinimumBytesPerItem);
if (fitting <= 0) { FailAll(sendable.Skip(offset).ToArray(), BadTooManyOperations); return; }
var from = offset;
var chunk = sendable.Skip(from).Take(Math.Min(batch, fitting)).ToArray();
offset += chunk.Length;
var items = chunk.Select((i, k) => new DataHistoryReadItem(k.ToString(System.Globalization.CultureInfo.InvariantCulture),
targets[i]!.OriginMetadata.View,
nodes[i].Resume is RemoteCursor c ? c.AggregateId : nodes[i].AggregateId,
(nodes[i].Resume as RemoteCursor)?.Token)).ToArray();
IReadOnlyList<DataHistoryReadResult> answers;
try
{
answers = await history.ReadAsync(new DataHistoryReadRequest(key.Details, items,
new DataBudget(now, items.Length, budget - received)), linked.Token).ConfigureAwait(false);
}
catch (OperationCanceledException)
{
// Our deadline or the SDK request ending: a timeout, never an origin fault (the connection records none).
// Any other cancel (the deployed lease retired by a redeploy) is not a timeout.
FailCancelled(sendable.Skip(from).ToArray());
return;
}
var assigned = new bool[answers.Count];
try
{
if (answers.Count != items.Length)
{
FailAll(chunk, BadNoCommunication);
continue;
}
for (var k = 0; k < answers.Count; k++)
{
var i = chunk[k];
var answer = answers[k];
if (answer.CorrelationId != items[k].CorrelationId)
{
outcomes[i] = Fail(BadNoCommunication);
continue; // its token (if any) is released in the finally
}
if (answer.StatusCode == BadTooManyOperations && answer.Diagnostic?.Contains("budget", StringComparison.OrdinalIgnoreCase) == true)
{
assemblyRefused[i] = true; // the connection's own share of the assembly budget ran out:
budgetExhausted = true; // no further origin call in this request (H3 review round 2)
}
long nodeBytes = 0;
foreach (var sample in answer.Samples) nodeBytes += sample.Value.EstimatedRetainedBytes;
assembled[i] = nodeBytes;
received += nodeBytes;
var target = targets[i]!;
var samples = Convert(answer.Samples, target.OriginMetadata, key.Details is DataHistoryProcessedDetails);
var next = answer.Continuation is { } token
? new RemoteCursor(this, target.OriginMetadata.View.Realm, demands[i]!.LocalIdentifier, token, key.ConnectionId, route,
target, callerKey, key.Details, nodes[i].Resume is RemoteCursor prior ? prior.AggregateId : nodes[i].AggregateId)
: null;
outcomes[i] = new ProjectedHistoryOutcome(answer.StatusCode, samples, next);
assigned[k] = true;
}
}
finally
{
// H3 review round 2: a new origin token whose answer never became an outcome (a mismatched answer, or an
// exception mid-answer) is released, never stranded at the origin until its idle expiry.
for (var k = 0; k < answers.Count; k++)
if (!assigned[k] && answers[k].Continuation is { } orphan) EnqueueRelease(key.ConnectionId, orphan);
foreach (var answer in answers) answer.Dispose();
}
}
}
catch (OperationCanceledException)
{
FailCancelled(indices.Where(i => outcomes[i] is null).ToArray());
}
catch (Exception ex) when (ex is not OutOfMemoryException)
{
// An unexpected fault (an escaping RpcException, a malformed answer): per node, never out of the batch.
var timedOut = ct.IsCancellationRequested || Remaining() <= TimeSpan.Zero;
foreach (var i in indices.Where(i => outcomes[i] is null).ToArray())
{
if (nodes[i].Resume is RemoteCursor c) c.ReleaseOrigin();
outcomes[i] = Fail(timedOut ? BadTimeout : nodes[i].Resume is null ? BadNoCommunication : BadContinuationPointInvalid);
}
}
finally
{
if (lease is not null) await lease.DisposeAsync().ConfigureAwait(false);
}
}
void FailCancelled(int[] indices)
{
if (cancellationToken.IsCancellationRequested || Remaining() <= TimeSpan.Zero) { FailAll(indices, BadTimeout); return; }
foreach (var i in indices)
{
if (nodes[i].Resume is RemoteCursor c) { c.ReleaseOrigin(); outcomes[i] = Fail(BadContinuationPointInvalid); }
else outcomes[i] = Fail(BadNoCommunication);
}
}
void FailAll(int[] indices, uint status)
{
foreach (var i in indices)
{
if (nodes[i].Resume is RemoteCursor c) c.ReleaseOrigin();
outcomes[i] = Fail(status);
}
}
}
/// <summary>
/// The sub-batch size of one call (H3 review D4): the deployed connection's own batch size. No separate capability probe
/// (H3 review round 2): a probe through the connection's unary path records a cancelled probe as an endpoint failure and
/// puts the connection into discovery backoff. The ORIGIN's advertised batch is applied by the gRPC connection itself,
/// from the capabilities each history call already negotiates.
/// </summary>
private static int BatchSize(IDataConnection connection) =>
Math.Max(1, connection is IHistoryBatchLimit limit ? limit.MaxHistoryBatchItems : DefaultBatchItems);
/// <summary>The sub-batch size when the connection is not a deployment lease (tests, direct facades).</summary>
internal const int DefaultBatchItems = 100;
/// <summary>An origin admits at most one item per this many bytes of a request's byte budget.</summary>
internal const long MinimumBytesPerItem = 256;
private static ProjectedHistoryOutcome Fail(uint status) => new(status, []);
private static DataHistoryDetails DetailsOf(ProjectedHistoryNode node, DataHistoryDetails request) =>
node.Resume is RemoteCursor cursor ? cursor.Details : request;
private static string ResumeKey(ProjectedHistoryNode node)
{
if (node.Resume is not RemoteCursor cursor) return "fresh";
return GrpcDataConnection.TryUnwrap(cursor.Token, out var endpoint, out var serving, out _)
? FormattableString.Invariant($"{endpoint}|{serving}") : "resume";
}
private static string CallerKey(RoleCarryingUserIdentity caller) =>
string.Join('\0', caller.Principal ?? "", caller.ApiKeyId ?? "", caller.CredentialVersion ?? "");
/// <summary>
/// Values verbatim (status, absent timestamps). Raw and AtTime values are the node's own values: a kind that disagrees
/// with the catalog is <c>BadTypeMismatch</c> (plan §3.3), never coerced. A Processed value has its AGGREGATE's type (a
/// Double Average or an Int32 Count of a UInt16 node), so only its shape is checked: any scalar kind is accepted.
/// </summary>
private static OriginHistorySample[] Convert(IReadOnlyList<DataHistorySample> samples, DataMetadata metadata, bool processed)
{
var converted = new OriginHistorySample[samples.Count];
for (var i = 0; i < samples.Count; i++)
{
var sample = samples[i];
object? value;
var status = sample.StatusCode;
try
{
var expected = processed && sample.Value.Kind is not (DataValueKind.Null or DataValueKind.Array)
? metadata with { ValueKind = sample.Value.Kind, ValueRank = -1, Dimensions = [], ArrayElementKind = null }
: metadata;
value = ProjectedDataAccess.DecodeValue(sample.Value, expected);
}
catch (Exception ex) when (ex is ArgumentException or InvalidCastException or InvalidOperationException)
{
value = null;
status = BadTypeMismatch;
}
converted[i] = new OriginHistorySample(value, status, sample.SourceTimestampUtc?.UtcDateTime, sample.ServerTimestampUtc?.UtcDateTime);
}
return converted;
}
/// <summary>Queues a release directly (tests: the flush's wake-up under concurrent enqueues).</summary>
internal void EnqueueReleaseForTests(string connectionId, byte[] token) => EnqueueRelease(connectionId, token);
/// <summary>Queues an origin token for a coalesced best-effort release on its connection.</summary>
private void EnqueueRelease(string connectionId, byte[] token)
{
if (Volatile.Read(ref _disposed) != 0) return;
lock (_releaseGate)
{
if (!_pendingReleases.TryGetValue(connectionId, out var list)) _pendingReleases[connectionId] = list = [];
list.Add(token);
// H3 review D6: a flag under the gate, not Task.IsCompleted — a flush past its last check but not yet completed
// would otherwise swallow this token (a lost wakeup). The flush clears the flag under the same gate.
if (_flushScheduled) return;
_flushScheduled = true;
_releaseFlush = Task.Run(FlushReleasesAsync);
}
}
private async Task FlushReleasesAsync()
{
try { await Task.Delay(ReleaseCoalesce, _clock, _stop.Token).ConfigureAwait(false); }
catch (OperationCanceledException) { lock (_releaseGate) _flushScheduled = false; return; }
Dictionary<string, List<byte[]>> batch;
lock (_releaseGate)
{
batch = new(_pendingReleases, StringComparer.OrdinalIgnoreCase);
_pendingReleases.Clear();
}
foreach (var (connectionId, tokens) in batch)
{
IGrpcDataAdapterConnectionLease? lease = null;
try
{
using var timeout = new CancellationTokenSource(TimeSpan.FromSeconds(30));
using var linked = CancellationTokenSource.CreateLinkedTokenSource(timeout.Token, _stop.Token);
lease = await _connections.AcquireAsync(connectionId, linked.Token).ConfigureAwait(false);
if (lease?.Connection is not IDataHistoryService history) continue;
Interlocked.Increment(ref _releaseCalls);
await history.ReleaseAsync(tokens, linked.Token).ConfigureAwait(false);
}
catch (Exception ex) when (ex is not OutOfMemoryException) { } // best effort; the origin's idle expiry is the backstop
finally
{
if (lease is not null) try { await lease.DisposeAsync().ConfigureAwait(false); } catch (Exception) { }
}
}
lock (_releaseGate)
{
if (_pendingReleases.Count > 0 && Volatile.Read(ref _disposed) == 0) _releaseFlush = Task.Run(FlushReleasesAsync);
else _flushScheduled = false;
}
}
/// <inheritdoc />
public void Dispose()
{
if (Interlocked.Exchange(ref _disposed, 1) != 0) return;
// Cancel only: a flush still running reads _stop.Token, so it is never disposed under it (H3 review D6). The source
// has no timer, so leaving it to the GC releases nothing.
_stop.Cancel();
}
/// <summary>
/// Whether a cursor issued under <paramref name="issued"/> for <paramref name="issuedCaller"/> may resume now: same caller
/// (principal, key, credential version), mapping and revision, deployed connection, projection generation, origin view
/// and serving identity (node, incarnation, serving generation, role — a failover or restart changes it).
/// </summary>
internal static bool CursorMatches(ProjectedHistoryTarget issued, string issuedCaller, ProjectedHistoryTarget now, string caller) =>
string.Equals(caller, issuedCaller, StringComparison.Ordinal)
&& string.Equals(now.MappingId, issued.MappingId, StringComparison.Ordinal) && now.MappingRevision == issued.MappingRevision
&& string.Equals(now.ConnectionId, issued.ConnectionId, StringComparison.OrdinalIgnoreCase)
&& now.ProjectionGeneration == issued.ProjectionGeneration && now.OriginMetadata.View == issued.OriginMetadata.View
&& string.Equals(now.Serving.NodeId, issued.Serving.NodeId, StringComparison.Ordinal)
&& string.Equals(now.Serving.Incarnation, issued.Serving.Incarnation, StringComparison.Ordinal)
&& now.Serving.ServingGeneration == issued.Serving.ServingGeneration
&& string.Equals(now.Serving.Role, issued.Serving.Role, StringComparison.Ordinal);
private sealed record GroupKey(string ConnectionId, DataHistoryDetails Details, string Resume);
/// <summary>The remote cursor in the consumer's SDK session store (<see cref="HistoryCursorKind"/> <c>Remote</c>).</summary>
private sealed class RemoteCursor(ProjectedHistoryAccess owner, DataRealm realm, string localIdentifier, byte[] token, string connectionId,
object? routeIdentity, ProjectedHistoryTarget target, string callerKey, DataHistoryDetails details, uint? aggregateId)
: ProjectedHistoryContinuation(realm, localIdentifier)
{
private int _originReleased;
internal ProjectedHistoryAccess Owner => owner;
internal byte[] Token => token;
internal object? RouteIdentity => routeIdentity;
internal DataHistoryDetails Details => details;
internal uint? AggregateId => aggregateId;
/// <summary>The caller, mapping revision, projection generation, serving identity and connection still match.</summary>
internal bool StillMatches(string caller, ProjectedHistoryTarget now, IProjectedDemandLease demand) =>
demand.Realm == Realm && string.Equals(demand.LocalIdentifier, LocalIdentifier, StringComparison.Ordinal)
&& CursorMatches(target, callerKey, now, caller);
/// <summary>Releases the origin token (once), whether the cursor was claimed for a resume or not.</summary>
internal void ReleaseOrigin()
{
if (Interlocked.Exchange(ref _originReleased, 1) == 0) owner.EnqueueRelease(connectionId, token);
}
protected override void OnRelease() => ReleaseOrigin();
}
}