/// The server-side game: connections, sessions, secrets and the command /// execution path (PLAN.md sections 3.3–3.6). /// /// One [GameServer] serves one game (the reference app's deployment model). /// It is the conceptual successor of the reference app's `Server extends /// GameServer`: same concepts — monotonic command index, full-state push on /// every action, full resync on reconnect, ping — native to WebSocket, and /// with the server as the only executor (clients send input only). library; import 'dart:async'; import 'dart:convert'; import 'package:collection/collection.dart'; import 'package:logging/logging.dart'; import 'package:web_socket_channel/web_socket_channel.dart'; import 'package:x_haven_server/core/commands/add_character_command.dart'; import 'package:x_haven_server/core/commands/command_registry.dart'; import 'package:x_haven_server/core/enums.dart'; import 'package:x_haven_server/core/game_methods.dart'; import 'package:x_haven_server/core/state/game_state.dart'; import 'protocol.dart'; import 'seat_store.dart'; import 'sessions.dart'; import 'visibility.dart'; final _log = Logger('GameServer'); /// One live connection: the channel, its session, and activity tracking. class _Connection { _Connection(this.channel, this.session) : lastActivityAt = DateTime.now(); final WebSocketChannel channel; final SessionRecord session; /// Last time anything was received on this connection (connect time /// initially). The heartbeat sweep closes connections quiet longer than /// the server's dead timeout. DateTime lastActivityAt; /// Whether the `hello` handshake completed. bool handshaken = false; /// Whether this connection has been detached (idempotent-cleanup guard). bool closed = false; void send(Map message) => channel.sink.add(jsonEncode(message)); } /// The game server bound to one [GameState]. class GameServer { GameServer({ required GameState gameState, required SessionManager sessions, required SeatStore seatStore, Duration heartbeatInterval = const Duration(seconds: 20), Duration deadTimeout = const Duration(seconds: 90), }) : _gameState = gameState, _sessions = sessions, _seatStore = seatStore, _deadTimeout = deadTimeout { // The action handler's broadcast hook: after every action/undo/redo the // index, description and event arrive here; the per-connection state // push happens in [_onAction]. gameState.onAction = _onAction; _restoreSeats(); _heartbeat = Timer.periodic(heartbeatInterval, (_) => _sweepDeadConnections()); } final GameState _gameState; final SessionManager _sessions; final SeatStore _seatStore; final Duration _deadTimeout; final Map> _connections = {}; late final Timer _heartbeat; SessionManager get sessions => _sessions; GameState get gameState => _gameState; /// Number of live connections (diagnostics/tests). int get connectionCount => _connections.values.fold(0, (sum, list) => sum + list.length); /// Attaches a live WebSocket channel. /// /// [cookieSessionId] comes from the `x-haven-session` cookie (or the /// `?session=` query parameter) of the upgrade request; null (or unknown) /// mints a new session. void attach(WebSocketChannel channel, {String? cookieSessionId}) { final session = _sessions.resolve(cookieSessionId); final connection = _Connection(channel, session); _connections.putIfAbsent(session.id, () => []).add(connection); _log.info( 'session ${session.id} connected ' '($connectionCount connection(s) live)', ); channel.stream.listen( (Object? raw) { connection.lastActivityAt = DateTime.now(); _onMessage(connection, raw); }, onDone: () => _detach(connection), onError: (Object error) { _log.warning('session ${session.id} connection error: $error'); _detach(connection); }, ); } /// Stops the heartbeat sweep. Does not close connections — the caller /// closes them (e.g. when the HTTP server shuts down, or to simulate a /// crash in tests). void dispose() { _heartbeat.cancel(); } // --- connection lifecycle ------------------------------------------------- void _detach(_Connection connection) { if (connection.closed) return; connection.closed = true; final list = _connections[connection.session.id]; list?.remove(connection); if (list != null && list.isEmpty) { _connections.remove(connection.session.id); _onSessionDisconnected(connection.session); } } /// The session's last connection is gone: its characters become unclaimed /// (PLAN.md section 3.3), the seat table is persisted, and the `seats` /// broadcast goes out so every screen can update its inputs. void _onSessionDisconnected(SessionRecord session) { _log.info('session ${session.id} left'); final released = _sessions.release(session.id); if (released.isNotEmpty) { _log.info('session ${session.id} released seats: $released'); _persistSeats(); } _broadcastSeats(); } /// Closes connections quiet longer than [_deadTimeout] (half-open /// connections the OS never reported). The sweep is the safety net; normal /// disconnects are handled by the socket's done/error events. void _sweepDeadConnections() { final now = DateTime.now(); for (final connection in _activeConnections().toList()) { final quietFor = now.difference(connection.lastActivityAt); if (quietFor > _deadTimeout) { _log.info( 'closing dead connection for session ${connection.session.id} ' '(no activity for ${quietFor.inSeconds}s)', ); unawaited(connection.channel.sink.close()); // onDone fires → _detach runs the seat release + broadcast. } } } List<_Connection> _activeConnections() { final result = <_Connection>[]; for (final list in _connections.values) { result.addAll(list); } return result; } // --- message dispatch ----------------------------------------------------- void _onMessage(_Connection connection, Object? raw) { final String? text = _coerceText(raw); if (text == null) { connection.send( Protocol.errorMessage( Protocol.errBadRequest, 'expected a UTF-8 JSON message', ), ); return; } final Map? message = _decodeMessage(text); if (message == null) { connection.send( Protocol.errorMessage(Protocol.errBadRequest, 'malformed JSON'), ); return; } final type = message['t']; switch (type) { case Protocol.hello: _handleHello(connection, message); case Protocol.ping: // Allowed before the handshake — a keepalive is harmless. connection.send(Protocol.pongMessage()); case Protocol.claim: _handleClaim(connection, message); case Protocol.cmd: _handleCmd(connection, message); case Protocol.undo: _handleUndoRedo(connection, undo: true); case Protocol.redo: _handleUndoRedo(connection, undo: false); default: connection.send( Protocol.errorMessage( Protocol.errUnknownMessage, 'unknown message type: $type', ), ); } } String? _coerceText(Object? raw) { if (raw is String) return raw; if (raw is List) return utf8.decode(raw, allowMalformed: true); return null; } Map? _decodeMessage(String text) { try { final dynamic decoded = jsonDecode(text); return decoded is Map ? decoded : null; } catch (_) { return null; } } void _notHandshaken(_Connection connection) { connection.send( Protocol.errorMessage(Protocol.errBadRequest, 'send hello first'), ); } /// The handshake: checks the protocol version, then answers with a full /// `welcome` (current state, role, seats). Re-sending `hello` re-answers /// with a fresh `welcome` — the client's resync tool. void _handleHello(_Connection connection, Map message) { final version = message['v']; if (version is! int || version != Protocol.version) { connection.send( Protocol.errorMessage( Protocol.errProtocol, 'protocol version mismatch: client $version, ' 'server ${Protocol.version}. Please update.', ), ); unawaited(connection.channel.sink.close()); return; } connection.handshaken = true; connection.send(_welcomeFor(connection)); } Map _welcomeFor(_Connection connection) { final session = connection.session; final index = _gameState.commandIndex; final descriptions = _gameState.commandDescriptions; final String? description = index >= 0 && index < descriptions.length ? descriptions[index] : null; return Protocol.welcomeMessage( session: session.id, role: session.role, index: index, description: description, event: null, state: _serializeFor(connection), seats: _sessions.seatsForState(_gameState), ); } // --- claims --------------------------------------------------------------- /// `{t: claim, characterId}` — any session may claim an unclaimed /// character; that is also how a session becomes a player. void _handleClaim(_Connection connection, Map message) { if (!connection.handshaken) { _notHandshaken(connection); return; } final characterId = message['characterId']; if (characterId is! String || characterId.isEmpty) { connection.send( Protocol.errorMessage( Protocol.errBadRequest, 'claim requires a non-empty "characterId" string', ), ); return; } final character = _gameState.currentList.firstWhereOrNull( (item) => item is Character && item.id == characterId, ); if (character == null) { connection.send( Protocol.errorMessage( Protocol.errRejected, 'no character with id "$characterId" in the current list', ), ); return; } final session = connection.session; final owner = _sessions.ownerOf(characterId); if (owner != null && owner.id != session.id) { connection.send( Protocol.errorMessage( Protocol.errRejected, 'character "$characterId" is already claimed', ), ); return; } if (owner == null) { _sessions.assign(session, characterId); _persistSeats(); } _broadcastSeats(); } // --- command execution path ------------------------------------------------ /// `{t: cmd, name, args}` — role check → game-rule guard → args /// validation (registry) → execute → per-connection `update` broadcast /// (via the action handler hook) → seat sync. /// /// A rejected command answers the sender with an `error` only — no /// broadcast, no index change. void _handleCmd(_Connection connection, Map message) { if (!connection.handshaken) { _notHandshaken(connection); return; } final name = message['name']; if (name is! String || name.isEmpty) { connection.send( Protocol.errorMessage( Protocol.errBadRequest, 'cmd requires a non-empty "name" string', ), ); return; } final rawArgs = message['args']; if (rawArgs != null && rawArgs is! Map) { connection.send( Protocol.errorMessage( Protocol.errBadRequest, 'cmd "args" must be an object', ), ); return; } final args = rawArgs is Map ? rawArgs : const {}; final session = connection.session; // Role gate: spectators cannot run commands — except `addCharacter`, // which is the way a session becomes a player (the session that adds a // character owns it, PLAN.md section 3.3). if (!session.isPlayer && name != 'addCharacter') { connection.send( Protocol.errorMessage( Protocol.errForbidden, 'spectators cannot run commands — claim a character first', ), ); return; } final String? guardMessage = _guard(name); if (guardMessage != null) { connection.send(Protocol.errorMessage(Protocol.errRejected, guardMessage)); return; } final Command command; try { command = buildCommand(name, args, _gameState); } on CommandRegistryError catch (error) { connection.send(Protocol.errorMessage(Protocol.errRejected, error.message)); return; } try { _gameState.action(command); } on Exception catch (error) { _log.warning('command "$name" failed during execution: $error'); connection.send( Protocol.errorMessage(Protocol.errRejected, 'command "$name" failed: $error'), ); return; } // Seat bookkeeping: a newly added character belongs to the session that // added it. if (name == 'addCharacter') { final character = (command as AddCharacterCommand).character; if (character != null) { _sessions.assign(session, character.id); _persistSeats(); _broadcastSeats(); } } // Other actions may have removed characters (undo, removeCharacter, // loadSave) — prune stale seats and broadcast if anything changed. _syncSeats(); } /// The preconditions the reference app enforced in its UI (the /// `runDrawOrNextRoundAction` gate): commands whose `execute()` would run /// outside their round phase are rejected here. This is the server-side /// replacement for the reference app's 300 ms draw-button lockout — /// sequential server execution makes a second draw deterministically /// lose, and the loser gets a clear `error`. String? _guard(String name) { if (name == 'draw') { if (_gameState.roundState != RoundState.chooseInitiative) { return 'the round has already been drawn'; } if (_gameState.currentList.isEmpty) { return 'add characters before drawing'; } if (!GameMethods.canDraw()) { return 'player initiative values must be set before drawing'; } } if (name == 'nextRound') { if (_gameState.roundState != RoundState.playTurns) { return 'the round has not started yet'; } } return null; } void _handleUndoRedo(_Connection connection, {required bool undo}) { if (!connection.handshaken) { _notHandshaken(connection); return; } if (!connection.session.isPlayer) { connection.send( Protocol.errorMessage( Protocol.errForbidden, 'spectators cannot undo or redo — claim a character first', ), ); return; } if (undo) { _gameState.undo(); } else { _gameState.redo(); } } // --- broadcasts ----------------------------------------------------------- /// The action handler's hook (set in the constructor): after every /// action/undo/redo, push the new index + description + event plus a /// full state snapshot serialized for each connection. void _onAction(int index, String description, String eventJson) { final Object? event = _decodeEvent(eventJson); for (final connection in _activeConnections()) { connection.send( Protocol.updateMessage( index: index, description: description, event: event, state: _serializeFor(connection), ), ); } } Object? _decodeEvent(String eventJson) { try { return jsonDecode(eventJson); } catch (_) { return const {'type': 'none'}; } } Map _serializeFor(_Connection connection) => serializeState( _gameState, SessionContext( sessionId: connection.session.id, seats: _sessions.seats(), ), ); /// Broadcasts the current seat table to every connection. void _broadcastSeats() { final seats = _sessions.seatsForState(_gameState); for (final connection in _activeConnections()) { connection.send(Protocol.seatsMessage(seats)); } } /// Prunes seats for characters no longer in the current list (undo, /// removeCharacter, loadSave, …); persists and broadcasts when the table /// changed. void _syncSeats() { final characterIds = _gameState.currentList .whereType() .map((c) => c.id) .toSet(); var changed = false; for (final session in _sessions.all) { final stale = session.ownedCharacters .where((id) => !characterIds.contains(id)) .toList(); if (stale.isNotEmpty) { session.ownedCharacters.removeAll(stale); changed = true; } } if (changed) { _persistSeats(); _broadcastSeats(); } } // --- seat persistence ------------------------------------------------------ void _persistSeats() { // The store format is session id → character ids (a session may own // several characters). final bySession = >{}; for (final entry in _sessions.seats().entries) { bySession.putIfAbsent(entry.value, () => []).add(entry.key); } _seatStore.write(bySession); } /// At startup: restore persisted seats onto the (lazily created) session /// records, keeping only characters that are actually in the restored /// list. void _restoreSeats() { final stored = _seatStore.read(); if (stored == null || stored.isEmpty) return; final characterIds = _gameState.currentList .whereType() .map((c) => c.id) .toSet(); for (final entry in stored.entries) { final session = _sessions.resolveOrCreate(entry.key); for (final characterId in entry.value) { if (characterIds.contains(characterId)) { session.ownedCharacters.add(characterId); } } } if (stored.isNotEmpty) { _log.info('restored seats for ${stored.length} session(s)'); } } }