Merge fix/review-2026-12-phase2 (2026-12-02 review fix plan)

This commit is contained in:
Joseph Doherty
2026-12-03 10:18:43 -05:00
44 changed files with 2264 additions and 123 deletions
@@ -714,6 +714,19 @@ public sealed class GatewayOptionsValidator : OptionsValidatorBase<GatewayOption
builder.Add(
$"MxGateway:Protocol:MaxGrpcMessageBytes must be between {MinimumMaxMessageBytes} and {MaximumMaxMessageBytes}.");
}
// Kestrel rejects a non-positive ping delay or timeout, so 0 is the explicit "off" for the
// delay only; the timeout must always be a real bound.
if (options.Http2KeepAlivePingDelaySeconds is < 0 or > 86400)
{
builder.Add(
"MxGateway:Protocol:Http2KeepAlivePingDelaySeconds must be between 0 (disabled) and 86400.");
}
if (options.Http2KeepAlivePingTimeoutSeconds is < 1 or > 3600)
{
builder.Add("MxGateway:Protocol:Http2KeepAlivePingTimeoutSeconds must be between 1 and 3600.");
}
}
// The worker-frame (pipe) maximum must stay above the public gRPC cap by the envelope-overhead
@@ -3,7 +3,7 @@ using ZB.MOM.WW.MxGateway.Contracts;
namespace ZB.MOM.WW.MxGateway.Server.Configuration;
/// <summary>
/// Configuration options for the worker protocol version.
/// Configuration options for the worker protocol version and the public gRPC (HTTP/2) transport.
/// </summary>
public sealed class ProtocolOptions
{
@@ -14,4 +14,21 @@ public sealed class ProtocolOptions
/// <summary>Gets or sets the maximum gRPC message size in bytes.</summary>
public int MaxGrpcMessageBytes { get; init; } = 16 * 1024 * 1024;
/// <summary>
/// Gets or sets how long an HTTP/2 connection may be idle (no frames received) before the
/// gateway sends a keepalive PING, in seconds. <c>0</c> disables server pings. Maps to
/// Kestrel's <c>Limits.Http2.KeepAlivePingDelay</c>. Without it a client that vanished
/// without a FIN or RST (power loss, a firewall or NAT idle drop) holds its
/// <c>StreamEvents</c> call, its session and its worker until a write times out, which on a
/// quiet session may be never.
/// </summary>
public int Http2KeepAlivePingDelaySeconds { get; init; } = 60;
/// <summary>
/// Gets or sets how long the gateway waits for any frame after sending a keepalive PING
/// before it closes the connection, in seconds. Maps to Kestrel's
/// <c>Limits.Http2.KeepAlivePingTimeout</c>.
/// </summary>
public int Http2KeepAlivePingTimeoutSeconds { get; init; } = 10;
}
@@ -147,12 +147,18 @@ public sealed class DashboardLiveDataService : IDashboardLiveDataService, IAsync
string[] toSubscribe = TouchAndCollectNewTags(tagAddresses, viewer, out HashSet<string> justRead);
if (toSubscribe.Length > 0)
{
await EvictForAsync(session, serverHandle, toSubscribe.Length, justRead, viewer, now, cancellationToken)
await EvictForAsync(session, serverHandle, toSubscribe.Length, justRead, viewer, now)
.ConfigureAwait(false);
// The subscribe and its tracking run as one step that the caller's token cannot
// split (DSH-007): a cancellation that lands after the worker advised the tags but
// before TrackSubscribed would leave advises nothing tracks — never unadvised, not
// counted against MaxSubscribedTags, and re-advised on the next read. The session's
// command timeout still bounds the call; the caller's token is observed after.
IReadOnlyList<SubscribeResult> subscribeResults = await session
.SubscribeBulkAsync(serverHandle, toSubscribe, cancellationToken)
.SubscribeBulkAsync(serverHandle, toSubscribe, CancellationToken.None)
.ConfigureAwait(false);
TrackSubscribed(toSubscribe, subscribeResults, viewer);
cancellationToken.ThrowIfCancellationRequested();
}
IReadOnlyList<BulkReadResult> results = await session
@@ -178,7 +184,17 @@ public sealed class DashboardLiveDataService : IDashboardLiveDataService, IAsync
}
catch (Exception exception) when (exception is not OperationCanceledException)
{
// Close the session being dropped, not just forget it (DSH-002). A command timeout or a
// non-Ok bulk reply leaves the session Ready with a live x86 worker and its advised
// tags; once unreferenced, nothing sweeps it until its lease expires, and the next poll
// opens another — a repeatedly failing Browse page could fill MaxSessions.
GatewaySession? failedSession = _session;
InvalidateSession();
if (failedSession is not null)
{
await CloseQuietlyAsync(failedSession.SessionId).ConfigureAwait(false);
}
_logger.LogWarning(exception, "Dashboard live read failed; the dashboard session will be re-opened.");
return new DashboardLiveReadResult([], exception.Message, null, null);
}
@@ -280,17 +296,16 @@ public sealed class DashboardLiveDataService : IDashboardLiveDataService, IAsync
// back at the cap). A read that subscribes nothing new evicts nothing, but it also
// cannot grow the set.
//
// Cancellation mid-eviction follows this file's policy: OperationCanceledException
// is deliberately not caught here or in ReadAsync, so it propagates with the tags
// already dropped from tracking — the same end state as a failed unadvise.
// The unadvise runs on CancellationToken.None, so a caller cancelling mid-read cannot
// strand evicted tags advised-but-untracked; only a failed unadvise can, and that is
// logged.
private async Task EvictForAsync(
GatewaySession session,
int serverHandle,
int incomingCount,
HashSet<string> justRead,
string reader,
DateTimeOffset now,
CancellationToken cancellationToken)
DateTimeOffset now)
{
int overflow = _subscribed.Count + incomingCount - MaxSubscribedTags;
if (overflow <= 0)
@@ -351,7 +366,10 @@ public sealed class DashboardLiveDataService : IDashboardLiveDataService, IAsync
try
{
await session.UnsubscribeBulkAsync(serverHandle, evictedHandles, cancellationToken)
// Not the caller's token: the evicted tags are already dropped from tracking, so an
// unadvise abandoned on cancellation would leave them advised with nothing to remove
// them (DSH-007). The session's command timeout bounds the call.
await session.UnsubscribeBulkAsync(serverHandle, evictedHandles, CancellationToken.None)
.ConfigureAwait(false);
}
catch (Exception exception) when (exception is not OperationCanceledException)
@@ -506,17 +524,28 @@ public sealed class DashboardLiveDataService : IDashboardLiveDataService, IAsync
cancellationToken)
.ConfigureAwait(false);
WorkerCommandReply reply = await session.InvokeAsync(
new WorkerCommand
{
Command = new MxCommand
// Until _session holds it, nothing else references the new session: any way out of the
// Register step (a fault, a timeout, the caller cancelling) must close it.
WorkerCommandReply reply;
try
{
reply = await session.InvokeAsync(
new WorkerCommand
{
Kind = MxCommandKind.Register,
Register = new RegisterCommand { ClientName = ClientName },
Command = new MxCommand
{
Kind = MxCommandKind.Register,
Register = new RegisterCommand { ClientName = ClientName },
},
},
},
cancellationToken)
.ConfigureAwait(false);
cancellationToken)
.ConfigureAwait(false);
}
catch
{
await CloseQuietlyAsync(session.SessionId).ConfigureAwait(false);
throw;
}
int? serverHandle = reply.Reply?.Register?.ServerHandle;
if (serverHandle is null)
@@ -110,6 +110,9 @@ public static class GatewayApplication
builder.AddZbSerilog(o => o.ServiceName = "mxgateway");
builder.Services.AddGatewayConfiguration(builder.Configuration);
builder.Services.AddSingleton<
Microsoft.Extensions.Options.IConfigureOptions<Microsoft.AspNetCore.Server.Kestrel.Core.KestrelServerOptions>,
GatewayKestrelKeepAliveConfiguration>();
builder.Services.AddZbSecrets(builder.Configuration, "Secrets");
builder.Services.AddSqliteAuthStore(builder.Configuration);
builder.Services.AddGatewayGrpcAuthorization();
@@ -0,0 +1,63 @@
using Microsoft.AspNetCore.Server.Kestrel.Core;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Options;
using ZB.MOM.WW.MxGateway.Server.Configuration;
namespace ZB.MOM.WW.MxGateway.Server.Grpc;
/// <summary>
/// Applies the gateway's HTTP/2 keepalive policy (<c>MxGateway:Protocol:Http2KeepAlive*</c>) to
/// Kestrel (SES-005).
/// </summary>
/// <remarks>
/// <para>
/// Kestrel's HTTP/2 keepalive ping is off unless configured. A client that disappears
/// without closing its connection (host power loss, a firewall or NAT idle drop, a pulled
/// cable) is otherwise noticed only when a write times out at the TCP layer, and a quiet
/// session writes nothing: its <c>StreamEvents</c> call stays open, the session's single
/// subscriber slot stays taken — so the real client's resume is refused with
/// <c>EventSubscriberAlreadyActive</c> — and the session and its x86 worker are never
/// swept. With the ping on, a dead peer is detected within the delay plus the timeout,
/// the call's token fires, and the subscriber detaches.
/// </para>
/// <para>
/// Kestrel has no minimum-client-ping-interval policy (no equivalent of grpc-core's
/// <c>GRPC_ARG_HTTP2_MIN_RECV_PING_INTERVAL_WITHOUT_DATA_MS</c>): it answers every client
/// PING and never sends <c>GOAWAY</c>/<c>ENHANCE_YOUR_CALM</c> for ping rate, with or without
/// an active call. A received PING also resets the connection's idle keep-alive timeout,
/// so client keepalive pings (the official clients send one every 30 s, also with no call
/// active) keep an otherwise idle connection open. There is therefore nothing to configure
/// on the server side for client pings.
/// </para>
/// <para>
/// The section is bound straight from configuration rather than through
/// <c>IOptions&lt;GatewayOptions&gt;</c>: Kestrel resolves its options while the server is
/// constructed, and reading the validated gateway options there would surface any
/// configuration error from inside Kestrel's construction instead of as the
/// <c>OptionsValidationException</c> startup validation reports.
/// </para>
/// </remarks>
/// <param name="configuration">The application configuration holding <c>MxGateway:Protocol</c>.</param>
public sealed class GatewayKestrelKeepAliveConfiguration(IConfiguration configuration)
: IConfigureOptions<KestrelServerOptions>
{
/// <summary>The configuration section the keepalive options bind from.</summary>
public const string SectionName = "MxGateway:Protocol";
/// <inheritdoc />
public void Configure(KestrelServerOptions options)
{
ArgumentNullException.ThrowIfNull(options);
ProtocolOptions protocol = configuration.GetSection(SectionName).Get<ProtocolOptions>() ?? new ProtocolOptions();
// Out-of-range values are rejected by GatewayOptionsValidator at startup; the guards here
// only keep Kestrel's own setters from throwing before that validation reports.
options.Limits.Http2.KeepAlivePingDelay = protocol.Http2KeepAlivePingDelaySeconds > 0
? TimeSpan.FromSeconds(protocol.Http2KeepAlivePingDelaySeconds)
: TimeSpan.MaxValue;
if (protocol.Http2KeepAlivePingTimeoutSeconds > 0)
{
options.Limits.Http2.KeepAlivePingTimeout = TimeSpan.FromSeconds(protocol.Http2KeepAlivePingTimeoutSeconds);
}
}
}
@@ -1697,6 +1697,13 @@ public sealed class GatewaySession : IAsyncDisposable
case MxCommandKind.UnsubscribeBulk:
RemoveItems(command.UnsubscribeBulk.ServerHandle, command.UnsubscribeBulk.ItemHandles);
break;
case MxCommandKind.Unregister:
// Unregister invalidates every item under the server handle in MXAccess, so
// keeping their registrations would grow _items on each register/unregister
// cycle and leave stale tag addresses for the constraint checks to read if
// MXAccess hands the same handle values out again.
RemoveServerItems(command.Unregister.ServerHandle);
break;
}
}
}
@@ -2630,6 +2637,28 @@ public sealed class GatewaySession : IAsyncDisposable
}
}
private void RemoveServerItems(int serverHandle)
{
List<(int ServerHandle, int ItemHandle)>? stale = null;
foreach ((int ServerHandle, int ItemHandle) key in _items.Keys)
{
if (key.ServerHandle == serverHandle)
{
(stale ??= []).Add(key);
}
}
if (stale is null)
{
return;
}
foreach ((int ServerHandle, int ItemHandle) key in stale)
{
_items.Remove(key);
}
}
private void DetachEventSubscriber()
{
lock (_syncRoot)
@@ -2659,11 +2688,23 @@ public sealed class GatewaySession : IAsyncDisposable
// before any subscriber registered; that never-subscribed session must not enter the
// grace window.
if (_everHadEventSubscriber
&& _detachGrace > TimeSpan.Zero
&& _activeEventSubscriberCount == 0
&& _state is not (SessionState.Closing or SessionState.Closed or SessionState.Faulted))
{
_detachedAtUtc = _eventStreaming.TimeProvider.GetUtcNow();
DateTimeOffset now = _eventStreaming.TimeProvider.GetUtcNow();
// Streaming is client activity, and the detach is its last moment. The lease only
// moves on unary commands, so a client that streamed for longer than the lease with
// no unary call would otherwise detach with a lease already in the past — and the
// next sweep would close it as lease-expired (which takes precedence) before the
// detach-grace window it is entitled to. Renewing here keeps the reconnect window.
_lastClientActivityAt = now;
_leaseExpiresAt = now + LeaseDuration;
if (_detachGrace > TimeSpan.Zero)
{
_detachedAtUtc = now;
}
}
}
}
@@ -54,6 +54,18 @@ public sealed class SessionManager : ISessionManager
// begun draining does not come back.
private int _stopping;
// The one host drain (SES-001). Started at ApplicationStopping, not at the shutdown hosted
// service's StopAsync: WebApplication registers Kestrel's hosted service last, so it stops
// FIRST, and Kestrel's stop waits for in-flight requests — an open StreamEvents is one, and it
// only ends when its session closes. Draining from StopAsync therefore let every stop with an
// active stream wait out the whole host shutdown timeout, after which Kestrel aborted the
// streams and the drain ran on an already-cancelled token, killing every worker. Started here,
// the drain closes the sessions (completing the streams with OK) while Kestrel is still
// draining, and StopAsync just awaits the same task.
private readonly object _shutdownSyncRoot = new();
private readonly CancellationTokenSource _shutdownCts = new();
private Task? _shutdownTask;
/// <summary>
/// Initializes a new instance of <see cref="SessionManager"/>.
/// </summary>
@@ -110,7 +122,7 @@ public sealed class SessionManager : ISessionManager
// The registration is never disposed: the manager is a host singleton that lives exactly
// as long as the lifetime it observes.
applicationLifetime?.ApplicationStopping.Register(MarkStopping);
applicationLifetime?.ApplicationStopping.Register(() => _ = BeginShutdown());
}
/// <inheritdoc />
@@ -495,7 +507,44 @@ public sealed class SessionManager : ISessionManager
}
/// <inheritdoc />
/// <remarks>
/// The drain itself starts once, at the host's <c>ApplicationStopping</c> signal when a
/// lifetime was supplied, otherwise at the first call here. This call awaits that drain;
/// <paramref name="cancellationToken"/> firing (the host's stop deadline) cancels the
/// graceful closes still in flight, which degrades them to the kill fallback.
/// </remarks>
public async Task ShutdownAsync(CancellationToken cancellationToken)
{
Task drain = BeginShutdown();
using CancellationTokenRegistration registration = cancellationToken.Register(
static state => CancelQuietly((CancellationTokenSource)state!),
_shutdownCts);
await drain.ConfigureAwait(false);
}
private static void CancelQuietly(CancellationTokenSource source)
{
try
{
source.Cancel();
}
catch (ObjectDisposedException)
{
}
}
// Starts the drain exactly once and returns it. Closes the open gate synchronously first, so
// an open that races ApplicationStopping is refused (or drained) exactly as before.
private Task BeginShutdown()
{
MarkStopping();
lock (_shutdownSyncRoot)
{
return _shutdownTask ??= Task.Run(() => ShutdownCoreAsync(_shutdownCts.Token));
}
}
private async Task ShutdownCoreAsync(CancellationToken cancellationToken)
{
// Sessions are drained in parallel: at a worst-case worker shutdown timeout each, a
// one-at-a-time drain of a full registry outruns any host stop-timeout and leaves the
@@ -697,9 +746,20 @@ public sealed class SessionManager : ISessionManager
return;
}
_metrics.RemoveSessionEvents(session.SessionId);
ReleaseSessionSlot();
await removedSession.DisposeAsync().ConfigureAwait(false);
try
{
await removedSession.DisposeAsync().ConfigureAwait(false);
}
finally
{
// After the dispose, not before (WRK-008): on the kill path the worker client's read
// loop is cancelled but not awaited, so it can still be inside DispatchEnvelope for a
// frame it already read, and its EventReceived would re-create the per-session entry
// that nothing removes again. Disposing the session disposes its worker client, which
// waits (bounded) for that loop to stop.
_metrics.RemoveSessionEvents(session.SessionId);
}
}
private void ReleaseSessionSlot()
@@ -18,6 +18,9 @@ public sealed class SessionShutdownHostedService(
/// <summary>Shuts down all gateway sessions as the host stops.</summary>
/// <remarks>
/// The drain normally started earlier, at <c>ApplicationStopping</c> (SES-001): Kestrel's
/// hosted service stops before this one and waits for open event streams, which end only
/// when their sessions close. This call awaits that same drain.
/// The catch below is now effectively unreachable: <see cref="ISessionManager.ShutdownAsync"/>
/// no longer aborts on the host's shutdown timeout, it degrades to a kill sweep and logs a
/// per-session warning for each session that failed its graceful close. The clause is kept as
@@ -79,7 +79,8 @@ public sealed class SessionWorkerClientFactory : ISessionWorkerClientFactory
.ConfigureAwait(false);
session.TransitionTo(SessionState.WaitingForPipe);
await WaitForPipeConnectionAsync(pipe, startupCancellation.Token).ConfigureAwait(false);
await WaitForPipeConnectionAsync(pipe, processHandle.Process, session.SessionId, startupCancellation.Token)
.ConfigureAwait(false);
session.TransitionTo(SessionState.Handshaking);
WorkerFrameProtocolOptions frameOptions = new(
@@ -126,23 +127,30 @@ public sealed class SessionWorkerClientFactory : ISessionWorkerClientFactory
}
else
{
if (processHandle is not null)
// Must not throw (WRK-006): Kill can raise Win32Exception or AggregateException for
// a process that is mid-termination, and an exception here would replace the
// startup failure the caller is owed and skip the pipe dispose, leaking the
// pipe server handle.
try
{
try
if (processHandle is not null && !processHandle.Process.HasExited)
{
if (!processHandle.Process.HasExited)
{
processHandle.Process.Kill(entireProcessTree: true);
_metrics.WorkerKilled("OpenSessionFailed");
}
}
finally
{
processHandle.Dispose();
processHandle.Process.Kill(entireProcessTree: true);
_metrics.WorkerKilled("OpenSessionFailed");
}
}
pipe?.Dispose();
catch (Exception killException)
{
_loggerFactory.CreateLogger<SessionWorkerClientFactory>().LogWarning(
killException,
"Killing the worker of session {SessionId} after a failed open failed.",
session.SessionId);
}
finally
{
processHandle?.Dispose();
pipe?.Dispose();
}
}
if (exception is OperationCanceledException
@@ -193,14 +201,63 @@ public sealed class SessionWorkerClientFactory : ISessionWorkerClientFactory
outBufferSize: PipeBufferSizeBytes);
}
/// <summary>Waits for a client to connect to the pipe.</summary>
/// <summary>
/// Waits for the worker to connect to the pipe, failing fast if the worker process exits
/// first (WRK-002).
/// </summary>
/// <remarks>
/// The launcher's startup probe checks <c>HasExited</c> once, right after the process starts,
/// which is almost always false. A worker that then dies before connecting (a missing
/// dependency, a bad argument, security software, an unhandled startup exception) used to
/// hold the open — and its session slot — for the full startup timeout and surface as a
/// timeout with no exit code. Racing the connect against the process exit reports the crash
/// as <see cref="WorkerProcessLaunchErrorCode.StartupFailed"/> with the exit code at once.
/// Once connected, a worker exit shows up as pipe EOF in the handshake reads.
/// </remarks>
/// <param name="pipe">The named pipe.</param>
/// <param name="cancellationToken">Cancellation token.</param>
private static async Task WaitForPipeConnectionAsync(
/// <param name="process">The launched worker process.</param>
/// <param name="sessionId">Session id, for the failure message.</param>
/// <param name="cancellationToken">Cancellation token (the startup deadline and the caller's).</param>
/// <returns>A task that represents the asynchronous operation.</returns>
internal static async Task WaitForPipeConnectionAsync(
NamedPipeServerStream pipe,
IWorkerProcess process,
string sessionId,
CancellationToken cancellationToken)
{
await pipe.WaitForConnectionAsync(cancellationToken).ConfigureAwait(false);
using CancellationTokenSource raceCancellation = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
Task connect = pipe.WaitForConnectionAsync(raceCancellation.Token);
Task exit = process.WaitForExitAsync(raceCancellation.Token).AsTask();
Task first = await Task.WhenAny(connect, exit).ConfigureAwait(false);
if (first == exit && exit.IsCompletedSuccessfully && !connect.IsCompletedSuccessfully)
{
await raceCancellation.CancelAsync().ConfigureAwait(false);
await ObserveQuietlyAsync(connect).ConfigureAwait(false);
int? exitCode = process.ExitCode;
throw new WorkerProcessLaunchException(
WorkerProcessLaunchErrorCode.StartupFailed,
$"Worker process for session {sessionId} exited with code "
+ $"{(exitCode?.ToString(System.Globalization.CultureInfo.InvariantCulture) ?? "unknown")} "
+ "before it connected to its pipe.");
}
// The connect won (or the exit wait itself failed, which says nothing about the worker):
// stop watching the process and let the connect decide the outcome.
await raceCancellation.CancelAsync().ConfigureAwait(false);
await ObserveQuietlyAsync(exit).ConfigureAwait(false);
await connect.ConfigureAwait(false);
}
private static async Task ObserveQuietlyAsync(Task task)
{
try
{
await task.ConfigureAwait(false);
}
catch (Exception exception) when (exception is OperationCanceledException or IOException or ObjectDisposedException or InvalidOperationException)
{
}
}
/// <summary>
@@ -18,6 +18,16 @@ public interface IRunningProcessInspector
/// <summary>Forcibly terminates the process with the given identifier.</summary>
/// <param name="processId">Identifier of the process to terminate.</param>
void Kill(int processId);
/// <summary>
/// Reports whether a process with the given identifier is running, and when it started.
/// Orphan cleanup uses it to tell a worker whose owning gateway is still alive from a real
/// orphan, and the start time to reject a recycled process id.
/// </summary>
/// <param name="processId">Identifier of the process to look up.</param>
/// <param name="startedAt">The process start time, or <see langword="null"/> when it cannot be read.</param>
/// <returns><see langword="true"/> when the process is running; otherwise <see langword="false"/>.</returns>
bool TryGetRunningProcess(int processId, out DateTimeOffset? startedAt);
}
/// <summary>Identifying information for a running process candidate.</summary>
@@ -26,4 +36,13 @@ public interface IRunningProcessInspector
/// Fully-qualified path to the process main module, or <see langword="null"/>
/// when it could not be read (e.g. access denied).
/// </param>
public sealed record RunningProcessInfo(int ProcessId, string? ExecutablePath);
/// <param name="CommandLine">
/// The process command line, or <see langword="null"/> when it could not be read (or the
/// platform offers no way to read it).
/// </param>
/// <param name="StartedAt">The process start time, or <see langword="null"/> when it could not be read.</param>
public sealed record RunningProcessInfo(
int ProcessId,
string? ExecutablePath,
string? CommandLine = null,
DateTimeOffset? StartedAt = null);
@@ -60,7 +60,7 @@ public sealed class OrphanWorkerTerminator
continue;
}
if (!IsOrphanWorker(candidate, configuredPath))
if (!IsOrphanWorker(candidate, configuredPath, currentProcessId))
{
continue;
}
@@ -94,21 +94,104 @@ public sealed class OrphanWorkerTerminator
return terminated;
}
private static bool IsOrphanWorker(RunningProcessInfo candidate, string? configuredPath)
private bool IsOrphanWorker(RunningProcessInfo candidate, string? configuredPath, int currentProcessId)
{
// When the executable path is readable, require an exact match against
// the configured worker path so unrelated processes that merely share
// the image name are never killed.
if (candidate.ExecutablePath is { } path)
if (candidate.ExecutablePath is { } path
&& (configuredPath is null
|| !string.Equals(path, configuredPath, StringComparison.OrdinalIgnoreCase)))
{
return configuredPath is not null
&& string.Equals(path, configuredPath, StringComparison.OrdinalIgnoreCase);
return false;
}
// A null path means the x64 gateway could not introspect the module —
// the expected case for the x86 worker. Image-name match is the only
// signal available; treat it as an orphan.
return true;
// Ownership (WRK-009): the worker's --pipe-name carries the PID of the gateway that
// launched it (mxgw-{gatewayPid}-{sessionUid}). A worker whose gateway is still running
// belongs to that gateway — a second gateway started from the same build output, a test
// host — and killing it would fault that gateway's live sessions.
if (TryParseOwnerGatewayProcessId(candidate.CommandLine, out int ownerProcessId))
{
if (ownerProcessId == currentProcessId)
{
return false;
}
if (_inspector.TryGetRunningProcess(ownerProcessId, out DateTimeOffset? ownerStartedAt)
&& !IsRecycledProcessId(ownerStartedAt, candidate.StartedAt))
{
_logger.LogInformation(
"Leaving worker process {ProcessId} alone: its gateway process {OwnerProcessId} is still running.",
candidate.ProcessId,
ownerProcessId);
return false;
}
return true;
}
if (candidate.ExecutablePath is not null)
{
// The configured path matches but the command line could not be read or carries no
// owner: the path is the only signal, as before.
return true;
}
// Neither the path nor the command line could be read, so nothing ties the process to
// this gateway's worker build. Image name alone is not enough: a same-named worker from a
// different build (a CI checkout) would be killed.
_logger.LogWarning(
"Leaving worker-named process {ProcessId} alone: neither its executable path nor its command line could be read to confirm it is an orphan of this gateway's worker build.",
candidate.ProcessId);
return false;
}
// An owner process that started after the worker cannot have launched it: the gateway that
// did is gone and its id was reused. Unknown start times give the live process the benefit
// of the doubt.
private static bool IsRecycledProcessId(DateTimeOffset? ownerStartedAt, DateTimeOffset? workerStartedAt)
=> ownerStartedAt is { } owner
&& workerStartedAt is { } worker
&& owner > worker;
/// <summary>
/// Extracts the owning gateway PID from a worker command line's <c>--pipe-name</c> value
/// (<c>mxgw-{gatewayPid}-{sessionUid}</c>, or the older <c>mxaccess-gateway-{gatewayPid}-…</c>).
/// </summary>
/// <param name="commandLine">The worker command line, or <see langword="null"/>.</param>
/// <param name="ownerProcessId">The parsed gateway PID.</param>
/// <returns><see langword="true"/> when an owner PID was found.</returns>
internal static bool TryParseOwnerGatewayProcessId(string? commandLine, out int ownerProcessId)
{
ownerProcessId = 0;
if (string.IsNullOrEmpty(commandLine))
{
return false;
}
const string PipeNameSwitch = "--pipe-name";
int switchIndex = commandLine.IndexOf(PipeNameSwitch, StringComparison.Ordinal);
if (switchIndex < 0)
{
return false;
}
ReadOnlySpan<char> rest = commandLine.AsSpan(switchIndex + PipeNameSwitch.Length).TrimStart().TrimStart('"');
foreach (string prefix in (string[])["mxgw-", "mxaccess-gateway-"])
{
if (!rest.StartsWith(prefix, StringComparison.Ordinal))
{
continue;
}
ReadOnlySpan<char> afterPrefix = rest[prefix.Length..];
int dash = afterPrefix.IndexOf('-');
return dash > 0
&& int.TryParse(afterPrefix[..dash], System.Globalization.NumberStyles.None, System.Globalization.CultureInfo.InvariantCulture, out ownerProcessId)
&& ownerProcessId > 0;
}
return false;
}
private string? ResolveConfiguredExecutablePath()
@@ -1,4 +1,5 @@
using System.Diagnostics;
using System.Runtime.InteropServices;
namespace ZB.MOM.WW.MxGateway.Server.Workers;
@@ -7,6 +8,14 @@ namespace ZB.MOM.WW.MxGateway.Server.Workers;
/// </summary>
public sealed class SystemRunningProcessInspector : IRunningProcessInspector
{
// PROCESS_QUERY_LIMITED_INFORMATION: the least access that reads the image path, the command
// line and the start time, and the one granted across WOW64 (x64 gateway, x86 worker).
private const uint ProcessQueryLimitedInformation = 0x1000;
// PROCESSINFOCLASS.ProcessCommandLineInformation (Windows 8.1+). Returns a UNICODE_STRING
// followed by its buffer, and works across bitness, unlike reading the target's PEB.
private const int ProcessCommandLineInformation = 60;
/// <inheritdoc />
public IReadOnlyList<RunningProcessInfo> GetProcessesByName(string processName)
{
@@ -16,7 +25,11 @@ public sealed class SystemRunningProcessInspector : IRunningProcessInspector
{
foreach (Process process in processes)
{
results.Add(new RunningProcessInfo(process.Id, TryGetExecutablePath(process)));
results.Add(new RunningProcessInfo(
process.Id,
TryGetExecutablePath(process),
TryGetCommandLine(process.Id),
TryGetStartTime(process)));
}
}
finally
@@ -37,6 +50,102 @@ public sealed class SystemRunningProcessInspector : IRunningProcessInspector
process.Kill(entireProcessTree: true);
}
/// <inheritdoc />
public bool TryGetRunningProcess(int processId, out DateTimeOffset? startedAt)
{
startedAt = null;
Process process;
try
{
process = Process.GetProcessById(processId);
}
catch (ArgumentException)
{
// Not running.
return false;
}
catch (InvalidOperationException)
{
return false;
}
using (process)
{
try
{
if (process.HasExited)
{
return false;
}
}
catch (Exception exception) when (exception is InvalidOperationException
or System.ComponentModel.Win32Exception
or NotSupportedException)
{
// Cannot open it to ask, but GetProcessById found it: treat it as running.
}
startedAt = TryGetStartTime(process);
return true;
}
}
/// <summary>
/// Reads another process's command line. Windows only; <see langword="null"/> elsewhere or
/// when it cannot be read (access denied, the process exited).
/// </summary>
/// <param name="processId">The process to read.</param>
/// <returns>The command line, or <see langword="null"/>.</returns>
internal static string? TryGetCommandLine(int processId)
{
if (!OperatingSystem.IsWindows())
{
return null;
}
IntPtr handle = OpenProcess(ProcessQueryLimitedInformation, inheritHandle: false, processId);
if (handle == IntPtr.Zero)
{
return null;
}
try
{
// The sizing call fails with STATUS_INFO_LENGTH_MISMATCH and reports the size needed.
_ = NtQueryInformationProcess(handle, ProcessCommandLineInformation, IntPtr.Zero, 0, out int length);
if (length <= 0 || length > 1024 * 1024)
{
return null;
}
IntPtr buffer = Marshal.AllocHGlobal(length);
try
{
int status = NtQueryInformationProcess(handle, ProcessCommandLineInformation, buffer, length, out _);
if (status != 0)
{
return null;
}
// UNICODE_STRING { USHORT Length; USHORT MaximumLength; PWSTR Buffer; } — the
// pointer is naturally aligned, so it sits at offset IntPtr.Size.
int byteLength = (ushort)Marshal.ReadInt16(buffer);
IntPtr text = Marshal.ReadIntPtr(buffer, IntPtr.Size);
return byteLength == 0 || text == IntPtr.Zero
? string.Empty
: Marshal.PtrToStringUni(text, byteLength / 2);
}
finally
{
Marshal.FreeHGlobal(buffer);
}
}
finally
{
_ = CloseHandle(handle);
}
}
private static string? TryGetExecutablePath(Process process)
{
try
@@ -52,4 +161,33 @@ public sealed class SystemRunningProcessInspector : IRunningProcessInspector
return null;
}
}
private static DateTimeOffset? TryGetStartTime(Process process)
{
try
{
return new DateTimeOffset(process.StartTime.ToUniversalTime(), TimeSpan.Zero);
}
catch (Exception exception) when (exception is InvalidOperationException
or System.ComponentModel.Win32Exception
or NotSupportedException)
{
return null;
}
}
[DllImport("kernel32.dll", SetLastError = true)]
private static extern IntPtr OpenProcess(uint desiredAccess, bool inheritHandle, int processId);
[DllImport("kernel32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool CloseHandle(IntPtr handle);
[DllImport("ntdll.dll")]
private static extern int NtQueryInformationProcess(
IntPtr processHandle,
int processInformationClass,
IntPtr processInformation,
int processInformationLength,
out int returnLength);
}
@@ -56,6 +56,12 @@ public sealed class WorkerClient : IWorkerClient
// task before reading State is woken by the next transition instead of polling (mxaccessgw#189).
private TaskCompletionSource _stateChanged = new(TaskCreationOptions.RunContinuationsAsynchronously);
private DateTimeOffset _lastHeartbeatAt;
// Monotonic twin of _lastHeartbeatAt (TimeProvider.GetTimestamp), the one the watchdog
// measures staleness on (WRK-005). A wall-clock step — a time-sync correction after a VM
// restore — must neither fault every Ready worker at once nor delay detecting a dead one.
// _lastHeartbeatAt stays for display. Both are written together under _syncRoot.
private long _lastHeartbeatTimestamp;
private int? _processId;
private string? _recordInfoPinStatus;
private int _eventQueueDepth;
@@ -140,6 +146,7 @@ public sealed class WorkerClient : IWorkerClient
_eventQueueDepthRegistration = _metrics?.RegisterWorkerEventQueueDepthSource(
() => Volatile.Read(ref _eventQueueDepth));
_lastHeartbeatAt = _timeProvider.GetUtcNow();
_lastHeartbeatTimestamp = _timeProvider.GetTimestamp();
}
/// <inheritdoc />
@@ -287,7 +294,24 @@ public sealed class WorkerClient : IWorkerClient
+ $"{MaxSequenceEncodingBytes}-byte sequence-stamp allowance.");
}
await EnqueueAsync(commandEnvelope, cancellationToken).ConfigureAwait(false);
// The command deadline covers the enqueue too (WRK-003). The bounded outbound channel
// fills when the write loop is parked in a pipe write the worker is not draining; an
// enqueue bound only to the caller's token then waited indefinitely for a caller with no
// deadline. The common case — room in the channel — takes TryWrite and allocates
// nothing; only a full channel pays for a linked, deadline-bound token.
cancellationToken.ThrowIfCancellationRequested();
TimeSpan replyTimeout = timeout;
if (!_outboundEnvelopes.Writer.TryWrite(commandEnvelope))
{
replyTimeout = await EnqueueCommandWithinDeadlineAsync(
commandEnvelope,
correlationId,
pendingCommand,
method,
timeout,
cancellationToken)
.ConfigureAwait(false);
}
// one pooled timer instead of a linked CTS + Task.Delay + WhenAny per command.
// Task.WaitAsync arms a TimerQueueTimer on the shared timer queue and cancels it when the
@@ -303,7 +327,7 @@ public sealed class WorkerClient : IWorkerClient
// and messages are unchanged.
try
{
return await pendingCommand.Task.WaitAsync(timeout, cancellationToken).ConfigureAwait(false);
return await pendingCommand.Task.WaitAsync(replyTimeout, cancellationToken).ConfigureAwait(false);
}
catch (TimeoutException) when (!cancellationToken.IsCancellationRequested)
{
@@ -321,14 +345,21 @@ public sealed class WorkerClient : IWorkerClient
// reply that won the race — the pending entry is already gone and the caller is about
// to see it — never has a cancel chase it. Best-effort by design; the send cannot
// throw, so it can never replace the timeout the caller is owed.
if (removed)
if (!removed)
{
TrySendCancelForAbandonedCommand(
correlationId,
method,
$"gateway command timeout after {timeout}");
// The reply (or a fault) won the race between the timer firing and the removal
// above (WRK-004): the read loop already removed the entry, recorded the
// outcome and completed the task. Return that outcome instead of a timeout —
// a Write the worker performed and the metrics counted as succeeded must not
// reach the client as DeadlineExceeded and be retried.
return await pendingCommand.Task.ConfigureAwait(false);
}
TrySendCancelForAbandonedCommand(
correlationId,
method,
$"gateway command timeout after {timeout}");
throw new WorkerClientException(
WorkerClientErrorCode.CommandTimeout,
timeoutMessage);
@@ -625,14 +656,28 @@ public sealed class WorkerClient : IWorkerClient
continue;
}
DateTimeOffset lastHeartbeatAt = LastHeartbeatAt;
DateTimeOffset now = _timeProvider.GetUtcNow();
if (now - lastHeartbeatAt <= _options.HeartbeatGrace)
DateTimeOffset lastHeartbeatAt;
long lastHeartbeatTimestamp;
lock (_syncRoot)
{
lastHeartbeatAt = _lastHeartbeatAt;
lastHeartbeatTimestamp = _lastHeartbeatTimestamp;
}
TimeSpan heartbeatAge = _timeProvider.GetElapsedTime(lastHeartbeatTimestamp);
if (heartbeatAge <= _options.HeartbeatGrace)
{
continue;
}
if (TryGetOldestPendingCommandAge(out TimeSpan oldestCommandAge)
// The in-flight-command skip is bounded by the heartbeat's own age as well as by the
// oldest command's (WRK-001). A command that hits its timeout leaves
// _pendingCommands, so with a command timeout below the ceiling no pending entry
// ever reaches it: a client that keeps issuing (and timing out) commands against a
// worker that has gone silent would otherwise hold the skip open forever, while an
// idle session over the same worker faults after HeartbeatGrace.
if (heartbeatAge <= _options.HeartbeatStuckCeiling
&& TryGetOldestPendingCommandAge(out TimeSpan oldestCommandAge)
&& oldestCommandAge <= _options.HeartbeatStuckCeiling)
{
continue;
@@ -1091,6 +1136,7 @@ public sealed class WorkerClient : IWorkerClient
? _processId ?? _connection.ProcessHandle?.ProcessId
: ready.WorkerProcessId;
_lastHeartbeatAt = _timeProvider.GetUtcNow();
_lastHeartbeatTimestamp = _timeProvider.GetTimestamp();
SetStateUnderLock(WorkerClientState.Ready);
_workerStartRecorded = true;
}
@@ -1146,6 +1192,7 @@ public sealed class WorkerClient : IWorkerClient
lock (_syncRoot)
{
_lastHeartbeatAt = _timeProvider.GetUtcNow();
_lastHeartbeatTimestamp = _timeProvider.GetTimestamp();
if (heartbeat.WorkerProcessId != 0)
{
_processId = heartbeat.WorkerProcessId;
@@ -1381,6 +1428,49 @@ public sealed class WorkerClient : IWorkerClient
}
}
/// <summary>
/// Slow path of the command enqueue, taken only when the outbound channel is full: waits for
/// room under the caller's token AND the command deadline, and returns what is left of the
/// deadline for the reply wait.
/// </summary>
/// <param name="commandEnvelope">Command envelope to enqueue.</param>
/// <param name="correlationId">Command correlation id.</param>
/// <param name="pendingCommand">The command's pending entry.</param>
/// <param name="method">Command method name for metrics and messages.</param>
/// <param name="timeout">The whole command deadline.</param>
/// <param name="cancellationToken">The caller's token.</param>
/// <returns>The part of <paramref name="timeout"/> left for the reply wait.</returns>
private async Task<TimeSpan> EnqueueCommandWithinDeadlineAsync(
WorkerEnvelope commandEnvelope,
string correlationId,
PendingCommand pendingCommand,
string method,
TimeSpan timeout,
CancellationToken cancellationToken)
{
using CancellationTokenSource deadlineCts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
deadlineCts.CancelAfter(timeout);
try
{
await EnqueueAsync(commandEnvelope, deadlineCts.Token).ConfigureAwait(false);
}
catch (OperationCanceledException) when (!cancellationToken.IsCancellationRequested)
{
// The deadline fired with the envelope never queued, so there is nothing for the
// worker to drop and no WorkerCancel to send.
string timeoutMessage = $"Worker command {method} timed out after {timeout} waiting for the outbound queue.";
RemovePendingCommandAsFailed(
correlationId,
pendingCommand,
WorkerClientErrorCode.CommandTimeout,
timeoutMessage);
throw new WorkerClientException(WorkerClientErrorCode.CommandTimeout, timeoutMessage);
}
TimeSpan remaining = timeout - _timeProvider.GetElapsedTime(pendingCommand.StartTimestamp);
return remaining > TimeSpan.Zero ? remaining : TimeSpan.FromTicks(1);
}
/// <summary>Creates gateway hello envelope.</summary>
/// <returns>The hello envelope.</returns>
private WorkerEnvelope CreateGatewayHelloEnvelope()
@@ -57,11 +57,13 @@ public sealed class WorkerClientOptions
/// <summary>
/// Ceiling on the in-flight-command heartbeat-skip. When
/// a command has been pending on the gateway↔worker pipe for longer
/// than this, the gateway-side <c>HeartbeatLoopAsync</c> fires the
/// <c>HeartbeatExpired</c> fault even if commands are still pending;
/// a truly stuck COM call shouldn't keep the watchdog suppressed
/// indefinitely. Mirrors <c>HeartbeatStuckCeiling</c> on
/// the worker side.
/// than this, or the last heartbeat is older than this, the gateway-side
/// <c>HeartbeatLoopAsync</c> fires the <c>HeartbeatExpired</c> fault even
/// if commands are still pending; a truly stuck COM call shouldn't keep
/// the watchdog suppressed indefinitely. The heartbeat-age bound matters
/// because a command that times out leaves the pending set, so with a
/// command timeout below this ceiling no pending entry ever reaches it.
/// Mirrors <c>HeartbeatStuckCeiling</c> on the worker side.
/// </summary>
public TimeSpan HeartbeatStuckCeiling { get; init; }
}
@@ -224,6 +224,9 @@ public sealed class WorkerProcessLauncher : IWorkerProcessLauncher
startInfo.Environment[WorkerLaunchEnvironment.HeartbeatStuckCeilingMilliseconds] =
(_workerOptions.WorkerHeartbeatStuckCeilingSeconds * 1000L).ToString(System.Globalization.CultureInfo.InvariantCulture);
startInfo.Environment[WorkerLaunchEnvironment.StartupTimeoutMilliseconds] =
(_workerOptions.StartupTimeoutSeconds * 1000L).ToString(System.Globalization.CultureInfo.InvariantCulture);
commandLine = new WorkerProcessCommandLine(executablePath, arguments);
return startInfo;
@@ -293,6 +296,10 @@ public sealed class WorkerProcessLauncher : IWorkerProcessLauncher
return workingDirectory;
}
// Called from the launch-failure catch blocks, so it must never throw: Kill can raise
// Win32Exception (the process is mid-termination, or access is denied) or AggregateException
// (a descendant could not be terminated), and an exception escaping here would replace the
// WorkerProcessLaunchException the caller is owed (WRK-006).
private void KillAndDispose(IWorkerProcess process, string reason)
{
try
@@ -303,12 +310,32 @@ public sealed class WorkerProcessLauncher : IWorkerProcessLauncher
_metrics.WorkerKilled(reason);
}
}
catch (Exception exception)
{
_logger.LogWarning(
exception,
"Killing worker process {ProcessId} after a failed launch ({Reason}) failed.",
SafeProcessId(process),
reason);
}
finally
{
process.Dispose();
}
}
private static int? SafeProcessId(IWorkerProcess process)
{
try
{
return process.Id;
}
catch (InvalidOperationException)
{
return null;
}
}
private static void ValidateRequest(WorkerProcessLaunchRequest request)
{
if (string.IsNullOrWhiteSpace(request.SessionId))
@@ -90,7 +90,9 @@
},
"Protocol": {
"WorkerProtocolVersion": 1,
"MaxGrpcMessageBytes": 16777216
"MaxGrpcMessageBytes": 16777216,
"Http2KeepAlivePingDelaySeconds": 60,
"Http2KeepAlivePingTimeoutSeconds": 10
},
"Galaxy": {
"ConnectionString": "Server=localhost;Database=ZB;Integrated Security=True;TrustServerCertificate=True;Encrypt=False;",