From 2c40fb036f071a09f5e7ad6231f680ed71f20c1a Mon Sep 17 00:00:00 2001 From: dingo Date: Wed, 18 Mar 2026 23:11:15 -0400 Subject: [PATCH] =?UTF-8?q?Phase=203:=20GameTurnTimerService=20=E2=80=94?= =?UTF-8?q?=20per-turn=20auto-end=20timer?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - GameTurnTimerService singleton manages CancellationTokenSource per session. Fires AutoEndTurnAsync on expiry: acquires row lock, calls GameEngine.EndTurn, saves state, pushes to players, finalizes game if turn-limit reached. Caps effective delay by TimeLimitMinutes remaining wall time. - FinalizeGameAsync (GameHandlerBase) calls GameTurnTimerService.Instance?.CancelTimer so all game-over paths (attack, concede, force-concede) cleanly cancel timers. - GamePlaceArchSpiritHandler: injects timer service; ResetTimer when bothPlaced. - GameEndTurnHandler: injects timer service; ResetTimer on normal end-turn, CancelTimer (via FinalizeGameAsync) on turn-limit game-over. - ServiceRegistration: singleton + AddHostedService delegate for lifetime callbacks. - GameHandlerBase: SaveStateAsync, PushStateToPlayersAsync, FinalizeGameAsync promoted from protected static → internal static for timer service access. Generated with [Claude Code](https://claude.ai/code) via [Happy](https://happy.engineering) Co-Authored-By: Claude Co-Authored-By: Happy --- Server/src/SOR.Game/GameTurnTimerService.cs | 189 ++++++++++++++++++ .../SOR.Game/Handlers/GameEndTurnHandler.cs | 19 +- .../src/SOR.Game/Handlers/GameHandlerBase.cs | 9 +- .../Handlers/GamePlaceArchSpiritHandler.cs | 28 ++- Server/src/SOR.Game/ServiceRegistration.cs | 5 + 5 files changed, 231 insertions(+), 19 deletions(-) create mode 100644 Server/src/SOR.Game/GameTurnTimerService.cs diff --git a/Server/src/SOR.Game/GameTurnTimerService.cs b/Server/src/SOR.Game/GameTurnTimerService.cs new file mode 100644 index 0000000..001c711 --- /dev/null +++ b/Server/src/SOR.Game/GameTurnTimerService.cs @@ -0,0 +1,189 @@ +namespace SOR.Game; + +using System.Collections.Concurrent; +using System.Text.Json; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; +using Microsoft.Extensions.Logging; +using SOR.Database.Contexts; +using SOR.Database.Enums; +using SOR.Game.Handlers; +using SOR.Networking.Abstractions.EventBus; +using SOR.Networking.Abstractions.Push; + +/// +/// Manages per-session turn timers. When a turn timer expires the active player's +/// turn is ended automatically (equivalent to game.end_turn fired by the engine). +/// +/// Registered as both a singleton (so handlers can inject it) and as an IHostedService +/// (so StartAsync / StopAsync are called on application lifecycle events). +/// +internal sealed class GameTurnTimerService : IHostedService +{ + /// + /// Static reference set in the constructor so that FinalizeGameAsync (a static method + /// on GameHandlerBase) can cancel timers without requiring DI injection. + /// Safe because the service is registered as a singleton. + /// + internal static GameTurnTimerService? Instance { get; private set; } + + private readonly IServiceScopeFactory _scopeFactory; + private readonly ILogger _logger; + + private readonly ConcurrentDictionary _timers = new(); + private CancellationToken _stoppingToken; + + public GameTurnTimerService(IServiceScopeFactory scopeFactory, ILogger logger) + { + _scopeFactory = scopeFactory; + _logger = logger; + Instance = this; + } + + public Task StartAsync(CancellationToken cancellationToken) + { + _stoppingToken = cancellationToken; + return Task.CompletedTask; + } + + public Task StopAsync(CancellationToken cancellationToken) + { + foreach (var cts in _timers.Values) + cts.Cancel(); + _timers.Clear(); + return Task.CompletedTask; + } + + /// + /// Reset (or start) the turn timer for a session. Cancels any existing timer first. + /// If is 0 the timer is simply cancelled and not restarted. + /// The effective deadline is also capped by the session time limit if one is configured. + /// + public void ResetTimer( + Guid sessionId, + int turnTimerSeconds, + int timeLimitMinutes, + DateTimeOffset sessionCreatedAt) + { + // Cancel the previous turn's timer. + if (_timers.TryRemove(sessionId, out var existing)) + existing.Cancel(); + + if (turnTimerSeconds <= 0) + return; // No per-turn timer configured. + + int effectiveSeconds = turnTimerSeconds; + + // Cap by remaining session time if a time limit is configured. + if (timeLimitMinutes > 0) + { + var elapsed = DateTimeOffset.UtcNow - sessionCreatedAt; + var remaining = TimeSpan.FromMinutes(timeLimitMinutes) - elapsed; + if (remaining.TotalSeconds <= 0) + return; // Session time already exhausted; let the next action resolve it. + effectiveSeconds = Math.Min(effectiveSeconds, (int)remaining.TotalSeconds); + } + + var cts = new CancellationTokenSource(); + _timers[sessionId] = cts; + + // Fire-and-forget: run the delay on the thread-pool. + _ = RunTimerAsync(sessionId, effectiveSeconds, cts.Token); + } + + /// + /// Cancel and remove the timer for a session (called when the game ends normally). + /// + public void CancelTimer(Guid sessionId) + { + if (_timers.TryRemove(sessionId, out var cts)) + cts.Cancel(); + } + + // ------------------------------------------------------------------------- + + private async Task RunTimerAsync(Guid sessionId, int seconds, CancellationToken ct) + { + try + { + await Task.Delay(TimeSpan.FromSeconds(seconds), ct); + await AutoEndTurnAsync(sessionId); + } + catch (OperationCanceledException) + { + // Timer was reset or the game ended — nothing to do. + } + catch (Exception ex) + { + _logger.LogError(ex, "Turn timer auto-end failed for session {SessionId}", sessionId); + } + } + + private async Task AutoEndTurnAsync(Guid sessionId) + { + using var scope = _scopeFactory.CreateScope(); + var sp = scope.ServiceProvider; + + var gameDb = sp.GetRequiredService(); + var identityDb = sp.GetRequiredService(); + var clientPush = sp.GetRequiredService(); + var eventBus = sp.GetRequiredService(); + + // Acquire a row-level lock, same pattern as LoadActiveSessionAsync. + await gameDb.Database.BeginTransactionAsync(_stoppingToken); + + var session = await gameDb.GameSessions + .FromSqlInterpolated( + $""" + SELECT * FROM game.game_sessions + WHERE "Id" = {sessionId} + FOR UPDATE + """) + .SingleOrDefaultAsync(_stoppingToken); + + if (session is null || session.Status != GameSessionStatus.Active) + { + // Game ended before the timer fired — roll back and exit cleanly. + await gameDb.Database.RollbackTransactionAsync(_stoppingToken); + return; + } + + var state = GameEngine.Deserialize(session.StateJson!); + var actorId = state.ActivePlayerAccountId; + + var (newState, gameOver) = GameEngine.EndTurn(state, actorId); + + if (gameOver) + { + var (winnerId, loserId) = GameEngine.GetTurnLimitWinner(newState); + + session.Status = GameSessionStatus.Completed; + session.WinnerAccountId = winnerId; + session.WinCondition = "turn_limit"; + session.EndedAt = DateTimeOffset.UtcNow; + + var dto = GameEngine.ToDto(newState, actorId); + await GameHandlerBase.SaveStateAsync(gameDb, session, newState, actorId, + "game.turn_timer_expired", null, _stoppingToken, JsonSerializer.Serialize(dto)); + + await GameHandlerBase.PushStateToPlayersAsync(clientPush, session, newState, _stoppingToken); + + await GameHandlerBase.FinalizeGameAsync( + gameDb, identityDb, clientPush, eventBus, + session, winnerId, loserId, "turn_limit", _stoppingToken); + } + else + { + var dto = GameEngine.ToDto(newState, actorId); + await GameHandlerBase.SaveStateAsync(gameDb, session, newState, actorId, + "game.turn_timer_expired", null, _stoppingToken, JsonSerializer.Serialize(dto)); + + await GameHandlerBase.PushStateToPlayersAsync(clientPush, session, newState, _stoppingToken); + + // Start the timer for the new active player's turn. + ResetTimer(session.Id, newState.Rules.TurnTimerSeconds, + newState.Rules.TimeLimitMinutes, session.CreatedAt); + } + } +} diff --git a/Server/src/SOR.Game/Handlers/GameEndTurnHandler.cs b/Server/src/SOR.Game/Handlers/GameEndTurnHandler.cs index f2000d8..3105502 100644 --- a/Server/src/SOR.Game/Handlers/GameEndTurnHandler.cs +++ b/Server/src/SOR.Game/Handlers/GameEndTurnHandler.cs @@ -21,19 +21,22 @@ internal sealed class GameEndTurnHandler : GameHandlerBase, IMessageHandler private readonly SorIdentityDbContext _identityDb; private readonly IClientPush _clientPush; private readonly IEventBus _eventBus; + private readonly GameTurnTimerService _timerService; public GameEndTurnHandler( IMessageSerializer serializer, GameDbContext gameDb, SorIdentityDbContext identityDb, IClientPush clientPush, - IEventBus eventBus) + IEventBus eventBus, + GameTurnTimerService timerService) { - _serializer = serializer; - _gameDb = gameDb; - _identityDb = identityDb; - _clientPush = clientPush; - _eventBus = eventBus; + _serializer = serializer; + _gameDb = gameDb; + _identityDb = identityDb; + _clientPush = clientPush; + _eventBus = eventBus; + _timerService = timerService; } public string MessageType => "game.end_turn"; @@ -81,6 +84,10 @@ internal sealed class GameEndTurnHandler : GameHandlerBase, IMessageHandler await PushStateToPlayersAsync(_clientPush, session, newState, ct); + // Reset the turn timer for the new active player. + _timerService.ResetTimer(session.Id, newState.Rules.TurnTimerSeconds, + newState.Rules.TimeLimitMinutes, session.CreatedAt); + return ServerMessage.Reply("game.end_turn.ack", message.Seq, new GameEndTurnResponse(stateDto)); } diff --git a/Server/src/SOR.Game/Handlers/GameHandlerBase.cs b/Server/src/SOR.Game/Handlers/GameHandlerBase.cs index 28dbc0a..dfbffd2 100644 --- a/Server/src/SOR.Game/Handlers/GameHandlerBase.cs +++ b/Server/src/SOR.Game/Handlers/GameHandlerBase.cs @@ -58,7 +58,7 @@ internal abstract class GameHandlerBase /// Persist the updated state JSON and append an action log entry, /// then commit the transaction opened by . /// - protected static async Task SaveStateAsync( + internal static async Task SaveStateAsync( GameDbContext gameDb, GameSession session, GameState state, @@ -92,7 +92,7 @@ internal abstract class GameHandlerBase /// /// Push the updated (filtered) game state to both players. /// - protected static async Task PushStateToPlayersAsync( + internal static async Task PushStateToPlayersAsync( IClientPush clientPush, GameSession session, GameState state, @@ -120,7 +120,7 @@ internal abstract class GameHandlerBase /// Finalize a completed game: update session status, adjust ELO ranks, /// award OriginPoints, push game-over to both players, publish GameEndedEvent. /// - protected static async Task FinalizeGameAsync( + internal static async Task FinalizeGameAsync( GameDbContext gameDb, SorIdentityDbContext identityDb, IClientPush clientPush, @@ -131,6 +131,9 @@ internal abstract class GameHandlerBase string winCondition, CancellationToken ct) { + // Cancel any pending turn timer — the game is over. + GameTurnTimerService.Instance?.CancelTimer(session.Id); + // These fields may already be set by the calling handler (so they are committed // atomically with the StateJson update in SaveStateAsync). Setting them here again // is idempotent and ensures correctness even if called without the pre-set pattern. diff --git a/Server/src/SOR.Game/Handlers/GamePlaceArchSpiritHandler.cs b/Server/src/SOR.Game/Handlers/GamePlaceArchSpiritHandler.cs index bd1a4c5..41dbd54 100644 --- a/Server/src/SOR.Game/Handlers/GamePlaceArchSpiritHandler.cs +++ b/Server/src/SOR.Game/Handlers/GamePlaceArchSpiritHandler.cs @@ -19,18 +19,21 @@ using SOR.Shared.Networking; /// internal sealed class GamePlaceArchSpiritHandler : GameHandlerBase, IMessageHandler { - private readonly IMessageSerializer _serializer; - private readonly GameDbContext _gameDb; - private readonly IClientPush _clientPush; + private readonly IMessageSerializer _serializer; + private readonly GameDbContext _gameDb; + private readonly IClientPush _clientPush; + private readonly GameTurnTimerService _timerService; public GamePlaceArchSpiritHandler( - IMessageSerializer serializer, - GameDbContext gameDb, - IClientPush clientPush) + IMessageSerializer serializer, + GameDbContext gameDb, + IClientPush clientPush, + GameTurnTimerService timerService) { - _serializer = serializer; - _gameDb = gameDb; - _clientPush = clientPush; + _serializer = serializer; + _gameDb = gameDb; + _clientPush = clientPush; + _timerService = timerService; } public string MessageType => "game.place_arch_spirit"; @@ -47,7 +50,7 @@ internal sealed class GamePlaceArchSpiritHandler : GameHandlerBase, IMessageHand var state = GameEngine.Deserialize(session.StateJson!); var coord = new Coord(req.Position.X, req.Position.Y); - var (newState, _) = GameEngine.PlaceArchSpirit(state, actorId, coord); + var (newState, bothPlaced) = GameEngine.PlaceArchSpirit(state, actorId, coord); var dto = GameEngine.ToDto(newState, actorId); await SaveStateAsync(_gameDb, session, newState, actorId, "game.place_arch_spirit", @@ -55,6 +58,11 @@ internal sealed class GamePlaceArchSpiritHandler : GameHandlerBase, IMessageHand await PushStateToPlayersAsync(_clientPush, session, newState, ct); + // Start the turn timer once both players have placed and turn 1 begins. + if (bothPlaced) + _timerService.ResetTimer(session.Id, newState.Rules.TurnTimerSeconds, + newState.Rules.TimeLimitMinutes, session.CreatedAt); + return ServerMessage.Reply("game.place_arch_spirit.ack", message.Seq, new GamePlaceArchSpiritResponse(dto)); } diff --git a/Server/src/SOR.Game/ServiceRegistration.cs b/Server/src/SOR.Game/ServiceRegistration.cs index 91b11ee..707d022 100644 --- a/Server/src/SOR.Game/ServiceRegistration.cs +++ b/Server/src/SOR.Game/ServiceRegistration.cs @@ -27,6 +27,11 @@ public static class ServiceRegistration // Monitors active sessions for player inactivity. services.AddHostedService(); + // Manages per-session turn timers; registered as singleton so handlers can inject it, + // and as a hosted service so it receives app-lifetime Start/Stop callbacks. + services.AddSingleton(); + services.AddHostedService(sp => sp.GetRequiredService()); + services.AddTransient(); services.AddTransient(); services.AddTransient();