Files
mxaccessgw/src/ZB.MOM.WW.MxGateway.Tests/Gateway/Sessions/SessionWorkerClientFactoryFakeWorkerTests.cs
T
Joseph Doherty ee0f836886
ci / windows-x86 (push) Successful in 3m50s
ci / java (push) Failing after 10m14s
ci / portable (push) Failing after 19m55s
fix(workers): capture worker stderr/stdout, forward it to the gateway log, and attach the stderr tail to early-exit StartupFailed (WRK-002, #259)
The worker was started with CreateNoWindow and no redirection, so its log lines
went to a hidden console of its own and were lost under both a console run and
the NSSM service (verified on windev). The launcher now redirects both streams
and WorkerOutputCapture drains them: each line is forwarded under the
ZB.MOM.WW.MxGateway.Worker category at the worker's own level, the session
nonce is scrubbed, and the last 50 lines / 4 KB of stderr are kept. The drain
never waits on the logger (bounded drop-oldest queue) and ends at EOF when the
worker exits. A worker that exits before connecting (session factory race) or
that the probe finds already exited now fails StartupFailed with the stderr tail.
2026-12-03 13:10:12 -05:00

534 lines
23 KiB
C#

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<IWorkerTaskLauncher> _launchers = [];
/// <summary>
/// Completes immediately; no asynchronous setup is required before each test.
/// </summary>
/// <returns>A task that represents the asynchronous operation.</returns>
public Task InitializeAsync() => Task.CompletedTask;
/// <summary>
/// Awaits every scripted worker task so an unhandled exception fails the owning test
/// instead of surfacing later as an unobserved <see cref="TaskScheduler.UnobservedTaskException"/>.
/// This must stay on <see cref="IAsyncLifetime"/>: xUnit v2 never invokes
/// <see cref="IAsyncDisposable.DisposeAsync"/> 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).
/// </summary>
/// <returns>A task that represents the asynchronous operation.</returns>
public async Task DisposeAsync()
{
foreach (IWorkerTaskLauncher launcher in _launchers)
{
await launcher.ObserveWorkerTaskAsync(TestTimeout);
}
}
/// <summary>Verifies that the factory creates a ready worker client with a scripted fake worker process.</summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[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<WorkerCommandReply> 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);
}
/// <summary>Verifies that a failed fake worker startup throws a worker client exception.</summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[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<WorkerClientException>(
async () => await factory.CreateAsync(session, CancellationToken.None).WaitAsync(HangGuardTimeout));
Assert.Equal(WorkerClientErrorCode.ProtocolViolation, exception.ErrorCode);
Assert.True(launcher.Process.IsDisposed);
}
/// <summary>Verifies that a worker that never sends ready times out and is killed.</summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[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<TimeoutException>(
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);
}
/// <summary>
/// WRK-002: a worker that exits before it connects to its pipe fails the open at once with
/// <see cref="WorkerProcessLaunchErrorCode.StartupFailed"/> and its exit code, instead of
/// holding the open for the whole startup timeout and reporting a timeout.
/// </summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[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<WorkerProcessLaunchException>(
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);
}
/// <summary>
/// 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.
/// </summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[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<WorkerProcessLaunchException>(
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);
}
/// <summary>
/// WRK-006: a <c>Kill</c> that throws during launch-failure cleanup does not replace the
/// startup failure, and the process handle is still disposed.
/// </summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[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<TimeoutException>(
async () => await factory.CreateAsync(session, CancellationToken.None).WaitAsync(HangGuardTimeout));
Assert.Contains("did not complete startup", exception.Message);
Assert.True(launcher.Process.IsDisposed);
}
/// <summary>
/// mxaccessgw#192: every <see cref="WorkerClientOptions"/> field comes from configuration.
/// The heartbeat check interval binds from <c>HeartbeatCheckIntervalSeconds</c> (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.
/// </summary>
[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);
}
/// <summary>
/// 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.
/// </summary>
[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>(T launcher)
where T : IWorkerTaskLauncher
{
_launchers.Add(launcher);
return launcher;
}
/// <summary>
/// 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.
/// </summary>
private interface IWorkerTaskLauncher : IWorkerProcessLauncher
{
/// <summary>
/// Awaits the scripted worker task within the timeout, swallowing only the pipe
/// teardown faults expected when the worker client kills or disposes the worker.
/// </summary>
/// <param name="timeout">Maximum time to wait for the worker task.</param>
/// <returns>A task that represents the asynchronous operation.</returns>
Task ObserveWorkerTaskAsync(TimeSpan timeout);
}
/// <summary>
/// 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.
/// </summary>
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.
}
}
/// <summary>Fake worker launcher that connects a scripted fake worker harness.</summary>
private sealed class ScriptedFakeWorkerProcessLauncher : IWorkerTaskLauncher
{
/// <summary>The fake process ID used by the scripted launcher.</summary>
public const int ProcessId = 2468;
private readonly FakeWorkerProcess _process = new(ProcessId);
/// <summary>Gets the connected fake worker harness.</summary>
public FakeWorkerHarness? Harness { get; private set; }
/// <summary>Gets the scripted worker task.</summary>
public Task WorkerTask { get; private set; } = Task.CompletedTask;
/// <inheritdoc />
public Task<WorkerProcessHandle> LaunchAsync(
WorkerProcessLaunchRequest request,
CancellationToken cancellationToken = default)
{
WorkerTask = RunWorkerAsync(request, cancellationToken);
return Task.FromResult(CreateHandle(_process));
}
/// <inheritdoc />
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);
}
}
/// <summary>Fake worker launcher that fails during startup with protocol version mismatch.</summary>
private sealed class FailingStartupWorkerProcessLauncher : IWorkerTaskLauncher
{
/// <summary>Gets the fake worker process.</summary>
public FakeWorkerProcess Process { get; } = new(processId: 3579);
/// <summary>Gets the scripted worker task.</summary>
public Task WorkerTask { get; private set; } = Task.CompletedTask;
/// <inheritdoc />
public Task<WorkerProcessHandle> LaunchAsync(
WorkerProcessLaunchRequest request,
CancellationToken cancellationToken = default)
{
WorkerTask = RunWorkerAsync(request, cancellationToken);
return Task.FromResult(CreateHandle(Process));
}
/// <inheritdoc />
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);
}
}
/// <summary>Fake worker launcher that never completes startup, simulating a hung worker.</summary>
private sealed class NeverReadyWorkerProcessLauncher : IWorkerTaskLauncher
{
private readonly CancellationTokenSource _stop = new();
/// <summary>Gets the fake worker process.</summary>
public FakeWorkerProcess Process { get; } = new(processId: 4680);
/// <summary>Gets the scripted worker task.</summary>
public Task WorkerTask { get; private set; } = Task.CompletedTask;
/// <inheritdoc />
public Task<WorkerProcessHandle> LaunchAsync(
WorkerProcessLaunchRequest request,
CancellationToken cancellationToken = default)
{
WorkerTask = RunWorkerAsync(request);
return Task.FromResult(CreateHandle(Process));
}
/// <inheritdoc />
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);
}
}
/// <summary>Fake launcher whose worker stays alive but never connects to its pipe.</summary>
private sealed class NeverConnectLauncher : IWorkerProcessLauncher
{
/// <summary>Gets the fake worker process.</summary>
public FakeWorkerProcess Process { get; } = new(processId: 6802);
/// <inheritdoc />
public Task<WorkerProcessHandle> LaunchAsync(
WorkerProcessLaunchRequest request,
CancellationToken cancellationToken = default) => Task.FromResult(CreateHandle(Process));
}
/// <summary>Fake launcher whose worker exits with code 3 shortly after start, never connecting.</summary>
private sealed class ExitBeforeConnectLauncher(string? standardError = null) : IWorkerProcessLauncher
{
/// <summary>Gets the fake worker process.</summary>
public FakeWorkerProcess Process { get; } = new(processId: 5791);
/// <inheritdoc />
public Task<WorkerProcessHandle> 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);
}
}