- 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>
190 lines
7.0 KiB
C#
190 lines
7.0 KiB
C#
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);
|
|
}
|
|
}
|
|
}
|