using System.IO.Pipes;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using ZB.MOM.WW.MxGateway.Contracts;
using ZB.MOM.WW.MxGateway.Contracts.Proto;
using ZB.MOM.WW.MxGateway.Server.Configuration;
using ZB.MOM.WW.MxGateway.Server.Metrics;
using ZB.MOM.WW.MxGateway.Server.Workers;
namespace ZB.MOM.WW.MxGateway.Server.Sessions;
/// Factory for creating worker clients and launching worker processes.
public sealed class SessionWorkerClientFactory : ISessionWorkerClientFactory
{
///
/// Kernel buffer quota requested for each direction of a worker pipe. A zero quota — what the
/// short overloads request — makes every byte-mode write
/// rendezvous with a pending read, so writer latency is coupled to reader scheduling and a
/// writer with no reader parked blocks indefinitely. That is the failure class behind the
/// historical windev full-suite wedge (all tests reported, testhost never exiting). A real
/// quota lets a whole frame land in the kernel and the writer return. 128 KiB comfortably
/// holds the control traffic and typical event batches without reserving nonpaged pool per
/// session for the rare maximum-sized frame, which still streams through in chunks.
///
private const int PipeBufferSizeBytes = 128 * 1024;
private readonly IWorkerProcessLauncher _workerProcessLauncher;
private readonly GatewayMetrics _metrics;
private readonly TimeProvider _timeProvider;
private readonly ILoggerFactory _loggerFactory;
private readonly GatewayOptions _options;
/// Initializes a new instance of the SessionWorkerClientFactory class.
/// Service for launching worker processes.
/// Configuration options.
/// Metrics collector for gateway events.
/// Logger factory for creating loggers.
/// Optional time provider for testing; defaults to system time.
public SessionWorkerClientFactory(
IWorkerProcessLauncher workerProcessLauncher,
IOptions options,
GatewayMetrics metrics,
ILoggerFactory loggerFactory,
TimeProvider? timeProvider = null)
{
_workerProcessLauncher = workerProcessLauncher ?? throw new ArgumentNullException(nameof(workerProcessLauncher));
ArgumentNullException.ThrowIfNull(options);
_metrics = metrics ?? throw new ArgumentNullException(nameof(metrics));
_loggerFactory = loggerFactory ?? throw new ArgumentNullException(nameof(loggerFactory));
_timeProvider = timeProvider ?? TimeProvider.System;
_options = options.Value;
}
///
public async Task CreateAsync(
GatewaySession session,
CancellationToken cancellationToken)
{
ArgumentNullException.ThrowIfNull(session);
NamedPipeServerStream? pipe = CreatePipe(session.PipeName);
WorkerProcessHandle? processHandle = null;
IWorkerClient? workerClient = null;
using CancellationTokenSource startupCancellation =
CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
startupCancellation.CancelAfter(session.StartupTimeout);
try
{
session.TransitionTo(SessionState.StartingWorker);
processHandle = await _workerProcessLauncher
.LaunchAsync(
new WorkerProcessLaunchRequest(
session.SessionId,
session.PipeName,
GatewayContractInfo.WorkerProtocolVersion,
session.Nonce,
pipe),
startupCancellation.Token)
.ConfigureAwait(false);
session.TransitionTo(SessionState.WaitingForPipe);
await WaitForPipeConnectionAsync(pipe, processHandle, session.SessionId, startupCancellation.Token)
.ConfigureAwait(false);
session.TransitionTo(SessionState.Handshaking);
WorkerFrameProtocolOptions frameOptions = new(
session.SessionId,
GatewayContractInfo.WorkerProtocolVersion,
_options.Worker.MaxMessageBytes);
WorkerClientConnection connection = new(
session.SessionId,
session.Nonce,
pipe,
frameOptions,
processHandle);
WorkerClientOptions clientOptions = CreateWorkerClientOptions(_options);
workerClient = new WorkerClient(
connection,
clientOptions,
_metrics,
_timeProvider,
_loggerFactory.CreateLogger());
pipe = null;
processHandle = null;
session.TransitionTo(SessionState.InitializingWorker);
await workerClient.StartAsync(startupCancellation.Token).ConfigureAwait(false);
return workerClient;
}
catch (Exception exception)
{
if (workerClient is not null)
{
try
{
workerClient.Kill("OpenSessionFailed");
}
catch
{
// Preserve the startup failure while still disposing below.
}
await workerClient.DisposeAsync().ConfigureAwait(false);
}
else
{
// Must not throw (WRK-006): Kill can raise Win32Exception or AggregateException for
// a process that is mid-termination, and an exception here would replace the
// startup failure the caller is owed and skip the pipe dispose, leaking the
// pipe server handle.
try
{
if (processHandle is not null && !processHandle.Process.HasExited)
{
processHandle.Process.Kill(entireProcessTree: true);
_metrics.WorkerKilled("OpenSessionFailed");
}
}
catch (Exception killException)
{
_loggerFactory.CreateLogger().LogWarning(
killException,
"Killing the worker of session {SessionId} after a failed open failed.",
session.SessionId);
}
finally
{
processHandle?.Dispose();
pipe?.Dispose();
}
}
if (exception is OperationCanceledException
&& startupCancellation.IsCancellationRequested
&& !cancellationToken.IsCancellationRequested)
{
throw new TimeoutException(
$"Worker session {session.SessionId} did not complete startup within {session.StartupTimeout}.",
exception);
}
throw;
}
}
/// Creates a named pipe for worker communication.
/// The pipe name.
/// Named pipe server stream.
///
/// The buffer sizes are explicit so the pipe is not created with a zero quota; see
/// . On Unix hosts (the macOS test matrix, where named pipes
/// are Unix domain sockets) the sizes are advisory — the fix targets Windows production.
/// Access is restricted to the gateway's own account (#187): on Windows by the explicit ACL
/// from , elsewhere by .
///
internal static NamedPipeServerStream CreatePipe(string pipeName)
{
if (OperatingSystem.IsWindows())
{
return NamedPipeServerStreamAcl.Create(
pipeName,
PipeDirection.InOut,
maxNumberOfServerInstances: 1,
PipeTransmissionMode.Byte,
PipeOptions.Asynchronous,
inBufferSize: PipeBufferSizeBytes,
outBufferSize: PipeBufferSizeBytes,
WorkerPipeSecurity.CreateForCurrentUser());
}
return new NamedPipeServerStream(
pipeName,
PipeDirection.InOut,
maxNumberOfServerInstances: 1,
PipeTransmissionMode.Byte,
WorkerPipeSecurity.UnixPipeOptions,
inBufferSize: PipeBufferSizeBytes,
outBufferSize: PipeBufferSizeBytes);
}
///
/// Waits for the worker to connect to the pipe, failing fast if the worker process exits
/// first (WRK-002).
///
///
/// The launcher's startup probe checks HasExited once, right after the process starts,
/// which is almost always false. A worker that then dies before connecting (a missing
/// dependency, a bad argument, security software, an unhandled startup exception) used to
/// hold the open — and its session slot — for the full startup timeout and surface as a
/// timeout with no exit code. Racing the connect against the process exit reports the crash
/// as with the exit code at once.
/// Once connected, a worker exit shows up as pipe EOF in the handshake reads.
/// The message ends with the tail of the worker's stderr when the launcher captured it
/// (mxaccessgw#259): a worker that dies this early usually said why on its way out.
///
/// The named pipe.
/// The launched worker process.
/// Session id, for the failure message.
/// Cancellation token (the startup deadline and the caller's).
/// A task that represents the asynchronous operation.
internal static async Task WaitForPipeConnectionAsync(
NamedPipeServerStream pipe,
WorkerProcessHandle processHandle,
string sessionId,
CancellationToken cancellationToken)
{
IWorkerProcess process = processHandle.Process;
using CancellationTokenSource raceCancellation = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
Task connect = pipe.WaitForConnectionAsync(raceCancellation.Token);
Task exit = process.WaitForExitAsync(raceCancellation.Token).AsTask();
Task first = await Task.WhenAny(connect, exit).ConfigureAwait(false);
if (first == exit && exit.IsCompletedSuccessfully && !connect.IsCompletedSuccessfully)
{
await raceCancellation.CancelAsync().ConfigureAwait(false);
await ObserveQuietlyAsync(connect).ConfigureAwait(false);
int? exitCode = process.ExitCode;
WorkerOutputCapture? outputCapture = processHandle.OutputCapture;
if (outputCapture is not null)
{
await outputCapture
.WaitForStandardErrorDrainedAsync(WorkerProcessLauncher.StandardErrorDrainWait)
.ConfigureAwait(false);
}
throw new WorkerProcessLaunchException(
WorkerProcessLaunchErrorCode.StartupFailed,
WorkerOutputCapture.AppendStandardErrorTail(
outputCapture,
$"Worker process for session {sessionId} exited with code "
+ $"{(exitCode?.ToString(System.Globalization.CultureInfo.InvariantCulture) ?? "unknown")} "
+ "before it connected to its pipe."));
}
// The connect won (or the exit wait itself failed, which says nothing about the worker):
// stop watching the process and let the connect decide the outcome.
await raceCancellation.CancelAsync().ConfigureAwait(false);
await ObserveQuietlyAsync(exit).ConfigureAwait(false);
await connect.ConfigureAwait(false);
}
private static async Task ObserveQuietlyAsync(Task task)
{
try
{
await task.ConfigureAwait(false);
}
catch (Exception exception) when (exception is OperationCanceledException or IOException or ObjectDisposedException or InvalidOperationException)
{
}
}
///
/// Maps the bound MxGateway:* options onto the per-session .
/// Every field is set from configuration here, so none is left
/// silently on its compile-time default.
///
/// The bound gateway options.
/// The worker client options for a new session.
internal static WorkerClientOptions CreateWorkerClientOptions(GatewayOptions options)
{
ArgumentNullException.ThrowIfNull(options);
return new WorkerClientOptions
{
HeartbeatGrace = TimeSpan.FromSeconds(options.Worker.HeartbeatGraceSeconds),
HeartbeatCheckInterval = TimeSpan.FromSeconds(options.Worker.ResolveHeartbeatCheckIntervalSeconds()),
HeartbeatStuckCeiling = TimeSpan.FromSeconds(options.Worker.HeartbeatStuckCeilingSeconds),
EventChannelCapacity = options.Events.QueueCapacity,
EventChannelFullModeTimeout = TimeSpan.FromMilliseconds(options.Worker.EventChannelFullModeTimeoutMilliseconds),
MaxPendingCommands = options.Sessions.MaxPendingCommandsPerSession,
};
}
}