diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/HistoryReadPort.cs b/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/HistoryReadPort.cs index 53a57d358..0d4802ee8 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/HistoryReadPort.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/HistoryReadPort.cs @@ -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; + } } } diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/IProjectedHistoryAccess.cs b/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/IProjectedHistoryAccess.cs index 35cc08751..dc050e9ef 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/IProjectedHistoryAccess.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/IProjectedHistoryAccess.cs @@ -12,7 +12,7 @@ namespace ZB.MOM.WW.OtOpcUa.OpcUaServer; /// public abstract class ProjectedHistoryContinuation { - private int _released; + private int _claimed, _released; /// Creates a cursor bound to one projected node. /// The projected node's realm. @@ -31,20 +31,34 @@ public abstract class ProjectedHistoryContinuation public string LocalIdentifier { get; } /// True once the cursor was released or handed back for a resume (it is single-use either way). - public bool IsSpent => Volatile.Read(ref _released) != 0; + public bool IsSpent => Volatile.Read(ref _released) != 0 || Volatile.Read(ref _claimed) != 0; /// /// Best-effort, idempotent, non-blocking release of the origin continuation (releaseContinuationPoints, 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 on every exit that does not send it). The origin's idle expiry is the + /// backstop. /// public void Release() { - if (Interlocked.Exchange(ref _released, 1) == 0) OnRelease(); + if (Volatile.Read(ref _claimed) != 0) return; + ReleaseOnce(); } + /// + /// 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. + /// + public void ReleaseEvenIfClaimed() => ReleaseOnce(); + /// Marks the cursor as handed back for a resume: the resume read owns the origin token from here on. /// false when it was already released or resumed. - 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(); + } /// Forwards the release to the origin (called at most once). protected abstract void OnRelease(); diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/OtOpcUaNodeManager.cs b/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/OtOpcUaNodeManager.cs index 6e2247825..d4a4aac1b 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/OtOpcUaNodeManager.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/OtOpcUaNodeManager.cs @@ -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) diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/ProjectedHistoryRead.cs b/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/ProjectedHistoryRead.cs index bc5c78f45..c50f6f9b3 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/ProjectedHistoryRead.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/ProjectedHistoryRead.cs @@ -26,6 +26,20 @@ public sealed partial class OtOpcUaNodeManager set => Volatile.Write(ref _projectedHistoryAccess, value); } + private volatile SemaphoreSlim? _projectedHistoryLimiter; + private readonly Lock _projectedHistoryLimiterGate = new(); + + /// + /// The projected share of the history batch slots, sized once from at first + /// use (as the shared limiter is): . + /// + internal SemaphoreSlim GetProjectedHistoryLimiter() + { + if (_projectedHistoryLimiter is { } gate) return gate; + lock (_projectedHistoryLimiterGate) + return _projectedHistoryLimiter ??= new SemaphoreSlim(OriginHistoryPort.RemoteSlots(Math.Max(1, MaxConcurrentHistoryReadBatches))); + } + /// Serves local handles through the port (unchanged) and projected handles remotely, each into its own slot. 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? 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; } diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests/DataConnections/ProjectedHistoryReadTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests/DataConnections/ProjectedHistoryReadTests.cs index 7bceeb877..2ea1d6ce9 100644 --- a/tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests/DataConnections/ProjectedHistoryReadTests.cs +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests/DataConnections/ProjectedHistoryReadTests.cs @@ -206,6 +206,115 @@ public sealed class ProjectedHistoryReadTests : IAsyncDisposable atTime.UseSimpleBounds.ShouldBeTrue(); } + [Fact] + public async Task A_claimed_cursor_is_released_on_every_exit_that_never_sends_it() + { + // H3 review D2: Release() after a claim is a no-op, so each post-claim exit must use ReleaseEvenIfClaimed — exactly once. + var (nm, f) = await BootAsync(aclEnabled: false, NodePermissions.Browse | NodePermissions.Read | NodePermissions.HistoryRead); + var store = new InMemoryHistoryContinuationStore(); + nm.HistoryContinuationStore = store; + var node = Project(nm, f, "Leak", historizing: true); + var paging = new FakeAccess { Paged = true }; + nm.ProjectedHistoryAccess = paging; + + (FakeCursor Cursor, ByteString Cp) HeldPoint() + { + var (results, _) = Raw(nm, f.Identity, [node]); + results[0].ContinuationPoint.IsEmpty.ShouldBeFalse(); + return (paging.Issued[^1], results[0].ContinuationPoint); + } + + // (a) the gateway disappears between the issue and the resume. + var (cursor, cp) = HeldPoint(); + nm.ProjectedHistoryAccess = null; + Raw(nm, f.Identity, [node], cp).Errors[0].StatusCode.Code.ShouldBe(StatusCodes.BadHistoryOperationUnsupported.Code); + cursor.Released.ShouldBe(1); + nm.ProjectedHistoryAccess = paging; + + // (b) the gateway throws (anything): BadNoCommunication, the resume released, nothing escapes. + (cursor, cp) = HeldPoint(); + nm.ProjectedHistoryAccess = new FakeAccess { Throw = new InvalidCastException("boom") }; + Raw(nm, f.Identity, [node], cp).Errors[0].StatusCode.Code.ShouldBe(StatusCodes.BadNoCommunication.Code); + cursor.Released.ShouldBe(1); + nm.ProjectedHistoryAccess = paging; + + // (c) the request deadline was spent by the time the projected half starts. + (cursor, cp) = HeldPoint(); + nm.HistoryReadDeadline = TimeSpan.FromTicks(1); + Raw(nm, f.Identity, [node], cp).Errors[0].StatusCode.Code.ShouldBe(StatusCodes.BadTimeout.Code); + cursor.Released.ShouldBe(1); + nm.HistoryReadDeadline = TimeSpan.FromSeconds(60); + + // (d) the projected sub-limit is exhausted (limiter rejection). + (cursor, cp) = HeldPoint(); + var limiter = nm.GetProjectedHistoryLimiter(); + var taken = 0; + while (limiter.Wait(0, TestContext.Current.CancellationToken)) taken++; + try + { + Raw(nm, f.Identity, [node], cp).Errors[0].StatusCode.Code.ShouldBe(StatusCodes.BadTooManyOperations.Code); + cursor.Released.ShouldBe(1); + } + finally { limiter.Release(taken); } + + // Positive control: a normal resume claims the cursor and does NOT release it (the read owns the token). + (cursor, cp) = HeldPoint(); + Raw(nm, f.Identity, [node], cp).Errors[0].StatusCode.Code.ShouldBe(StatusCodes.Good.Code); + cursor.Released.ShouldBe(0); + paging.Issued.Where(c => !ReferenceEquals(c, paging.Issued[^1])).ShouldAllBe(c => c.Released <= 1, "never released twice"); + } + + [Fact] + public async Task Projected_reads_cannot_take_every_history_slot_local_history_is_still_served() + { + // H3 review D3: projected reads hold at most N - max(1, N/4) of the N shared batch slots. + var (nm, f) = await BootAsync(aclEnabled: false, NodePermissions.Browse | NodePermissions.Read | NodePermissions.HistoryRead); + nm.MaxConcurrentHistoryReadBatches = 4; // => 3 projected slots, 1 always left for local history + nm.EnsureVariable("Plant/LocalSlot", "Plant", "LocalSlot", "Double", false, AddressSpaceRealm.Raw, historianTagname: "L.slot"); + var local = nm.TryGetVariable("Plant/LocalSlot", AddressSpaceRealm.Raw)!.NodeId; + var node = Project(nm, f, "Slow", historizing: true); + var hold = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + var slow = new FakeAccess { Hold = hold }; + nm.ProjectedHistoryAccess = slow; + var held = Enumerable.Range(0, 3).Select(_ => Task.Run(() => Raw(nm, f.Identity, [node]))).ToArray(); + var deadline = DateTime.UtcNow.AddSeconds(10); + while (Volatile.Read(ref slow.Entries) < 3 && DateTime.UtcNow < deadline) await Task.Delay(10, TestContext.Current.CancellationToken); + slow.Entries.ShouldBe(3, "three projected reads hold the three projected slots"); + try + { + // A fourth projected read is refused at once, unsent; local history is still served. + // (Bounded: without the sub-limit this read would take the 4th shared slot and wait on the held gateway.) + var (_, refused) = await Task.Run(() => Raw(nm, f.Identity, [node])) + .WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken); + refused[0].StatusCode.Code.ShouldBe(StatusCodes.BadTooManyOperations.Code); + slow.Entries.ShouldBe(3); + var (localResults, localErrors) = Raw(nm, f.Identity, [local]); + StatusCode.IsGood(localErrors[0].StatusCode).ShouldBeTrue(localErrors[0].StatusCode.ToString()); + localResults[0].StatusCode.Code.ShouldBe(StatusCodes.GoodNoData.Code); + } + finally { hold.SetResult(); } + foreach (var (_, errors) in await Task.WhenAll(held)) StatusCode.IsGood(errors[0].StatusCode).ShouldBeTrue(); + } + + [Fact] + public async Task A_remote_cursor_presented_to_a_local_node_is_invalid_and_released() + { + // H3 review D5: the local take removes the SDK slot, so it must release the origin continuation. + var (nm, f) = await BootAsync(aclEnabled: false, NodePermissions.Browse | NodePermissions.Read | NodePermissions.HistoryRead); + var store = new InMemoryHistoryContinuationStore(); + nm.HistoryContinuationStore = store; + nm.EnsureVariable("Plant/LocalCp", "Plant", "LocalCp", "Double", false, AddressSpaceRealm.Raw, historianTagname: "L.cp"); + var local = nm.TryGetVariable("Plant/LocalCp", AddressSpaceRealm.Raw)!.NodeId; + var node = Project(nm, f, "Remote", historizing: true); + var access = new FakeAccess { Paged = true }; + nm.ProjectedHistoryAccess = access; + var (results, _) = Raw(nm, f.Identity, [node]); + var (_, errors) = Raw(nm, f.Identity, [local], results[0].ContinuationPoint); + errors[0].StatusCode.Code.ShouldBe(StatusCodes.BadContinuationPointInvalid.Code); + access.Issued.Single().Released.ShouldBe(1); + store.Count.ShouldBe(0); + } + // ------------------------------------------------------------------------------------------------------------------ private static (List Results, List Errors) Raw(OtOpcUaNodeManager nm, IUserIdentity? identity, @@ -326,12 +435,22 @@ public sealed class ProjectedHistoryReadTests : IAsyncDisposable public uint Status { get; init; } public Func Answer { get; init; } = _ => [1.0, 2.0]; - public Task> ReadAsync(RoleCarryingUserIdentity caller, DataHistoryDetails details, + /// When set, every call waits on it (a projected read holding its slot). + public TaskCompletionSource? Hold { get; set; } + public TaskCompletionSource Entered { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously); + /// When set, every call throws it (after claiming nothing — the cursors are the caller's to release). + public Exception? Throw { get; set; } + public int Entries; + + public async Task> ReadAsync(RoleCarryingUserIdentity caller, DataHistoryDetails details, IReadOnlyList nodes, TimeSpan deadline, CancellationToken cancellationToken) { - Calls++; + Interlocked.Increment(ref Calls); LastNodes = nodes; - return Task.FromResult>(nodes.Select(node => + if (Interlocked.Increment(ref Entries) > 0) Entered.TrySetResult(); + if (Hold is { } hold) await hold.Task.ConfigureAwait(false); + if (Throw is { } error) throw error; + return (nodes.Select(node => { FakeCursor? next = null; if (Paged)