Files
mxaccessgw/src/ZB.MOM.WW.MxGateway.Worker/MxAccess/IWorkerRuntimeSession.cs
T
Joseph Doherty 659bb831a2 perf(worker,gateway): pin MXSTATUS_PROXY record info, dedicated event-drain thread, cap thread-pool spin
At ~240 events/s the worker burned 8-12% system CPU on wonder-app-vd03. A WPR
trace put 72% of it in lmxproxy's per-event GetRecordInfoFromGuids (type
library reload through the registry, amplified by WOW64 and the EDR registry
filter) and 26% in the .NET Framework thread pool spinning after each
per-event work item.

- Worker: MxStatusProxyRecordInfoPin holds the LMXProxy ITypeLib and the
  MXSTATUS_PROXY IRecordInfo for the process lifetime, so oleaut32 serves the
  per-event lookup from cache (~1 ms -> <1 us per call). Best-effort, never
  fatal; status logged at handshake.
- Worker: the event drain loop runs on a dedicated background thread with a
  synchronous wait and a synchronous pipe flush, removing the per-event
  thread-pool hops.
- Gateway: runtimeconfig sets ThreadPool.UnfairSemaphoreSpinLimit=10 to cut
  PortableThreadPool spin-wait CPU.

windev bench at ~242 ev/s: worker 67% -> 6.2% of one core; gateway 8.1% -> 6.9%.
Worker suite 785 passed / 14 skipped (x86, windev).
2026-11-21 08:00:13 -05:00

120 lines
5.9 KiB
C#

using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using ZB.MOM.WW.MxGateway.Contracts.Proto;
using ZB.MOM.WW.MxGateway.Worker.Sta;
namespace ZB.MOM.WW.MxGateway.Worker.MxAccess;
/// <summary>
/// Manages the runtime session between the worker and the MXAccess COM instance on an STA thread.
/// </summary>
public interface IWorkerRuntimeSession : IDisposable
{
/// <summary>
/// Starts the session, creates the MXAccess COM object, and returns ready metadata.
/// </summary>
/// <param name="sessionId">Identifier of the session.</param>
/// <param name="workerProcessId">ID of the worker process.</param>
/// <param name="cancellationToken">Token to cancel the asynchronous operation.</param>
/// <returns>Asynchronous task returning worker readiness metadata.</returns>
Task<WorkerReady> StartAsync(
string sessionId,
int workerProcessId,
CancellationToken cancellationToken = default);
/// <summary>
/// Dispatches an STA command to the MXAccess runtime and returns the reply.
/// </summary>
/// <param name="command">STA command to execute on the STA thread.</param>
/// <returns>Asynchronous task returning the command reply.</returns>
Task<MxCommandReply> DispatchAsync(StaCommand command);
/// <summary>
/// Captures a heartbeat snapshot of the runtime state.
/// </summary>
/// <returns>The current heartbeat snapshot.</returns>
WorkerRuntimeHeartbeatSnapshot CaptureHeartbeat();
/// <summary>
/// Drains up to the specified number of pending events from the queue.
/// </summary>
/// <param name="maxEvents">Maximum number of events to drain.</param>
/// <returns>List of drained events.</returns>
IReadOnlyList<WorkerEvent> DrainEvents(uint maxEvents);
/// <summary>
/// Drains pending events bounded by both a count cap and a byte budget, so a caller building a
/// single reply frame never removes an event it cannot ship.
/// </summary>
/// <remarks>
/// Declared as a second method rather than a default interface method: the worker targets
/// .NET Framework 4.8, which has no runtime support for default interface members.
/// </remarks>
/// <param name="maxEvents">Maximum number of events to drain; 0 means "no count limit".</param>
/// <param name="maxTotalBytes">Byte budget for the drained events' estimated serialized size.</param>
/// <returns>The drained events and the truncation facts describing what stayed queued.</returns>
WorkerEventDrainResult DrainEvents(uint maxEvents, int maxTotalBytes);
/// <summary>
/// Waits until the outbound event queue has something for the caller to look at (an
/// enqueued event or a recorded fault), the fallback timeout elapses, or the token is
/// cancelled. Lets a drain loop be signal-driven instead of polling.
/// </summary>
/// <remarks>
/// Declared on the interface because the pipe session only ever sees an
/// <see cref="IWorkerRuntimeSession"/>, never the queue behind it; .NET Framework 4.8 has
/// no default interface members, so every implementation supplies it. The wait's outcome is
/// not surfaced: the caller re-drains and re-checks <see cref="DrainFault"/> after every
/// wait, because the signal is coalesced and the timeout is a ceiling, not a poll period.
/// <para>
/// Precondition: <b>at most one waiter</b>. The implementation's wake signal carries a
/// single permit, which is sufficient only because a session has exactly one event
/// drain loop; a second concurrent waiter would degrade to the fallback timeout.
/// </para>
/// </remarks>
/// <param name="timeout">Maximum time to wait before the wait completes unsignalled.</param>
/// <param name="cancellationToken">Token cancelling the wait.</param>
/// <returns>A task that completes when the queue is signalled or the timeout elapses.</returns>
Task WaitForEventsAsync(TimeSpan timeout, CancellationToken cancellationToken);
/// <summary>
/// Blocking form of <see cref="WaitForEventsAsync"/> for a drain loop that runs on its own
/// dedicated thread. Same contract (coalesced signal, timeout is a ceiling, at most one
/// waiter); it parks the calling thread instead of scheduling a thread-pool continuation per
/// wake, which on .NET Framework also triggers the pool's spin-wait on every event.
/// </summary>
/// <param name="timeout">Maximum time to wait before the wait completes unsignalled.</param>
/// <param name="cancellationToken">Token cancelling the wait.</param>
void WaitForEvents(TimeSpan timeout, CancellationToken cancellationToken);
/// <summary>
/// Drains a pending fault from the queue, if any.
/// </summary>
/// <returns>The pending fault, or <see langword="null"/> if none is queued.</returns>
WorkerFault? DrainFault();
/// <summary>
/// Cancels a pending command by correlation ID.
/// </summary>
/// <param name="correlationId">Correlation ID of the command to cancel.</param>
/// <returns>True if the command was found and cancelled; otherwise, false.</returns>
bool CancelCommand(string correlationId);
/// <summary>
/// Requests a graceful shutdown of the session.
/// </summary>
void RequestShutdown();
/// <summary>
/// Shuts down the session gracefully within the specified timeout.
/// </summary>
/// <param name="timeout">Maximum time to allow for graceful shutdown.</param>
/// <param name="cancellationToken">Token to cancel the asynchronous operation.</param>
/// <returns>Asynchronous task returning the shutdown result.</returns>
Task<MxAccessShutdownResult> ShutdownGracefullyAsync(
TimeSpan timeout,
CancellationToken cancellationToken = default);
}