diff --git a/Server/src/SOR.Game/GameStartupCleanupService.cs b/Server/src/SOR.Game/GameStartupCleanupService.cs index e59545b..8972859 100644 --- a/Server/src/SOR.Game/GameStartupCleanupService.cs +++ b/Server/src/SOR.Game/GameStartupCleanupService.cs @@ -17,11 +17,22 @@ using SOR.Shared.Networking; /// those sessions are stuck on a loading screen and will never recover on their own /// because they already sent game.ready to the old process. /// -/// This service abandons every Initializing session and pushes game.session_abandoned -/// to both players so their clients can return to the main menu. +/// This service abandons Initializing sessions that are clearly stale (older than +/// StaleThresholdSeconds) and pushes game.session_abandoned to both players so +/// their clients can return to the main menu. +/// +/// The staleness threshold exists to avoid a race condition: MatchmakerService is +/// registered before GameStartupCleanupService and its BackgroundService.ExecuteAsync +/// fires immediately (no leading delay) on a background thread. If queued players +/// were waiting when the process restarted, the matchmaker can create a brand-new +/// Initializing session within the first few milliseconds of startup — before this +/// service's query runs. Excluding sessions younger than 60 s ensures those fresh +/// sessions are left alone so game.ready can proceed normally. /// internal sealed class GameStartupCleanupService : IHostedService { + private const int StaleThresholdSeconds = 60; + private readonly IServiceScopeFactory _scopeFactory; private readonly ILogger _logger; @@ -39,8 +50,13 @@ internal sealed class GameStartupCleanupService : IHostedService var gameDb = scope.ServiceProvider.GetRequiredService(); var clientPush = scope.ServiceProvider.GetRequiredService(); + // Only target sessions old enough to be definitely stuck. + // Sessions created in the last 60 s may still be mid-handshake. + var staleThreshold = DateTimeOffset.UtcNow.AddSeconds(-StaleThresholdSeconds); + var stuck = await gameDb.GameSessions - .Where(s => s.Status == GameSessionStatus.Initializing) + .Where(s => s.Status == GameSessionStatus.Initializing + && s.CreatedAt <= staleThreshold) .ToListAsync(cancellationToken); if (stuck.Count == 0)