using System; using System.Collections.Generic; using System.IO; using ZB.MOM.WW.MxGateway.Contracts.Proto; using ZB.MOM.WW.MxGateway.Worker.Bootstrap; using ZB.MOM.WW.MxGateway.Worker.Ipc; namespace ZB.MOM.WW.MxGateway.Worker; /// Entry point for the worker process. public static class WorkerApplication { /// Initializes and runs the worker with default environment and logging. /// Command-line arguments. /// The process exit code. public static int Run(string[] args) { WorkerConsoleLogger logger = new(Console.Error); // WRK-09: installed only on the production entry point (not the // injectable overloads tests call) because the hook is process-global. AppDomain.CurrentDomain.UnhandledException += (_, eventArgs) => HandleUnhandledException( logger, eventArgs.ExceptionObject, eventArgs.IsTerminating, Environment.Exit); return Run( args, new EnvironmentVariableWorkerEnvironment(), logger); } /// /// Body of the worker's AppDomain.CurrentDomain.UnhandledException /// hook. Logs one WorkerUnhandledException line and exits the /// process with , so the /// gateway's launcher sees a defined worker exit code rather than the /// CLR's crash code. /// /// /// Logs the exception type only — never its message or stack. An /// exception reaching this hook can come from any thread, including a /// COM callback or a command path whose message can carry tag values /// or credentials, so it gets none of the content that /// 's /// own catch blocks log through /// (those see only pipe-session failures). A logging failure is /// swallowed so the exit always happens. /// /// Worker logger. /// The unhandled exception object (not necessarily an ). /// Whether the CLR is terminating the process. /// Process-exit action; in production. internal static void HandleUnhandledException( IWorkerLogger logger, object? exceptionObject, bool isTerminating, Action exit) { try { logger.Error("WorkerUnhandledException", new Dictionary { ["exit_code"] = WorkerExitCode.UnhandledException, ["exception_type"] = exceptionObject?.GetType().FullName ?? "null", ["is_terminating"] = isTerminating, }); } catch { // Never let a logging failure skip the defined exit. } exit((int)WorkerExitCode.UnhandledException); } /// Initializes and runs the worker with custom environment and logging. /// Command-line arguments. /// Worker environment for resolving configuration. /// Worker logger for diagnostics. /// The process exit code. public static int Run( string[] args, IWorkerEnvironment environment, IWorkerLogger logger) { return Run( args, environment, logger, new WorkerPipeClient(logger)); } /// Parses arguments, bootstraps the handshake, and runs the worker until shutdown. /// Command-line arguments. /// Worker environment for resolving configuration. /// Worker logger for diagnostics. /// Named pipe client for gateway communication. /// The process exit code. public static int Run( string[] args, IWorkerEnvironment environment, IWorkerLogger logger, IWorkerPipeClient pipeClient) { if (args is null) { throw new ArgumentNullException(nameof(args)); } if (environment is null) { throw new ArgumentNullException(nameof(environment)); } if (logger is null) { throw new ArgumentNullException(nameof(logger)); } if (pipeClient is null) { throw new ArgumentNullException(nameof(pipeClient)); } try { WorkerOptionsParser parser = new(environment); WorkerBootstrapResult result = parser.Parse(args); if (!result.Succeeded) { logger.Error("WorkerBootstrapFailed", new Dictionary { ["exit_code"] = result.ExitCode, ["errors"] = string.Join(";", result.Errors), }); return (int)result.ExitCode; } WorkerOptions options = result.Options ?? throw new InvalidOperationException("Successful bootstrap result did not include worker options."); logger.Information("WorkerBootstrapSucceeded", new Dictionary { ["session_id"] = options.SessionId, ["pipe_name"] = options.PipeName, ["protocol_version"] = options.ProtocolVersion, ["nonce"] = options.Nonce, }); pipeClient.RunAsync(options).GetAwaiter().GetResult(); logger.Information("WorkerPipeSessionCompleted", new Dictionary { ["session_id"] = options.SessionId, ["pipe_name"] = options.PipeName, ["protocol_version"] = options.ProtocolVersion, }); return (int)WorkerExitCode.Success; } catch (WorkerFrameProtocolException exception) when (exception.ErrorCode == WorkerFrameProtocolErrorCode.EndOfStream) { // A read that hits end of stream means the gateway closed its end of the pipe — most // often because the gateway process died. That is a lost connection, not a malformed // frame, so it exits as PipeConnectionFailed alongside the IOException a broken pipe // raises, rather than as ProtocolViolation. logger.Error("WorkerPipeConnectionFailed", new Dictionary { ["exit_code"] = WorkerExitCode.PipeConnectionFailed, ["error_code"] = exception.ErrorCode, ["exception_type"] = exception.GetType().FullName, ["exception_message"] = WorkerLogRedactor.RedactMessage(exception.Message), }); return (int)WorkerExitCode.PipeConnectionFailed; } catch (WorkerFrameProtocolException exception) { logger.Error("WorkerPipeProtocolFailure", new Dictionary { ["exit_code"] = WorkerExitCode.ProtocolViolation, ["error_code"] = exception.ErrorCode, ["exception_type"] = exception.GetType().FullName, ["exception_message"] = WorkerLogRedactor.RedactMessage(exception.Message), }); return (int)WorkerExitCode.ProtocolViolation; } catch (WorkerEventQueueFaultException exception) when (exception.Category == WorkerFaultCategory.QueueOverflow) { logger.Error("WorkerEventQueueOverflow", new Dictionary { ["exit_code"] = WorkerExitCode.EventQueueOverflow, ["exception_type"] = exception.GetType().FullName, ["exception_message"] = WorkerLogRedactor.RedactMessage(exception.Message), }); return (int)WorkerExitCode.EventQueueOverflow; } catch (Exception exception) when (exception is IOException or TimeoutException) { logger.Error("WorkerPipeConnectionFailed", new Dictionary { ["exit_code"] = WorkerExitCode.PipeConnectionFailed, ["exception_type"] = exception.GetType().FullName, ["exception_message"] = WorkerLogRedactor.RedactMessage(exception.Message), }); return (int)WorkerExitCode.PipeConnectionFailed; } catch (Exception exception) { logger.Error("WorkerBootstrapUnexpectedFailure", new Dictionary { ["exit_code"] = WorkerExitCode.UnexpectedFailure, ["exception_type"] = exception.GetType().FullName, ["exception_message"] = WorkerLogRedactor.RedactMessage(exception.Message), }); return (int)WorkerExitCode.UnexpectedFailure; } } }