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
@@ -50,4 +50,13 @@ public static class WorkerLaunchEnvironment
/// exceed it.
/// </summary>
public const string HeartbeatGraceMilliseconds = "MXGATEWAY_WORKER_HEARTBEAT_GRACE_MS";
/// <summary>
/// Deadline, in milliseconds, for the worker's startup handshake (the <c>GatewayHello</c> read
/// and MXAccess initialization). Set from <c>MxGateway:Worker:StartupTimeoutSeconds</c>, the
/// same bound the gateway applies to the whole launch, so a live gateway always gives up
/// (and kills the worker) first; the worker's own deadline only matters when the gateway is
/// gone.
/// </summary>
public const string StartupTimeoutMilliseconds = "MXGATEWAY_WORKER_STARTUP_TIMEOUT_MS";
}
@@ -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;",
@@ -1330,6 +1330,35 @@ public sealed class GatewayOptionsValidatorTests
Assert.True(result.Succeeded);
}
/// <summary>SES-005: the HTTP/2 keepalive knobs are range-checked; a delay of 0 (off) is valid.</summary>
/// <param name="delaySeconds">Configured ping delay.</param>
/// <param name="timeoutSeconds">Configured ping timeout.</param>
/// <param name="valid">Whether validation should pass.</param>
[Theory]
[InlineData(60, 10, true)]
[InlineData(0, 10, true)]
[InlineData(86400, 3600, true)]
[InlineData(-1, 10, false)]
[InlineData(86401, 10, false)]
[InlineData(60, 0, false)]
[InlineData(60, 3601, false)]
public void Validate_Http2KeepAlive_IsRangeChecked(int delaySeconds, int timeoutSeconds, bool valid)
{
GatewayOptions options = WithWorkerAndProtocol(
new WorkerOptions(),
new ProtocolOptions
{
Http2KeepAlivePingDelaySeconds = delaySeconds,
Http2KeepAlivePingTimeoutSeconds = timeoutSeconds,
});
ValidateOptionsResult result = new GatewayOptionsValidator().Validate(null, options);
bool keepAliveFailure = result.Failed
&& result.Failures!.Any(f => f.Contains("Http2KeepAlive", StringComparison.Ordinal));
Assert.Equal(!valid, keepAliveFailure);
}
/// <summary>
/// Verifies that a worker-frame maximum equal to the gRPC cap (zero headroom) fails validation:
/// a maximally-sized accepted gRPC payload would not fit one worker frame once wrapped in a
@@ -342,6 +342,57 @@ public sealed class DashboardLiveDataServiceTests
Assert.Equal(DashboardTagValue.RedactedValueText, succeeded.ValueText);
}
/// <summary>
/// DSH-002: a read that fails without faulting the session (here a worker-side
/// bulk-read failure) closes the dashboard session it drops, so the next read's
/// fresh session never coexists with an orphaned one.
/// </summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[Fact]
public async Task ReadAsync_WhenReadFails_ClosesTheDroppedSession()
{
RecordingWorkerClient worker = new() { FailReadBulk = true };
await using FakeSessionManager sessionManager = new(worker);
await using DashboardLiveDataService service = CreateService(sessionManager);
DashboardLiveReadResult first = await service.ReadAsync(["Tank_001.PV"], CancellationToken.None);
Assert.NotNull(first.Error);
Assert.Equal(["dashboard-session-1"], sessionManager.ClosedSessionIds);
worker.FailReadBulk = false;
DashboardLiveReadResult second = await service.ReadAsync(["Tank_001.PV"], CancellationToken.None);
Assert.Null(second.Error);
Assert.Equal(2, sessionManager.OpenCount);
Assert.Equal("dashboard-session-2", second.SessionId);
Assert.Equal(["dashboard-session-1"], sessionManager.ClosedSessionIds);
}
/// <summary>
/// DSH-007: a caller that cancels after the worker advised the tags still gets them
/// tracked, so the next read does not advise them a second time.
/// </summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[Fact]
public async Task ReadAsync_CancelledMidSubscribe_StillTracksTheAdvisedTags()
{
RecordingWorkerClient worker = new();
await using FakeSessionManager sessionManager = new(worker);
await using DashboardLiveDataService service = CreateService(sessionManager);
using CancellationTokenSource pageToken = new();
worker.OnSubscribe = pageToken.Cancel;
await Assert.ThrowsAnyAsync<OperationCanceledException>(
() => service.ReadAsync(["Tank_001.PV", "Tank_002.PV"], pageToken.Token));
worker.OnSubscribe = null;
DashboardLiveReadResult next = await service.ReadAsync(["Tank_001.PV", "Tank_002.PV"], CancellationToken.None);
Assert.Null(next.Error);
Assert.Equal(["Tank_001.PV", "Tank_002.PV"], worker.SubscribedTags);
Assert.Equal(1, sessionManager.OpenCount);
}
private static DashboardLiveDataService CreateService(
ISessionManager sessionManager,
bool showTagValues = false,
@@ -414,9 +465,13 @@ public sealed class DashboardLiveDataServiceTests
return session is not null;
}
/// <summary>Gets the ids of the sessions the dashboard service closed, in order.</summary>
public List<string> ClosedSessionIds { get; } = [];
/// <inheritdoc />
public Task<SessionCloseResult> CloseSessionAsync(string sessionId, CancellationToken cancellationToken)
{
ClosedSessionIds.Add(sessionId);
return Task.FromResult(new SessionCloseResult(sessionId, SessionState.Closed, AlreadyClosed: false));
}
@@ -494,6 +549,16 @@ public sealed class DashboardLiveDataServiceTests
/// </summary>
public MxValue? ReadValue { get; set; }
/// <summary>Gets or sets a value indicating whether every bulk read throws, as a worker-side failure would.</summary>
public bool FailReadBulk { get; set; }
/// <summary>
/// Gets or sets a hook run after a subscribe was applied worker-side and before the
/// reply returns; the fake then honours the command's cancellation token, as a real
/// reply wait would.
/// </summary>
public Action? OnSubscribe { get; set; }
/// <summary>Gets the tag addresses whose bulk read comes back unsuccessful.</summary>
public HashSet<string> FailReadFor { get; } = new(StringComparer.OrdinalIgnoreCase);
@@ -527,6 +592,12 @@ public sealed class DashboardLiveDataServiceTests
break;
case MxCommandKind.SubscribeBulk:
reply.SubscribeBulk = Subscribe(mxCommand.SubscribeBulk.TagAddresses);
if (OnSubscribe is not null)
{
OnSubscribe();
cancellationToken.ThrowIfCancellationRequested();
}
break;
case MxCommandKind.UnsubscribeBulk:
UnsubscribeCommandCount++;
@@ -538,6 +609,8 @@ public sealed class DashboardLiveDataServiceTests
UnsubscribedHandles.AddRange(mxCommand.UnsubscribeBulk.ItemHandles);
reply.UnsubscribeBulk = new BulkSubscribeReply();
break;
case MxCommandKind.ReadBulk when FailReadBulk:
throw new InvalidOperationException("Simulated worker bulk-read failure.");
case MxCommandKind.ReadBulk:
reply.ReadBulk = Read(mxCommand.ReadBulk.TagAddresses);
break;
@@ -0,0 +1,122 @@
using System.Net;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Hosting.Server;
using Microsoft.AspNetCore.Hosting.Server.Features;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Server.Kestrel.Core;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using ZB.MOM.WW.MxGateway.Server.Grpc;
using ZB.MOM.WW.MxGateway.Tests.TestSupport;
namespace ZB.MOM.WW.MxGateway.Tests.Gateway.Grpc;
/// <summary>
/// SES-005: the gateway configures Kestrel's HTTP/2 keepalive from <c>MxGateway:Protocol</c>, and
/// Kestrel tolerates the official clients' keepalive pings (every 30 s, also with no call active).
/// </summary>
public sealed class GatewayKestrelKeepAliveTests
{
/// <summary>The defaults are the D7 policy: server ping after 60 s idle, 10 s timeout.</summary>
[Fact]
public void Configure_WithDefaults_AppliesSixtySecondDelayAndTenSecondTimeout()
{
KestrelServerOptions kestrel = new();
new GatewayKestrelKeepAliveConfiguration(Config()).Configure(kestrel);
Assert.Equal(TimeSpan.FromSeconds(60), kestrel.Limits.Http2.KeepAlivePingDelay);
Assert.Equal(TimeSpan.FromSeconds(10), kestrel.Limits.Http2.KeepAlivePingTimeout);
}
/// <summary>Configured values are applied; a delay of 0 turns server pings off.</summary>
[Fact]
public void Configure_WithZeroDelay_DisablesServerPings()
{
KestrelServerOptions kestrel = new();
new GatewayKestrelKeepAliveConfiguration(Config(
("MxGateway:Protocol:Http2KeepAlivePingDelaySeconds", "0"),
("MxGateway:Protocol:Http2KeepAlivePingTimeoutSeconds", "25")))
.Configure(kestrel);
Assert.Equal(TimeSpan.MaxValue, kestrel.Limits.Http2.KeepAlivePingDelay);
Assert.Equal(TimeSpan.FromSeconds(25), kestrel.Limits.Http2.KeepAlivePingTimeout);
}
/// <summary>The real gateway host wires the configuration into its Kestrel options.</summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[Fact]
public async Task GatewayHost_ConfiguresKestrelKeepAlive()
{
await using WebApplication app = TestGatewayHost.Build("--MxGateway:Protocol:Http2KeepAlivePingDelaySeconds=45");
KestrelServerOptions kestrel = app.Services.GetRequiredService<IOptions<KestrelServerOptions>>().Value;
Assert.Equal(TimeSpan.FromSeconds(45), kestrel.Limits.Http2.KeepAlivePingDelay);
Assert.Equal(TimeSpan.FromSeconds(10), kestrel.Limits.Http2.KeepAlivePingTimeout);
}
/// <summary>
/// Kestrel accepts client keepalive pings on a connection with no active call without a
/// GOAWAY, and the pings keep the idle connection open past Kestrel's idle keep-alive
/// timeout: the second request reuses the first request's connection. A client that does
/// not ping is the control — its idle connection is closed and the second request lands on a
/// new one, so the test can tell the two apart.
/// </summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[Fact]
public async Task ClientPingsWithNoActiveCall_AreAcceptedAndKeepTheIdleConnectionOpen()
{
WebApplicationBuilder builder = WebApplication.CreateSlimBuilder();
builder.Logging.ClearProviders();
builder.WebHost.UseKestrel(options =>
{
options.Limits.KeepAliveTimeout = TimeSpan.FromSeconds(2);
options.Listen(IPAddress.Loopback, 0, listen => listen.Protocols = HttpProtocols.Http2);
});
await using WebApplication app = builder.Build();
app.MapGet("/connection", (HttpContext context) => context.Connection.Id);
await app.StartAsync();
string address = app.Services.GetRequiredService<IServer>().Features.Get<IServerAddressesFeature>()!.Addresses.First();
Task<(string First, string Second)> pinging = TwoRequestsAcrossIdleGapAsync(address, ping: true);
Task<(string First, string Second)> silent = TwoRequestsAcrossIdleGapAsync(address, ping: false);
(string pingFirst, string pingSecond) = await pinging;
(string silentFirst, string silentSecond) = await silent;
Assert.Equal(pingFirst, pingSecond);
Assert.NotEqual(silentFirst, silentSecond);
await app.StopAsync();
}
private static IConfiguration Config(params (string Key, string Value)[] values)
=> new ConfigurationBuilder()
.AddInMemoryCollection(values.Select(pair => new KeyValuePair<string, string?>(pair.Key, pair.Value)))
.Build();
private static async Task<(string First, string Second)> TwoRequestsAcrossIdleGapAsync(string address, bool ping)
{
using SocketsHttpHandler handler = new()
{
KeepAlivePingDelay = ping ? TimeSpan.FromSeconds(1) : Timeout.InfiniteTimeSpan,
KeepAlivePingTimeout = TimeSpan.FromSeconds(5),
KeepAlivePingPolicy = HttpKeepAlivePingPolicy.Always,
PooledConnectionIdleTimeout = TimeSpan.FromMinutes(5),
};
using HttpClient client = new(handler)
{
BaseAddress = new Uri(address),
DefaultRequestVersion = HttpVersion.Version20,
DefaultVersionPolicy = HttpVersionPolicy.RequestVersionExact,
Timeout = TimeSpan.FromSeconds(10),
};
string first = await client.GetStringAsync("/connection");
await Task.Delay(TimeSpan.FromSeconds(4.5));
string second = await client.GetStringAsync("/connection");
return (first, second);
}
}
@@ -595,6 +595,93 @@ public sealed class GatewaySessionTests
second.Dispose();
}
/// <summary>
/// SES-004: a client that only streams (no unary call) for longer than the lease must still
/// get its full detach-grace window when the stream drops. The detach renews the lease, so
/// the session is neither lease-expired nor grace-expired until the grace elapses, and is
/// then closed for detach-grace rather than for the lease.
/// </summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[Fact]
public async Task DetachGrace_StreamOutlivesLease_DetachStillGetsFullGraceWindow()
{
FakeTimeProvider clock = new(DateTimeOffset.UtcNow);
FakeWorkerClient workerClient = new();
await using GatewaySession session = CreateReadySessionWithDetachGrace(
workerClient,
clock,
detachGrace: TimeSpan.FromSeconds(30));
IEventSubscriberLease lease = session.AttachEventSubscriber(maxSubscribers: 1);
// Stream for longer than the 30-minute lease with no unary command.
clock.Advance(TimeSpan.FromMinutes(31));
lease.Dispose();
clock.Advance(TimeSpan.FromSeconds(5));
Assert.False(session.IsLeaseExpired(clock.GetUtcNow()));
Assert.False(session.IsDetachGraceExpired(clock.GetUtcNow()));
Assert.False(session.TryBeginCloseIfExpired(clock.GetUtcNow(), out _));
Assert.Equal(SessionState.Ready, session.State);
clock.Advance(TimeSpan.FromSeconds(25));
Assert.False(session.IsLeaseExpired(clock.GetUtcNow()));
Assert.True(session.IsDetachGraceExpired(clock.GetUtcNow()));
}
/// <summary>
/// SES-007: a successful <c>Unregister</c> drops every item registration under that server
/// handle (MXAccess invalidates them all), and leaves other server handles alone.
/// </summary>
[Fact]
public void TrackCommandReply_SuccessfulUnregister_PurgesThatServerHandlesItems()
{
GatewaySession session = CreateSession();
TrackAddItem(session, serverHandle: 1, itemHandle: 10, "A.PV");
TrackAddItem(session, serverHandle: 1, itemHandle: 11, "B.PV");
TrackAddItem(session, serverHandle: 1, itemHandle: 12, "C.PV");
TrackAddItem(session, serverHandle: 2, itemHandle: 10, "D.PV");
session.TrackCommandReply(
new MxCommand { Kind = MxCommandKind.Unregister, Unregister = new UnregisterCommand { ServerHandle = 1 } },
new MxCommandReply { ProtocolStatus = MxAccessGrpcMapper.Ok() });
Assert.False(session.TryGetItemRegistration(1, 10, out _));
Assert.False(session.TryGetItemRegistration(1, 11, out _));
Assert.False(session.TryGetItemRegistration(1, 12, out _));
Assert.True(session.TryGetItemRegistration(2, 10, out SessionItemRegistration other));
Assert.Equal("D.PV", other.TagAddress);
}
/// <summary>A failed <c>Unregister</c> leaves the registrations in place.</summary>
[Fact]
public void TrackCommandReply_FailedUnregister_KeepsRegistrations()
{
GatewaySession session = CreateSession();
TrackAddItem(session, serverHandle: 1, itemHandle: 10, "A.PV");
session.TrackCommandReply(
new MxCommand { Kind = MxCommandKind.Unregister, Unregister = new UnregisterCommand { ServerHandle = 1 } },
new MxCommandReply { ProtocolStatus = new ProtocolStatus { Code = ProtocolStatusCode.MxaccessFailure } });
Assert.True(session.TryGetItemRegistration(1, 10, out _));
}
private static void TrackAddItem(GatewaySession session, int serverHandle, int itemHandle, string tagAddress)
{
session.TrackCommandReply(
new MxCommand
{
Kind = MxCommandKind.AddItem,
AddItem = new AddItemCommand { ServerHandle = serverHandle, ItemDefinition = tagAddress },
},
new MxCommandReply
{
ProtocolStatus = MxAccessGrpcMapper.Ok(),
AddItem = new AddItemReply { ItemHandle = itemHandle },
});
}
/// <summary>
/// With detach-grace disabled (<c>0</c>), dropping the last subscriber must
/// match today's behavior: the session stays <see cref="SessionState.Ready"/> with no
@@ -1939,6 +1939,28 @@ public sealed class SessionManagerTests
Assert.Equal(0, metrics.GetSnapshot().OpenSessions);
}
/// <summary>
/// WRK-008: a worker read loop that records one more event while the killed session's
/// worker client is being disposed must not leave a per-session metrics entry behind; the
/// entry is dropped after the dispose.
/// </summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[Fact]
public async Task KillWorkerAsync_EventRecordedDuringWorkerDispose_LeavesNoPerSessionEntry()
{
using GatewayMetrics metrics = new();
string? sessionId = null;
FakeWorkerClient workerClient = new() { OnDispose = () => metrics.EventReceived(sessionId!, "OnDataChange") };
SessionManager manager = CreateManager(new FakeSessionWorkerClientFactory(workerClient), metrics: metrics);
GatewaySession session = await manager.OpenSessionAsync(CreateOpenRequest(), "client-1", ownerKeyId: null, CancellationToken.None);
sessionId = session.SessionId;
await manager.KillWorkerAsync(session.SessionId, "test-kill", CancellationToken.None);
Assert.Equal(1, workerClient.DisposeCount);
Assert.False(metrics.GetSnapshot().EventsBySession.ContainsKey(session.SessionId));
}
/// <summary>Creates a session manager for testing.</summary>
/// <param name="factory">Worker client factory.</param>
/// <param name="registry">Session registry; defaults to a new registry.</param>
@@ -2467,9 +2489,16 @@ public sealed class SessionManagerTests
public ValueTask DisposeAsync()
{
DisposeCount++;
OnDispose?.Invoke();
return ValueTask.CompletedTask;
}
/// <summary>
/// Gets a hook run inside <see cref="DisposeAsync"/>, standing in for a worker read loop
/// that is still finishing a frame while the client is disposed.
/// </summary>
public Action? OnDispose { get; init; }
/// <summary>Waits for shutdown to start on the fake worker client.</summary>
/// <returns>A task that represents the asynchronous operation.</returns>
public Task WaitForShutdownStartAsync()
@@ -0,0 +1,248 @@
using System.Diagnostics;
using System.Runtime.CompilerServices;
using System.Threading.Channels;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Hosting.Server;
using Microsoft.AspNetCore.Hosting.Server.Features;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
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;
namespace ZB.MOM.WW.MxGateway.Tests.Gateway.Sessions;
/// <summary>
/// SES-001: the host drain must close sessions while Kestrel is still draining, not after it.
/// <c>WebApplication</c> stops Kestrel's hosted service first, and Kestrel waits for in-flight
/// requests; an open event stream is one, and it ends only when its session closes.
/// </summary>
public sealed class SessionShutdownOrderingTests
{
private static readonly TimeSpan HostShutdownTimeout = TimeSpan.FromSeconds(20);
/// <summary>
/// <c>ApplicationStopping</c> starts the drain by itself: the session is closed gracefully
/// before anyone calls <see cref="SessionManager.ShutdownAsync"/>, and the later call (made by
/// the hosted service, possibly on an already-cancelled token) awaits that same drain
/// instead of killing the worker.
/// </summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[Fact]
public async Task ApplicationStopping_StartsDrain_AndShutdownAsyncAwaitsItWithoutKilling()
{
StreamingWorkerClient worker = new();
ApplicationLifetimeStub lifetime = new();
using GatewayMetrics metrics = new();
SessionManager manager = CreateManager(worker, metrics, lifetime);
GatewaySession session = await manager.OpenSessionAsync(new SessionOpenRequest(RequestedBackend: null, ClientSessionName: "ordering", ClientCorrelationId: "ordering-1", CommandTimeout: null), "client-1", ownerKeyId: null, CancellationToken.None);
lifetime.SignalStopping();
await worker.ShutdownCalled.WaitAsync(TimeSpan.FromSeconds(5));
using CancellationTokenSource alreadyCancelled = new();
await alreadyCancelled.CancelAsync();
await manager.ShutdownAsync(alreadyCancelled.Token).WaitAsync(TimeSpan.FromSeconds(5));
Assert.Equal(SessionState.Closed, session.State);
Assert.Equal(1, worker.ShutdownCount);
Assert.Equal(0, worker.KillCount);
Assert.Equal(0, metrics.GetSnapshot().OpenSessions);
}
/// <summary>
/// Kestrel-backed: with an event subscriber streaming over a real HTTP request, stopping the
/// host finishes well inside the host shutdown timeout, the request ends normally (its
/// subscriber channel completed, not a transport abort), and the worker is shut down
/// gracefully rather than killed.
/// </summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[Fact]
public async Task HostStop_WithOpenEventStream_ClosesSessionGracefullyAndEndsStreamCleanly()
{
StreamingWorkerClient worker = new();
TaskCompletionSource attached = new(TaskCreationOptions.RunContinuationsAsynchronously);
TaskCompletionSource<string> streamOutcome = new(TaskCreationOptions.RunContinuationsAsynchronously);
using GatewayMetrics metrics = new();
WebApplicationBuilder builder = WebApplication.CreateSlimBuilder();
builder.Logging.ClearProviders();
builder.WebHost.UseKestrel().UseUrls("http://127.0.0.1:0");
builder.Services.Configure<HostOptions>(options => options.ShutdownTimeout = HostShutdownTimeout);
builder.Services.AddSingleton<ISessionManager>(provider => CreateManager(
worker,
metrics,
provider.GetRequiredService<IHostApplicationLifetime>()));
builder.Services.AddHostedService<SessionShutdownHostedService>();
await using WebApplication app = builder.Build();
app.MapGet("/stream/{sessionId}", async (string sessionId, HttpContext context, ISessionManager sessions) =>
{
Assert.True(sessions.TryGetSession(sessionId, out GatewaySession? session));
using IEventSubscriberLease lease = session!.AttachEventSubscriber(maxSubscribers: 1);
await context.Response.WriteAsync("attached\n", context.RequestAborted);
await context.Response.Body.FlushAsync(context.RequestAborted);
attached.TrySetResult();
try
{
await foreach (MxEvent _ in lease.Reader.ReadAllAsync(context.RequestAborted))
{
}
streamOutcome.TrySetResult("completed");
}
catch (OperationCanceledException)
{
streamOutcome.TrySetResult("aborted");
throw;
}
});
await app.StartAsync();
string address = app.Services.GetRequiredService<IServer>().Features.Get<IServerAddressesFeature>()!.Addresses.First();
ISessionManager manager = app.Services.GetRequiredService<ISessionManager>();
GatewaySession session = await manager.OpenSessionAsync(new SessionOpenRequest(RequestedBackend: null, ClientSessionName: "ordering", ClientCorrelationId: "ordering-1", CommandTimeout: null), "client-1", ownerKeyId: null, CancellationToken.None);
using HttpClient client = new() { BaseAddress = new Uri(address), Timeout = TimeSpan.FromSeconds(10) };
using HttpResponseMessage response = await client.GetAsync(
$"/stream/{session.SessionId}",
HttpCompletionOption.ResponseHeadersRead);
await attached.Task.WaitAsync(TimeSpan.FromSeconds(5));
Stopwatch stopwatch = Stopwatch.StartNew();
await app.StopAsync();
stopwatch.Stop();
Assert.True(
stopwatch.Elapsed < TimeSpan.FromSeconds(10),
$"host stop took {stopwatch.Elapsed}; the drain did not end the open stream before Kestrel's drain");
Assert.Equal("completed", await streamOutcome.Task.WaitAsync(TimeSpan.FromSeconds(5)));
Assert.Equal(SessionState.Closed, session.State);
Assert.Equal(1, worker.ShutdownCount);
Assert.Equal(0, worker.KillCount);
}
private static SessionManager CreateManager(
IWorkerClient worker,
GatewayMetrics metrics,
IHostApplicationLifetime lifetime)
{
GatewayOptions options = new()
{
Sessions = new ZB.MOM.WW.MxGateway.Server.Configuration.SessionOptions { DefaultCommandTimeoutSeconds = 30, MaxSessions = 4 },
Worker = new WorkerOptions { StartupTimeoutSeconds = 30, ShutdownTimeoutSeconds = 10 },
};
return new SessionManager(
new SessionRegistry(),
new SingleWorkerClientFactory(worker),
Options.Create(options),
metrics,
applicationLifetime: lifetime);
}
private sealed class SingleWorkerClientFactory(IWorkerClient worker) : ISessionWorkerClientFactory
{
/// <inheritdoc />
public Task<IWorkerClient> CreateAsync(GatewaySession session, CancellationToken cancellationToken)
=> Task.FromResult(worker);
}
/// <summary>
/// Worker client whose event stream stays open until it is shut down or killed, like a real
/// worker's: so a subscriber only ends when the session is torn down.
/// </summary>
private sealed class StreamingWorkerClient : IWorkerClient
{
private readonly Channel<WorkerEvent> _events = Channel.CreateUnbounded<WorkerEvent>();
private readonly TaskCompletionSource _shutdownCalled = new(TaskCreationOptions.RunContinuationsAsynchronously);
private int _shutdownCount;
private int _killCount;
private volatile WorkerClientState _state = WorkerClientState.Ready;
/// <inheritdoc />
public string SessionId => "session-ordering";
/// <inheritdoc />
public int? ProcessId => 4242;
/// <inheritdoc />
public WorkerClientState State => _state;
/// <inheritdoc />
public DateTimeOffset LastHeartbeatAt => DateTimeOffset.UtcNow;
/// <summary>Gets a task that completes when a graceful shutdown was requested.</summary>
public Task ShutdownCalled => _shutdownCalled.Task;
/// <summary>Gets the number of graceful shutdowns.</summary>
public int ShutdownCount => Volatile.Read(ref _shutdownCount);
/// <summary>Gets the number of kills.</summary>
public int KillCount => Volatile.Read(ref _killCount);
/// <inheritdoc />
public Task StartAsync(CancellationToken cancellationToken) => Task.CompletedTask;
/// <inheritdoc />
public Task<WorkerCommandReply> InvokeAsync(WorkerCommand command, TimeSpan timeout, CancellationToken cancellationToken)
=> Task.FromResult(new WorkerCommandReply());
/// <inheritdoc />
public async IAsyncEnumerable<WorkerEvent> ReadEventsAsync([EnumeratorCancellation] CancellationToken cancellationToken)
{
await foreach (WorkerEvent workerEvent in _events.Reader.ReadAllAsync(cancellationToken).ConfigureAwait(false))
{
yield return workerEvent;
}
}
/// <inheritdoc />
public Task ShutdownAsync(TimeSpan timeout, CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();
Interlocked.Increment(ref _shutdownCount);
_state = WorkerClientState.Closed;
_events.Writer.TryComplete();
_shutdownCalled.TrySetResult();
return Task.CompletedTask;
}
/// <inheritdoc />
public void Kill(string reason)
{
Interlocked.Increment(ref _killCount);
_state = WorkerClientState.Faulted;
_events.Writer.TryComplete();
}
/// <inheritdoc />
public ValueTask DisposeAsync() => ValueTask.CompletedTask;
}
private sealed class ApplicationLifetimeStub : IHostApplicationLifetime
{
private readonly CancellationTokenSource _stopping = new();
/// <inheritdoc />
public CancellationToken ApplicationStarted => CancellationToken.None;
/// <inheritdoc />
public CancellationToken ApplicationStopping => _stopping.Token;
/// <inheritdoc />
public CancellationToken ApplicationStopped => CancellationToken.None;
/// <summary>Fires <see cref="ApplicationStopping"/>.</summary>
public void SignalStopping() => _stopping.Cancel();
/// <inheritdoc />
public void StopApplication() => SignalStopping();
}
}
@@ -124,6 +124,63 @@ public sealed class SessionWorkerClientFactoryFakeWorkerTests : IAsyncLifetime
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>
/// 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
@@ -391,6 +448,35 @@ public sealed class SessionWorkerClientFactoryFakeWorkerTests : IAsyncLifetime
}
}
/// <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 : 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);
return Task.FromResult(CreateHandle(Process));
}
}
private static WorkerProcessHandle CreateHandle(IWorkerProcess process)
{
return new WorkerProcessHandle(
@@ -98,5 +98,11 @@ public sealed class OrphanWorkerCleanupHostedServiceTests
}
public void Kill(int processId) => Killed.Add(processId);
public bool TryGetRunningProcess(int processId, out DateTimeOffset? startedAt)
{
startedAt = null;
return false;
}
}
}
@@ -8,8 +8,9 @@ namespace ZB.MOM.WW.MxGateway.Tests.Gateway.Workers;
/// <summary>
/// Per <c>gateway.md</c> the gateway must terminate
/// orphaned worker processes on startup. These tests pin that the terminator
/// kills leftover workers (matched by executable path, or by image name when
/// the path is unreadable) without touching unrelated processes or itself.
/// kills leftover workers (matched by executable path, or confirmed by a command line
/// whose pipe name names a gateway that is gone) without touching unrelated processes,
/// another live gateway's workers, or itself.
/// </summary>
public sealed class OrphanWorkerTerminatorTests
{
@@ -44,13 +45,13 @@ public sealed class OrphanWorkerTerminatorTests
Assert.Equal([101, 102], inspector.KilledProcessIds.Order());
}
/// <summary>Verifies that orphan workers are killed when executable path is unreadable but image name matches.</summary>
/// <summary>
/// WRK-009: with neither the path nor the command line readable, an image-name match alone is
/// not enough to kill — it could be a same-named worker from another build.
/// </summary>
[Fact]
public void TerminateOrphans_KillsImageNameMatchWhenExecutablePathUnreadable()
public void TerminateOrphans_LeavesImageNameMatchAloneWhenPathAndCommandLineUnreadable()
{
// The x64 gateway cannot introspect the x86 worker's main module, so the
// path comes back null. Image-name match is the only signal — and it is
// exactly the orphan worker case, so the process must still be killed.
FakeProcessInspector inspector = new(
[
new RunningProcessInfo(201, ExecutablePath: null),
@@ -59,10 +60,106 @@ public sealed class OrphanWorkerTerminatorTests
int killed = terminator.TerminateOrphans();
Assert.Equal(1, killed);
Assert.Equal([201], inspector.KilledProcessIds);
Assert.Equal(0, killed);
Assert.Empty(inspector.KilledProcessIds);
}
/// <summary>
/// With the path unreadable, a command line whose pipe name names a gateway that is no longer
/// running confirms the orphan, and it is killed.
/// </summary>
[Fact]
public void TerminateOrphans_KillsWorkerWhoseOwningGatewayIsGone()
{
FakeProcessInspector inspector = new(
[
new RunningProcessInfo(202, ExecutablePath: null, WorkerCommandLine(ownerPid: 9001)),
]);
OrphanWorkerTerminator terminator = CreateTerminator(inspector);
int killed = terminator.TerminateOrphans();
Assert.Equal(1, killed);
Assert.Equal([202], inspector.KilledProcessIds);
}
/// <summary>
/// WRK-009: a worker whose owning gateway (from its pipe name) is still running belongs to
/// that gateway and is not killed, even when its path matches.
/// </summary>
[Fact]
public void TerminateOrphans_LeavesWorkerOfALiveGatewayAlone()
{
DateTimeOffset workerStarted = DateTimeOffset.UtcNow;
FakeProcessInspector inspector = new(
[
new RunningProcessInfo(203, WorkerExecutablePath, WorkerCommandLine(ownerPid: 9002), workerStarted),
]);
inspector.RunningProcesses[9002] = workerStarted.AddMinutes(-5);
OrphanWorkerTerminator terminator = CreateTerminator(inspector);
int killed = terminator.TerminateOrphans();
Assert.Equal(0, killed);
Assert.Empty(inspector.KilledProcessIds);
}
/// <summary>
/// An "owner" process that started after the worker is a recycled process id, not the
/// gateway that launched it, so the worker is still an orphan.
/// </summary>
[Fact]
public void TerminateOrphans_KillsWorkerWhoseOwnerPidWasRecycled()
{
DateTimeOffset workerStarted = DateTimeOffset.UtcNow.AddHours(-1);
FakeProcessInspector inspector = new(
[
new RunningProcessInfo(204, WorkerExecutablePath, WorkerCommandLine(ownerPid: 9003), workerStarted),
]);
inspector.RunningProcesses[9003] = workerStarted.AddMinutes(10);
OrphanWorkerTerminator terminator = CreateTerminator(inspector);
int killed = terminator.TerminateOrphans();
Assert.Equal(1, killed);
Assert.Equal([204], inspector.KilledProcessIds);
}
/// <summary>The owner PID parses from both the current and the older pipe-name formats, quoted or not.</summary>
/// <param name="commandLine">Worker command line.</param>
/// <param name="expected">Expected owner PID, or 0 when none should parse.</param>
[Theory]
[InlineData("Worker.exe --session-id session-x --pipe-name mxgw-1234-abcdef --protocol-version 1", 1234)]
[InlineData("\"C:\\w\\Worker.exe\" --pipe-name \"mxgw-77-abc\"", 77)]
[InlineData("Worker.exe --pipe-name mxaccess-gateway-555-session-1", 555)]
[InlineData("Worker.exe --pipe-name other-555-session-1", 0)]
[InlineData("Worker.exe --session-id x", 0)]
[InlineData("", 0)]
public void TryParseOwnerGatewayProcessId_ParsesPipeName(string commandLine, int expected)
{
bool parsed = OrphanWorkerTerminator.TryParseOwnerGatewayProcessId(commandLine, out int ownerProcessId);
Assert.Equal(expected != 0, parsed);
Assert.Equal(expected, ownerProcessId);
}
/// <summary>
/// On Windows the system inspector reads a live process's command line (the cross-bitness
/// NtQueryInformationProcess path orphan cleanup depends on).
/// </summary>
[ZB.MOM.WW.MxGateway.Tests.Gateway.Sessions.WindowsFact]
public void SystemInspector_ReadsCurrentProcessCommandLine()
{
string? commandLine = SystemRunningProcessInspector.TryGetCommandLine(Environment.ProcessId);
Assert.False(string.IsNullOrEmpty(commandLine));
Assert.True(new SystemRunningProcessInspector().TryGetRunningProcess(Environment.ProcessId, out DateTimeOffset? startedAt));
Assert.NotNull(startedAt);
}
private static string WorkerCommandLine(int ownerPid)
=> $"\"{WorkerExecutablePath}\" --session-id session-1 --pipe-name mxgw-{ownerPid}-0123456789abcdef --protocol-version 1";
/// <summary>Verifies that unrelated processes with the same image name are not killed.</summary>
[Fact]
public void TerminateOrphans_DoesNotKillUnrelatedProcessSharingImageName()
@@ -147,6 +244,9 @@ public sealed class OrphanWorkerTerminatorTests
/// <inheritdoc />
public IReadOnlyList<RunningProcessInfo> GetProcessesByName(string processName) => processes;
/// <summary>Gets the processes reported as running, by id, with their start times.</summary>
public Dictionary<int, DateTimeOffset?> RunningProcesses { get; } = [];
/// <inheritdoc />
public void Kill(int processId)
{
@@ -157,5 +257,9 @@ public sealed class OrphanWorkerTerminatorTests
KilledProcessIds.Add(processId);
}
/// <inheritdoc />
public bool TryGetRunningProcess(int processId, out DateTimeOffset? startedAt)
=> RunningProcesses.TryGetValue(processId, out startedAt);
}
}
@@ -1152,6 +1152,197 @@ public sealed class WorkerClientTests
Assert.Equal(WorkerClientState.Faulted, client.State);
}
/// <summary>
/// WRK-001: a client that keeps issuing commands against a silent worker, each abandoned
/// before it reaches the stuck ceiling (here by caller cancellation; a command timeout
/// removes the entry the same way), must not hold the in-flight-command skip open forever.
/// Once the heartbeat itself is older than the ceiling the watchdog faults.
/// </summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[Fact]
public async Task HeartbeatMonitor_WhenYoungCommandsKeepArrivingPastStuckCeiling_FaultsClient()
{
TickObservingTimeProvider clock = new() { WatchedDueTime = TimeSpan.FromSeconds(1) };
clock.SetUtcNow(DateTimeOffset.Parse("2026-05-20T15:00:00Z", System.Globalization.CultureInfo.InvariantCulture));
await using PipePair pipePair = await PipePair.CreateAsync();
await using WorkerClient client = CreateClient(
pipePair,
new WorkerClientOptions
{
HeartbeatGrace = TimeSpan.FromSeconds(15),
HeartbeatCheckInterval = TimeSpan.FromSeconds(1),
EventChannelCapacity = 8,
HeartbeatStuckCeiling = TimeSpan.FromSeconds(30),
},
timeProvider: clock);
await CompleteHandshakeAsync(client, pipePair);
CancellationTokenSource? previousCaller = null;
Task<WorkerCommandReply>? previousInvoke = null;
for (int round = 0; round < 6 && client.State == WorkerClientState.Ready; round++)
{
CancellationTokenSource caller = new();
Task<WorkerCommandReply> invoke = client.InvokeAsync(
CreateCommand(MxCommandKind.Ping),
TestTimeout,
caller.Token);
await pipePair.WorkerReader.ReadAsync().AsTask().WaitAsync(TestTimeout);
// Abandon the older command so the oldest pending one is never more than 10 s old.
if (previousCaller is not null)
{
await previousCaller.CancelAsync();
await Assert.ThrowsAnyAsync<Exception>(async () => await previousInvoke!.WaitAsync(TestTimeout));
previousCaller.Dispose();
await pipePair.WorkerReader.ReadAsync().AsTask().WaitAsync(TestTimeout);
}
previousCaller = caller;
previousInvoke = invoke;
for (int i = 0; i < 10 && client.State == WorkerClientState.Ready; i++)
{
await clock.AdvanceAndAwaitTickAsync(TimeSpan.FromSeconds(1), TestTimeout);
}
}
await WaitUntilAsync(() => client.State == WorkerClientState.Faulted, TestTimeout);
Assert.Equal(WorkerClientState.Faulted, client.State);
previousCaller?.Dispose();
}
/// <summary>
/// WRK-005: heartbeat staleness is measured on the monotonic clock, so a forward step of the
/// wall clock larger than the grace does not fault a worker whose heartbeat is current.
/// </summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[Fact]
public async Task HeartbeatMonitor_WhenWallClockStepsForward_DoesNotFault()
{
TickObservingTimeProvider clock = new() { WatchedDueTime = TimeSpan.FromSeconds(1) };
clock.SetUtcNow(DateTimeOffset.Parse("2026-05-20T16:00:00Z", System.Globalization.CultureInfo.InvariantCulture));
await using PipePair pipePair = await PipePair.CreateAsync();
await using WorkerClient client = CreateClient(
pipePair,
new WorkerClientOptions
{
HeartbeatGrace = TimeSpan.FromSeconds(15),
HeartbeatCheckInterval = TimeSpan.FromSeconds(1),
EventChannelCapacity = 8,
},
timeProvider: clock);
await CompleteHandshakeAsync(client, pipePair);
// The wall clock steps 60 s forward; the monotonic clock moves only 1 s.
clock.MonotonicLag = TimeSpan.FromSeconds(59);
await clock.AdvanceAndAwaitTickAsync(TimeSpan.FromSeconds(60), TestTimeout);
for (int i = 0; i < 3; i++)
{
await clock.AdvanceAndAwaitTickAsync(TimeSpan.FromSeconds(1), TestTimeout);
}
Assert.Equal(WorkerClientState.Ready, client.State);
}
/// <summary>
/// WRK-003: the command deadline covers the outbound enqueue. With the write loop parked in a
/// pipe write and the outbound channel full, a caller with no token of its own still gets
/// <see cref="WorkerClientErrorCode.CommandTimeout"/> after its timeout instead of waiting
/// indefinitely.
/// </summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[Fact]
public async Task InvokeAsync_WhenOutboundQueueIsFull_TimesOutWithinTheCommandTimeout()
{
await using PipePair pipePair = await PipePair.CreateAsync();
await using StallableWriteStream gatewayStream = new(pipePair.GatewayStream);
WorkerClientOptions options = new()
{
MaxPendingCommands = 1,
HeartbeatGrace = TimeSpan.FromSeconds(30),
HeartbeatCheckInterval = TimeSpan.FromSeconds(30),
};
await using WorkerClient client = CreateClient(pipePair, options, gatewayStream: gatewayStream);
await CompleteHandshakeAsync(client, pipePair);
gatewayStream.StallWrites();
// Same fill as the shutdown test: three abandoned commands leave the write loop parked on
// the first and the five-envelope channel full behind it.
for (int round = 0; round < 3; round++)
{
using CancellationTokenSource callerCts = new();
Task<WorkerCommandReply> invokeTask = client.InvokeAsync(
CreateCommand(MxCommandKind.Advise),
TestTimeout,
callerCts.Token);
if (round == 0)
{
await gatewayStream.FirstStalledWrite.WaitAsync(TestTimeout);
}
await callerCts.CancelAsync();
await Assert.ThrowsAnyAsync<OperationCanceledException>(
async () => await invokeTask.WaitAsync(TestTimeout));
}
TimeSpan commandTimeout = TimeSpan.FromMilliseconds(300);
WorkerClientException exception = await Assert.ThrowsAsync<WorkerClientException>(
async () => await client.InvokeAsync(CreateCommand(MxCommandKind.Ping), commandTimeout, CancellationToken.None)
.WaitAsync(TestTimeout));
Assert.Equal(WorkerClientErrorCode.CommandTimeout, exception.ErrorCode);
Assert.Equal(WorkerClientState.Ready, client.State);
// The slot was released: the next command is admitted (and times out the same way)
// rather than refused with PendingCommandLimitExceeded.
WorkerClientException second = await Assert.ThrowsAsync<WorkerClientException>(
async () => await client.InvokeAsync(CreateCommand(MxCommandKind.Ping), commandTimeout, CancellationToken.None)
.WaitAsync(TestTimeout));
Assert.Equal(WorkerClientErrorCode.CommandTimeout, second.ErrorCode);
}
/// <summary>
/// WRK-004: when a reply lands right at the deadline, the caller's outcome agrees with the
/// metrics — every command counted as succeeded returned its reply, never a timeout. Runs
/// the race many times; before the fix a reply that won the removal still surfaced as
/// <see cref="WorkerClientErrorCode.CommandTimeout"/>.
/// </summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[Fact]
public async Task InvokeAsync_WhenReplyRacesTheDeadline_OutcomeMatchesTheSucceededMetric()
{
using GatewayMetrics metrics = new();
await using PipePair pipePair = await PipePair.CreateAsync();
await using WorkerClient client = CreateClient(pipePair, metrics: metrics);
await CompleteHandshakeAsync(client, pipePair);
int returnedReplies = 0;
TimeSpan commandTimeout = TimeSpan.FromMilliseconds(15);
for (int i = 0; i < 60; i++)
{
Task<WorkerCommandReply> invoke = client.InvokeAsync(
CreateCommand(MxCommandKind.Ping),
commandTimeout,
CancellationToken.None);
WorkerEnvelope command = await pipePair.WorkerReader.ReadAsync().AsTask().WaitAsync(TestTimeout);
await Task.Delay(commandTimeout - TimeSpan.FromMilliseconds(i % 4));
await pipePair.WriteAsync(CreateCommandReplyEnvelope(command.CorrelationId, MxCommandKind.Ping));
try
{
await invoke.WaitAsync(TestTimeout);
returnedReplies++;
}
catch (WorkerClientException exception) when (exception.ErrorCode == WorkerClientErrorCode.CommandTimeout)
{
// The timeout won: the abandonment forwards a WorkerCancel; drain it.
WorkerEnvelope cancel = await pipePair.WorkerReader.ReadAsync().AsTask().WaitAsync(TestTimeout);
Assert.Equal(WorkerEnvelope.BodyOneofCase.WorkerCancel, cancel.BodyCase);
}
}
Assert.Equal(metrics.GetSnapshot().CommandsSucceeded, returnedReplies);
}
/// <summary>
/// A transient burst that exceeds
/// <see cref="WorkerClientOptions.EventChannelCapacity"/> must be
@@ -186,6 +186,11 @@ public sealed class WorkerProcessLauncherTests
Assert.Equal(
"30000",
processFactory.LastStartInfo.Environment[WorkerLaunchEnvironment.HeartbeatGraceMilliseconds]);
// WIP-009: the worker bounds its own startup handshake with the gateway's startup budget.
Assert.Equal(
"30000",
processFactory.LastStartInfo.Environment[WorkerLaunchEnvironment.StartupTimeoutMilliseconds]);
}
/// <summary>Verifies that a failed startup probe kills and disposes the worker process.</summary>
@@ -216,6 +221,35 @@ public sealed class WorkerProcessLauncherTests
Assert.Equal(1, metrics.GetSnapshot().WorkerKills);
}
/// <summary>
/// WRK-006: a <c>Kill</c> that throws during launch-failure cleanup is logged, not thrown, so
/// the caller still gets the launch error code and the process is still disposed.
/// </summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[Fact]
public async Task LaunchAsync_WhenCleanupKillThrows_StillThrowsLaunchErrorAndDisposes()
{
using TestDirectory directory = TestDirectory.Create();
string executablePath = directory.CreateWorkerExecutable(machine: 0x014c);
FakeWorkerProcess process = new(processId: 1234)
{
KillException = new System.ComponentModel.Win32Exception(5, "Access is denied."),
};
GatewayMetrics metrics = new();
WorkerProcessLauncher launcher = CreateLauncher(
executablePath,
new FakeWorkerProcessFactory(process),
new FailingStartupProbe(),
metrics);
WorkerProcessLaunchException exception =
await Assert.ThrowsAsync<WorkerProcessLaunchException>(
async () => await launcher.LaunchAsync(CreateRequest()));
Assert.Equal(WorkerProcessLaunchErrorCode.StartupFailed, exception.ErrorCode);
Assert.True(process.DisposeCalled);
}
/// <summary>Verifies that a startup probe timeout kills and disposes the worker process.</summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[Fact]
@@ -57,11 +57,19 @@ public sealed class FakeWorkerProcess(int processId) : IWorkerProcess
/// <inheritdoc />
public void Kill(bool entireProcessTree)
{
if (KillException is not null)
{
throw KillException;
}
KillCount++;
KillEntireProcessTree = entireProcessTree;
MarkExited(-1);
}
/// <summary>Gets or sets an exception <see cref="Kill"/> throws instead of killing, as <c>Process.Kill</c> can for a process that is mid-termination.</summary>
public Exception? KillException { get; set; }
/// <summary>Marks this fake as disposed so tests can assert <see cref="Dispose"/> was called.</summary>
public void Dispose() => IsDisposed = true;
@@ -13,9 +13,27 @@ public sealed class TickObservingTimeProvider : FakeTimeProvider
private long _watchedTimersCreated;
private long _watchedTimersConsumed;
private long _timestampReads;
/// <summary>Gets the number of times <see cref="GetUtcNow"/> has been read.</summary>
public long UtcNowReads => Interlocked.Read(ref _utcNowReads);
/// <summary>
/// Gets the number of times <see cref="GetTimestamp"/> has been read. A loop that measures
/// elapsed time on the monotonic clock (<see cref="TimeProvider.GetElapsedTime(long)"/>)
/// evaluates its condition through this read rather than through <see cref="GetUtcNow"/>.
/// </summary>
public long TimestampReads => Interlocked.Read(ref _timestampReads);
/// <summary>
/// Gets or sets how far the monotonic timestamp (<see cref="GetTimestamp"/>) lags the wall
/// clock. Raising it right before an <see cref="FakeTimeProvider.Advance"/> of the same size
/// models a host wall-clock step: <see cref="GetUtcNow"/> and the timers jump, the
/// monotonic clock does not. The timers run on the wall clock here, so the step is modelled
/// on the timestamp side.
/// </summary>
public TimeSpan MonotonicLag { get; set; }
/// <inheritdoc />
public override DateTimeOffset GetUtcNow()
{
@@ -23,6 +41,13 @@ public sealed class TickObservingTimeProvider : FakeTimeProvider
return base.GetUtcNow();
}
/// <inheritdoc />
public override long GetTimestamp()
{
Interlocked.Increment(ref _timestampReads);
return base.GetTimestamp() - (long)(MonotonicLag.TotalSeconds * TimestampFrequency);
}
/// <summary>
/// Gets or sets the due time of the timer the loop under test re-arms each iteration
/// (for <c>Task.Delay(interval, timeProvider, ct)</c> this is the interval). When set,
@@ -66,8 +91,9 @@ public sealed class TickObservingTimeProvider : FakeTimeProvider
}
/// <summary>
/// Advances the clock and waits until a consumer has read <see cref="GetUtcNow"/> again,
/// which proves the awakened loop evaluated its condition against the advanced time.
/// Advances the clock and waits until a consumer has read <see cref="GetUtcNow"/> or
/// <see cref="GetTimestamp"/> again, which proves the awakened loop evaluated its condition
/// against the advanced time.
/// </summary>
/// <param name="delta">Amount to advance.</param>
/// <param name="timeout">Real-time bound on the wait.</param>
@@ -86,9 +112,9 @@ public sealed class TickObservingTimeProvider : FakeTimeProvider
Interlocked.Increment(ref _watchedTimersConsumed);
}
long before = UtcNowReads;
long before = UtcNowReads + TimestampReads;
Advance(delta);
while (UtcNowReads == before)
while (UtcNowReads + TimestampReads == before)
{
await Task.Yield();
cts.Token.ThrowIfCancellationRequested();
@@ -1273,6 +1273,122 @@ public sealed class WorkerPipeSessionTests
await SendShutdownAndWaitAsync(pipePair, runTask, cancellation.Token);
}
/// <summary>
/// WIP-007: a graceful shutdown whose STA cleanup outlasts <c>HeartbeatGrace</c> must not be
/// reported as <c>StaHung</c>. The watchdog stands down once the shutdown has begun, and the
/// shutdown still ends with an OK <c>WorkerShutdownAck</c>.
/// </summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[Fact]
public async Task RunAsync_WhenShutdownCleanupOutlastsHeartbeatGrace_DoesNotWriteWatchdogFault()
{
using CancellationTokenSource cancellation = new(TimeSpan.FromSeconds(10));
using PipePair pipePair = await PipePair.CreateAsync(cancellation.Token);
FakeRuntimeSession runtime = new() { ShutdownDuration = TimeSpan.FromMilliseconds(500) };
WorkerPipeSession session = CreatePipeSession(
pipePair.WorkerStream,
runtime,
new WorkerPipeSessionOptions
{
HeartbeatInterval = TimeSpan.FromMilliseconds(20),
HeartbeatGrace = TimeSpan.FromMilliseconds(100),
});
Task runTask = session.RunAsync(cancellation.Token);
await CompleteGatewayHandshakeAsync(pipePair, cancellation.Token);
await pipePair.GatewayWriter.WriteAsync(CreateShutdownEnvelope(), cancellation.Token);
WorkerEnvelope envelope;
do
{
envelope = await pipePair.GatewayReader.ReadAsync(cancellation.Token);
Assert.NotEqual(WorkerEnvelope.BodyOneofCase.WorkerFault, envelope.BodyCase);
}
while (envelope.BodyCase != WorkerEnvelope.BodyOneofCase.WorkerShutdownAck);
Assert.Equal(ProtocolStatusCode.Ok, envelope.WorkerShutdownAck.Status.Code);
Task completedTask = await Task.WhenAny(runTask, Task.Delay(TimeSpan.FromSeconds(5), cancellation.Token));
Assert.Same(runTask, completedTask);
await runTask;
}
/// <summary>
/// WIP-009: a peer that connects and never sends <c>GatewayHello</c> does not hold the worker
/// forever; the handshake fails with a <see cref="TimeoutException"/> at its deadline.
/// </summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[Fact]
public async Task CompleteStartupHandshakeAsync_WhenGatewayNeverSendsHello_TimesOut()
{
WorkerFrameProtocolOptions options = CreateOptions();
using NeverReadingStream inbound = new();
using MemoryStream outbound = new();
WorkerPipeSession session = new(
new WorkerFrameReader(inbound, options),
new WorkerFrameWriter(outbound, options),
options,
() => 1234,
new WorkerPipeSessionOptions { StartupHandshakeTimeout = TimeSpan.FromMilliseconds(200) },
() => new FakeRuntimeSession());
bool initialized = false;
Task handshake = session.CompleteStartupHandshakeAsync(
_ =>
{
initialized = true;
return Task.CompletedTask;
});
Task completed = await Task.WhenAny(handshake, Task.Delay(TimeSpan.FromSeconds(5)));
Assert.Same(handshake, completed);
await Assert.ThrowsAsync<TimeoutException>(async () => await handshake);
Assert.False(initialized);
}
/// <summary>
/// WIP-009: MXAccess initialization that hangs (as a COM activation can, with the gateway
/// gone and no pipe read outstanding to notice) is bounded by the same startup deadline.
/// </summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[Fact]
public async Task CompleteStartupHandshakeAsync_WhenInitializationHangs_TimesOut()
{
WorkerFrameProtocolOptions options = CreateOptions();
using MemoryStream inbound = new();
await new WorkerFrameWriter(inbound, options).WriteAsync(CreateGatewayHelloEnvelope());
inbound.Position = 0;
using MemoryStream outbound = new();
WorkerPipeSession session = new(
new WorkerFrameReader(inbound, options),
new WorkerFrameWriter(outbound, options),
options,
() => 1234,
new WorkerPipeSessionOptions { StartupHandshakeTimeout = TimeSpan.FromMilliseconds(200) },
() => new FakeRuntimeSession());
TaskCompletionSource<bool> never = new();
Task handshake = session.CompleteStartupHandshakeAsync(_ => never.Task);
Task completed = await Task.WhenAny(handshake, Task.Delay(TimeSpan.FromSeconds(5)));
Assert.Same(handshake, completed);
await Assert.ThrowsAsync<TimeoutException>(async () => await handshake);
WorkerEnvelope[] written = ReadWrittenFrames(outbound, options);
Assert.Equal(WorkerEnvelope.BodyOneofCase.WorkerHello, written[0].BodyCase);
Assert.DoesNotContain(written, envelope => envelope.BodyCase == WorkerEnvelope.BodyOneofCase.WorkerReady);
}
/// <summary>The startup deadline is conveyed by the launcher's environment.</summary>
[Fact]
public void FromEnvironment_ReadsStartupHandshakeTimeout()
{
WorkerPipeSessionOptions conveyed = WorkerPipeSessionOptions.FromEnvironment(
name => name == WorkerLaunchEnvironment.StartupTimeoutMilliseconds ? "45000" : null);
WorkerPipeSessionOptions missing = WorkerPipeSessionOptions.FromEnvironment(_ => null);
Assert.Equal(TimeSpan.FromSeconds(45), conveyed.StartupHandshakeTimeout);
Assert.Equal(WorkerPipeSessionOptions.DefaultStartupHandshakeTimeout, missing.StartupHandshakeTimeout);
}
/// <summary>
/// While a command is in flight (snapshot's current command
/// correlation id is non-empty), stale STA activity must NOT trigger
@@ -2794,6 +2910,45 @@ public sealed class WorkerPipeSessionTests
// that batch before the flush runs. Neither "I read the frames" nor any fixed sleep is evidence
// that a flush has been counted; WaitForAllWritesFlushedAsync is the explicit edge a test must
// take before sampling the counters.
/// <summary>A readable stream whose reads never complete, as a connected but silent peer's pipe.</summary>
private sealed class NeverReadingStream : Stream
{
private readonly TaskCompletionSource<int> _never = new();
public override bool CanRead => true;
public override bool CanSeek => false;
public override bool CanWrite => false;
public override long Length => throw new NotSupportedException();
public override long Position
{
get => throw new NotSupportedException();
set => throw new NotSupportedException();
}
public override void Flush()
{
}
public override int Read(byte[] buffer, int offset, int count)
{
_never.Task.Wait();
return 0;
}
public override Task<int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
=> _never.Task;
public override long Seek(long offset, SeekOrigin origin) => throw new NotSupportedException();
public override void SetLength(long value) => throw new NotSupportedException();
public override void Write(byte[] buffer, int offset, int count) => throw new NotSupportedException();
}
private sealed class FlushCountingPassthroughStream : Stream
{
private readonly Stream inner;
@@ -574,6 +574,48 @@ public sealed class MxAccessStaSessionTests
"Expected StaCallInProgress to clear once the alarm poll returned.");
}
/// <summary>
/// MXA-003: the graceful-shutdown grace covers the alarm poll join and the alarm handler
/// dispose. With the STA stuck inside a poll, ShutdownGracefullyAsync reports a
/// <see cref="TimeoutException"/> at roughly its grace period instead of waiting on the STA.
/// </summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[Fact]
public async Task ShutdownGracefullyAsync_WhenStaIsStuckInAlarmPoll_TimesOutWithinGrace()
{
FakeAlarmCommandHandler handler = new() { BlockPoll = true };
FakeMxAccessComObjectFactory factory = new();
FakeMxAccessEventSink eventSink = new();
using StaRuntime runtime = CreateRuntime();
using MxAccessStaSession session = new(
runtime,
factory,
eventSink,
new MxAccessEventQueue(),
(_eq, _affinity, _comFactory) => handler);
await session.StartAsync("session-1", workerProcessId: 1);
Assert.True(
handler.WaitForPollEntered(TimeSpan.FromSeconds(5)),
"Expected the alarm poll to start within 5 seconds.");
System.Diagnostics.Stopwatch stopwatch = System.Diagnostics.Stopwatch.StartNew();
Task<MxAccessShutdownResult> shutdown = session.ShutdownGracefullyAsync(TimeSpan.FromMilliseconds(200));
Task completed = await Task.WhenAny(shutdown, Task.Delay(TimeSpan.FromSeconds(5)));
stopwatch.Stop();
try
{
Assert.Same(shutdown, completed);
await Assert.ThrowsAsync<TimeoutException>(async () => await shutdown);
Assert.True(stopwatch.Elapsed < TimeSpan.FromSeconds(3), $"shutdown took {stopwatch.Elapsed}");
}
finally
{
handler.BlockPoll = false;
handler.ReleasePoll();
}
}
/// <summary>
/// A transient PollOnce failure must not fault the whole session: with a
/// failure threshold of 3, a poll pattern that never fails three times in
@@ -64,6 +64,13 @@ internal sealed class FakeRuntimeSession : IWorkerRuntimeSession
/// <summary>Gets or sets whether ShutdownGracefullyAsync throws a TimeoutException.</summary>
public bool ThrowTimeoutOnShutdown { get; set; }
/// <summary>
/// Gets or sets how long a graceful shutdown takes. While it runs, the heartbeat snapshot
/// reports STA activity frozen at the moment the shutdown began, the way one long STA
/// cleanup work item leaves it in production.
/// </summary>
public TimeSpan ShutdownDuration { get; set; }
/// <summary>
/// Optional diagnostic message stuffed into every dispatched command reply. A long value
/// pushes the STA command reply past a small negotiated frame maximum, which is how a test
@@ -519,9 +526,26 @@ internal sealed class FakeRuntimeSession : IWorkerRuntimeSession
new TimeoutException("Simulated graceful shutdown timeout."));
}
if (ShutdownDuration > TimeSpan.Zero)
{
return SlowShutdownAsync();
}
return Task.FromResult(new MxAccessShutdownResult(Array.Empty<MxAccessShutdownFailure>()));
}
private async Task<MxAccessShutdownResult> SlowShutdownAsync()
{
SetSnapshot(new WorkerRuntimeHeartbeatSnapshot(
DateTimeOffset.UtcNow - TimeSpan.FromSeconds(10),
pendingCommandCount: 0,
outboundEventQueueDepth: 0,
lastEventSequence: 0,
currentCommandCorrelationId: string.Empty));
await Task.Delay(ShutdownDuration).ConfigureAwait(false);
return new MxAccessShutdownResult(Array.Empty<MxAccessShutdownFailure>());
}
/// <summary>Releases a blocked dispatch.</summary>
public void ReleaseDispatch()
{
@@ -346,15 +346,32 @@ public sealed class WorkerPipeSession
throw new ArgumentNullException(nameof(initializeMxAccessAsync));
}
// One deadline over the hello read and MXAccess initialization (WIP-009). Neither observes
// gateway death on its own: net48 pipe reads ignore the token, so a peer that connects and
// never sends parks the read forever, and no read is outstanding while initialization
// runs, so a COM activation that hangs after the gateway died keeps this worker alive. The
// abandoned step is left running; the caller exits the process (the STA is a background
// thread), which is the only way to end either.
Stopwatch handshakeClock = Stopwatch.StartNew();
try
{
WorkerEnvelope envelope = await _reader.ReadAsync(cancellationToken).ConfigureAwait(false);
WorkerEnvelope envelope = await WithinStartupDeadlineAsync(
_reader.ReadAsync(cancellationToken),
handshakeClock,
"GatewayHello",
cancellationToken)
.ConfigureAwait(false);
_state = WorkerState.Handshaking;
ValidateGatewayHello(envelope);
await WriteWorkerHelloAsync(cancellationToken).ConfigureAwait(false);
_state = WorkerState.InitializingSta;
WorkerReady ready = await initializeMxAccessAsync(cancellationToken).ConfigureAwait(false);
WorkerReady ready = await WithinStartupDeadlineAsync(
initializeMxAccessAsync(cancellationToken),
handshakeClock,
"MXAccess initialization",
cancellationToken)
.ConfigureAwait(false);
if (MxStatusProxyRecordInfoPin.Status is { } pinStatus)
{
_logger?.Information(
@@ -386,6 +403,35 @@ public sealed class WorkerPipeSession
}
}
private async Task<T> WithinStartupDeadlineAsync<T>(
Task<T> step,
Stopwatch handshakeClock,
string stepName,
CancellationToken cancellationToken)
{
if (!step.IsCompleted)
{
TimeSpan remaining = _sessionOptions.StartupHandshakeTimeout - handshakeClock.Elapsed;
Task completed = remaining > TimeSpan.Zero
? await Task.WhenAny(step, Task.Delay(remaining, cancellationToken)).ConfigureAwait(false)
: Task.CompletedTask;
if (completed != step)
{
cancellationToken.ThrowIfCancellationRequested();
_ = step.ContinueWith(
static abandoned => _ = abandoned.Exception,
CancellationToken.None,
TaskContinuationOptions.OnlyOnFaulted | TaskContinuationOptions.ExecuteSynchronously,
TaskScheduler.Default);
throw new TimeoutException(
$"Worker startup handshake did not complete within {_sessionOptions.StartupHandshakeTimeout} "
+ $"(waiting for {stepName}); the gateway is gone or stopped responding.");
}
}
return await step.ConfigureAwait(false);
}
private void ValidateGatewayHello(WorkerEnvelope envelope)
{
if (envelope.BodyCase != WorkerEnvelope.BodyOneofCase.GatewayHello)
@@ -1521,6 +1567,16 @@ public sealed class WorkerPipeSession
WorkerRuntimeHeartbeatSnapshot snapshot,
CancellationToken cancellationToken)
{
// A graceful shutdown runs its cleanup as one STA work item, which leaves LastActivityUtc
// frozen with no command correlation advertised. With a grace longer than HeartbeatGrace
// the watchdog would overwrite ShuttingDown with Faulted and report StaHung for a session
// that is closing cleanly (WIP-007). The shutdown has its own bound (its timeout raises the
// shutdown-timeout fault), so the watchdog stands down once it has begun.
if (_state is WorkerState.ShuttingDown or WorkerState.Stopped)
{
return;
}
TimeSpan staleFor = DateTimeOffset.UtcNow - snapshot.LastStaActivityUtc;
if (staleFor <= _sessionOptions.HeartbeatGrace)
{
@@ -20,12 +20,20 @@ public sealed class WorkerPipeSessionOptions
/// </summary>
public static readonly TimeSpan DefaultHeartbeatStuckCeiling = TimeSpan.FromSeconds(75);
/// <summary>
/// Default startup-handshake deadline (120 seconds), used when the launcher did not convey
/// one (<see cref="WorkerLaunchEnvironment.StartupTimeoutMilliseconds"/>). Generous so it
/// never undercuts a gateway's own startup timeout.
/// </summary>
public static readonly TimeSpan DefaultStartupHandshakeTimeout = TimeSpan.FromSeconds(120);
/// <summary>Initializes a new instance of the WorkerPipeSessionOptions class with default values.</summary>
public WorkerPipeSessionOptions()
{
HeartbeatInterval = DefaultHeartbeatInterval;
HeartbeatGrace = DefaultHeartbeatGrace;
HeartbeatStuckCeiling = DefaultHeartbeatStuckCeiling;
StartupHandshakeTimeout = DefaultStartupHandshakeTimeout;
}
/// <summary>
@@ -54,6 +62,11 @@ public sealed class WorkerPipeSessionOptions
options.HeartbeatInterval = interval;
}
if (TryReadPositiveMilliseconds(lookup, WorkerLaunchEnvironment.StartupTimeoutMilliseconds, out TimeSpan startupTimeout))
{
options.StartupHandshakeTimeout = startupTimeout;
}
TimeSpan grace = options.HeartbeatGrace;
bool haveGrace = TryReadPositiveMilliseconds(lookup, WorkerLaunchEnvironment.HeartbeatGraceMilliseconds, out TimeSpan configuredGrace);
if (haveGrace)
@@ -123,6 +136,16 @@ public sealed class WorkerPipeSessionOptions
/// </summary>
public TimeSpan HeartbeatStuckCeiling { get; set; }
/// <summary>
/// Gets or sets the deadline for the startup handshake: reading the <c>GatewayHello</c> and
/// initializing MXAccess. Gateway death is otherwise noticed only through a pipe read
/// returning end-of-stream or a failed write, and the handshake has two windows with
/// neither: a peer that connects and never sends (net48 pipe reads ignore the token), and
/// MXAccess initialization, during which no read is outstanding. A hung COM activation with
/// the gateway gone would otherwise keep the x86 worker alive indefinitely.
/// </summary>
public TimeSpan StartupHandshakeTimeout { get; set; }
/// <summary>Validates the session options.</summary>
public void Validate()
{
@@ -140,6 +163,13 @@ public sealed class WorkerPipeSessionOptions
"Worker heartbeat grace must be greater than zero.");
}
if (StartupHandshakeTimeout <= TimeSpan.Zero)
{
throw new ArgumentOutOfRangeException(
nameof(StartupHandshakeTimeout),
"Worker startup handshake timeout must be greater than zero.");
}
if (HeartbeatStuckCeiling <= TimeSpan.Zero)
{
throw new ArgumentOutOfRangeException(
@@ -773,6 +773,15 @@ public sealed class MxAccessStaSession : IWorkerRuntimeSession
commandDispatcher?.RequestShutdown();
// The grace period covers the whole shutdown, the alarm poll join and the alarm handler
// dispose included (MXA-003). Both of those wait on the STA: the poll loop's in-flight
// PollOnce and the dispose work item cannot be cancelled once started, so with the STA stuck
// in a COM call (a hung Write, GetXmlCurrentAlarms2 or ReadBulk) an unbounded await here
// never reached the timeout below — no TimeoutException, no shutdown-timeout fault, no
// ShutdownAck — and the worker sat until the gateway killed it. A hung STA is exactly the
// case the grace period exists for.
Stopwatch stopwatch = Stopwatch.StartNew();
// Cancel the STA poll loop before disposing the alarm handler.
// The loop references the alarm handler and must be stopped first
// so that no further PollOnce calls race with disposal.
@@ -785,15 +794,9 @@ public sealed class MxAccessStaSession : IWorkerRuntimeSession
pollCtsToDispose.Cancel();
if (pollTaskToAwait is not null)
{
try
{
await pollTaskToAwait.ConfigureAwait(false);
}
catch
{
// Swallow — poll loop cancellation must not block data shutdown.
}
await AwaitWithinGraceAsync(pollTaskToAwait, timeout, stopwatch, cancellationToken).ConfigureAwait(false);
}
pollCtsToDispose.Dispose();
}
@@ -806,19 +809,14 @@ public sealed class MxAccessStaSession : IWorkerRuntimeSession
alarmCommandHandler = null;
if (alarmHandlerToDispose is not null)
{
try
{
await staRuntime.InvokeAsync(
() => alarmHandlerToDispose.Dispose(),
cancellationToken).ConfigureAwait(false);
}
catch
{
// Swallow — alarm cleanup must not block data shutdown.
}
await AwaitWithinGraceAsync(
staRuntime.InvokeAsync(() => alarmHandlerToDispose.Dispose(), cancellationToken),
timeout,
stopwatch,
cancellationToken)
.ConfigureAwait(false);
}
Stopwatch stopwatch = Stopwatch.StartNew();
MxAccessShutdownResult result;
if (session is null)
{
@@ -826,14 +824,20 @@ public sealed class MxAccessStaSession : IWorkerRuntimeSession
}
else
{
TimeSpan cleanupBudget = timeout - stopwatch.Elapsed;
if (cleanupBudget <= TimeSpan.Zero)
{
throw new TimeoutException($"MXAccess graceful shutdown exceeded {timeout}.");
}
using CancellationTokenSource shutdownCancellation =
CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
shutdownCancellation.CancelAfter(timeout);
shutdownCancellation.CancelAfter(cleanupBudget);
Task<MxAccessShutdownResult> cleanupTask = staRuntime.InvokeAsync(
() => session.ShutdownGracefully(),
shutdownCancellation.Token);
Task delayTask = Task.Delay(timeout, cancellationToken);
Task delayTask = Task.Delay(cleanupBudget, cancellationToken);
Task completedTask = await Task.WhenAny(cleanupTask, delayTask).ConfigureAwait(false);
if (completedTask != cleanupTask)
{
@@ -862,6 +866,54 @@ public sealed class MxAccessStaSession : IWorkerRuntimeSession
return result;
}
// Awaits one alarm-side shutdown step within what is left of the grace period. A step that
// fails is swallowed (alarm cleanup must not block data shutdown); a step that does not finish
// in time means the STA is stuck, so the shutdown reports the same TimeoutException the data
// cleanup would. The step is left running: the STA work item cannot be abandoned, and if the
// STA recovers it simply completes.
private static async Task AwaitWithinGraceAsync(
Task step,
TimeSpan timeout,
Stopwatch stopwatch,
CancellationToken cancellationToken)
{
TimeSpan remaining = timeout - stopwatch.Elapsed;
if (!step.IsCompleted)
{
if (remaining <= TimeSpan.Zero)
{
ObserveFault(step);
throw new TimeoutException($"MXAccess graceful shutdown exceeded {timeout}.");
}
Task completed = await Task.WhenAny(step, Task.Delay(remaining, cancellationToken)).ConfigureAwait(false);
if (completed != step)
{
ObserveFault(step);
cancellationToken.ThrowIfCancellationRequested();
throw new TimeoutException($"MXAccess graceful shutdown exceeded {timeout}.");
}
}
try
{
await step.ConfigureAwait(false);
}
catch
{
// Swallow — alarm cleanup must not block data shutdown.
}
}
private static void ObserveFault(Task step)
{
_ = step.ContinueWith(
static completed => _ = completed.Exception,
CancellationToken.None,
TaskContinuationOptions.OnlyOnFaulted | TaskContinuationOptions.ExecuteSynchronously,
TaskScheduler.Default);
}
/// <inheritdoc />
public void Dispose()
{