using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
namespace ZB.MOM.WW.MxGateway.Server.Sessions;
/// Hosted service that cleanly shuts down all gateway sessions on application shutdown.
public sealed class SessionShutdownHostedService(
ISessionManager sessionManager,
ILogger logger) : IHostedService
{
/// No-op startup hook; this service only has work to do on shutdown.
/// Token that signals startup should be aborted.
/// A task that represents the asynchronous operation.
public Task StartAsync(CancellationToken cancellationToken)
{
return Task.CompletedTask;
}
/// Shuts down all gateway sessions as the host stops, logging (without throwing) if the host's shutdown timeout cancels the operation first.
/// Token that signals the host's shutdown timeout has elapsed.
/// A task that represents the asynchronous operation.
public async Task StopAsync(CancellationToken cancellationToken)
{
try
{
await sessionManager.ShutdownAsync(cancellationToken).ConfigureAwait(false);
}
catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested)
{
logger.LogWarning("Gateway session shutdown was canceled by host shutdown timeout.");
}
}
}