From 0b93fe8263246b10e02bb81d0461518e475ebf07 Mon Sep 17 00:00:00 2001 From: Joseph Doherty Date: Thu, 3 Dec 2026 09:51:46 -0500 Subject: [PATCH] perf(worker): start the STA dispatcher drain outside its gate so command logging cannot stall the read loop (WIP-010, #256) --- .../Sta/StaCommandDispatcherTests.cs | 67 +++++++++++++++++++ .../Sta/StaCommandDispatcher.cs | 28 ++++++-- 2 files changed, 91 insertions(+), 4 deletions(-) diff --git a/src/ZB.MOM.WW.MxGateway.Worker.Tests/Sta/StaCommandDispatcherTests.cs b/src/ZB.MOM.WW.MxGateway.Worker.Tests/Sta/StaCommandDispatcherTests.cs index e3dffbef..92d333b4 100644 --- a/src/ZB.MOM.WW.MxGateway.Worker.Tests/Sta/StaCommandDispatcherTests.cs +++ b/src/ZB.MOM.WW.MxGateway.Worker.Tests/Sta/StaCommandDispatcherTests.cs @@ -255,6 +255,51 @@ public sealed class StaCommandDispatcherTests value => value?.ToString()?.Contains("provider detail") == true); } + /// + /// WIP-010: a command-log write that blocks (a slow or full stderr sink) must not hold the + /// dispatcher gate, so DispatchAsync, PendingCommandCount and + /// CancelQueuedCommand still return while it is stuck. + /// + /// A task that represents the asynchronous operation. + [Fact] + public async Task DispatchAsync_WhenCommandLoggerBlocks_DoesNotHoldTheGate() + { + using StaRuntime runtime = CreateRuntime(); + runtime.Start(); + using ManualResetEventSlim release = new(false); + using ManualResetEventSlim entered = new(false); + BlockingWorkerLogger logger = new(entered, release); + StaCommandDispatcher dispatcher = new(runtime, new RecordingCommandExecutor()) + { + CommandLogger = logger, + }; + + try + { + Task first = await Task.Run(() => dispatcher.DispatchAsync(CreateCommand("correlation-1", MxCommandKind.Register))) + .WaitAsync(TimeSpan.FromSeconds(10)); + Assert.True(entered.Wait(TimeSpan.FromSeconds(10)), "The command logger was never called."); + + // The first command's log line is now blocked. Everything that takes the gate must still return. + Task second = await Task.Run(() => dispatcher.DispatchAsync(CreateCommand("correlation-2", MxCommandKind.AddItem))) + .WaitAsync(TimeSpan.FromSeconds(10)); + bool canceled = await Task.Run(() => dispatcher.CancelQueuedCommand("correlation-2")) + .WaitAsync(TimeSpan.FromSeconds(10)); + int pending = await Task.Run(() => dispatcher.PendingCommandCount) + .WaitAsync(TimeSpan.FromSeconds(10)); + + Assert.True(canceled); + Assert.Equal(0, pending); + Assert.Equal(ProtocolStatusCode.Canceled, (await second).ProtocolStatus.Code); + } + finally + { + release.Set(); + } + + Assert.Equal(ProtocolStatusCode.Ok, (await Task.Run(() => dispatcher.DispatchAsync(CreateCommand("correlation-3", MxCommandKind.Register)))).ProtocolStatus.Code); + } + /// Verifies the opt-in environment value is parsed strictly. /// Raw environment value. /// Whether logging should be enabled. @@ -302,6 +347,28 @@ public sealed class StaCommandDispatcherTests /// /// Test executor that records executed command correlations and thread IDs. /// + private sealed class BlockingWorkerLogger : IWorkerLogger + { + private readonly ManualResetEventSlim entered; + private readonly ManualResetEventSlim release; + + public BlockingWorkerLogger(ManualResetEventSlim entered, ManualResetEventSlim release) + { + this.entered = entered; + this.release = release; + } + + public void Information(string eventName, IReadOnlyDictionary fields) + { + entered.Set(); + release.Wait(TimeSpan.FromSeconds(30)); + } + + public void Error(string eventName, IReadOnlyDictionary fields) + { + } + } + private sealed class RecordingCommandExecutor : IStaCommandExecutor { private readonly object gate = new(); diff --git a/src/ZB.MOM.WW.MxGateway.Worker/Sta/StaCommandDispatcher.cs b/src/ZB.MOM.WW.MxGateway.Worker/Sta/StaCommandDispatcher.cs index 9ef6a74f..544b6973 100644 --- a/src/ZB.MOM.WW.MxGateway.Worker/Sta/StaCommandDispatcher.cs +++ b/src/ZB.MOM.WW.MxGateway.Worker/Sta/StaCommandDispatcher.cs @@ -122,6 +122,8 @@ public sealed class StaCommandDispatcher throw new ArgumentNullException(nameof(command)); } + QueuedStaCommand queuedCommand; + bool startDrain = false; lock (gate) { if (shutdownRequested) @@ -140,17 +142,27 @@ public sealed class StaCommandDispatcher $"The STA command dispatcher already has {maxPendingCommands} pending command(s).")); } - QueuedStaCommand queuedCommand = new(command); + queuedCommand = new QueuedStaCommand(command); commandQueue.Enqueue(queuedCommand); if (!drainActive) { drainActive = true; - _ = DrainAsync(); + startDrain = true; } - - return queuedCommand.Task; } + + // Started after the gate is released. An async method runs synchronously to its first + // incomplete await, so starting it under the lock ran the dequeue, the optional command-log + // console write and the STA enqueue under the same lock the heartbeat, PendingCommandCount + // and CancelQueuedCommand take: a slow stderr sink stalled the pipe read loop and those + // callers together. + if (startDrain) + { + _ = DrainAsync(); + } + + return queuedCommand.Task; } /// @@ -242,6 +254,14 @@ public sealed class StaCommandDispatcher private async Task DrainAsync() { + // With command logging on, the first step writes to the console. Yield so that write runs on + // a pool thread instead of the pipe read loop that called DispatchAsync. Not done when logging + // is off: the extra pool hop would cost a wake-up per idle-to-busy transition for nothing. + if (CommandLogger is not null) + { + await Task.Yield(); + } + while (true) { QueuedStaCommand queuedCommand;