diff --git a/docs/ServerScalability.md b/docs/ServerScalability.md index f0d7587d95..50477156db 100644 --- a/docs/ServerScalability.md +++ b/docs/ServerScalability.md @@ -187,7 +187,7 @@ Two runtime settings bring CPU per request back to the .NET 10 level (medians of | `System.Threading.ThreadPool.SpuriousDispatchNoSpinThreshold` = 0 (`DOTNET_ThreadPool_SpuriousDispatchNoSpinThreshold=0`) | −14 % (Read), −40 % (Write), ±0 (Browse) | −23 %, −58 %, −54 % | +9 %, +6 %, +7 % | | `System.Threading.ThreadPool.UnfairSemaphoreSpinLimit` = 70 (`DOTNET_ThreadPool_UnfairSemaphoreSpinLimit=46`, hexadecimal) | −13 %, −40 %, −1 % | −18 %, −55 %, −51 % | −1 %, +2 %, +1 % | -The changes are relative to .NET 11 with default settings. `SpuriousDispatchNoSpinThreshold=0` stops the spinning only after a wake-up that found no work, so it also kept the throughput gains of .NET 11. Neither setting is among the documented [threading settings](https://learn.microsoft.com/dotnet/core/runtime-config/threading), and both can change between releases; measure before and after with the [server load harness](../perf/README.md) (`SERVER_DOTNET_ThreadPool_…` for the server child, `DOTNET_ThreadPool_…` for the client). The client channel starts its writer on the requesting thread instead of queuing a work item for it, which removes one of these wake-ups per request on every runtime. +The changes are relative to .NET 11 with default settings. `SpuriousDispatchNoSpinThreshold=0` stops the spinning only after a wake-up that found no work, so it also kept the throughput gains of .NET 11. Neither setting is among the documented [threading settings](https://learn.microsoft.com/dotnet/core/runtime-config/threading), and both can change between releases; measure before and after with the [server load harness](../perf/README.md) (`SERVER_DOTNET_ThreadPool_…` for the server child, `DOTNET_ThreadPool_…` for the client). The client channel starts its writer on the requesting thread instead of queuing a work item for it, and its receive loop runs the continuations of the requests it answered on its own thread once the next receive is pending, which removes two of these wake-ups per request on every runtime (client CPU per request on .NET 11 −8 to −23 % for the second). ### JIT warm-up diff --git a/src/Opc.Ua.Core/Stack/Bindings/BufferManagerMemoryLimiter.cs b/src/Opc.Ua.Core/Stack/Bindings/BufferManagerMemoryLimiter.cs index 995e2d6a61..ca765f5ff7 100644 --- a/src/Opc.Ua.Core/Stack/Bindings/BufferManagerMemoryLimiter.cs +++ b/src/Opc.Ua.Core/Stack/Bindings/BufferManagerMemoryLimiter.cs @@ -156,6 +156,9 @@ internal long Reserve( using CapacityWaiter waiter = registration.Value; try { + // A receive loop that blocks here completes the response it holds on the + // pool first: that request's caller may be the one to return the budget. + Bindings.ResponseContinuationDeferral.CompletePending(inline: false); BeforeCapacityWaitForTesting?.Invoke(); waiter.Wait(ct); } diff --git a/src/Opc.Ua.Core/Stack/Tcp/ChannelAsyncOperation.cs b/src/Opc.Ua.Core/Stack/Tcp/ChannelAsyncOperation.cs index af3ab0d4e4..c2f75dbede 100644 --- a/src/Opc.Ua.Core/Stack/Tcp/ChannelAsyncOperation.cs +++ b/src/Opc.Ua.Core/Stack/Tcp/ChannelAsyncOperation.cs @@ -40,7 +40,7 @@ namespace Opc.Ua.Bindings /// Stores the results of an asynchronous operation. /// /// - public class ChannelAsyncOperation : IAsyncResult, IDisposable, IValueTaskSource + public class ChannelAsyncOperation : IAsyncResult, IDisposable, IValueTaskSource, IDeferredWaitCompletion { /// /// Initializes the object with a callback @@ -435,12 +435,22 @@ internal ValueTask WaitForCompletionAsync(CancellationToken ct) /// private void TrySetWaitResult(bool completed) { - if (Interlocked.Exchange(ref m_waitResultSet, 1) == 0) + if (Interlocked.Exchange(ref m_waitResultSet, 1) == 0 && + !(completed && ResponseContinuationDeferral.TryDefer(this))) { m_waitCore.SetResult(completed); } } + /// + void IDeferredWaitCompletion.CompleteDeferredWait(bool inline) + { + // the receive loop that deferred the completion holds no lock now and no + // longer depends on its thread (see ResponseContinuationDeferral) + m_waitCore.RunContinuationsAsynchronously = !inline; + m_waitCore.SetResult(true); + } + /// void IValueTaskSource.GetResult(short token) { diff --git a/src/Opc.Ua.Core/Stack/Tcp/ResponseContinuationDeferral.cs b/src/Opc.Ua.Core/Stack/Tcp/ResponseContinuationDeferral.cs new file mode 100644 index 0000000000..2f1feba097 --- /dev/null +++ b/src/Opc.Ua.Core/Stack/Tcp/ResponseContinuationDeferral.cs @@ -0,0 +1,294 @@ +/* ======================================================================== + * Copyright (c) 2005-2025 The OPC Foundation, Inc. All rights reserved. + * + * OPC Foundation MIT License 1.00 + * + * Permission is hereby granted, free of charge, to any person + * obtaining a copy of this software and associated documentation + * files (the "Software"), to deal in the Software without + * restriction, including without limitation the rights to use, + * copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the + * Software is furnished to do so, subject to the following + * conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES + * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT + * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, + * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR + * OTHER DEALINGS IN THE SOFTWARE. + * + * The complete license agreement can be found here: + * http://opcfoundation.org/License/MIT/1.00/ + * ======================================================================*/ + +using System; +using System.Runtime.CompilerServices; +using System.Threading.Tasks; + +namespace Opc.Ua.Bindings +{ + /// + /// A wait for a channel operation whose completion the receive loop deferred. + /// + internal interface IDeferredWaitCompletion + { + /// + /// Ends the deferred wait. + /// + /// Whether the continuation of the wait may run on the + /// calling thread. + void CompleteDeferredWait(bool inline); + } + + /// + /// Lets a receive loop run the continuations of the requests its responses completed + /// on its own thread once it has nothing more to receive, instead of queueing a pool + /// work item for each. + /// + /// + /// + /// A request waits for its response on a value task source that runs its + /// continuation asynchronously: the receive loop holds the channel gate when it + /// completes the request, and must not run the caller's code. The source queues the + /// continuation with preferLocal, so the receive loop's thread runs it once + /// the next receive goes pending and the thread returns to the pool, or a worker + /// the enqueue woke takes it. When the loop's thread runs it, the woken worker found + /// no work, and since .NET 11 such a worker spins much longer before it blocks again + /// (UnfairSemaphoreSpinLimit 70 to 1024 backoff units). + /// + /// + /// The receive loop defers the completion instead and runs it where its thread + /// would have run the queued item: after the loop registered its continuation on a + /// receive (or another wait) that went pending. The loop then no longer depends on + /// the thread, so a caller's continuation that blocks it cannot stall the receive + /// loop, as with a pool thread today. + /// + /// + /// A thread holds at most one deferred completion. A later response completes the + /// one held before it on the pool, as without deferral: a continuation run inline + /// may block until another of its requests completes, and that one must not wait + /// for the blocked thread. The held completion also goes to the pool once the loop + /// dispatched more chunks without its receive going + /// pending, so a busy channel does not hold a response back. + /// + /// + internal static class ResponseContinuationDeferral + { + /// + /// How many more chunks a receive loop dispatches while it holds a completion + /// before it completes it on the pool. + /// + private const int kMaxDeferredChunks = 4; + + /// + /// Opens a scope in which a completed wait is deferred. + /// + /// + /// Called by the receive loop before it dispatches a chunk, while it holds no lock. + /// + public static void Enter() + { + if (t_pending != null && ++t_deferredChunks > kMaxDeferredChunks) + { + CompletePending(inline: false); + } + t_depth++; + } + + /// + /// Closes the scope opened by . + /// + public static void Exit() + { + t_depth--; + } + + /// + /// Defers the completion of a wait, when the calling thread is in a scope. A + /// completion deferred before completes on the pool. + /// + /// + /// The caller may hold locks: a completion on the pool only queues the + /// continuation. + /// + /// if the caller must complete the wait. + public static bool TryDefer(IDeferredWaitCompletion wait) + { + if (t_depth <= 0) + { + return false; + } + IDeferredWaitCompletion? previous = t_pending; + t_pending = wait; + t_deferredChunks = 0; + previous?.CompleteDeferredWait(inline: false); + return true; + } + + /// + /// Completes the wait deferred on this thread, if any. + /// + /// Whether its continuation runs on this thread; only when + /// the thread holds no lock and nothing waits for it to return. + public static void CompletePending(bool inline) + { + IDeferredWaitCompletion? pending = t_pending; + if (pending == null) + { + return; + } + t_pending = null; + int depth = t_depth; + t_depth = 0; + if (inline) + { + t_inline++; + } + try + { + pending.CompleteDeferredWait(inline); + } + finally + { + t_depth = depth; + if (inline) + { + t_inline--; + } + } + } + + /// + /// Completes the deferred wait inline once the awaiting receive loop suspended, + /// unless the loop ran inside the dispatch of another loop on this thread, which + /// may hold locks: that loop completes it when it suspends. + /// + /// + /// A loop can also resume inside a continuation this thread runs inline, when that + /// continuation completes the loop's receive synchronously. The wait it deferred + /// then completes on the pool: run inline as well, its continuation would be + /// nested in the first and could wait for it forever. + /// + private static void CompleteOnSuspended() + { + if (t_depth == 0) + { + CompletePending(inline: t_inline == 0); + } + } + + /// + /// Awaits and, if it goes pending, completes the deferred + /// wait on this thread once the continuation is registered. + /// + public static CompleteOnSuspend AwaitAndComplete(ValueTask task) + { + return new CompleteOnSuspend(task); + } + + /// + /// Awaits and, if it goes pending, completes the deferred + /// wait on this thread once the continuation is registered. + /// + /// The result type. + public static CompleteOnSuspend AwaitAndComplete(ValueTask task) + { + return new CompleteOnSuspend(task); + } + + /// + /// Awaits a value task; when the awaiting method suspends, its continuation is + /// registered first, then the deferred wait completes inline. + /// + internal readonly struct CompleteOnSuspend : ICriticalNotifyCompletion + { + private readonly ValueTask m_task; + + public CompleteOnSuspend(ValueTask task) + { + m_task = task; + } + + public CompleteOnSuspend GetAwaiter() + { + return this; + } + + public bool IsCompleted => m_task.IsCompleted; + + public void GetResult() + { + m_task.GetAwaiter().GetResult(); + } + + public void OnCompleted(Action continuation) + { + m_task.ConfigureAwait(false).GetAwaiter().OnCompleted(continuation); + CompleteOnSuspended(); + } + + public void UnsafeOnCompleted(Action continuation) + { + m_task.ConfigureAwait(false).GetAwaiter().UnsafeOnCompleted(continuation); + CompleteOnSuspended(); + } + } + + /// + /// Awaits a value task; when the awaiting method suspends, its continuation is + /// registered first, then the deferred wait completes inline. + /// + /// The result type. + internal readonly struct CompleteOnSuspend : ICriticalNotifyCompletion + { + private readonly ValueTask m_task; + + public CompleteOnSuspend(ValueTask task) + { + m_task = task; + } + + public CompleteOnSuspend GetAwaiter() + { + return this; + } + + public bool IsCompleted => m_task.IsCompleted; + + public T GetResult() + { + return m_task.GetAwaiter().GetResult(); + } + + public void OnCompleted(Action continuation) + { + m_task.ConfigureAwait(false).GetAwaiter().OnCompleted(continuation); + CompleteOnSuspended(); + } + + public void UnsafeOnCompleted(Action continuation) + { + m_task.ConfigureAwait(false).GetAwaiter().UnsafeOnCompleted(continuation); + CompleteOnSuspended(); + } + } + + [ThreadStatic] + private static IDeferredWaitCompletion? t_pending; + + [ThreadStatic] + private static int t_deferredChunks; + + [ThreadStatic] + private static int t_depth; + + [ThreadStatic] + private static int t_inline; + } +} diff --git a/src/Opc.Ua.Core/Stack/Tcp/UaSCBinaryChannel.cs b/src/Opc.Ua.Core/Stack/Tcp/UaSCBinaryChannel.cs index 8a56fd5af3..9772d9546c 100644 --- a/src/Opc.Ua.Core/Stack/Tcp/UaSCBinaryChannel.cs +++ b/src/Opc.Ua.Core/Stack/Tcp/UaSCBinaryChannel.cs @@ -1418,63 +1418,88 @@ protected void StartReceiveLoopWithBody( /// /// Receives and dispatches chunks while the transport remains current, reporting receive and dispatch failures. /// + /// + /// The requests that the received responses complete continue once the loop waits: + /// every wait of the loop that goes pending runs them on the loop's thread (see + /// ). + /// private async Task RunReceiveLoopAsync(IUaSCByteTransport transport, CancellationToken ct) { - while (!ct.IsCancellationRequested && ReferenceEquals(Transport, transport)) + try { - ArraySegment chunk; - try - { - // backpressure: do not read more requests while their responses - // cannot be written; the peer's sends block in TCP flow control. - await WaitForWriteCapacityAsync(ct).ConfigureAwait(false); - chunk = await transport.ReceiveChunkAsync(ct).ConfigureAwait(false); - } - catch (OperationCanceledException) when (ct.IsCancellationRequested) - { - return; - } - catch (ServiceResultException sre) + while (!ct.IsCancellationRequested && ReferenceEquals(Transport, transport)) { - OnTransportError(transport, sre.Result, ct); - return; - } - catch (Exception ex) - { - OnTransportError(transport, ServiceResult.Create( - ex, - StatusCodes.BadTcpInternalError, - ex.Message), ct); - return; - } + ArraySegment chunk; + try + { + // backpressure: do not read more requests while their responses + // cannot be written; the peer's sends block in TCP flow control. + await ResponseContinuationDeferral.AwaitAndComplete(WaitForWriteCapacityAsync(ct)); + chunk = await ResponseContinuationDeferral.AwaitAndComplete(transport.ReceiveChunkAsync(ct)); + } + catch (OperationCanceledException) when (ct.IsCancellationRequested) + { + return; + } + catch (ServiceResultException sre) + { + OnTransportError(transport, sre.Result, ct); + return; + } + catch (Exception ex) + { + OnTransportError(transport, ServiceResult.Create( + ex, + StatusCodes.BadTcpInternalError, + ex.Message), ct); + return; + } - if (ct.IsCancellationRequested || !ReferenceEquals(Transport, transport)) - { - BufferManager.ReturnBuffer(chunk.Array, nameof(RunReceiveLoopAsync)); - return; - } + if (ct.IsCancellationRequested || !ReferenceEquals(Transport, transport)) + { + BufferManager.ReturnBuffer(chunk.Array, nameof(RunReceiveLoopAsync)); + return; + } - try - { - await OnChunkReceivedAsync(chunk, ct).ConfigureAwait(false); - } - catch (OperationCanceledException) when (ct.IsCancellationRequested) - { - return; - } - catch (Exception ex) - { - // Dispatching a chunk must never end the loop silently. The - // task this runs on is fire-and-forget, so an escaping - // exception would otherwise stop the channel receiving with no - // report at all, and the peer would simply time out. - OnTransportError(transport, ServiceResult.Create( - ex, - StatusCodes.BadTcpInternalError, - "An error occurred dispatching a received message."), ct); - return; + try + { + // the responses in the chunk defer the continuations of their requests + ValueTask dispatch; + ResponseContinuationDeferral.Enter(); + try + { + dispatch = OnChunkReceivedAsync(chunk, ct); + } + finally + { + ResponseContinuationDeferral.Exit(); + } + await ResponseContinuationDeferral.AwaitAndComplete(dispatch); + } + catch (OperationCanceledException) when (ct.IsCancellationRequested) + { + return; + } + catch (Exception ex) + { + // Dispatching a chunk must never end the loop silently. The + // task this runs on is fire-and-forget, so an escaping + // exception would otherwise stop the channel receiving with no + // report at all, and the peer would simply time out. + OnTransportError(transport, ServiceResult.Create( + ex, + StatusCodes.BadTcpInternalError, + "An error occurred dispatching a received message."), ct); + return; + } } } + finally + { + // A completion deferred by the last chunk goes to the pool. The loop ends + // on the thread that dispatched that chunk, which holds the completion. + ResponseContinuationDeferral.CompletePending(inline: false); + } } /// diff --git a/tests/Opc.Ua.Core.Tests/Stack/Transport/ResponseContinuationDeferralTests.cs b/tests/Opc.Ua.Core.Tests/Stack/Transport/ResponseContinuationDeferralTests.cs new file mode 100644 index 0000000000..672c91a2eb --- /dev/null +++ b/tests/Opc.Ua.Core.Tests/Stack/Transport/ResponseContinuationDeferralTests.cs @@ -0,0 +1,386 @@ +/* ======================================================================== + * Copyright (c) 2005-2025 The OPC Foundation, Inc. All rights reserved. + * + * OPC Foundation MIT License 1.00 + * + * Permission is hereby granted, free of charge, to any person + * obtaining a copy of this software and associated documentation + * files (the "Software"), to deal in the Software without + * restriction, including without limitation the rights to use, + * copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the + * Software is furnished to do so, subject to the following + * conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES + * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT + * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, + * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR + * OTHER DEALINGS IN THE SOFTWARE. + * + * The complete license agreement can be found here: + * http://opcfoundation.org/License/MIT/1.00/ + * ======================================================================*/ + +using System; +using System.Threading; +using System.Threading.Tasks; +using Microsoft.Extensions.Logging; +using NUnit.Framework; +using Opc.Ua.Bindings; +using Opc.Ua.Tests; + +namespace Opc.Ua.Core.Tests.Stack.Transport +{ + /// + /// The receive loop runs the continuations of the requests it completed once it + /// waits for the next chunk (see ). + /// + [TestFixture] + [Category("TcpTransport")] + [Parallelizable] + public sealed class ResponseContinuationDeferralTests + { + private readonly ILogger m_logger = + NUnitTelemetryContext.Create().CreateLogger(); + + [Test] + [CancelAfter(10000)] + public async Task CompletionOutsideAScopeIsNotDeferredAsync() + { + using var operation = new ChannelAsyncOperation(int.MaxValue, null, null, m_logger); + ValueTask wait = operation.WaitForCompletionAsync(CancellationToken.None); + + Assert.That(operation.Complete(true, 7), Is.True); + + Assert.That(wait.IsCompleted, Is.True); + await wait.ConfigureAwait(false); + Assert.That(operation.End(0), Is.EqualTo(7)); + } + + [Test] + [CancelAfter(10000)] + public async Task CompletionInAScopeRunsItsContinuationWhenPendingCompletesInlineAsync() + { + using var operation = new ChannelAsyncOperation(int.MaxValue, null, null, m_logger); + Task waiter = ContinuationThreadAsync(operation.WaitForCompletionAsync(CancellationToken.None)); + + ResponseContinuationDeferral.Enter(); + try + { + Assert.That(operation.Complete(true, 7), Is.True); + } + finally + { + ResponseContinuationDeferral.Exit(); + } + Assert.That(waiter.IsCompleted, Is.False, "the completion is deferred"); + + ResponseContinuationDeferral.CompletePending(inline: true); + + Assert.That(waiter.IsCompleted, Is.True, "the continuation ran inline"); + Assert.That(await waiter.ConfigureAwait(false), Is.EqualTo(Environment.CurrentManagedThreadId)); + Assert.That(operation.End(0), Is.EqualTo(7)); + } + + [Test] + [CancelAfter(10000)] + public async Task CompletionsDeferredOnLoopExitRunOnThePoolAsync() + { + using var operation = new ChannelAsyncOperation(int.MaxValue, null, null, m_logger); + Task waiter = ContinuationThreadAsync(operation.WaitForCompletionAsync(CancellationToken.None)); + + ResponseContinuationDeferral.Enter(); + try + { + operation.Complete(true, 7); + } + finally + { + ResponseContinuationDeferral.Exit(); + } + ResponseContinuationDeferral.CompletePending(inline: false); + + await waiter.ConfigureAwait(false); + Assert.That(operation.End(0), Is.EqualTo(7)); + } + + [Test] + [CancelAfter(10000)] + public async Task LaterCompletionCompletesTheHeldOneOnThePoolAsync() + { + using var first = new ChannelAsyncOperation(int.MaxValue, null, null, m_logger); + using var second = new ChannelAsyncOperation(int.MaxValue, null, null, m_logger); + Task firstWaiter = ContinuationThreadAsync(first.WaitForCompletionAsync(CancellationToken.None)); + Task secondWaiter = ContinuationThreadAsync(second.WaitForCompletionAsync(CancellationToken.None)); + + ResponseContinuationDeferral.Enter(); + try + { + first.Complete(true, 1); + second.Complete(true, 2); + } + finally + { + ResponseContinuationDeferral.Exit(); + } + + // the first completes on the pool without the loop suspending; waited for on + // this thread, which holds the second + Assert.That(firstWaiter.Wait(TimeSpan.FromSeconds(5)), Is.True); + Assert.That(secondWaiter.IsCompleted, Is.False, "the latest completion is held"); + + ResponseContinuationDeferral.CompletePending(inline: true); + Assert.That(secondWaiter.IsCompleted, Is.True); + Assert.That(await secondWaiter.ConfigureAwait(false), Is.EqualTo(Environment.CurrentManagedThreadId)); + } + + [Test] + [CancelAfter(10000)] + public async Task HeldCompletionGoesToThePoolAfterFourMoreChunksAsync() + { + using var operation = new ChannelAsyncOperation(int.MaxValue, null, null, m_logger); + Task waiter = ContinuationThreadAsync(operation.WaitForCompletionAsync(CancellationToken.None)); + + ResponseContinuationDeferral.Enter(); + try + { + operation.Complete(true, 7); + } + finally + { + ResponseContinuationDeferral.Exit(); + } + + // chunks without responses, received without the loop suspending + for (int ii = 0; ii < 4; ii++) + { + ResponseContinuationDeferral.Enter(); + ResponseContinuationDeferral.Exit(); + } + Assert.That(waiter.IsCompleted, Is.False, "held while the loop dispatches four more chunks"); + + ResponseContinuationDeferral.Enter(); + ResponseContinuationDeferral.Exit(); + await waiter.ConfigureAwait(false); + Assert.That(operation.End(0), Is.EqualTo(7)); + ResponseContinuationDeferral.CompletePending(inline: true); + } + + /// + /// Two responses in a row: the continuation of the first blocks until the second + /// request completes, which must not wait for the blocked thread. + /// + [Test] + [CancelAfter(20000)] + public async Task ContinuationBlockingOnTheNextResponseDoesNotDeadlockAsync() + { + using var first = new ChannelAsyncOperation(int.MaxValue, null, null, m_logger); + using var second = new ChannelAsyncOperation(int.MaxValue, null, null, m_logger); + var receive = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + Task secondWaiter = ContinuationThreadAsync(second.WaitForCompletionAsync(CancellationToken.None)); + Task firstCaller = BlockOnAsync(first.WaitForCompletionAsync(CancellationToken.None), secondWaiter); + + Task loop = Task.Run(async () => + { + ResponseContinuationDeferral.Enter(); + try + { + first.Complete(true, 1); + second.Complete(true, 2); + } + finally + { + ResponseContinuationDeferral.Exit(); + } + return await ResponseContinuationDeferral.AwaitAndComplete(new ValueTask(receive.Task)); + }); + + Assert.That(await firstCaller.ConfigureAwait(false), Is.True, "the second response completed"); + receive.SetResult(1); + Assert.That(await loop.ConfigureAwait(false), Is.EqualTo(1)); + } + + /// + /// A receive loop that blocks for buffer budget completes the response it holds on + /// the pool: that request's caller returns the budget the loop waits for. + /// + [Test] + [CancelAfter(20000)] + public async Task LoopBlockedOnBufferBudgetCompletesTheHeldResponseAsync() + { + using var limiter = new BufferManagerMemoryLimiter(100); + long held = limiter.Reserve(100, CancellationToken.None); + using var operation = new ChannelAsyncOperation(int.MaxValue, null, null, m_logger); + Task caller = ReturnBudgetAsync(operation.WaitForCompletionAsync(CancellationToken.None), limiter, held); + + Task loop = Task.Run(() => + { + ResponseContinuationDeferral.Enter(); + try + { + operation.Complete(true, 7); + } + finally + { + ResponseContinuationDeferral.Exit(); + } + // the next receive rents a buffer from the exhausted budget + using var timeout = new CancellationTokenSource(TimeSpan.FromSeconds(5)); + long next = limiter.Reserve(50, timeout.Token); + limiter.Cancel(next); + }); + + await loop.ConfigureAwait(false); + await caller.ConfigureAwait(false); + Assert.That(operation.End(0), Is.EqualTo(7)); + } + + /// + /// An inline continuation completes the loop's receive synchronously, so the loop + /// resumes on its stack and defers the next response. That one completes on the + /// pool: run nested inline, it would wait for the first continuation forever. + /// + [Test] + [CancelAfter(20000)] + public async Task LoopResumedInsideAnInlineContinuationDoesNotNestTheNextAsync() + { + using var first = new ChannelAsyncOperation(int.MaxValue, null, null, m_logger); + using var second = new ChannelAsyncOperation(int.MaxValue, null, null, m_logger); + // continuations of a default source run synchronously, as with an in-process peer + var firstReceive = new TaskCompletionSource(); + var secondReceive = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + using var firstDone = new ManualResetEventSlim(); + + Task firstCaller = CompleteReceiveAsync( + first.WaitForCompletionAsync(CancellationToken.None), firstReceive, firstDone); + Task secondCaller = WaitForEventAsync( + second.WaitForCompletionAsync(CancellationToken.None), firstDone); + + Task loop = Task.Run(async () => + { + ResponseContinuationDeferral.Enter(); + try + { + first.Complete(true, 1); + } + finally + { + ResponseContinuationDeferral.Exit(); + } + await ResponseContinuationDeferral.AwaitAndComplete(new ValueTask(firstReceive.Task)); + + // resumed inside the first caller's continuation + ResponseContinuationDeferral.Enter(); + try + { + second.Complete(true, 2); + } + finally + { + ResponseContinuationDeferral.Exit(); + } + return await ResponseContinuationDeferral.AwaitAndComplete(new ValueTask(secondReceive.Task)); + }); + + await firstCaller.ConfigureAwait(false); + Assert.That(await secondCaller.ConfigureAwait(false), Is.True, "the first caller finished"); + secondReceive.SetResult(3); + Assert.That(await loop.ConfigureAwait(false), Is.EqualTo(3)); + } + + private static async Task CompleteReceiveAsync( + ValueTask wait, + TaskCompletionSource receive, + ManualResetEventSlim done) + { + await wait.ConfigureAwait(false); + receive.SetResult(1); + done.Set(); + } + + private static async Task WaitForEventAsync(ValueTask wait, ManualResetEventSlim done) + { + await wait.ConfigureAwait(false); + return done.Wait(TimeSpan.FromSeconds(5)); + } + + private static async Task ReturnBudgetAsync(ValueTask wait, BufferManagerMemoryLimiter limiter, long reservation) + { + await wait.ConfigureAwait(false); + limiter.Cancel(reservation); + } + + private static async Task BlockOnAsync(ValueTask wait, Task other) + { + await wait.ConfigureAwait(false); + return other.Wait(TimeSpan.FromSeconds(5)); + } + + /// + /// A continuation that blocks until the receive loop resumes does not stall the + /// loop: the loop registers its continuation on the pending receive before it + /// runs the deferred continuations on its thread. + /// + [Test] + [CancelAfter(20000)] + public async Task BlockingContinuationDoesNotStallTheLoopAsync() + { + using var operation = new ChannelAsyncOperation(int.MaxValue, null, null, m_logger); + var receive = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + using var loopResumed = new ManualResetEventSlim(); + + // the caller of the request: completes the next receive, then blocks until + // the loop has processed it, as a synchronous call on the channel would + Task caller = CallerAsync( + operation.WaitForCompletionAsync(CancellationToken.None), + receive, + loopResumed); + + Task loop = Task.Run(() => LoopAsync(operation, receive, loopResumed)); + + Assert.That(await loop.ConfigureAwait(false), Is.EqualTo(1)); + Assert.That(await caller.ConfigureAwait(false), Is.True, "the loop resumed while the caller blocked"); + } + + private static async Task LoopAsync( + ChannelAsyncOperation operation, + TaskCompletionSource receive, + ManualResetEventSlim loopResumed) + { + ResponseContinuationDeferral.Enter(); + try + { + operation.Complete(true, 7); + } + finally + { + ResponseContinuationDeferral.Exit(); + } + int received = await ResponseContinuationDeferral.AwaitAndComplete(new ValueTask(receive.Task)); + loopResumed.Set(); + return received; + } + + private static async Task CallerAsync( + ValueTask wait, + TaskCompletionSource receive, + ManualResetEventSlim loopResumed) + { + await wait.ConfigureAwait(false); + receive.SetResult(1); + return loopResumed.Wait(TimeSpan.FromSeconds(5)); + } + + private static async Task ContinuationThreadAsync(ValueTask wait) + { + await wait.ConfigureAwait(false); + return Environment.CurrentManagedThreadId; + } + } +} diff --git a/tests/Opc.Ua.Core.Tests/Stack/Transport/TcpTransportListenerRequestCompletionTests.cs b/tests/Opc.Ua.Core.Tests/Stack/Transport/TcpTransportListenerRequestCompletionTests.cs index 21a2f7725c..5e479a09d6 100644 --- a/tests/Opc.Ua.Core.Tests/Stack/Transport/TcpTransportListenerRequestCompletionTests.cs +++ b/tests/Opc.Ua.Core.Tests/Stack/Transport/TcpTransportListenerRequestCompletionTests.cs @@ -282,6 +282,12 @@ public async Task ResponseAfterChannelClosedIsDroppedQuietlyAsync() closing.Dispose(); await Assert.CatchAsync(async () => await abandoned.ConfigureAwait(false)); + // the client does not wait for the server to process the close: the response + // is dropped only once the listener has closed its side of the channel + Assert.That(await WaitForAsync(() => loopback.Logs.Any(l => + l.EventId == CoreEventIds.TcpTransportListener + 4)) + .ConfigureAwait(false), Is.True, "The server did not close the channel."); + source.SetResult(Respond(CreateReadRequest(1))); Assert.That(await WaitForAsync(() => loopback.Logs.Any(l =>