summaryrefslogtreecommitdiff
path: root/server/lib/net/sessions.dart
blob: ae999ae4933c34ead312fd2c77689ce554feb618 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
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);
}