From 0673b0c76c3b1d3cddd5aa18b94d6994e009885f Mon Sep 17 00:00:00 2001 From: Joseph Doherty Date: Thu, 3 Dec 2026 09:46:17 -0500 Subject: [PATCH] fix(sessions): start the host session drain at ApplicationStopping, before Kestrel's drain (SES-001, #247) --- docs/Sessions.md | 8 +- .../Sessions/SessionManager.cs | 51 +++- .../Sessions/SessionShutdownHostedService.cs | 3 + .../Sessions/SessionShutdownOrderingTests.cs | 248 ++++++++++++++++++ 4 files changed, 306 insertions(+), 4 deletions(-) create mode 100644 src/ZB.MOM.WW.MxGateway.Tests/Gateway/Sessions/SessionShutdownOrderingTests.cs diff --git a/docs/Sessions.md b/docs/Sessions.md index 25e84fb6..75214ef1 100644 --- a/docs/Sessions.md +++ b/docs/Sessions.md @@ -109,7 +109,7 @@ The named pipe is created with `maxNumberOfServerInstances: 1` so a second worke ### SessionShutdownHostedService -`SessionShutdownHostedService` is an `IHostedService` whose only job is to call `ISessionManager.ShutdownAsync` from `StopAsync`. It catches `OperationCanceledException` triggered by the host shutdown timeout and logs a warning so that an over-running shutdown does not surface as an unhandled exception. +`SessionShutdownHostedService` is an `IHostedService` whose only job is to call `ISessionManager.ShutdownAsync` from `StopAsync`. The drain itself has normally already run by then: it starts at `ApplicationStopping` (see [Shutdown Coordination](#shutdown-coordination)), and `ShutdownAsync` awaits that same drain. It catches `OperationCanceledException` triggered by the host shutdown timeout and logs a warning so that an over-running shutdown does not surface as an unhandled exception. ### SessionOpenRequest @@ -354,7 +354,9 @@ Only if both the graceful shutdown and the kill fall-back fail are the original ## Shutdown Coordination -`SessionShutdownHostedService.StopAsync` calls `SessionManager.ShutdownAsync`, which closes every registered session with `GatewayShutdownReason`. Sessions are drained with the same bounded fan-out the lease sweep uses (`MaxParallelSessionCloses`), because a one-at-a-time drain of a full registry at a worst-case worker shutdown timeout each outruns any host stop-timeout and leaves the tail to the orphan killer. Each iteration catches its own exceptions — *every* exception, including from the fallback — calls `KillWorkerAsync` on an uncancellable token, and removes the session, so that neither one stuck worker nor one failing teardown can block or abort the rest of the host's drain: +The drain starts at the host's `IHostApplicationLifetime.ApplicationStopping` signal, not at `SessionShutdownHostedService.StopAsync`. `WebApplication` registers Kestrel's hosted service last, so it stops first, and Kestrel's stop waits for in-flight requests. An open `StreamEvents` call is an in-flight request that ends only when its session closes. When the drain ran from `StopAsync`, every stop with an active stream waited out the whole host shutdown timeout (30 s by default); Kestrel then aborted the streams, and the drain ran on an already-cancelled token, so every worker fell to the kill fallback with no MXAccess cleanup. Starting at `ApplicationStopping`, the drain closes the sessions while Kestrel is still draining: each close completes the subscriber channels, the streams end with `OK`, and Kestrel's drain finishes at once. The manager starts the drain exactly once (`BeginShutdown`), and `ShutdownAsync` — called by `SessionShutdownHostedService.StopAsync`, or directly by a host without a lifetime — awaits that same task. The stop token passed to `ShutdownAsync` cancels the graceful closes still in flight, which turns them into the kill fallback; it never abandons the drain. + +The drain closes every registered session with `GatewayShutdownReason`. Sessions are drained with the same bounded fan-out the lease sweep uses (`MaxParallelSessionCloses`), because a one-at-a-time drain of a full registry at a worst-case worker shutdown timeout each outruns any host stop-timeout and leaves the tail to the orphan killer. Each iteration catches its own exceptions — *every* exception, including from the fallback — calls `KillWorkerAsync` on an uncancellable token, and removes the session, so that neither one stuck worker nor one failing teardown can block or abort the rest of the host's drain: ```csharp MarkStopping(); @@ -422,7 +424,7 @@ public static IServiceCollection AddGatewaySessions(this IServiceCollection serv } ``` -The registry must be a singleton because its `ConcurrentDictionary` is the source of truth for session state across the gRPC service, the lease sweeper, the dashboard, and the shutdown hosted service. Registering `SessionShutdownHostedService` last ensures it is constructed after `ISessionManager` and therefore drains sessions during host stop. +The registry must be a singleton because its `ConcurrentDictionary` is the source of truth for session state across the gRPC service, the lease sweeper, the dashboard, and the shutdown hosted service. Registering `SessionShutdownHostedService` last ensures it is constructed after `ISessionManager` and therefore awaits the session drain during host stop. Constructing `SessionManager` is also what subscribes the drain to `ApplicationStopping`. ## Related Documentation diff --git a/src/ZB.MOM.WW.MxGateway.Server/Sessions/SessionManager.cs b/src/ZB.MOM.WW.MxGateway.Server/Sessions/SessionManager.cs index ffbc7a54..a3f6e526 100644 --- a/src/ZB.MOM.WW.MxGateway.Server/Sessions/SessionManager.cs +++ b/src/ZB.MOM.WW.MxGateway.Server/Sessions/SessionManager.cs @@ -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; + /// /// Initializes a new instance of . /// @@ -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()); } /// @@ -495,7 +507,44 @@ public sealed class SessionManager : ISessionManager } /// + /// + /// The drain itself starts once, at the host's ApplicationStopping signal when a + /// lifetime was supplied, otherwise at the first call here. This call awaits that drain; + /// firing (the host's stop deadline) cancels the + /// graceful closes still in flight, which degrades them to the kill fallback. + /// 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 diff --git a/src/ZB.MOM.WW.MxGateway.Server/Sessions/SessionShutdownHostedService.cs b/src/ZB.MOM.WW.MxGateway.Server/Sessions/SessionShutdownHostedService.cs index d02fe36c..0ae996a9 100644 --- a/src/ZB.MOM.WW.MxGateway.Server/Sessions/SessionShutdownHostedService.cs +++ b/src/ZB.MOM.WW.MxGateway.Server/Sessions/SessionShutdownHostedService.cs @@ -18,6 +18,9 @@ public sealed class SessionShutdownHostedService( /// Shuts down all gateway sessions as the host stops. /// + /// The drain normally started earlier, at ApplicationStopping (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: /// 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 diff --git a/src/ZB.MOM.WW.MxGateway.Tests/Gateway/Sessions/SessionShutdownOrderingTests.cs b/src/ZB.MOM.WW.MxGateway.Tests/Gateway/Sessions/SessionShutdownOrderingTests.cs new file mode 100644 index 00000000..47b23d2a --- /dev/null +++ b/src/ZB.MOM.WW.MxGateway.Tests/Gateway/Sessions/SessionShutdownOrderingTests.cs @@ -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; + +/// +/// SES-001: the host drain must close sessions while Kestrel is still draining, not after it. +/// WebApplication 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. +/// +public sealed class SessionShutdownOrderingTests +{ + private static readonly TimeSpan HostShutdownTimeout = TimeSpan.FromSeconds(20); + + /// + /// ApplicationStopping starts the drain by itself: the session is closed gracefully + /// before anyone calls , and the later call (made by + /// the hosted service, possibly on an already-cancelled token) awaits that same drain + /// instead of killing the worker. + /// + /// A task that represents the asynchronous operation. + [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); + } + + /// + /// 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. + /// + /// A task that represents the asynchronous operation. + [Fact] + public async Task HostStop_WithOpenEventStream_ClosesSessionGracefullyAndEndsStreamCleanly() + { + StreamingWorkerClient worker = new(); + TaskCompletionSource attached = new(TaskCreationOptions.RunContinuationsAsynchronously); + TaskCompletionSource 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(options => options.ShutdownTimeout = HostShutdownTimeout); + builder.Services.AddSingleton(provider => CreateManager( + worker, + metrics, + provider.GetRequiredService())); + builder.Services.AddHostedService(); + + 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().Features.Get()!.Addresses.First(); + ISessionManager manager = app.Services.GetRequiredService(); + 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 + { + /// + public Task CreateAsync(GatewaySession session, CancellationToken cancellationToken) + => Task.FromResult(worker); + } + + /// + /// 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. + /// + private sealed class StreamingWorkerClient : IWorkerClient + { + private readonly Channel _events = Channel.CreateUnbounded(); + private readonly TaskCompletionSource _shutdownCalled = new(TaskCreationOptions.RunContinuationsAsynchronously); + private int _shutdownCount; + private int _killCount; + private volatile WorkerClientState _state = WorkerClientState.Ready; + + /// + public string SessionId => "session-ordering"; + + /// + public int? ProcessId => 4242; + + /// + public WorkerClientState State => _state; + + /// + public DateTimeOffset LastHeartbeatAt => DateTimeOffset.UtcNow; + + /// Gets a task that completes when a graceful shutdown was requested. + public Task ShutdownCalled => _shutdownCalled.Task; + + /// Gets the number of graceful shutdowns. + public int ShutdownCount => Volatile.Read(ref _shutdownCount); + + /// Gets the number of kills. + public int KillCount => Volatile.Read(ref _killCount); + + /// + public Task StartAsync(CancellationToken cancellationToken) => Task.CompletedTask; + + /// + public Task InvokeAsync(WorkerCommand command, TimeSpan timeout, CancellationToken cancellationToken) + => Task.FromResult(new WorkerCommandReply()); + + /// + public async IAsyncEnumerable ReadEventsAsync([EnumeratorCancellation] CancellationToken cancellationToken) + { + await foreach (WorkerEvent workerEvent in _events.Reader.ReadAllAsync(cancellationToken).ConfigureAwait(false)) + { + yield return workerEvent; + } + } + + /// + public Task ShutdownAsync(TimeSpan timeout, CancellationToken cancellationToken) + { + cancellationToken.ThrowIfCancellationRequested(); + Interlocked.Increment(ref _shutdownCount); + _state = WorkerClientState.Closed; + _events.Writer.TryComplete(); + _shutdownCalled.TrySetResult(); + return Task.CompletedTask; + } + + /// + public void Kill(string reason) + { + Interlocked.Increment(ref _killCount); + _state = WorkerClientState.Faulted; + _events.Writer.TryComplete(); + } + + /// + public ValueTask DisposeAsync() => ValueTask.CompletedTask; + } + + private sealed class ApplicationLifetimeStub : IHostApplicationLifetime + { + private readonly CancellationTokenSource _stopping = new(); + + /// + public CancellationToken ApplicationStarted => CancellationToken.None; + + /// + public CancellationToken ApplicationStopping => _stopping.Token; + + /// + public CancellationToken ApplicationStopped => CancellationToken.None; + + /// Fires . + public void SignalStopping() => _stopping.Cancel(); + + /// + public void StopApplication() => SignalStopping(); + } +}