Feature: model retry + rejoin on login + 5-min inactivity detection
**Feature 1 — Model retry (client)** - `ModelCache.gd`: add `evict(url)` to remove failed entries so re-download is possible - `game_screen.gd`: when GLB load fails, `_schedule_model_retry` queues a 60-second retry (up to 10 attempts); `_do_model_retry` evicts + re-downloads and swaps the placeholder mesh for the real model if/when it succeeds **Feature 2 — Rejoin on login (server + client)** - Server: `GameGetActiveSessionHandler` (`game.get_active_session`) — returns the caller's active session ID + phase, or null when no session exists - Client: `init_screen.gd` checks for an active session after content sync; shows a "Rejoin / Concede" dialog when one is found; rejoin navigates to GameScreen with the session ID already set so `send_ready` → `AlreadyStarted` → `_fetch_state` **Feature 3 — 5-minute inactivity detection (server + client)** - `GameSession`: add `LastActionAt` column + EF migration (`20260317000001_AddLastActionAt`) - `GameHandlerBase.SaveStateAsync`: sets `session.LastActionAt` on every action - `GameInactivityMonitorService`: background poll every 60 s; when a session hasn't had an action in ≥ 5 min, pushes `game.inactive_warning` to the stalled player and `game.opponent_inactive` to their opponent (once per session per server lifetime) - `GameForceConcedeHandler` (`game.force_concede`): lets the waiting player claim the win; validates caller is not the active player and `LastActionAt` is stale - `Game.gd`: new `opponent_inactive` / `inactive_warning` signals + push handlers + `send_force_concede()` helper - `game_screen.gd`: handles `opponent_inactive` with Accept/Wait dialog; handles `inactive_warning` with informational popup 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:
@@ -48,6 +48,15 @@ public sealed class GameSession
|
||||
/// </summary>
|
||||
public string? WinCondition { get; set; }
|
||||
|
||||
// ── Inactivity tracking ──────────────────────────────────────────────────────
|
||||
|
||||
/// <summary>
|
||||
/// Timestamp of the last game action (set by SaveStateAsync after every action).
|
||||
/// Used by GameInactivityMonitorService to detect stalled games.
|
||||
/// Null for sessions that predate this field.
|
||||
/// </summary>
|
||||
public DateTimeOffset? LastActionAt { get; set; }
|
||||
|
||||
// ── Live state ───────────────────────────────────────────────────────────
|
||||
|
||||
/// <summary>
|
||||
|
||||
+312
@@ -0,0 +1,312 @@
|
||||
// <auto-generated />
|
||||
using System;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.EntityFrameworkCore.Infrastructure;
|
||||
using Microsoft.EntityFrameworkCore.Migrations;
|
||||
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
|
||||
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
|
||||
using SOR.Database.Contexts;
|
||||
|
||||
#nullable disable
|
||||
|
||||
namespace SOR.Database.Migrations.Game
|
||||
{
|
||||
[DbContext(typeof(GameDbContext))]
|
||||
[Migration("20260317000001_AddLastActionAt")]
|
||||
partial class AddLastActionAt
|
||||
{
|
||||
/// <inheritdoc />
|
||||
protected override void BuildTargetModel(ModelBuilder modelBuilder)
|
||||
{
|
||||
#pragma warning disable 612, 618
|
||||
modelBuilder
|
||||
.HasDefaultSchema("game")
|
||||
.HasAnnotation("ProductVersion", "8.0.0")
|
||||
.HasAnnotation("Relational:MaxIdentifierLength", 63);
|
||||
|
||||
NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder);
|
||||
|
||||
modelBuilder.Entity("SOR.Database.Entities.Game.CustomLobby", b =>
|
||||
{
|
||||
b.Property<Guid>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("uuid");
|
||||
|
||||
b.Property<DateTimeOffset>("CreatedAt")
|
||||
.HasColumnType("timestamp with time zone");
|
||||
|
||||
b.Property<int?>("DrawPerTurnOverride")
|
||||
.HasColumnType("integer");
|
||||
|
||||
b.Property<bool?>("FirstPlayerSkipsDrawOverride")
|
||||
.HasColumnType("boolean");
|
||||
|
||||
b.Property<Guid?>("GameSessionId")
|
||||
.HasColumnType("uuid");
|
||||
|
||||
b.Property<Guid?>("GuestAccountId")
|
||||
.HasColumnType("uuid");
|
||||
|
||||
b.Property<Guid?>("GuestDeckId")
|
||||
.HasColumnType("uuid");
|
||||
|
||||
b.Property<Guid>("HostAccountId")
|
||||
.HasColumnType("uuid");
|
||||
|
||||
b.Property<Guid>("HostDeckId")
|
||||
.HasColumnType("uuid");
|
||||
|
||||
b.Property<string>("Name")
|
||||
.IsRequired()
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<int?>("OpeningHandSizeOverride")
|
||||
.HasColumnType("integer");
|
||||
|
||||
b.Property<int?>("SpAccumulationPerTurnOverride")
|
||||
.HasColumnType("integer");
|
||||
|
||||
b.Property<int?>("SpCapOverride")
|
||||
.HasColumnType("integer");
|
||||
|
||||
b.Property<bool?>("SpHasCapOverride")
|
||||
.HasColumnType("boolean");
|
||||
|
||||
b.Property<string>("Status")
|
||||
.IsRequired()
|
||||
.HasColumnType("text");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.HasIndex("HostAccountId");
|
||||
|
||||
b.HasIndex("Status", "CreatedAt");
|
||||
|
||||
b.ToTable("custom_lobbies", "game");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("SOR.Database.Entities.Game.GameActionLog", b =>
|
||||
{
|
||||
b.Property<Guid>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("uuid");
|
||||
|
||||
b.Property<string>("ActionType")
|
||||
.IsRequired()
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<Guid>("ActorAccountId")
|
||||
.HasColumnType("uuid");
|
||||
|
||||
b.Property<Guid>("GameSessionId")
|
||||
.HasColumnType("uuid");
|
||||
|
||||
b.Property<DateTimeOffset>("OccurredAt")
|
||||
.HasColumnType("timestamp with time zone");
|
||||
|
||||
b.Property<string>("PayloadJson")
|
||||
.HasColumnType("jsonb")
|
||||
.HasColumnName("payload");
|
||||
|
||||
b.Property<string>("ResultJson")
|
||||
.HasColumnType("jsonb")
|
||||
.HasColumnName("result");
|
||||
|
||||
b.Property<int>("SequenceNumber")
|
||||
.HasColumnType("integer");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.HasIndex("ActorAccountId");
|
||||
|
||||
b.HasIndex("GameSessionId", "SequenceNumber")
|
||||
.IsUnique();
|
||||
|
||||
b.ToTable("action_logs", "game");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("SOR.Database.Entities.Game.GameRuleSet", b =>
|
||||
{
|
||||
b.Property<Guid>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("uuid");
|
||||
|
||||
b.Property<int>("BoardHeight")
|
||||
.HasColumnType("integer");
|
||||
|
||||
b.Property<int>("BoardWidth")
|
||||
.HasColumnType("integer");
|
||||
|
||||
b.Property<DateTimeOffset>("CreatedAt")
|
||||
.HasColumnType("timestamp with time zone");
|
||||
|
||||
b.Property<int>("DrawPerTurn")
|
||||
.HasColumnType("integer");
|
||||
|
||||
b.Property<bool>("FirstPlayerSkipsDraw")
|
||||
.HasColumnType("boolean");
|
||||
|
||||
b.Property<bool>("IsCustomDefault")
|
||||
.HasColumnType("boolean");
|
||||
|
||||
b.Property<bool>("IsRankedDefault")
|
||||
.HasColumnType("boolean");
|
||||
|
||||
b.Property<int>("LoserOpReward")
|
||||
.HasColumnType("integer");
|
||||
|
||||
b.Property<string>("Name")
|
||||
.IsRequired()
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<int>("OpeningHandSize")
|
||||
.HasColumnType("integer");
|
||||
|
||||
b.Property<int>("RankDiffOpMultiplierPct")
|
||||
.HasColumnType("integer");
|
||||
|
||||
b.Property<int>("SpAccumulationPerTurn")
|
||||
.HasColumnType("integer");
|
||||
|
||||
b.Property<int>("SpCap")
|
||||
.HasColumnType("integer");
|
||||
|
||||
b.Property<bool>("SpHasCap")
|
||||
.HasColumnType("boolean");
|
||||
|
||||
b.Property<DateTimeOffset>("UpdatedAt")
|
||||
.HasColumnType("timestamp with time zone");
|
||||
|
||||
b.Property<int>("WinnerOpReward")
|
||||
.HasColumnType("integer");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.HasIndex("IsCustomDefault");
|
||||
|
||||
b.HasIndex("IsRankedDefault");
|
||||
|
||||
b.ToTable("game_rule_sets", "game");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("SOR.Database.Entities.Game.GameSession", b =>
|
||||
{
|
||||
b.Property<Guid>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("uuid");
|
||||
|
||||
b.Property<DateTimeOffset>("CreatedAt")
|
||||
.HasColumnType("timestamp with time zone");
|
||||
|
||||
b.Property<DateTimeOffset?>("EndedAt")
|
||||
.HasColumnType("timestamp with time zone");
|
||||
|
||||
b.Property<DateTimeOffset?>("LastActionAt")
|
||||
.HasColumnType("timestamp with time zone");
|
||||
|
||||
b.Property<Guid>("PlayerOneAccountId")
|
||||
.HasColumnType("uuid");
|
||||
|
||||
b.Property<Guid>("PlayerOneDeckId")
|
||||
.HasColumnType("uuid");
|
||||
|
||||
b.Property<bool>("PlayerOneReady")
|
||||
.HasColumnType("boolean");
|
||||
|
||||
b.Property<Guid>("PlayerTwoAccountId")
|
||||
.HasColumnType("uuid");
|
||||
|
||||
b.Property<Guid>("PlayerTwoDeckId")
|
||||
.HasColumnType("uuid");
|
||||
|
||||
b.Property<bool>("PlayerTwoReady")
|
||||
.HasColumnType("boolean");
|
||||
|
||||
b.Property<string>("RuleSnapshotJson")
|
||||
.HasColumnType("jsonb")
|
||||
.HasColumnName("rule_snapshot");
|
||||
|
||||
b.Property<DateTimeOffset?>("StartedAt")
|
||||
.HasColumnType("timestamp with time zone");
|
||||
|
||||
b.Property<string>("StateJson")
|
||||
.HasColumnType("jsonb")
|
||||
.HasColumnName("state");
|
||||
|
||||
b.Property<string>("Status")
|
||||
.IsRequired()
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<string>("WinCondition")
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<Guid?>("WinnerAccountId")
|
||||
.HasColumnType("uuid");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.HasIndex("PlayerOneAccountId");
|
||||
|
||||
b.HasIndex("PlayerTwoAccountId");
|
||||
|
||||
b.HasIndex("Status", "CreatedAt");
|
||||
|
||||
b.ToTable("game_sessions", "game");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("SOR.Database.Entities.Game.MatchmakingEntry", b =>
|
||||
{
|
||||
b.Property<Guid>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("uuid");
|
||||
|
||||
b.Property<Guid>("AccountId")
|
||||
.HasColumnType("uuid");
|
||||
|
||||
b.Property<Guid>("DeckId")
|
||||
.HasColumnType("uuid");
|
||||
|
||||
b.Property<DateTimeOffset>("JoinedAt")
|
||||
.HasColumnType("timestamp with time zone");
|
||||
|
||||
b.Property<Guid?>("MatchedGameSessionId")
|
||||
.HasColumnType("uuid");
|
||||
|
||||
b.Property<int>("RankScore")
|
||||
.HasColumnType("integer");
|
||||
|
||||
b.Property<DateTimeOffset?>("ResolvedAt")
|
||||
.HasColumnType("timestamp with time zone");
|
||||
|
||||
b.Property<string>("Status")
|
||||
.IsRequired()
|
||||
.HasColumnType("text");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.HasIndex("AccountId", "Status");
|
||||
|
||||
b.HasIndex("Status", "RankScore");
|
||||
|
||||
b.ToTable("matchmaking_entries", "game");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("SOR.Database.Entities.Game.GameActionLog", b =>
|
||||
{
|
||||
b.HasOne("SOR.Database.Entities.Game.GameSession", "Session")
|
||||
.WithMany("ActionLog")
|
||||
.HasForeignKey("GameSessionId")
|
||||
.OnDelete(DeleteBehavior.Cascade)
|
||||
.IsRequired();
|
||||
|
||||
b.Navigation("Session");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("SOR.Database.Entities.Game.GameSession", b =>
|
||||
{
|
||||
b.Navigation("ActionLog");
|
||||
});
|
||||
#pragma warning restore 612, 618
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
using System;
|
||||
using Microsoft.EntityFrameworkCore.Migrations;
|
||||
|
||||
#nullable disable
|
||||
|
||||
namespace SOR.Database.Migrations.Game
|
||||
{
|
||||
/// <inheritdoc />
|
||||
public partial class AddLastActionAt : Migration
|
||||
{
|
||||
/// <inheritdoc />
|
||||
protected override void Up(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
migrationBuilder.AddColumn<DateTimeOffset>(
|
||||
name: "LastActionAt",
|
||||
schema: "game",
|
||||
table: "game_sessions",
|
||||
type: "timestamp with time zone",
|
||||
nullable: true);
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override void Down(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
migrationBuilder.DropColumn(
|
||||
name: "LastActionAt",
|
||||
schema: "game",
|
||||
table: "game_sessions");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -198,6 +198,9 @@ namespace SOR.Database.Migrations.Game
|
||||
b.Property<DateTimeOffset?>("EndedAt")
|
||||
.HasColumnType("timestamp with time zone");
|
||||
|
||||
b.Property<DateTimeOffset?>("LastActionAt")
|
||||
.HasColumnType("timestamp with time zone");
|
||||
|
||||
b.Property<Guid>("PlayerOneAccountId")
|
||||
.HasColumnType("uuid");
|
||||
|
||||
|
||||
@@ -0,0 +1,118 @@
|
||||
namespace SOR.Game;
|
||||
|
||||
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.Networking.Abstractions.Push;
|
||||
using SOR.Shared.Networking;
|
||||
|
||||
/// <summary>
|
||||
/// Background service that polls for game sessions where no action has been taken
|
||||
/// for InactivityThreshold minutes.
|
||||
///
|
||||
/// When a stalled session is found for the first time:
|
||||
/// • Pushes game.inactive_warning to the active player (whose turn it is).
|
||||
/// • Pushes game.opponent_inactive to the waiting player (who can then
|
||||
/// choose to accept the forfeit via game.force_concede).
|
||||
///
|
||||
/// Each session is only notified once per service lifetime (tracked in
|
||||
/// _notifiedSessions). If the session later becomes Completed/Abandoned,
|
||||
/// it drops out of the Active query naturally.
|
||||
/// </summary>
|
||||
internal sealed class GameInactivityMonitorService : BackgroundService
|
||||
{
|
||||
private static readonly TimeSpan InactivityThreshold = TimeSpan.FromMinutes(5);
|
||||
private static readonly TimeSpan PollInterval = TimeSpan.FromSeconds(60);
|
||||
|
||||
private readonly IServiceScopeFactory _scopeFactory;
|
||||
private readonly ILogger<GameInactivityMonitorService> _logger;
|
||||
|
||||
// Track which sessions we have already notified so we don't spam.
|
||||
private readonly HashSet<Guid> _notifiedSessions = new();
|
||||
|
||||
public GameInactivityMonitorService(
|
||||
IServiceScopeFactory scopeFactory,
|
||||
ILogger<GameInactivityMonitorService> logger)
|
||||
{
|
||||
_scopeFactory = scopeFactory;
|
||||
_logger = logger;
|
||||
}
|
||||
|
||||
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
|
||||
{
|
||||
// Wait a bit after startup so the DB is warmed up.
|
||||
await Task.Delay(TimeSpan.FromSeconds(30), stoppingToken);
|
||||
|
||||
while (!stoppingToken.IsCancellationRequested)
|
||||
{
|
||||
try
|
||||
{
|
||||
await CheckInactiveSessionsAsync(stoppingToken);
|
||||
}
|
||||
catch (OperationCanceledException) when (stoppingToken.IsCancellationRequested)
|
||||
{
|
||||
break;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogWarning(ex, "GameInactivityMonitor: error during poll — will retry next cycle.");
|
||||
}
|
||||
|
||||
await Task.Delay(PollInterval, stoppingToken);
|
||||
}
|
||||
}
|
||||
|
||||
private async Task CheckInactiveSessionsAsync(CancellationToken ct)
|
||||
{
|
||||
await using var scope = _scopeFactory.CreateAsyncScope();
|
||||
var gameDb = scope.ServiceProvider.GetRequiredService<GameDbContext>();
|
||||
var clientPush = scope.ServiceProvider.GetRequiredService<IClientPush>();
|
||||
|
||||
var threshold = DateTimeOffset.UtcNow - InactivityThreshold;
|
||||
|
||||
var staleSessions = await gameDb.GameSessions
|
||||
.Where(s => s.Status == GameSessionStatus.Active
|
||||
&& s.LastActionAt != null
|
||||
&& s.LastActionAt < threshold
|
||||
&& s.StateJson != null)
|
||||
.ToListAsync(ct);
|
||||
|
||||
foreach (var session in staleSessions)
|
||||
{
|
||||
if (_notifiedSessions.Contains(session.Id))
|
||||
continue;
|
||||
|
||||
_notifiedSessions.Add(session.Id);
|
||||
|
||||
try
|
||||
{
|
||||
var state = GameEngine.Deserialize(session.StateJson!);
|
||||
var activeId = state.ActivePlayerAccountId; // inactive (hasn't acted)
|
||||
var otherId = session.PlayerOneAccountId.ToString() == activeId
|
||||
? session.PlayerTwoAccountId.ToString()
|
||||
: session.PlayerOneAccountId.ToString();
|
||||
|
||||
_logger.LogInformation(
|
||||
"GameInactivityMonitor: session {SessionId} — active player {ActiveId} inactive for >{Minutes} min.",
|
||||
session.Id, activeId, (int)InactivityThreshold.TotalMinutes);
|
||||
|
||||
await Task.WhenAll(
|
||||
clientPush.PushAsync(activeId,
|
||||
ServerMessage.Push("game.inactive_warning",
|
||||
new GameInactiveWarningPush(session.Id)), ct),
|
||||
clientPush.PushAsync(otherId,
|
||||
ServerMessage.Push("game.opponent_inactive",
|
||||
new GameOpponentInactivePush(session.Id)), ct));
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogWarning(ex,
|
||||
"GameInactivityMonitor: could not push notifications for session {SessionId}.",
|
||||
session.Id);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -80,6 +80,12 @@ public sealed record GameActivateAbilityRequest(
|
||||
int AbilityIndex,
|
||||
IReadOnlyList<AbilityTarget>? Targets = null);
|
||||
|
||||
/// <summary>Query whether the caller has an Active game session they can rejoin.</summary>
|
||||
public sealed record GameGetActiveSessionRequest();
|
||||
|
||||
/// <summary>Force-concede a game where the opponent has been inactive.</summary>
|
||||
public sealed record GameForceConcedeRequest(Guid SessionId);
|
||||
|
||||
// ── Custom lobby requests ─────────────────────────────────────────────────────
|
||||
|
||||
/// <summary>Create a new custom lobby. Host provides their deck and optional rule overrides.</summary>
|
||||
@@ -140,6 +146,14 @@ public sealed record GameTransitionResponse(GameStateDto State);
|
||||
|
||||
public sealed record GameActivateAbilityResponse(GameStateDto State);
|
||||
|
||||
/// <summary>
|
||||
/// Response for game.get_active_session.
|
||||
/// SessionId is null when the player has no in-progress game.
|
||||
/// </summary>
|
||||
public sealed record GameGetActiveSessionResponse(Guid? SessionId, string? Phase);
|
||||
|
||||
public sealed record GameForceConcedeResponse(GameStateDto State);
|
||||
|
||||
// ── Custom lobby responses ─────────────────────────────────────────────────────
|
||||
|
||||
public sealed record CreateCustomLobbyResponse(
|
||||
@@ -187,6 +201,18 @@ public sealed record GameOverPush(
|
||||
/// </summary>
|
||||
public sealed record GameSessionAbandonedPush(Guid SessionId, string Reason);
|
||||
|
||||
/// <summary>
|
||||
/// Pushed to the active player when they have been inactive for 5 minutes.
|
||||
/// Their opponent now has the option to accept the forfeit.
|
||||
/// </summary>
|
||||
public sealed record GameInactiveWarningPush(Guid SessionId);
|
||||
|
||||
/// <summary>
|
||||
/// Pushed to the non-active player when the opponent has been inactive for 5 minutes.
|
||||
/// The client should offer "Accept forfeit" or "Wait" options.
|
||||
/// </summary>
|
||||
public sealed record GameOpponentInactivePush(Guid SessionId);
|
||||
|
||||
/// <summary>
|
||||
/// Pushed to both players when a custom lobby is full and a GameSession has been created.
|
||||
/// Players should navigate to the game screen and send game.ready.
|
||||
|
||||
@@ -0,0 +1,86 @@
|
||||
namespace SOR.Game.Handlers;
|
||||
|
||||
using System.Text.Json;
|
||||
using SOR.Database.Contexts;
|
||||
using SOR.Networking.Abstractions.EventBus;
|
||||
using SOR.Networking.Abstractions.Messaging;
|
||||
using SOR.Networking.Abstractions.Push;
|
||||
using SOR.Networking.Abstractions.Transport;
|
||||
using SOR.Shared.Networking;
|
||||
|
||||
/// <summary>
|
||||
/// game.force_concede — allows the non-inactive player to claim a win when
|
||||
/// the opponent has been inactive for at least 5 minutes.
|
||||
///
|
||||
/// Validates:
|
||||
/// 1. The caller is NOT the active player (i.e., it is the opponent's turn that is stalled).
|
||||
/// 2. The session's LastActionAt is older than 5 minutes.
|
||||
///
|
||||
/// On success: finalizes the game with the caller as winner, win condition "inactive".
|
||||
/// </summary>
|
||||
internal sealed class GameForceConcedeHandler : GameHandlerBase, IMessageHandler
|
||||
{
|
||||
private static readonly TimeSpan InactivityThreshold = TimeSpan.FromMinutes(5);
|
||||
|
||||
private readonly IMessageSerializer _serializer;
|
||||
private readonly GameDbContext _gameDb;
|
||||
private readonly SorIdentityDbContext _identityDb;
|
||||
private readonly IClientPush _clientPush;
|
||||
private readonly IEventBus _eventBus;
|
||||
|
||||
public GameForceConcedeHandler(
|
||||
IMessageSerializer serializer,
|
||||
GameDbContext gameDb,
|
||||
SorIdentityDbContext identityDb,
|
||||
IClientPush clientPush,
|
||||
IEventBus eventBus)
|
||||
{
|
||||
_serializer = serializer;
|
||||
_gameDb = gameDb;
|
||||
_identityDb = identityDb;
|
||||
_clientPush = clientPush;
|
||||
_eventBus = eventBus;
|
||||
}
|
||||
|
||||
public string MessageType => "game.force_concede";
|
||||
|
||||
public async Task<IServerMessage?> HandleAsync(
|
||||
IClientMessage message,
|
||||
AuthenticatedConnection connection,
|
||||
CancellationToken ct)
|
||||
{
|
||||
var req = _serializer.DeserializePayload<GameForceConcedeRequest>(message.Payload);
|
||||
var actorId = connection.UserId;
|
||||
|
||||
var session = await LoadActiveSessionAsync(_gameDb, req.SessionId, actorId, ct);
|
||||
var state = GameEngine.Deserialize(session.StateJson!);
|
||||
|
||||
// The caller must NOT be the active player — they are the waiting player.
|
||||
if (state.ActivePlayerAccountId == actorId)
|
||||
throw new GameException("YOU_ARE_THE_ACTIVE_PLAYER");
|
||||
|
||||
// Check inactivity threshold.
|
||||
if (session.LastActionAt == null ||
|
||||
session.LastActionAt > DateTimeOffset.UtcNow - InactivityThreshold)
|
||||
throw new GameException("OPPONENT_NOT_INACTIVE");
|
||||
|
||||
// Treat as the inactive player conceding.
|
||||
var inactivePlayerId = state.ActivePlayerAccountId;
|
||||
var newState = GameEngine.Concede(state, inactivePlayerId);
|
||||
var dto = GameEngine.ToDto(newState, actorId);
|
||||
|
||||
await SaveStateAsync(_gameDb, session, newState, actorId, "game.force_concede",
|
||||
JsonSerializer.Serialize(req), ct, JsonSerializer.Serialize(dto));
|
||||
|
||||
await FinalizeGameAsync(
|
||||
_gameDb, _identityDb, _clientPush, _eventBus,
|
||||
session,
|
||||
winnerAccountId: Guid.Parse(actorId),
|
||||
loserAccountId: Guid.Parse(inactivePlayerId),
|
||||
winCondition: "inactive",
|
||||
ct);
|
||||
|
||||
return ServerMessage.Reply("game.force_concede.ack", message.Seq,
|
||||
new GameForceConcedeResponse(dto));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
namespace SOR.Game.Handlers;
|
||||
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using SOR.Database.Contexts;
|
||||
using SOR.Database.Enums;
|
||||
using SOR.Networking.Abstractions.Messaging;
|
||||
using SOR.Networking.Abstractions.Transport;
|
||||
using SOR.Shared.Networking;
|
||||
|
||||
/// <summary>
|
||||
/// game.get_active_session — returns the caller's in-progress game session, if any.
|
||||
///
|
||||
/// Used by the client on startup/login to detect an active game that can be rejoined
|
||||
/// (e.g. after a crash or disconnect). No session ID is required in the request;
|
||||
/// the authenticated actor ID is used to find the session.
|
||||
///
|
||||
/// Returns GameGetActiveSessionResponse with SessionId = null when no active session exists.
|
||||
/// </summary>
|
||||
internal sealed class GameGetActiveSessionHandler : IMessageHandler
|
||||
{
|
||||
private readonly GameDbContext _gameDb;
|
||||
|
||||
public GameGetActiveSessionHandler(GameDbContext gameDb)
|
||||
{
|
||||
_gameDb = gameDb;
|
||||
}
|
||||
|
||||
public string MessageType => "game.get_active_session";
|
||||
|
||||
public async Task<IServerMessage?> HandleAsync(
|
||||
IClientMessage message,
|
||||
AuthenticatedConnection connection,
|
||||
CancellationToken ct)
|
||||
{
|
||||
var actorId = Guid.Parse(connection.UserId);
|
||||
|
||||
var session = await _gameDb.GameSessions
|
||||
.AsNoTracking()
|
||||
.Where(s => (s.PlayerOneAccountId == actorId || s.PlayerTwoAccountId == actorId)
|
||||
&& s.Status == GameSessionStatus.Active
|
||||
&& s.StateJson != null)
|
||||
.OrderByDescending(s => s.CreatedAt)
|
||||
.FirstOrDefaultAsync(ct);
|
||||
|
||||
if (session == null)
|
||||
return ServerMessage.Reply("game.get_active_session.ack", message.Seq,
|
||||
new GameGetActiveSessionResponse(null, null));
|
||||
|
||||
// Deserialize state to extract the current phase.
|
||||
var state = GameEngine.Deserialize(session.StateJson!);
|
||||
|
||||
return ServerMessage.Reply("game.get_active_session.ack", message.Seq,
|
||||
new GameGetActiveSessionResponse(session.Id, state.Phase.ToString()));
|
||||
}
|
||||
}
|
||||
@@ -69,7 +69,8 @@ internal abstract class GameHandlerBase
|
||||
string? resultJson = null)
|
||||
{
|
||||
var seqNum = state.NextActionSequence++; // increment before serialize so the saved JSON reflects the consumed number
|
||||
session.StateJson = GameEngine.Serialize(state);
|
||||
session.StateJson = GameEngine.Serialize(state);
|
||||
session.LastActionAt = DateTimeOffset.UtcNow;
|
||||
gameDb.ActionLogs.Add(new GameActionLog
|
||||
{
|
||||
GameSessionId = session.Id,
|
||||
|
||||
@@ -24,8 +24,12 @@ public static class ServiceRegistration
|
||||
// Abandons any Initializing sessions left over from a previous process (redeploy/crash).
|
||||
services.AddHostedService<GameStartupCleanupService>();
|
||||
|
||||
// Monitors active sessions for player inactivity.
|
||||
services.AddHostedService<GameInactivityMonitorService>();
|
||||
|
||||
services.AddTransient<IMessageHandler, GameReadyHandler>();
|
||||
services.AddTransient<IMessageHandler, GameGetStateHandler>();
|
||||
services.AddTransient<IMessageHandler, GameGetActiveSessionHandler>();
|
||||
services.AddTransient<IMessageHandler, GameDrawHandler>();
|
||||
services.AddTransient<IMessageHandler, GamePlaceArchSpiritHandler>();
|
||||
services.AddTransient<IMessageHandler, GamePlayCardHandler>();
|
||||
@@ -37,6 +41,7 @@ public static class ServiceRegistration
|
||||
services.AddTransient<IMessageHandler, GameActivateAbilityHandler>();
|
||||
services.AddTransient<IMessageHandler, GameEndTurnHandler>();
|
||||
services.AddTransient<IMessageHandler, GameConcedeHandler>();
|
||||
services.AddTransient<IMessageHandler, GameForceConcedeHandler>();
|
||||
|
||||
// Custom lobby handlers
|
||||
services.AddTransient<IMessageHandler, GameCreateCustomLobbyHandler>();
|
||||
|
||||
Reference in New Issue
Block a user