Phase 3: GameTurnTimerService — per-turn auto-end timer

- 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 <noreply@anthropic.com>
Co-Authored-By: Happy <yesreply@happy.engineering>
This commit is contained in:
dingo
2026-03-18 23:11:15 -04:00
co-authored by Claude Happy
parent 93d27e9270
commit 2c40fb036f
5 changed files with 231 additions and 19 deletions
+189
View File
@@ -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;
/// <summary>
/// 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).
/// </summary>
internal sealed class GameTurnTimerService : IHostedService
{
/// <summary>
/// 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.
/// </summary>
internal static GameTurnTimerService? Instance { get; private set; }
private readonly IServiceScopeFactory _scopeFactory;
private readonly ILogger<GameTurnTimerService> _logger;
private readonly ConcurrentDictionary<Guid, CancellationTokenSource> _timers = new();
private CancellationToken _stoppingToken;
public GameTurnTimerService(IServiceScopeFactory scopeFactory, ILogger<GameTurnTimerService> 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;
}
/// <summary>
/// Reset (or start) the turn timer for a session. Cancels any existing timer first.
/// If <paramref name="turnTimerSeconds"/> 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.
/// </summary>
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);
}
/// <summary>
/// Cancel and remove the timer for a session (called when the game ends normally).
/// </summary>
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<GameDbContext>();
var identityDb = sp.GetRequiredService<SorIdentityDbContext>();
var clientPush = sp.GetRequiredService<IClientPush>();
var eventBus = sp.GetRequiredService<IEventBus>();
// 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);
}
}
}
@@ -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));
}
@@ -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 <see cref="LoadActiveSessionAsync"/>.
/// </summary>
protected static async Task SaveStateAsync(
internal static async Task SaveStateAsync(
GameDbContext gameDb,
GameSession session,
GameState state,
@@ -92,7 +92,7 @@ internal abstract class GameHandlerBase
/// <summary>
/// Push the updated (filtered) game state to both players.
/// </summary>
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.
/// </summary>
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.
@@ -19,18 +19,21 @@ using SOR.Shared.Networking;
/// </summary>
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));
}
@@ -27,6 +27,11 @@ public static class ServiceRegistration
// Monitors active sessions for player inactivity.
services.AddHostedService<GameInactivityMonitorService>();
// 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<GameTurnTimerService>();
services.AddHostedService(sp => sp.GetRequiredService<GameTurnTimerService>());
services.AddTransient<IMessageHandler, GameReadyHandler>();
services.AddTransient<IMessageHandler, GameGetStateHandler>();
services.AddTransient<IMessageHandler, GameGetActiveSessionHandler>();