summaryrefslogtreecommitdiff
path: root/server/lib/net/sessions.dart
diff options
context:
space:
mode:
authorJoel Klinghed <the_jk@spawned.biz>2026-11-13 00:04:16 +0100
committerJoel Klinghed <the_jk@spawned.biz>2026-11-13 00:04:16 +0100
commit3ebbdf6ffa16f751c82e3bd2e74294f4fe843155 (patch)
treedb4c92ce26f274073453e2a085af3105be823f74 /server/lib/net/sessions.dart
parent808294adad3f378ad8d66b698acf8df7f49c2302 (diff)
Phase 2: networking, sessions, secrets over WebSocket (M2)
Server owns all state; browsers send input only. New server/lib/net/ layer on top of the Phase 1 engine: - protocol.dart: JSON wire protocol (v1) — hello/welcome handshake, claim, cmd, undo/redo, ping/pong, update, seats, error - sessions.dart: 32-hex session ids carried in the x-haven-session cookie; role derived from seat ownership (player vs spectator); resolve() adopts a well-formed cookie id so a seat survives restarts - seat_store.dart: seat table persisted to saves/seats.json beside the state snapshot; restored on startup - visibility.dart: per-connection state serialization; the initiative rule masks every non-owned character's initiative to null until the round is drawn — the server never sends a secret to a non-owner - game_server.dart: the command execution path (role check → game-rule guard → registry build → execute → per-connection update broadcast); seat assign/claim/release with seats broadcasts; heartbeat sweep closes dead connections and releases their seats - ws_upgrade.dart: custom WS upgrade handler so the server reads the session cookie (shelf_web_socket hides the Request); app.dart wires shelf + static SPA; bin/main.dart starts the server - game_state.dart: onAction setter so the network layer installs its broadcast hook; save_store.dart / seat_store.dart writes made synchronous (writeAsStringSync) so a snapshot/seat table is on disk when write() returns — the kill -9 persistence test exposed the async write race Server-side guards replace the reference app's 300 ms draw-button lockout: sequential execution makes a duplicate draw deterministically lose, with a clear error to the sender only. The session that adds a character owns it and becomes a player; spectators may only claim/ addCharacter. Command index resets to -1 on restart (the snapshot carries state, not undo history). Tests: 34 new network tests over a real WS stack on an ephemeral port (sessions 9, visibility 5, app 9, multiplayer 9, persistence 2) — secret initiative never reaches non-owners, reveal on draw, reconnect resync, rejected duplicate draw, claim/lose/re-claim seats, undo/redo broadcast to every screen, dead-connection cleanup, snapshot + seat file restored across a restart. Replaces the Phase 0 smoke test. dart analyze warning-free; dart test 591/591; scripts/ci.sh green.
Diffstat (limited to 'server/lib/net/sessions.dart')
-rw-r--r--server/lib/net/sessions.dart134
1 files changed, 134 insertions, 0 deletions
diff --git a/server/lib/net/sessions.dart b/server/lib/net/sessions.dart
new file mode 100644
index 0000000..ae999ae
--- /dev/null
+++ b/server/lib/net/sessions.dart
@@ -0,0 +1,134 @@
+/// 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<String> 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<String, SessionRecord> _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<String> release(String id) {
+ final record = _sessions[id];
+ if (record == null) return const {};
+ final released = Set<String>.of(record.ownedCharacters);
+ record.ownedCharacters.clear();
+ return released;
+ }
+
+ /// character id → owning session id (owned characters only).
+ Map<String, String> seats() {
+ final result = <String, String>{};
+ 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<String, String?> seatsForState(GameState state) {
+ final owned = seats();
+ final result = <String, String?>{};
+ 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<SessionRecord> 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);
+}