Retain fake worker fault diagnostics in test fixtures
ci / nightly-windev (push) Has been skipped
ci / windows-x86 (push) Successful in 1m20s
ci / java (push) Successful in 2m19s
ci / windows-x86 (pull_request) Successful in 1m20s
ci / nightly-windev (pull_request) Has been skipped
ci / java (pull_request) Successful in 2m23s
ci / portable (push) Successful in 9m10s
ci / portable (pull_request) Successful in 9m2s

This commit is contained in:
Joseph Doherty
2026-10-13 10:35:28 -04:00
parent d779daf6af
commit 83aa76c33d
5 changed files with 340 additions and 26 deletions
@@ -0,0 +1,135 @@
using Microsoft.Extensions.Logging;
using ZB.MOM.WW.MxGateway.Contracts.Proto;
using ZB.MOM.WW.MxGateway.Server.Workers;
namespace ZB.MOM.WW.MxGateway.Tests.TestSupport;
/// <summary>Exposes test-owned worker tasks and safe diagnostic context to fixture cleanup.</summary>
internal interface IDiagnosticFakeWorker
{
/// <summary>Gets the diagnostic collector for this launcher's workers.</summary>
FakeWorkerDiagnostics Diagnostics { get; }
}
/// <summary>Observes fake worker faults without replacing the test's primary exception.</summary>
internal sealed class FakeWorkerDiagnostics : ILoggerFactory, ILogger
{
private readonly object _sync = new();
private readonly List<Task> _observations = [];
private Action<string>? _output;
private int _remaining = 16;
private bool _closed;
private string _phase = "startup";
private MxCommandKind? _command;
private ulong? _sequence;
/// <summary>Attaches the fixture's output sink before any workers are launched.</summary>
/// <param name="output">Destination for safe, bounded metadata.</param>
public void SetOutput(Action<string>? output) => _output = output;
/// <summary>Records only structural context, never envelopes or command arguments.</summary>
/// <param name="envelope">Incoming envelope whose safe metadata is retained.</param>
public void Received(WorkerEnvelope envelope)
{
lock (_sync)
{
_phase = envelope.BodyCase == WorkerEnvelope.BodyOneofCase.WorkerCommand ? "command" : "shutdown";
_command = envelope.BodyCase == WorkerEnvelope.BodyOneofCase.WorkerCommand
? envelope.WorkerCommand.Command.Kind : null;
_sequence = envelope.Sequence;
}
}
/// <summary>Retains an observation that consumes faults even if bounded teardown times out.</summary>
/// <param name="worker">Background task launched by the fake worker.</param>
/// <param name="source">Whether the task belongs to a fake worker or fixture teardown.</param>
public void Track(Task worker, string source = "fake-worker")
{
Task observation = worker.ContinueWith(completed =>
{
// Reading Exception observes every fault; retain no unobserved continuation fault.
if (completed.Exception is { } faults)
{
foreach (Exception fault in faults.Flatten().InnerExceptions)
{
Report(source, fault);
}
}
}, CancellationToken.None, TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default);
_observations.Add(observation);
}
/// <summary>Drains workers under the fixture's existing time limit and closes output.</summary>
/// <param name="timeout">Existing test timeout; never extended for diagnostics.</param>
/// <returns>The bounded cleanup operation.</returns>
public async Task DrainAsync(TimeSpan timeout)
{
try
{
await Task.WhenAll(_observations).WaitAsync(timeout).ConfigureAwait(false);
}
catch (TimeoutException exception)
{
Report("teardown", exception);
}
finally
{
Dispose();
}
}
private void Report(string source, Exception exception)
{
lock (_sync)
{
if (_closed || _remaining-- <= 0)
{
return;
}
string code = exception is WorkerFrameProtocolException protocol ? protocol.ErrorCode.ToString() : "none";
string line = $"source={source} type={exception.GetType().Name} code={code} phase={_phase} command={_command} sequence={_sequence}";
try
{
_output?.Invoke(line);
}
catch (Exception)
{
// A completed output helper must never mask the primary test failure.
}
}
}
/// <inheritdoc />
public ILogger CreateLogger(string categoryName) => this;
/// <inheritdoc />
public void AddProvider(ILoggerProvider provider) => throw new NotSupportedException();
/// <inheritdoc />
public void Dispose()
{
lock (_sync)
{
_closed = true;
_output = null;
}
}
/// <inheritdoc />
public IDisposable? BeginScope<TState>(TState state) where TState : notnull => null;
/// <inheritdoc />
public bool IsEnabled(LogLevel logLevel) => logLevel >= LogLevel.Warning;
/// <inheritdoc />
public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception? exception,
Func<TState, Exception?, string> formatter)
{
// Never invoke formatter: state and exception messages may contain item names/secrets.
if (IsEnabled(logLevel) && exception is not null)
{
Report("gateway", exception);
}
}
}