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;
///
/// 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.
///
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 _logger;
private readonly HashSet _tier1Notified = new();
private readonly HashSet _tier2Notified = new();
public GameInactivityMonitorService(
IServiceScopeFactory scopeFactory,
ILogger 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();
var clientPush = scope.ServiceProvider.GetRequiredService();
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);
}
}
}
}