fix(sessions): start the host session drain at ApplicationStopping, before Kestrel's drain (SES-001, #247)
This commit is contained in:
@@ -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
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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();
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user