using System.Threading.Channels;
using Microsoft.Extensions.Logging;
namespace ZB.MOM.WW.MxGateway.Server.Workers;
///
/// Drains a worker process's redirected standard error and standard output, forwards each line
/// to the gateway log, and keeps a bounded tail of recent stderr lines for startup-failure
/// messages (WRK-002, mxaccessgw#259).
///
///
///
/// Before this capture existed the worker was started with CreateNoWindow and no
/// redirection, so its output went to a hidden console of its own and was discarded, both for a
/// console run and under the NSSM service. Redirecting it therefore loses nothing; the
/// worker's level=... event=... lines now appear in the gateway log under the
/// category, with the session id and worker process id as properties.
///
///
/// The pipes are always drained, whatever the gateway logger is doing: each reader only
/// truncates the line, appends it to the tail and offers it to a bounded drop-oldest queue,
/// which never waits. A separate task logs from that queue. A slow log sink therefore drops
/// the oldest queued lines (and reports how many) rather than backing up the pipe and blocking
/// the worker's own Console.Error writes, which can run on its STA thread.
///
///
/// The readers run until end-of-stream, which arrives when the worker exits (the gateway kills
/// the worker before it disposes the process handle), and each disposes its own reader then. No
/// cancellation is needed, and lines the worker wrote just before it exited are not cut off.
///
///
/// The worker redacts its own log lines (WorkerLogRedactor). As a second line of defense
/// the capture replaces any occurrence of the session's bootstrap nonce, the one secret the
/// gateway hands the worker, with [redacted] before a line is logged or kept.
///
///
internal sealed class WorkerOutputCapture
{
/// Logger category the forwarded worker lines are written under.
public const string LogCategory = "ZB.MOM.WW.MxGateway.Worker";
/// Most stderr lines kept for the startup-failure tail.
public const int MaxTailLines = 50;
/// Most characters kept for the startup-failure tail.
public const int MaxTailCharacters = 4096;
/// Longest single line forwarded or kept; the rest is cut and marked.
public const int MaxLineCharacters = 2048;
/// Lines that may wait for the logger before the oldest are dropped.
public const int ForwardQueueCapacity = 1024;
private const string RedactedValue = "[redacted]";
private const string TruncatedMarker = "...[truncated]";
private readonly string _sessionId;
private readonly int _processId;
private readonly string? _nonce;
private readonly ILogger _logger;
private readonly Channel _forwardQueue;
private readonly Queue _tail = new();
private readonly object _tailLock = new();
private readonly Task _standardErrorDrained;
private readonly Task _completion;
private int _tailCharacters;
private long _droppedLines;
private int _drainedStreams;
private WorkerOutputCapture(
TextReader? standardError,
TextReader? standardOutput,
string sessionId,
int processId,
string? nonce,
ILogger logger)
{
_sessionId = sessionId;
_processId = processId;
_nonce = string.IsNullOrEmpty(nonce) ? null : nonce;
_logger = logger;
_forwardQueue = Channel.CreateBounded(
new BoundedChannelOptions(ForwardQueueCapacity)
{
FullMode = BoundedChannelFullMode.DropOldest,
SingleReader = true,
SingleWriter = false,
},
_ => Interlocked.Increment(ref _droppedLines));
// A missing stream counts as drained from the start; the queue completes when both are.
_drainedStreams = (standardError is null ? 1 : 0) + (standardOutput is null ? 1 : 0);
if (_drainedStreams == 2)
{
_forwardQueue.Writer.TryComplete();
}
Task forwarding = Task.Run(ForwardLoopAsync);
_standardErrorDrained = standardError is null
? Task.CompletedTask
: Task.Run(() => DrainAsync(standardError, WorkerOutputStream.StandardError));
Task standardOutputDrained = standardOutput is null
? Task.CompletedTask
: Task.Run(() => DrainAsync(standardOutput, WorkerOutputStream.StandardOutput));
_completion = CompleteAsync(_standardErrorDrained, standardOutputDrained, forwarding);
}
///
/// Gets a task that completes once both streams reached end-of-stream and every queued line
/// was logged. It never faults.
///
public Task Completion => _completion;
///
/// Starts draining the redirected streams of , or returns
/// null when neither stream is redirected (test doubles, or a process factory that
/// reads the streams itself).
///
/// The started worker process.
/// Session id, logged with every line.
/// The session's bootstrap nonce, scrubbed from every line.
/// Logger for the forwarded lines.
/// The running capture, or null.
public static WorkerOutputCapture? StartIfRedirected(
IWorkerProcess process,
string sessionId,
string? nonce,
ILogger logger)
{
ArgumentNullException.ThrowIfNull(process);
ArgumentNullException.ThrowIfNull(logger);
TextReader? standardError = process.StandardError;
TextReader? standardOutput = process.StandardOutput;
if (standardError is null && standardOutput is null)
{
return null;
}
return Start(standardError, standardOutput, sessionId, process.Id, nonce, logger);
}
/// Starts draining the given readers.
/// Worker stderr, or null.
/// Worker stdout, or null.
/// Session id, logged with every line.
/// Worker process id, logged with every line.
/// The session's bootstrap nonce, scrubbed from every line.
/// Logger for the forwarded lines.
/// The running capture.
public static WorkerOutputCapture Start(
TextReader? standardError,
TextReader? standardOutput,
string sessionId,
int processId,
string? nonce,
ILogger logger)
{
ArgumentNullException.ThrowIfNull(logger);
return new WorkerOutputCapture(standardError, standardOutput, sessionId, processId, nonce, logger);
}
///
/// Waits, up to , for stderr to reach end-of-stream, so lines the
/// worker wrote just before it exited are in the tail. Never throws.
///
/// Longest wait.
/// A task that represents the asynchronous operation.
public async Task WaitForStandardErrorDrainedAsync(TimeSpan timeout)
{
try
{
await _standardErrorDrained.WaitAsync(timeout).ConfigureAwait(false);
}
catch (TimeoutException)
{
// Something else still holds the pipe's write end; report what has arrived so far.
}
}
/// Gets the most recent stderr lines (at most lines and characters), oldest first.
/// The lines joined with newlines, or an empty string when nothing was captured.
public string GetStandardErrorTail()
{
lock (_tailLock)
{
return string.Join('\n', _tail);
}
}
///
/// Appends the stderr tail to a startup-failure message, or returns the message unchanged
/// when the capture is absent or nothing was written to stderr.
///
/// The capture, or null.
/// The failure message.
/// The message, with the tail appended when there is one.
public static string AppendStandardErrorTail(WorkerOutputCapture? capture, string message)
{
string tail = capture?.GetStandardErrorTail() ?? string.Empty;
return tail.Length == 0
? message
: message + " Last worker stderr output:\n" + tail;
}
/// Maps a worker log line's level= prefix to a gateway log level.
/// The worker line.
/// The stream it came from.
/// The level to log it at.
internal static LogLevel MapLevel(string line, WorkerOutputStream stream)
{
if (line.StartsWith("level=", StringComparison.Ordinal))
{
int end = line.IndexOf(' ', 6);
ReadOnlySpan level = end < 0 ? line.AsSpan(6) : line.AsSpan(6, end - 6);
if (level.Equals("Information", StringComparison.Ordinal))
{
return LogLevel.Information;
}
if (level.Equals("Warning", StringComparison.Ordinal))
{
return LogLevel.Warning;
}
if (level.Equals("Error", StringComparison.Ordinal))
{
return LogLevel.Error;
}
}
// Unstructured stderr is not the worker logger talking: it is the CLR, a native component
// or a crash, so it is worth a Warning. The worker writes nothing to stdout on purpose.
return stream == WorkerOutputStream.StandardError ? LogLevel.Warning : LogLevel.Information;
}
private static async Task CompleteAsync(Task standardError, Task standardOutput, Task forwarding)
{
await Task.WhenAll(standardError, standardOutput).ConfigureAwait(false);
await forwarding.ConfigureAwait(false);
}
private async Task DrainAsync(TextReader reader, WorkerOutputStream stream)
{
try
{
while (await reader.ReadLineAsync().ConfigureAwait(false) is { } rawLine)
{
string line = Sanitize(rawLine);
if (stream == WorkerOutputStream.StandardError)
{
AppendToTail(line);
}
// Never waits: a full queue drops its oldest line instead.
_forwardQueue.Writer.TryWrite(new WorkerOutputLine(stream, line));
}
}
catch (Exception exception) when (exception is IOException or ObjectDisposedException or InvalidOperationException)
{
// The pipe broke or was closed under us; the worker is gone either way.
}
finally
{
reader.Dispose();
if (Interlocked.Increment(ref _drainedStreams) == 2)
{
_forwardQueue.Writer.TryComplete();
}
}
}
private async Task ForwardLoopAsync()
{
long reportedDrops = 0;
await foreach (WorkerOutputLine item in _forwardQueue.Reader.ReadAllAsync().ConfigureAwait(false))
{
long dropped = Interlocked.Read(ref _droppedLines);
if (dropped != reportedDrops)
{
LogSafely(
LogLevel.Warning,
"Dropped {DroppedLineCount} worker output lines for session {SessionId} (pid {WorkerProcessId}) because the gateway log fell behind.",
dropped - reportedDrops);
reportedDrops = dropped;
}
ForwardSafely(item);
}
}
private void ForwardSafely(WorkerOutputLine item)
{
try
{
LogLevel level = MapLevel(item.Line, item.Stream);
if (_logger.IsEnabled(level))
{
_logger.Log(
level,
"Worker {SessionId} (pid {WorkerProcessId}) {WorkerStream}: {WorkerLogLine:l}",
_sessionId,
_processId,
item.Stream == WorkerOutputStream.StandardError ? "stderr" : "stdout",
item.Line);
}
}
catch (Exception)
{
// A failing log sink must not stop the drain; the line is still in the tail.
}
}
private void LogSafely(LogLevel level, string message, long count)
{
try
{
_logger.Log(level, message, count, _sessionId, _processId);
}
catch (Exception)
{
// See ForwardSafely.
}
}
private string Sanitize(string line)
{
if (_nonce is not null && line.Contains(_nonce, StringComparison.Ordinal))
{
line = line.Replace(_nonce, RedactedValue, StringComparison.Ordinal);
}
return line.Length <= MaxLineCharacters
? line
: string.Concat(line.AsSpan(0, MaxLineCharacters), TruncatedMarker);
}
private void AppendToTail(string line)
{
lock (_tailLock)
{
_tail.Enqueue(line);
_tailCharacters += line.Length;
while (_tail.Count > MaxTailLines || (_tail.Count > 1 && _tailCharacters > MaxTailCharacters))
{
_tailCharacters -= _tail.Dequeue().Length;
}
}
}
private readonly record struct WorkerOutputLine(WorkerOutputStream Stream, string Line);
}
/// The worker stream a captured line came from.
internal enum WorkerOutputStream
{
/// Standard error: the worker's log.
StandardError,
/// Standard output: unused by the worker itself.
StandardOutput,
}