Files
sor/Server/src/SOR.Game/Handlers/GameHandlerBase.cs
T
6fd1b07ab2 Fix custom lobby staying in Started state after game ends
Add CustomLobbyStatus.Completed; in FinalizeGameAsync, query the lobby
linked via GameSessionId and set Status=Completed when the game ends.
This removes finished games from the active-games browser (list_active
only returns Started lobbies) and from the admin "active" count.

Admin page: add Completed filter option, dark badge, include Started
lobbies in the always-loaded set so stale in-progress games are visible.

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>
2026-03-19 13:27:39 -04:00

249 lines
10 KiB
C#

namespace SOR.Game.Handlers;
using System.Text.Json;
using Microsoft.EntityFrameworkCore;
using SOR.Database.Contexts;
using SOR.Database.Entities.Game;
using SOR.Database.Enums;
using SOR.Networking.Abstractions.EventBus;
using SOR.Networking.Abstractions.Push;
using SOR.Networking.Abstractions.Transport;
using SOR.Shared.Nats;
using SOR.Shared.Networking;
/// <summary>
/// Shared helpers for all game message handlers.
/// </summary>
internal abstract class GameHandlerBase
{
/// <summary>
/// Load and validate an active game session for the calling player,
/// acquiring a row-level lock (SELECT FOR UPDATE) inside an explicit
/// transaction so that concurrent mutations to the same session are
/// serialized. The transaction is committed by <see cref="SaveStateAsync"/>.
/// Throws GameException on any validation failure.
/// </summary>
protected static async Task<GameSession> LoadActiveSessionAsync(
GameDbContext gameDb,
Guid sessionId,
string actorId,
CancellationToken ct)
{
// Begin a transaction so the FOR UPDATE lock is held until SaveStateAsync commits.
if (gameDb.Database.CurrentTransaction == null)
await gameDb.Database.BeginTransactionAsync(ct);
// Lock the row so concurrent handlers for the same session queue up.
var session = await gameDb.GameSessions
.FromSqlInterpolated(
$"""
SELECT * FROM game.game_sessions
WHERE "Id" = {sessionId}
FOR UPDATE
""")
.SingleOrDefaultAsync(ct)
?? throw new GameException("SESSION_NOT_FOUND");
if (session.PlayerOneAccountId.ToString() != actorId &&
session.PlayerTwoAccountId.ToString() != actorId)
throw new GameException("NOT_IN_SESSION");
if (session.Status != GameSessionStatus.Active)
throw new GameException("SESSION_NOT_ACTIVE");
return session;
}
/// <summary>
/// Persist the updated state JSON and append an action log entry,
/// then commit the transaction opened by <see cref="LoadActiveSessionAsync"/>.
/// </summary>
internal static async Task SaveStateAsync(
GameDbContext gameDb,
GameSession session,
GameState state,
string actorId,
string actionType,
string? payloadJson,
CancellationToken ct,
string? resultJson = null)
{
var seqNum = state.NextActionSequence++; // increment before serialize so the saved JSON reflects the consumed number
session.StateJson = GameEngine.Serialize(state);
session.LastActionAt = DateTimeOffset.UtcNow;
gameDb.ActionLogs.Add(new GameActionLog
{
GameSessionId = session.Id,
ActorAccountId = Guid.Parse(actorId),
ActionType = actionType,
PayloadJson = payloadJson,
ResultJson = resultJson,
SequenceNumber = seqNum,
OccurredAt = DateTimeOffset.UtcNow,
});
await gameDb.SaveChangesAsync(ct);
// Commit and release the FOR UPDATE lock.
if (gameDb.Database.CurrentTransaction != null)
await gameDb.Database.CommitTransactionAsync(ct);
}
/// <summary>
/// Push the updated (filtered) game state to both players and any current spectators.
/// Spectators receive a hand-hidden view via SpectatorRegistryService.Instance.
/// </summary>
internal static async Task PushStateToPlayersAsync(
IClientPush clientPush,
GameSession session,
GameState state,
CancellationToken ct)
{
var p1Id = session.PlayerOneAccountId.ToString();
var p2Id = session.PlayerTwoAccountId.ToString();
var tasks = new List<Task>
{
clientPush.PushAsync(p1Id,
ServerMessage.Push("game.state_update",
new GameStateUpdatePush(GameEngine.ToDto(state, p1Id))), ct),
clientPush.PushAsync(p2Id,
ServerMessage.Push("game.state_update",
new GameStateUpdatePush(GameEngine.ToDto(state, p2Id))), ct),
};
var registry = SpectatorRegistryService.Instance;
if (registry != null)
{
var spectators = registry.GetSpectators(session.Id);
if (spectators.Count > 0)
{
var spectatorDto = GameEngine.ToDtoSpectator(state);
foreach (var specId in spectators)
tasks.Add(clientPush.PushAsync(specId.ToString(),
ServerMessage.Push("game.state_update",
new GameStateUpdatePush(spectatorDto)), ct));
}
}
await Task.WhenAll(tasks);
}
// OP config snapshot — read from RuleSnapshotJson at finalization time.
private sealed record OpSnapshot(
int WinnerOpReward = 50,
int LoserOpReward = 10,
int RankDiffOpMultiplierPct = 0);
/// <summary>
/// Finalize a completed game: update session status, adjust ELO ranks,
/// award OriginPoints, push game-over to both players, publish GameEndedEvent.
/// </summary>
internal static async Task FinalizeGameAsync(
GameDbContext gameDb,
SorIdentityDbContext identityDb,
IClientPush clientPush,
IEventBus eventBus,
GameSession session,
Guid winnerAccountId,
Guid loserAccountId,
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.
session.Status = GameSessionStatus.Completed;
session.WinnerAccountId = winnerAccountId;
session.WinCondition = winCondition;
session.EndedAt = DateTimeOffset.UtcNow;
// Mark the linked custom lobby as Completed so it disappears from the active-games
// browser. Ranked sessions have no linked lobby; the query safely returns null.
var linkedLobby = await gameDb.CustomLobbies
.FirstOrDefaultAsync(l => l.GameSessionId == session.Id, ct);
if (linkedLobby != null && linkedLobby.Status == CustomLobbyStatus.Started)
linkedLobby.Status = CustomLobbyStatus.Completed;
// Save game session status FIRST — this must succeed before we touch ELO.
// If identity DB fails below, the session is still correctly marked Completed
// so players won't be stuck in a ghost match on next login.
await gameDb.SaveChangesAsync(ct);
// Load both accounts for ELO + OP adjustment.
var accounts = await identityDb.Users
.Where(a => a.Id == winnerAccountId || a.Id == loserAccountId)
.ToListAsync(ct);
var winner = accounts.First(a => a.Id == winnerAccountId);
var loser = accounts.First(a => a.Id == loserAccountId);
// Capture pre-ELO ranks for OP scaling.
var winnerPreRank = winner.RankScore;
var loserPreRank = loser.RankScore;
var (winnerDelta, loserDelta) = GameEngine.ComputeEloDelta(winner.RankScore, loser.RankScore);
winner.RankScore += winnerDelta;
loser.RankScore = Math.Max(0, loser.RankScore - loserDelta);
// Compute OriginPoints rewards from the rule snapshot.
var snap = JsonSerializer.Deserialize<OpSnapshot>(
session.RuleSnapshotJson ?? "{}",
new JsonSerializerOptions { PropertyNameCaseInsensitive = true }) ?? new OpSnapshot();
var rankDiff = loserPreRank - winnerPreRank; // positive = winner was underdog
var adjustment = rankDiff * snap.RankDiffOpMultiplierPct / 1000;
var winnerOp = Math.Max(1, snap.WinnerOpReward + adjustment);
var loserOp = Math.Max(0, snap.LoserOpReward - adjustment);
winner.OriginPoints += winnerOp;
loser.OriginPoints += loserOp;
await identityDb.SaveChangesAsync(ct);
var push = new GameOverPush(
SessionId : session.Id,
WinnerAccountId : winnerAccountId,
LoserAccountId : loserAccountId,
WinCondition : winCondition,
WinnerRankDelta : winnerDelta,
LoserRankDelta : loserDelta,
WinnerOpDelta : winnerOp,
LoserOpDelta : loserOp);
var gameOverTasks = new List<Task>
{
clientPush.PushAsync(winnerAccountId.ToString(),
ServerMessage.Push("game.over", push), ct),
clientPush.PushAsync(loserAccountId.ToString(),
ServerMessage.Push("game.over", push), ct),
};
// Push game.over to spectators then evict the session from the registry.
var spectatorRegistry = SpectatorRegistryService.Instance;
if (spectatorRegistry != null)
{
foreach (var specId in spectatorRegistry.GetSpectators(session.Id))
gameOverTasks.Add(clientPush.PushAsync(specId.ToString(),
ServerMessage.Push("game.over", push), ct));
spectatorRegistry.RemoveSession(session.Id);
}
await Task.WhenAll(gameOverTasks);
// Publish inter-service event so ChatLifecycleHostedService archives the match channel.
await eventBus.PublishAsync(NatsSubjects.GameEnded,
new GameEndedEvent(
GameId : session.Id,
WinnerId : winnerAccountId,
LoserId : loserAccountId,
DurationSeconds : (int)(session.EndedAt!.Value - session.CreatedAt).TotalSeconds,
EndedAt : session.EndedAt.Value),
ct);
}
}