Phase 4: Spectator support — SpectatorRegistryService + handlers

- SpectatorRegistryService singleton: ConcurrentDictionary<Guid, ImmutableHashSet<Guid>>
  tracking spectators per session. Static Instance for use in static base-class helpers.
- GameEngine.ToDtoSpectator: delegates to ToDto(state, "") — both hands hidden.
- GameHandlerBase.PushStateToPlayersAsync: extended to push hand-hidden state_update
  to all registered spectators via SpectatorRegistryService.Instance.
- GameHandlerBase.FinalizeGameAsync: pushes game.over to spectators then calls
  RemoveSession to evict the entry from the registry.
- GameSpectateHandler (game.spectate): validates session Active, registers spectator,
  returns current spectator-view state as ack.
- GameStopSpectatingHandler (game.spectate.stop): unregisters the caller.
- GameMessages.cs: SpectateRequest/Response, StopSpectatingRequest/Response.
- ServiceRegistration.cs: register SpectatorRegistryService singleton + both handlers.

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:
dingo
2026-03-18 23:14:24 -04:00
co-authored by Claude Happy
parent 2c40fb036f
commit 02d469490b
7 changed files with 198 additions and 5 deletions
+6
View File
@@ -932,6 +932,12 @@ public static class GameEngine
// ── DTO projection ────────────────────────────────────────────────────────
/// <summary>
/// Build a spectator-safe GameStateDto — both players' hands are hidden (null).
/// </summary>
public static GameStateDto ToDtoSpectator(GameState state)
=> ToDto(state, string.Empty); // Empty string matches neither player → both hands hidden.
/// <summary>
/// Build a client-safe GameStateDto for a specific player's perspective.
/// Opponent's hand is hidden (null); only the count is shown.
+12
View File
@@ -124,6 +124,12 @@ public sealed record JoinCustomLobbyRequest(Guid LobbyId, Guid DeckId, string? P
/// <summary>Leave or cancel a custom lobby.</summary>
public sealed record LeaveCustomLobbyRequest(Guid LobbyId);
/// <summary>Join a game session as a spectator.</summary>
public sealed record SpectateRequest(Guid SessionId);
/// <summary>Stop spectating a game session.</summary>
public sealed record StopSpectatingRequest(Guid SessionId);
/// <summary>List open custom lobbies. NameSearch filters by lobby name (case-insensitive contains).</summary>
public sealed record ListCustomLobbiesRequest(
int Page = 1,
@@ -182,6 +188,12 @@ public sealed record JoinCustomLobbyResponse(
public sealed record LeaveCustomLobbyResponse(Guid LobbyId);
/// <summary>Ack for game.spectate — spectator receives current filtered game state.</summary>
public sealed record SpectateResponse(GameStateDto State);
/// <summary>Ack for game.spectate.stop.</summary>
public sealed record StopSpectatingResponse(Guid SessionId);
public sealed record ListCustomLobbiesResponse(
IEnumerable<CustomLobbyDto> Lobbies,
int TotalCount,
@@ -90,7 +90,8 @@ internal abstract class GameHandlerBase
}
/// <summary>
/// Push the updated (filtered) game state to both players.
/// 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,
@@ -101,13 +102,31 @@ internal abstract class GameHandlerBase
var p1Id = session.PlayerOneAccountId.ToString();
var p2Id = session.PlayerTwoAccountId.ToString();
await Task.WhenAll(
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));
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.
@@ -189,11 +208,25 @@ internal abstract class GameHandlerBase
WinnerOpDelta : winnerOp,
LoserOpDelta : loserOp);
await Task.WhenAll(
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));
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,
@@ -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.spectate — register as a spectator for an active game session.
/// Returns the current game state filtered for spectator view (both hands hidden).
/// The spectator will receive game.state_update pushes for the remainder of the game.
/// </summary>
internal sealed class GameSpectateHandler : GameHandlerBase, IMessageHandler
{
private readonly IMessageSerializer _serializer;
private readonly GameDbContext _gameDb;
private readonly SpectatorRegistryService _registry;
public GameSpectateHandler(
IMessageSerializer serializer,
GameDbContext gameDb,
SpectatorRegistryService registry)
{
_serializer = serializer;
_gameDb = gameDb;
_registry = registry;
}
public string MessageType => "game.spectate";
public async Task<IServerMessage?> HandleAsync(
IClientMessage message,
AuthenticatedConnection connection,
CancellationToken ct)
{
var req = _serializer.DeserializePayload<SpectateRequest>(message.Payload);
var accountId = Guid.Parse(connection.UserId);
var session = await _gameDb.GameSessions
.AsNoTracking()
.Where(s => s.Id == req.SessionId && s.Status == GameSessionStatus.Active)
.SingleOrDefaultAsync(ct)
?? throw new GameException("SESSION_NOT_FOUND");
_registry.Register(req.SessionId, accountId);
var state = GameEngine.Deserialize(session.StateJson!);
var dto = GameEngine.ToDtoSpectator(state);
return ServerMessage.Reply("game.spectate.ack", message.Seq,
new SpectateResponse(dto));
}
}
@@ -0,0 +1,39 @@
namespace SOR.Game.Handlers;
using SOR.Networking.Abstractions.Messaging;
using SOR.Networking.Abstractions.Transport;
using SOR.Shared.Networking;
/// <summary>
/// game.spectate.stop — unregister from spectating a session.
/// </summary>
internal sealed class GameStopSpectatingHandler : GameHandlerBase, IMessageHandler
{
private readonly IMessageSerializer _serializer;
private readonly SpectatorRegistryService _registry;
public GameStopSpectatingHandler(
IMessageSerializer serializer,
SpectatorRegistryService registry)
{
_serializer = serializer;
_registry = registry;
}
public string MessageType => "game.spectate.stop";
public Task<IServerMessage?> HandleAsync(
IClientMessage message,
AuthenticatedConnection connection,
CancellationToken ct)
{
var req = _serializer.DeserializePayload<StopSpectatingRequest>(message.Payload);
var accountId = Guid.Parse(connection.UserId);
_registry.Unregister(req.SessionId, accountId);
return Task.FromResult<IServerMessage?>(
ServerMessage.Reply("game.spectate.stop.ack", message.Seq,
new StopSpectatingResponse(req.SessionId)));
}
}
@@ -32,6 +32,9 @@ public static class ServiceRegistration
services.AddSingleton<GameTurnTimerService>();
services.AddHostedService(sp => sp.GetRequiredService<GameTurnTimerService>());
// Tracks spectators per session (in-memory; spectators only, players are not registered here).
services.AddSingleton<SpectatorRegistryService>();
services.AddTransient<IMessageHandler, GameReadyHandler>();
services.AddTransient<IMessageHandler, GameGetStateHandler>();
services.AddTransient<IMessageHandler, GameGetActiveSessionHandler>();
@@ -54,6 +57,10 @@ public static class ServiceRegistration
services.AddTransient<IMessageHandler, GameLeaveCustomLobbyHandler>();
services.AddTransient<IMessageHandler, GameListCustomLobbiesHandler>();
// Spectator handlers
services.AddTransient<IMessageHandler, GameSpectateHandler>();
services.AddTransient<IMessageHandler, GameStopSpectatingHandler>();
return services;
}
}
@@ -0,0 +1,41 @@
namespace SOR.Game;
using System.Collections.Concurrent;
using System.Collections.Immutable;
/// <summary>
/// In-memory registry that tracks which accounts are currently spectating each session.
/// Registered as a singleton. Handlers call Register/Unregister; FinalizeGameAsync
/// calls RemoveSession via the static Instance reference.
/// </summary>
internal sealed class SpectatorRegistryService
{
/// <summary>
/// Static reference for use in static helpers (FinalizeGameAsync, PushStateToPlayersAsync)
/// without requiring DI injection into every call site.
/// </summary>
internal static SpectatorRegistryService? Instance { get; private set; }
private readonly ConcurrentDictionary<Guid, ImmutableHashSet<Guid>> _map = new();
public SpectatorRegistryService()
{
Instance = this;
}
public void Register(Guid sessionId, Guid accountId)
=> _map.AddOrUpdate(sessionId,
ImmutableHashSet.Create(accountId),
(_, existing) => existing.Add(accountId));
public void Unregister(Guid sessionId, Guid accountId)
=> _map.AddOrUpdate(sessionId,
ImmutableHashSet<Guid>.Empty,
(_, existing) => existing.Remove(accountId));
public void RemoveSession(Guid sessionId)
=> _map.TryRemove(sessionId, out _);
public IReadOnlySet<Guid> GetSpectators(Guid sessionId)
=> _map.TryGetValue(sessionId, out var set) ? set : ImmutableHashSet<Guid>.Empty;
}