Tier 1 (5 min, unchanged): - Active player: game.inactive_warning — "you may be forfeited" - Waiting player: game.opponent_inactive — "Accept Forfeit / Wait" Tier 2 (10 min — mutual idle): - If the game is still stalled after 10 min the waiting player also hasn't claimed forfeit, so both are treated as mutually idle - Sends game.both_idle_warning to BOTH players - Client closes any open tier-1 dialogs and shows "Wait" only — no concede or force-concede available - Prevents the tactic of both players going idle to pressure the other into conceding Monitor service now prunes notified sets on each poll so sessions that become active again can be re-notified if they stall again. 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>
146 lines
6.0 KiB
C#
146 lines
6.0 KiB
C#
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.
|
|
///
|
|
/// Tier 1 — 5 min idle (one player's turn stalled):
|
|
/// • Pushes game.inactive_warning to the active player.
|
|
/// • Pushes game.opponent_inactive to the waiting player, who may claim a forfeit.
|
|
///
|
|
/// Tier 2 — 10 min idle (waiting player also hasn't claimed forfeit → mutual idle):
|
|
/// • Pushes game.both_idle_warning to BOTH players.
|
|
/// • Client shows only a "Wait" option — no concede or force-concede allowed.
|
|
/// • Prevents the tactic of both players going idle to pressure the other to concede.
|
|
///
|
|
/// Sessions are tracked in in-memory sets; if a player acts the session drops out of
|
|
/// the stale query and both sets are pruned on the next poll.
|
|
/// </summary>
|
|
internal sealed class GameInactivityMonitorService : BackgroundService
|
|
{
|
|
private static readonly TimeSpan Tier1Threshold = TimeSpan.FromMinutes(5);
|
|
private static readonly TimeSpan Tier2Threshold = TimeSpan.FromMinutes(10);
|
|
private static readonly TimeSpan PollInterval = TimeSpan.FromSeconds(60);
|
|
|
|
private readonly IServiceScopeFactory _scopeFactory;
|
|
private readonly ILogger<GameInactivityMonitorService> _logger;
|
|
|
|
private readonly HashSet<Guid> _tier1Notified = new();
|
|
private readonly HashSet<Guid> _tier2Notified = 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 now = DateTimeOffset.UtcNow;
|
|
var tier1Cutoff = now - Tier1Threshold;
|
|
var tier2Cutoff = now - Tier2Threshold;
|
|
|
|
var staleSessions = await gameDb.GameSessions
|
|
.Where(s => s.Status == GameSessionStatus.Active
|
|
&& s.LastActionAt != null
|
|
&& s.LastActionAt < tier1Cutoff
|
|
&& s.StateJson != null)
|
|
.ToListAsync(ct);
|
|
|
|
// Prune notified sets: remove sessions no longer stale (player acted since last poll).
|
|
var staleIds = staleSessions.Select(s => s.Id).ToHashSet();
|
|
_tier1Notified.IntersectWith(staleIds);
|
|
_tier2Notified.IntersectWith(staleIds);
|
|
|
|
foreach (var session in staleSessions)
|
|
{
|
|
try
|
|
{
|
|
var p1 = session.PlayerOneAccountId.ToString();
|
|
var p2 = session.PlayerTwoAccountId.ToString();
|
|
|
|
// ── Tier 2: mutual idle (10 min) ──────────────────────────────
|
|
if (!_tier2Notified.Contains(session.Id) && session.LastActionAt < tier2Cutoff)
|
|
{
|
|
_tier2Notified.Add(session.Id);
|
|
|
|
_logger.LogInformation(
|
|
"GameInactivityMonitor: session {Id} — both players idle >10 min. Sending both_idle_warning.",
|
|
session.Id);
|
|
|
|
await Task.WhenAll(
|
|
clientPush.PushAsync(p1, ServerMessage.Push("game.both_idle_warning",
|
|
new GameBothIdlePush(session.Id)), ct),
|
|
clientPush.PushAsync(p2, ServerMessage.Push("game.both_idle_warning",
|
|
new GameBothIdlePush(session.Id)), ct));
|
|
continue;
|
|
}
|
|
|
|
// ── Tier 1: one player idle (5 min) ───────────────────────────
|
|
if (!_tier1Notified.Contains(session.Id))
|
|
{
|
|
_tier1Notified.Add(session.Id);
|
|
|
|
var state = GameEngine.Deserialize(session.StateJson!);
|
|
var activeId = state.ActivePlayerAccountId;
|
|
var otherId = p1 == activeId ? p2 : p1;
|
|
|
|
_logger.LogInformation(
|
|
"GameInactivityMonitor: session {Id} — active player {ActiveId} idle >5 min.",
|
|
session.Id, activeId);
|
|
|
|
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);
|
|
}
|
|
}
|
|
}
|
|
}
|