fix(grpc-data): H3 review D2/D3/D5 — claimed cursors never leak; projected slot sub-limit
D2: Release() after TryClaimForResume() was a no-op, so a claimed cursor leaked its origin continuation on every exit that never sent it (no gateway/identity, deadline spent after the local half, limiter rejection, a gateway fault). New ReleaseEvenIfClaimed() (at most once) on every post-claim exit; any exception from the gateway now fails the projected half per node instead of escaping. D3: projected reads hold at most N - max(1, N/4) of the N shared history batch slots (OriginHistoryPort.RemoteSlots), Wait(0) => BadTooManyOperations for the projected half, so a slow origin cannot starve local HistoryRead/HistoryUpdate. D5: a Remote cursor presented to a local node (raw/modified/events take paths) is released when it is taken. Red/green: each test fails with its fix reverted.
This commit is contained in:
@@ -462,7 +462,14 @@ public sealed partial class OtOpcUaNodeManager
|
||||
public byte[]? Save(HistoryContinuationState state, HistoryContinuationBinding binding) =>
|
||||
nm._historyContinuationStore.Save(session, state);
|
||||
|
||||
public HistoryContinuationState? TryTake(byte[] continuationPoint, HistoryContinuationBinding binding) =>
|
||||
nm._historyContinuationStore.TryTake(session, continuationPoint);
|
||||
public HistoryContinuationState? TryTake(byte[] continuationPoint, HistoryContinuationBinding binding)
|
||||
{
|
||||
var state = nm._historyContinuationStore.TryTake(session, continuationPoint);
|
||||
if (state?.Remote is not { } remote) return state;
|
||||
// H3 review D5: a projected node's Remote cursor presented to a LOCAL node is invalid here (the port refuses an
|
||||
// unknown/mismatched cursor) — but it was taken out of the session, so release its origin continuation now.
|
||||
remote.Release();
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -12,7 +12,7 @@ namespace ZB.MOM.WW.OtOpcUa.OpcUaServer;
|
||||
/// </summary>
|
||||
public abstract class ProjectedHistoryContinuation
|
||||
{
|
||||
private int _released;
|
||||
private int _claimed, _released;
|
||||
|
||||
/// <summary>Creates a cursor bound to one projected node.</summary>
|
||||
/// <param name="realm">The projected node's realm.</param>
|
||||
@@ -31,20 +31,34 @@ public abstract class ProjectedHistoryContinuation
|
||||
public string LocalIdentifier { get; }
|
||||
|
||||
/// <summary>True once the cursor was released or handed back for a resume (it is single-use either way).</summary>
|
||||
public bool IsSpent => Volatile.Read(ref _released) != 0;
|
||||
public bool IsSpent => Volatile.Read(ref _released) != 0 || Volatile.Read(ref _claimed) != 0;
|
||||
|
||||
/// <summary>
|
||||
/// Best-effort, idempotent, non-blocking release of the origin continuation (<c>releaseContinuationPoints</c>, session
|
||||
/// close, eviction, a store refusal). The origin's idle expiry is the backstop.
|
||||
/// close, eviction, a store refusal). A no-op once the cursor was claimed for a resume: the resume owns it from then on
|
||||
/// (and uses <see cref="ReleaseEvenIfClaimed"/> on every exit that does not send it). The origin's idle expiry is the
|
||||
/// backstop.
|
||||
/// </summary>
|
||||
public void Release()
|
||||
{
|
||||
if (Interlocked.Exchange(ref _released, 1) == 0) OnRelease();
|
||||
if (Volatile.Read(ref _claimed) != 0) return;
|
||||
ReleaseOnce();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Releases the origin continuation whether or not the cursor was claimed for a resume — for every post-claim exit that
|
||||
/// never sends it (refused, limiter-rejected, timed out, faulted). Never releases twice.
|
||||
/// </summary>
|
||||
public void ReleaseEvenIfClaimed() => ReleaseOnce();
|
||||
|
||||
/// <summary>Marks the cursor as handed back for a resume: the resume read owns the origin token from here on.</summary>
|
||||
/// <returns><c>false</c> when it was already released or resumed.</returns>
|
||||
public bool TryClaimForResume() => Interlocked.Exchange(ref _released, 1) == 0;
|
||||
public bool TryClaimForResume() => Volatile.Read(ref _released) == 0 && Interlocked.Exchange(ref _claimed, 1) == 0;
|
||||
|
||||
private void ReleaseOnce()
|
||||
{
|
||||
if (Interlocked.Exchange(ref _released, 1) == 0) OnRelease();
|
||||
}
|
||||
|
||||
/// <summary>Forwards the release to the origin (called at most once).</summary>
|
||||
protected abstract void OnRelease();
|
||||
|
||||
@@ -9045,6 +9045,8 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage
|
||||
// Single-use take. A miss (unknown / evicted / malformed / a RAW cursor) ⇒ BadContinuationPointInvalid
|
||||
// for THIS node only.
|
||||
var state = _historyContinuationStore.TryTake(session, inboundCp.ToArray());
|
||||
// H3: a projected node's Remote cursor taken here is a miss — release its origin continuation.
|
||||
state?.Remote?.Release();
|
||||
// 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, HistoryBindingTag(handle.NodeId), historyEpoch) || state.Kind != HistoryCursorKind.Events || state.Tagname != sourceName)
|
||||
|
||||
@@ -26,6 +26,20 @@ public sealed partial class OtOpcUaNodeManager
|
||||
set => Volatile.Write(ref _projectedHistoryAccess, value);
|
||||
}
|
||||
|
||||
private volatile SemaphoreSlim? _projectedHistoryLimiter;
|
||||
private readonly Lock _projectedHistoryLimiterGate = new();
|
||||
|
||||
/// <summary>
|
||||
/// The projected share of the history batch slots, sized once from <see cref="MaxConcurrentHistoryReadBatches"/> at first
|
||||
/// use (as the shared limiter is): <see cref="OriginHistoryPort.RemoteSlots"/>.
|
||||
/// </summary>
|
||||
internal SemaphoreSlim GetProjectedHistoryLimiter()
|
||||
{
|
||||
if (_projectedHistoryLimiter is { } gate) return gate;
|
||||
lock (_projectedHistoryLimiterGate)
|
||||
return _projectedHistoryLimiter ??= new SemaphoreSlim(OriginHistoryPort.RemoteSlots(Math.Max(1, MaxConcurrentHistoryReadBatches)));
|
||||
}
|
||||
|
||||
/// <summary>Serves local handles through the port (unchanged) and projected handles remotely, each into its own slot.</summary>
|
||||
private void ServeHistoryReadSplit(
|
||||
ServerSystemContext context,
|
||||
@@ -94,7 +108,7 @@ public sealed partial class OtOpcUaNodeManager
|
||||
if (access is null || identity is null || remote is null)
|
||||
{
|
||||
// No projection gateway, no session identity, or a variant a remote read never serves (a modified read).
|
||||
resume?.Release();
|
||||
resume?.ReleaseEvenIfClaimed();
|
||||
SetProjectedStatus(handle, results, errors, StatusCodes.BadHistoryOperationUnsupported);
|
||||
continue;
|
||||
}
|
||||
@@ -119,46 +133,69 @@ public sealed partial class OtOpcUaNodeManager
|
||||
if (pending.Count == 0) return;
|
||||
var nodes = pending.Select(p => p.Node).ToArray();
|
||||
IReadOnlyList<ProjectedHistoryOutcome>? outcomes = null;
|
||||
// The same process-wide batch limiter as local reads: a remote read also holds an SDK request thread.
|
||||
WithHistoryBatchLimiter(pending, () =>
|
||||
void ReleaseResumes()
|
||||
{
|
||||
TimeSpan remaining;
|
||||
if (HistoryReadDeadline > TimeSpan.Zero)
|
||||
{
|
||||
remaining = HistoryReadDeadline - Stopwatch.GetElapsedTime(started);
|
||||
if (remaining <= TimeSpan.Zero)
|
||||
{
|
||||
outcomes = nodes.Select(_ => new ProjectedHistoryOutcome(StatusCodes.BadTimeout.Code, [])).ToArray();
|
||||
foreach (var node in nodes) node.Resume?.Release();
|
||||
return;
|
||||
}
|
||||
}
|
||||
else remaining = TimeSpan.Zero;
|
||||
foreach (var node in nodes) node.Resume?.ReleaseEvenIfClaimed();
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
outcomes = access!.ReadAsync(identity!, remote!, nodes, remaining,
|
||||
context.OperationContext?.CancellationToken ?? CancellationToken.None).GetAwaiter().GetResult();
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
// The SDK request ended: a timeout for this caller, never an origin fault (the access owns the resumes).
|
||||
outcomes = nodes.Select(_ => new ProjectedHistoryOutcome(StatusCodes.BadTimeout.Code, [])).ToArray();
|
||||
}
|
||||
catch (Exception ex) when (ex is InvalidOperationException or ArgumentException or ObjectDisposedException)
|
||||
{
|
||||
outcomes = nodes.Select(_ => new ProjectedHistoryOutcome(StatusCodes.BadNoCommunication.Code, [])).ToArray();
|
||||
}
|
||||
}, p =>
|
||||
// H3 review D3: projected reads may hold at most N - max(1, N/4) of the N process-wide history batch slots (the rule
|
||||
// OriginHistoryPort.RemoteSlots applies to remote peers), so a slow origin can never starve local HistoryRead /
|
||||
// HistoryUpdate. Exhausted => BadTooManyOperations for the projected half, unsent; the local half is unaffected.
|
||||
var projectedSlots = GetProjectedHistoryLimiter();
|
||||
if (!projectedSlots.Wait(0))
|
||||
{
|
||||
p.Node.Resume?.Release();
|
||||
SetProjectedStatus(p.Handle, results, errors, StatusCodes.BadTooManyOperations);
|
||||
});
|
||||
ReleaseResumes();
|
||||
foreach (var p in pending) SetProjectedStatus(p.Handle, results, errors, StatusCodes.BadTooManyOperations);
|
||||
return;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
// The same process-wide batch limiter as local reads: a remote read also holds an SDK request thread.
|
||||
WithHistoryBatchLimiter(pending, () =>
|
||||
{
|
||||
TimeSpan remaining;
|
||||
if (HistoryReadDeadline > TimeSpan.Zero)
|
||||
{
|
||||
remaining = HistoryReadDeadline - Stopwatch.GetElapsedTime(started);
|
||||
if (remaining <= TimeSpan.Zero)
|
||||
{
|
||||
outcomes = nodes.Select(_ => new ProjectedHistoryOutcome(StatusCodes.BadTimeout.Code, [])).ToArray();
|
||||
ReleaseResumes();
|
||||
return;
|
||||
}
|
||||
}
|
||||
else remaining = TimeSpan.Zero;
|
||||
|
||||
try
|
||||
{
|
||||
outcomes = access!.ReadAsync(identity!, remote!, nodes, remaining,
|
||||
context.OperationContext?.CancellationToken ?? CancellationToken.None).GetAwaiter().GetResult();
|
||||
}
|
||||
catch (Exception ex) when (ex is not OutOfMemoryException)
|
||||
{
|
||||
// Whatever escaped the gateway — the SDK request ending is a timeout, never an origin fault. The gateway
|
||||
// normally owns the resumes; releasing them again is idempotent, so nothing claimed can leak (H3 review D2).
|
||||
var status = ex is OperationCanceledException ? StatusCodes.BadTimeout.Code : StatusCodes.BadNoCommunication.Code;
|
||||
outcomes = nodes.Select(_ => new ProjectedHistoryOutcome(status, [])).ToArray();
|
||||
ReleaseResumes();
|
||||
}
|
||||
}, p =>
|
||||
{
|
||||
p.Node.Resume?.ReleaseEvenIfClaimed();
|
||||
SetProjectedStatus(p.Handle, results, errors, StatusCodes.BadTooManyOperations);
|
||||
});
|
||||
}
|
||||
finally
|
||||
{
|
||||
projectedSlots.Release();
|
||||
}
|
||||
|
||||
if (outcomes is null) return; // the limiter rejected the batch
|
||||
if (outcomes.Count != pending.Count)
|
||||
{
|
||||
foreach (var o in outcomes) o.Continuation?.Release();
|
||||
ReleaseResumes();
|
||||
foreach (var p in pending) SetProjectedStatus(p.Handle, results, errors, StatusCodes.BadInternalError);
|
||||
return;
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user