using Microsoft.Extensions.Logging.Abstractions; 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.Sessions; using ZB.MOM.WW.MxGateway.Server.Workers; using ZB.MOM.WW.MxGateway.Tests.Gateway.Workers.Fakes; using ZB.MOM.WW.MxGateway.Tests.TestSupport; namespace ZB.MOM.WW.MxGateway.Tests.Gateway.Sessions; public sealed class SessionWorkerClientFactoryFakeWorkerTests : IAsyncLifetime { private static readonly TimeSpan TestTimeout = TimeSpan.FromSeconds(5); // Anti-hang guard for the CreateAsync failure/timeout tests. It only exists to stop a genuine // hang from wedging the run, so it must be far larger than any in-test semantic timeout (the // factory startup timeout being exercised) — otherwise, under CI load, this WaitAsync net can // trip before the factory's own timeout propagates and the test observes .NET's generic // "The operation has timed out." instead of the asserted "did not complete startup". private static readonly TimeSpan HangGuardTimeout = TimeSpan.FromSeconds(30); private readonly List _launchers = []; /// /// Completes immediately; no asynchronous setup is required before each test. /// /// A task that represents the asynchronous operation. public Task InitializeAsync() => Task.CompletedTask; /// /// Awaits every scripted worker task so an unhandled exception fails the owning test /// instead of surfacing later as an unobserved . /// This must stay on : xUnit v2 never invokes /// on a test class, so under the previous /// declaration this teardown silently never ran (the NeverReady launcher's parked infinite /// delay was still pending in a post-run process dump). /// /// A task that represents the asynchronous operation. public async Task DisposeAsync() { foreach (IWorkerTaskLauncher launcher in _launchers) { await launcher.ObserveWorkerTaskAsync(TestTimeout); } } /// Verifies that the factory creates a ready worker client with a scripted fake worker process. /// A task that represents the asynchronous operation. [Fact] public async Task CreateAsync_WithScriptedFakeWorker_ReturnsReadyClient() { ScriptedFakeWorkerProcessLauncher launcher = Track(new ScriptedFakeWorkerProcessLauncher()); using GatewayMetrics metrics = new(); SessionWorkerClientFactory factory = new( launcher, Options.Create(CreateOptions()), metrics, NullLoggerFactory.Instance); GatewaySession session = CreateSession(); await using IWorkerClient workerClient = await factory.CreateAsync( session, CancellationToken.None); Assert.Equal(WorkerClientState.Ready, workerClient.State); Assert.Equal(ScriptedFakeWorkerProcessLauncher.ProcessId, workerClient.ProcessId); Assert.NotNull(launcher.Harness); Task invokeTask = workerClient.InvokeAsync( CreateCommand(MxCommandKind.Ping), TestTimeout, CancellationToken.None); WorkerEnvelope commandEnvelope = await launcher.Harness.ReadCommandAsync(); await launcher.Harness.ReplyToCommandAsync(commandEnvelope); WorkerCommandReply reply = await invokeTask.WaitAsync(TestTimeout); Assert.Equal(MxCommandKind.Ping, reply.Reply.Kind); Assert.Equal(ProtocolStatusCode.Ok, reply.Reply.ProtocolStatus.Code); } /// Verifies that a failed fake worker startup throws a worker client exception. /// A task that represents the asynchronous operation. [Fact] public async Task CreateAsync_WhenFakeWorkerStartupFails_ThrowsWorkerClientException() { FailingStartupWorkerProcessLauncher launcher = Track(new FailingStartupWorkerProcessLauncher()); using GatewayMetrics metrics = new(); SessionWorkerClientFactory factory = new( launcher, Options.Create(CreateOptions()), metrics, NullLoggerFactory.Instance); GatewaySession session = CreateSession(); WorkerClientException exception = await Assert.ThrowsAsync( async () => await factory.CreateAsync(session, CancellationToken.None).WaitAsync(HangGuardTimeout)); Assert.Equal(WorkerClientErrorCode.ProtocolViolation, exception.ErrorCode); Assert.True(launcher.Process.IsDisposed); } /// Verifies that a worker that never sends ready times out and is killed. /// A task that represents the asynchronous operation. [Fact] public async Task CreateAsync_WhenFakeWorkerNeverSendsReady_TimesOutAndKillsWorker() { NeverReadyWorkerProcessLauncher launcher = Track(new NeverReadyWorkerProcessLauncher()); using GatewayMetrics metrics = new(); SessionWorkerClientFactory factory = new( launcher, Options.Create(CreateOptions(startupTimeoutSeconds: 1)), metrics, NullLoggerFactory.Instance); GatewaySession session = CreateSession(startupTimeout: TimeSpan.FromSeconds(1)); TimeoutException exception = await Assert.ThrowsAsync( async () => await factory.CreateAsync(session, CancellationToken.None).WaitAsync(HangGuardTimeout)); Assert.Contains("did not complete startup", exception.Message); Assert.Equal(1, launcher.Process.KillCount); Assert.True(launcher.Process.IsDisposed); } /// /// WRK-002: a worker that exits before it connects to its pipe fails the open at once with /// and its exit code, instead of /// holding the open for the whole startup timeout and reporting a timeout. /// /// A task that represents the asynchronous operation. [Fact] public async Task CreateAsync_WhenWorkerExitsBeforeConnecting_FailsFastWithExitCode() { ExitBeforeConnectLauncher launcher = new(); using GatewayMetrics metrics = new(); SessionWorkerClientFactory factory = new( launcher, Options.Create(CreateOptions(startupTimeoutSeconds: 20)), metrics, NullLoggerFactory.Instance); GatewaySession session = CreateSession(startupTimeout: TimeSpan.FromSeconds(20)); System.Diagnostics.Stopwatch stopwatch = System.Diagnostics.Stopwatch.StartNew(); WorkerProcessLaunchException exception = await Assert.ThrowsAsync( async () => await factory.CreateAsync(session, CancellationToken.None).WaitAsync(HangGuardTimeout)); stopwatch.Stop(); Assert.Equal(WorkerProcessLaunchErrorCode.StartupFailed, exception.ErrorCode); Assert.Contains("exited with code 3", exception.Message); Assert.True(stopwatch.Elapsed < TimeSpan.FromSeconds(10), $"open took {stopwatch.Elapsed}"); Assert.Equal(0, launcher.Process.KillCount); Assert.True(launcher.Process.IsDisposed); } /// /// mxaccessgw#259: the early-exit failure ends with the tail of the worker's stderr, so the /// operator sees why it died, not only its exit code. /// /// A task that represents the asynchronous operation. [Fact] public async Task CreateAsync_WhenWorkerExitsBeforeConnecting_FailureCarriesStderrTail() { ExitBeforeConnectLauncher launcher = new( "level=Information event=WorkerBootstrapSucceeded session_id=s\n" + "level=Error event=WorkerBootstrapUnexpectedFailure exit_code=3 exception_type=System.IO.FileNotFoundException\n"); using GatewayMetrics metrics = new(); SessionWorkerClientFactory factory = new( launcher, Options.Create(CreateOptions(startupTimeoutSeconds: 20)), metrics, NullLoggerFactory.Instance); GatewaySession session = CreateSession(startupTimeout: TimeSpan.FromSeconds(20)); WorkerProcessLaunchException exception = await Assert.ThrowsAsync( async () => await factory.CreateAsync(session, CancellationToken.None).WaitAsync(HangGuardTimeout)); Assert.Equal(WorkerProcessLaunchErrorCode.StartupFailed, exception.ErrorCode); Assert.Contains("exited with code 3", exception.Message); Assert.Contains("Last worker stderr output:", exception.Message); Assert.EndsWith("exception_type=System.IO.FileNotFoundException", exception.Message); Assert.True(launcher.Process.IsDisposed); } /// /// WRK-006: a Kill that throws during launch-failure cleanup does not replace the /// startup failure, and the process handle is still disposed. /// /// A task that represents the asynchronous operation. [Fact] public async Task CreateAsync_WhenCleanupKillThrows_SurfacesTheStartupFailure() { // The worker never connects, so the open fails in the pipe wait — before a worker client // exists — and the cleanup kills the process handle directly. NeverConnectLauncher launcher = new(); launcher.Process.KillException = new System.ComponentModel.Win32Exception(5, "Access is denied."); using GatewayMetrics metrics = new(); SessionWorkerClientFactory factory = new( launcher, Options.Create(CreateOptions(startupTimeoutSeconds: 1)), metrics, NullLoggerFactory.Instance); GatewaySession session = CreateSession(startupTimeout: TimeSpan.FromSeconds(1)); TimeoutException exception = await Assert.ThrowsAsync( async () => await factory.CreateAsync(session, CancellationToken.None).WaitAsync(HangGuardTimeout)); Assert.Contains("did not complete startup", exception.Message); Assert.True(launcher.Process.IsDisposed); } /// /// mxaccessgw#192: every field comes from configuration. /// The heartbeat check interval binds from HeartbeatCheckIntervalSeconds (not the /// worker send cadence), and the event-channel full-mode timeout and heartbeat stuck /// ceiling — previously fixed compile-time defaults — follow their new options. /// [Fact] public void CreateWorkerClientOptions_MapsEveryFieldFromConfiguration() { GatewayOptions options = new() { Worker = new WorkerOptions { HeartbeatCheckIntervalSeconds = 3, HeartbeatGraceSeconds = 20, HeartbeatStuckCeilingSeconds = 90, EventChannelFullModeTimeoutMilliseconds = 2500, }, Events = new EventOptions { QueueCapacity = 64 }, Sessions = new SessionOptions { MaxPendingCommandsPerSession = 32 }, }; WorkerClientOptions clientOptions = SessionWorkerClientFactory.CreateWorkerClientOptions(options); Assert.Equal(TimeSpan.FromSeconds(3), clientOptions.HeartbeatCheckInterval); Assert.Equal(TimeSpan.FromSeconds(20), clientOptions.HeartbeatGrace); Assert.Equal(TimeSpan.FromSeconds(90), clientOptions.HeartbeatStuckCeiling); Assert.Equal(TimeSpan.FromMilliseconds(2500), clientOptions.EventChannelFullModeTimeout); Assert.Equal(64, clientOptions.EventChannelCapacity); Assert.Equal(32, clientOptions.MaxPendingCommands); } /// /// mxaccessgw#192: with no worker options set, the mapped values equal the historical /// compile-time defaults, so the change is behaviour-neutral for existing deployments. /// [Fact] public void CreateWorkerClientOptions_Defaults_MatchHistoricalConstants() { WorkerClientOptions clientOptions = SessionWorkerClientFactory.CreateWorkerClientOptions(new GatewayOptions()); Assert.Equal(TimeSpan.FromSeconds(5), clientOptions.HeartbeatCheckInterval); Assert.Equal(WorkerClientOptions.DefaultHeartbeatStuckCeiling, clientOptions.HeartbeatStuckCeiling); Assert.Equal(WorkerClientOptions.DefaultEventChannelFullModeTimeout, clientOptions.EventChannelFullModeTimeout); } private static GatewayOptions CreateOptions(int startupTimeoutSeconds = 5) { return new GatewayOptions { Worker = new WorkerOptions { StartupTimeoutSeconds = startupTimeoutSeconds, ShutdownTimeoutSeconds = 5, HeartbeatCheckIntervalSeconds = 30, HeartbeatGraceSeconds = 30, MaxMessageBytes = WorkerFrameProtocolOptions.DefaultMaxMessageBytes, }, Events = new EventOptions { QueueCapacity = 16, }, }; } private static GatewaySession CreateSession(TimeSpan? startupTimeout = null) { return new GatewaySession( FakeWorkerHarness.DefaultSessionId, GatewayContractInfo.DefaultBackendName, $"mxgw-sf-{Guid.NewGuid():N}", FakeWorkerHarness.DefaultNonce, "test-client", "fake-worker-session-test", "client-correlation-1", startupTimeout ?? TestTimeout, TestTimeout, TestTimeout, DateTimeOffset.UtcNow); } private static WorkerCommand CreateCommand(MxCommandKind kind) { return new WorkerCommand { Command = new MxCommand { Kind = kind, }, }; } private T Track(T launcher) where T : IWorkerTaskLauncher { _launchers.Add(launcher); return launcher; } /// /// A fake worker launcher that runs a scripted worker on a background task and exposes /// that task so the owning test observes it rather than leaking an unobserved fault. /// private interface IWorkerTaskLauncher : IWorkerProcessLauncher { /// /// Awaits the scripted worker task within the timeout, swallowing only the pipe /// teardown faults expected when the worker client kills or disposes the worker. /// /// Maximum time to wait for the worker task. /// A task that represents the asynchronous operation. Task ObserveWorkerTaskAsync(TimeSpan timeout); } /// /// Awaits a scripted worker task, treating cancellation and pipe-disconnect I/O faults as /// the expected outcome of the worker client tearing the worker down, and rethrowing anything else. /// private static async Task ObserveWorkerTaskAsync(Task workerTask, TimeSpan timeout) { try { await workerTask.WaitAsync(timeout).ConfigureAwait(false); } catch (OperationCanceledException) { // Expected: the worker client cancelled the scripted worker during teardown. } catch (IOException) { // Expected: the gateway pipe was closed when the worker client disposed. } } /// Fake worker launcher that connects a scripted fake worker harness. private sealed class ScriptedFakeWorkerProcessLauncher : IWorkerTaskLauncher { /// The fake process ID used by the scripted launcher. public const int ProcessId = 2468; private readonly FakeWorkerProcess _process = new(ProcessId); /// Gets the connected fake worker harness. public FakeWorkerHarness? Harness { get; private set; } /// Gets the scripted worker task. public Task WorkerTask { get; private set; } = Task.CompletedTask; /// public Task LaunchAsync( WorkerProcessLaunchRequest request, CancellationToken cancellationToken = default) { WorkerTask = RunWorkerAsync(request, cancellationToken); return Task.FromResult(CreateHandle(_process)); } /// public Task ObserveWorkerTaskAsync(TimeSpan timeout) => SessionWorkerClientFactoryFakeWorkerTests.ObserveWorkerTaskAsync(WorkerTask, timeout); private async Task RunWorkerAsync( WorkerProcessLaunchRequest request, CancellationToken cancellationToken) { Harness = await FakeWorkerHarness.ConnectToGatewayPipeAsync( request.SessionId, request.Nonce, request.PipeName, request.ProtocolVersion, cancellationToken: cancellationToken).ConfigureAwait(false); await Harness.CompleteStartupAsync(ProcessId, cancellationToken: cancellationToken).ConfigureAwait(false); } } /// Fake worker launcher that fails during startup with protocol version mismatch. private sealed class FailingStartupWorkerProcessLauncher : IWorkerTaskLauncher { /// Gets the fake worker process. public FakeWorkerProcess Process { get; } = new(processId: 3579); /// Gets the scripted worker task. public Task WorkerTask { get; private set; } = Task.CompletedTask; /// public Task LaunchAsync( WorkerProcessLaunchRequest request, CancellationToken cancellationToken = default) { WorkerTask = RunWorkerAsync(request, cancellationToken); return Task.FromResult(CreateHandle(Process)); } /// public Task ObserveWorkerTaskAsync(TimeSpan timeout) => SessionWorkerClientFactoryFakeWorkerTests.ObserveWorkerTaskAsync(WorkerTask, timeout); private async Task RunWorkerAsync( WorkerProcessLaunchRequest request, CancellationToken cancellationToken) { await using FakeWorkerHarness harness = await FakeWorkerHarness.ConnectToGatewayPipeAsync( request.SessionId, request.Nonce, request.PipeName, request.ProtocolVersion, cancellationToken: cancellationToken).ConfigureAwait(false); _ = await harness.ReadGatewayEnvelopeAsync(cancellationToken).ConfigureAwait(false); await harness.SendWorkerHelloAsync( workerProcessId: Process.Id, workerProtocolVersion: request.ProtocolVersion + 1, cancellationToken: cancellationToken).ConfigureAwait(false); } } /// Fake worker launcher that never completes startup, simulating a hung worker. private sealed class NeverReadyWorkerProcessLauncher : IWorkerTaskLauncher { private readonly CancellationTokenSource _stop = new(); /// Gets the fake worker process. public FakeWorkerProcess Process { get; } = new(processId: 4680); /// Gets the scripted worker task. public Task WorkerTask { get; private set; } = Task.CompletedTask; /// public Task LaunchAsync( WorkerProcessLaunchRequest request, CancellationToken cancellationToken = default) { WorkerTask = RunWorkerAsync(request); return Task.FromResult(CreateHandle(Process)); } /// public async Task ObserveWorkerTaskAsync(TimeSpan timeout) { // The scripted worker parks on an infinite delay; cancel it so disposal observes // the task instead of leaking it as an unobserved fault. await _stop.CancelAsync().ConfigureAwait(false); await SessionWorkerClientFactoryFakeWorkerTests .ObserveWorkerTaskAsync(WorkerTask, timeout) .ConfigureAwait(false); _stop.Dispose(); } private async Task RunWorkerAsync(WorkerProcessLaunchRequest request) { await using FakeWorkerHarness harness = await FakeWorkerHarness.ConnectToGatewayPipeAsync( request.SessionId, request.Nonce, request.PipeName, request.ProtocolVersion, cancellationToken: _stop.Token).ConfigureAwait(false); _ = await harness.ReadGatewayEnvelopeAsync(_stop.Token).ConfigureAwait(false); await harness.SendWorkerHelloAsync( workerProcessId: Process.Id, workerProtocolVersion: request.ProtocolVersion, cancellationToken: _stop.Token).ConfigureAwait(false); await Task.Delay(Timeout.InfiniteTimeSpan, _stop.Token).ConfigureAwait(false); } } /// Fake launcher whose worker stays alive but never connects to its pipe. private sealed class NeverConnectLauncher : IWorkerProcessLauncher { /// Gets the fake worker process. public FakeWorkerProcess Process { get; } = new(processId: 6802); /// public Task LaunchAsync( WorkerProcessLaunchRequest request, CancellationToken cancellationToken = default) => Task.FromResult(CreateHandle(Process)); } /// Fake launcher whose worker exits with code 3 shortly after start, never connecting. private sealed class ExitBeforeConnectLauncher(string? standardError = null) : IWorkerProcessLauncher { /// Gets the fake worker process. public FakeWorkerProcess Process { get; } = new(processId: 5791); /// public Task LaunchAsync( WorkerProcessLaunchRequest request, CancellationToken cancellationToken = default) { _ = Task.Delay(TimeSpan.FromMilliseconds(50), CancellationToken.None) .ContinueWith(_ => Process.MarkExited(3), TaskScheduler.Default); if (standardError is null) { return Task.FromResult(CreateHandle(Process)); } WorkerOutputCapture capture = WorkerOutputCapture.Start( new StringReader(standardError), standardOutput: null, request.SessionId, Process.Id, request.Nonce, Microsoft.Extensions.Logging.Abstractions.NullLogger.Instance); return Task.FromResult(new WorkerProcessHandle( Process, new WorkerProcessCommandLine("fake-worker.exe", []), DateTimeOffset.UtcNow, capture)); } } private static WorkerProcessHandle CreateHandle(IWorkerProcess process) { return new WorkerProcessHandle( process, new WorkerProcessCommandLine("fake-worker.exe", []), DateTimeOffset.UtcNow); } }