/// Sessions and seat ownership (PLAN.md section 3.3). /// /// Every browser session has a persistent id (the `x-haven-session` cookie, /// or the `?session=` query parameter) that survives page refreshes, so a /// player keeps their seat. A session owning at least one character is a /// *player*; any other session is a *spectator*. A character has at most one /// owning session; when the owner's session disconnects, the character /// becomes unclaimed and any session may claim it. library; import 'dart:math'; import 'package:x_haven_server/core/state/game_state.dart'; import 'protocol.dart'; /// A persistent session: one browser (cookie) connecting to the game. class SessionRecord { SessionRecord(this.id); final String id; /// The ids of the characters this session owns. A character has at most /// one owning session; a session may own several characters. final Set ownedCharacters = {}; bool get isPlayer => ownedCharacters.isNotEmpty; String get role => isPlayer ? Protocol.rolePlayer : Protocol.roleSpectator; } /// The in-memory session table: session id → [SessionRecord]. /// /// Records are kept even after a session disconnects — its id may come back /// on the next connection (cookie), and persisted seats (see /// `seat_store.dart`) may be restored onto it. class SessionManager { final Map _sessions = {}; /// Resolves [existingId] to its record. A well-formed but unknown id is /// adopted as-is (the client presents its own session id via the cookie; /// after a restart it must keep landing on the same session — including /// any seats restored onto it). A malformed value is ignored and a fresh /// id is minted. SessionRecord resolve(String? existingId) { if (existingId != null && isKnownFormat(existingId)) { return _sessions[existingId] ?? resolveOrCreate(existingId); } return create(); } /// Resolves [id], creating the record with exactly that id when it is not /// known yet — used when restoring persisted seats at startup. SessionRecord resolveOrCreate(String id) { final existing = _sessions[id]; if (existing != null) return existing; final record = SessionRecord(id); _sessions[id] = record; return record; } SessionRecord create() { final record = SessionRecord(newSessionId()); _sessions[record.id] = record; return record; } SessionRecord? lookup(String id) => _sessions[id]; /// Grants ownership of [characterId] to [session]. /// /// A character has at most one owning session, so any previous owner is /// stripped first; callers should only assign characters that are /// unclaimed (or that [session] already owns). void assign(SessionRecord session, String characterId) { for (final record in _sessions.values) { record.ownedCharacters.remove(characterId); } session.ownedCharacters.add(characterId); } /// The owning session of [characterId], if any. SessionRecord? ownerOf(String characterId) { for (final record in _sessions.values) { if (record.ownedCharacters.contains(characterId)) return record; } return null; } /// Releases every seat owned by session [id] (called when the session's /// last connection is lost). Returns the released character ids. Set release(String id) { final record = _sessions[id]; if (record == null) return const {}; final released = Set.of(record.ownedCharacters); record.ownedCharacters.clear(); return released; } /// character id → owning session id (owned characters only). Map seats() { final result = {}; for (final record in _sessions.values) { for (final characterId in record.ownedCharacters) { result[characterId] = record.id; } } return result; } /// Every character in [state]'s current list mapped to its owning session /// id, or null when unclaimed — the payload of `seats` messages. Map seatsForState(GameState state) { final owned = seats(); final result = {}; for (final item in state.currentList) { if (item is Character) result[item.id] = owned[item.id]; } return result; } /// All known session records, including disconnected ones. Iterable get all => _sessions.values; /// A new session id: 32 lowercase hex characters. static String newSessionId() { final random = Random.secure(); return List.generate(32, (_) => random.nextInt(16).toRadixString(16)).join(); } /// Whether [id] is a well-formed session id (32 lowercase hex characters). static bool isKnownFormat(String id) => id.length == 32 && RegExp(r'^[0-9a-f]{32}$').hasMatch(id); }