@hadoku/rooms-server 0.45.55 → 0.45.57

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.ts CHANGED
@@ -2,8 +2,9 @@
2
2
  * @wolffm/rooms-server — room mechanics for a socket.io server.
3
3
  *
4
4
  * Room lifecycle and membership, stable participant identity, seating, avatar
5
- * claims, name persistence across reconnect, backpressure-aware emit, per-key
6
- * rate limiting, and idle/empty reaping.
5
+ * claims, name persistence across reconnect, presence (heartbeat, online/offline,
6
+ * left-after-grace), one live tab per player per room (session claims), backpressure-aware emit, per-key rate limiting, and
7
+ * idle/empty reaping.
7
8
  *
8
9
  * Carries no hosting-app vocabulary and no opinion about what a room is FOR —
9
10
  * that lives in `CoreRoomState<TApp>`'s `app`. Three things a hosting app
@@ -17,4 +18,6 @@ export * from './identity.js';
17
18
  export * from './emit.js';
18
19
  export * from './gc.js';
19
20
  export * from './rateLimiter.js';
21
+ export * from './presence.js';
22
+ export * from './session-claims.js';
20
23
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;GAaG;AACH,cAAc,YAAY,CAAC;AAC3B,cAAc,eAAe,CAAC;AAC9B,cAAc,WAAW,CAAC;AAC1B,cAAc,SAAS,CAAC;AACxB,cAAc,kBAAkB,CAAC"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AACH,cAAc,YAAY,CAAC;AAC3B,cAAc,eAAe,CAAC;AAC9B,cAAc,WAAW,CAAC;AAC1B,cAAc,SAAS,CAAC;AACxB,cAAc,kBAAkB,CAAC;AACjC,cAAc,eAAe,CAAC;AAC9B,cAAc,qBAAqB,CAAC"}
package/dist/index.js CHANGED
@@ -2,8 +2,9 @@
2
2
  * @wolffm/rooms-server — room mechanics for a socket.io server.
3
3
  *
4
4
  * Room lifecycle and membership, stable participant identity, seating, avatar
5
- * claims, name persistence across reconnect, backpressure-aware emit, per-key
6
- * rate limiting, and idle/empty reaping.
5
+ * claims, name persistence across reconnect, presence (heartbeat, online/offline,
6
+ * left-after-grace), one live tab per player per room (session claims), backpressure-aware emit, per-key rate limiting, and
7
+ * idle/empty reaping.
7
8
  *
8
9
  * Carries no hosting-app vocabulary and no opinion about what a room is FOR —
9
10
  * that lives in `CoreRoomState<TApp>`'s `app`. Three things a hosting app
@@ -17,6 +18,8 @@ export * from './identity.js';
17
18
  export * from './emit.js';
18
19
  export * from './gc.js';
19
20
  export * from './rateLimiter.js';
21
+ export * from './presence.js';
22
+ export * from './session-claims.js';
20
23
  // NOT `export * from '@wolffm/rooms-protocol'`. Re-exporting it would give
21
24
  // every symbol two import paths, and the first thing that drifts is which one
22
25
  // a file happens to use. Consumers depend on both packages explicitly.
@@ -0,0 +1,124 @@
1
+ /**
2
+ * Presence: is a person here, and when have they LEFT?
3
+ *
4
+ * Every room app answers this, and each answered it again by hand: watchparty
5
+ * with an app heartbeat in its socket handler plus a deferred "X left" chat
6
+ * line, cardtable with two connection counters and a draft's deferred vacate,
7
+ * the game template with its own. The rules are the same everywhere, so they
8
+ * live here once:
9
+ *
10
+ * - **A person is a set of connections.** A second tab, or a reconnect whose
11
+ * old socket has not closed yet, is routine. The person is online while ANY
12
+ * connection is live, and goes offline only when the last one goes.
13
+ * - **A connection is live while it beats.** Transports do not reliably report
14
+ * their own death (an upstream cut never reaches the server as a close), so
15
+ * a connection silent for `idleMs` is dropped as if it had closed, and the
16
+ * host is told (`idle`) so it can close the transport.
17
+ * - **Offline is not left.** Phones hand off between networks and deploys drop
18
+ * every socket at once; a person offline for `graceMs` has LEFT. A connection
19
+ * from them inside the grace cancels the leave, and `online` says so
20
+ * (`returned: true`), so the app can suppress its "joined again" noise.
21
+ *
22
+ * Deliberately transport-, storage- and app-agnostic: keys are whatever the
23
+ * app calls a person (a `ParticipantId`, a member id), connection ids are
24
+ * whatever it calls a connection (a socket id). Takeover, announcements,
25
+ * seating and avatar release are the app's, driven from these events.
26
+ *
27
+ * No periodic sweep: each connection holds ONE timeout, re-armed by its
28
+ * heartbeat, and each offline person holds one for the grace. A timer exists
29
+ * only while there is something for it to decide.
30
+ */
31
+ /** What a tracker decided. Every event names the person (`key`). */
32
+ export type PresenceEvent<K extends string = string> =
33
+ /** The person has a live connection again. `returned`: it ended a grace, so they never left. */
34
+ {
35
+ type: 'online';
36
+ key: K;
37
+ at: number;
38
+ returned: boolean;
39
+ }
40
+ /** The person's last live connection went. The grace starts now. */
41
+ | {
42
+ type: 'offline';
43
+ key: K;
44
+ at: number;
45
+ }
46
+ /** The grace ran out with no connection from them: they have left. Their state is forgotten. */
47
+ | {
48
+ type: 'left';
49
+ key: K;
50
+ at: number;
51
+ offlineSince: number;
52
+ lastSeen: number;
53
+ }
54
+ /**
55
+ * A connection stopped beating for `idleMs` and was dropped. The host should
56
+ * close the transport. `offline` follows if it was the person's last.
57
+ */
58
+ | {
59
+ type: 'idle';
60
+ key: K;
61
+ connectionId: string;
62
+ at: number;
63
+ lastSeen: number;
64
+ };
65
+ export type PresenceListener<K extends string = string> = (event: PresenceEvent<K>) => void;
66
+ export interface PresenceOptions {
67
+ /** A connection with no heartbeat for this long is dropped (`idle`). */
68
+ idleMs: number;
69
+ /** A person offline this long has left (`left`). 0 decides on the next timer tick. */
70
+ graceMs: number;
71
+ /** Clock. Defaults to `Date.now`. */
72
+ now?: () => number;
73
+ /** One-shot timer. Defaults to `setTimeout`; injectable for tests and non-Node hosts. */
74
+ setTimer?: (fn: () => void, ms: number) => unknown;
75
+ /** Cancels a `setTimer` handle. Defaults to `clearTimeout`. */
76
+ clearTimer?: (handle: unknown) => void;
77
+ }
78
+ export declare class PresenceTracker<K extends string = string> {
79
+ private readonly idleMs;
80
+ private readonly graceMs;
81
+ private readonly now;
82
+ private readonly setTimer;
83
+ private readonly clearTimer;
84
+ private readonly people;
85
+ private readonly conns;
86
+ private readonly listeners;
87
+ constructor(opts: PresenceOptions);
88
+ /** Subscribe. Returns the unsubscribe. Listeners run synchronously, in order. */
89
+ on(listener: PresenceListener<K>): () => void;
90
+ /**
91
+ * A connection for `key` opened (counts as a heartbeat). Re-registering a
92
+ * connection id under another key moves it: the old person loses it first.
93
+ */
94
+ connect(key: K, connectionId: string): void;
95
+ /** The connection is alive. False when it is not tracked (closed, reaped, never connected). */
96
+ heartbeat(connectionId: string): boolean;
97
+ /** The connection closed. Idempotent: an unknown id is ignored. */
98
+ disconnect(connectionId: string): void;
99
+ /** Whether `key` has a live connection. */
100
+ isOnline(key: K): boolean;
101
+ /** Whether `key` is offline but inside the grace (not yet left). */
102
+ isInGrace(key: K): boolean;
103
+ /** When `key` was last heard from on any connection; undefined once they have left. */
104
+ lastSeen(key: K): number | undefined;
105
+ /** `key`'s live connection ids. */
106
+ connections(key: K): string[];
107
+ /** The person a connection belongs to, while it is live. */
108
+ keyOf(connectionId: string): K | undefined;
109
+ /** Everyone with a live connection. */
110
+ online(): K[];
111
+ /**
112
+ * Forget `key` at once, with NO events — for an app that removed the person
113
+ * itself (kicked, room deleted). Their connections stop being tracked.
114
+ */
115
+ forget(key: K): void;
116
+ /** Cancel every timer and forget everyone, with no events. For shutdown and room deletion. */
117
+ dispose(): void;
118
+ private armIdle;
119
+ private reapIdle;
120
+ private drop;
121
+ private leave;
122
+ private emit;
123
+ }
124
+ //# sourceMappingURL=presence.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"presence.d.ts","sourceRoot":"","sources":["../src/presence.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA6BG;AAEH,oEAAoE;AACpE,MAAM,MAAM,aAAa,CAAC,CAAC,SAAS,MAAM,GAAG,MAAM;AACjD,gGAAgG;AAC9F;IAAE,IAAI,EAAE,QAAQ,CAAC;IAAC,GAAG,EAAE,CAAC,CAAC;IAAC,EAAE,EAAE,M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T?
3
+ *
4
+ * Every room app answers this, and each answered it again by hand: watchparty
5
+ * with an app heartbeat in its socket handler plus a deferred "X left" chat
6
+ * line, cardtable with two connection counters and a draft's deferred vacate,
7
+ * the game template with its own. The rules are the same everywhere, so they
8
+ * live here once:
9
+ *
10
+ * - **A person is a set of connections.** A second tab, or a reconnect whose
11
+ * old socket has not closed yet, is routine. The person is online while ANY
12
+ * connection is live, and goes offline only when the last one goes.
13
+ * - **A connection is live while it beats.** Transports do not reliably report
14
+ * their own death (an upstream cut never reaches the server as a close), so
15
+ * a connection silent for `idleMs` is dropped as if it had closed, and the
16
+ * host is told (`idle`) so it can close the transport.
17
+ * - **Offline is not left.** Phones hand off between networks and deploys drop
18
+ * every socket at once; a person offline for `graceMs` has LEFT. A connection
19
+ * from them inside the grace cancels the leave, and `online` says so
20
+ * (`returned: true`), so the app can suppress its "joined again" noise.
21
+ *
22
+ * Deliberately transport-, storage- and app-agnostic: keys are whatever the
23
+ * app calls a person (a `ParticipantId`, a member id), connection ids are
24
+ * whatever it calls a connection (a socket id). Takeover, announcements,
25
+ * seating and avatar release are the app's, driven from these events.
26
+ *
27
+ * No periodic sweep: each connection holds ONE timeout, re-armed by its
28
+ * heartbeat, and each offline person holds one for the grace. A timer exists
29
+ * only while there is something for it to decide.
30
+ */
31
+ export class PresenceTracker {
32
+ idleMs;
33
+ graceMs;
34
+ now;
35
+ setTimer;
36
+ clearTimer;
37
+ people = new Map();
38
+ conns = new Map();
39
+ listeners = new Set();
40
+ constructor(opts) {
41
+ if (!(opts.idleMs > 0))
42
+ throw new RangeError(`idleMs must be > 0, got ${opts.idleMs}`);
43
+ if (!(opts.graceMs >= 0))
44
+ throw new RangeError(`graceMs must be >= 0, got ${opts.graceMs}`);
45
+ this.idleMs = opts.idleMs;
46
+ this.graceMs = opts.graceMs;
47
+ this.now = opts.now ?? Date.now;
48
+ this.setTimer = opts.setTimer ?? ((fn, ms) => setTimeout(fn, ms));
49
+ this.clearTimer = opts.clearTimer ?? ((h) => clearTimeout(h));
50
+ }
51
+ /** Subscribe. Returns the unsubscribe. Listeners run synchronously, in order. */
52
+ on(listener) {
53
+ this.listeners.add(listener);
54
+ return () => { this.listeners.delete(listener); };
55
+ }
56
+ /**
57
+ * A connection for `key` opened (counts as a heartbeat). Re-registering a
58
+ * connection id under another key moves it: the old person loses it first.
59
+ */
60
+ connect(key, connectionId) {
61
+ const existing = this.conns.get(connectionId);
62
+ if (existing) {
63
+ if (existing.key === key) {
64
+ this.heartbeat(connectionId);
65
+ return;
66
+ }
67
+ this.drop(connectionId);
68
+ }
69
+ const at = this.now();
70
+ let person = this.people.get(key);
71
+ if (!person) {
72
+ person = { connections: new Set(), lastSeen: at };
73
+ this.people.set(key, person);
74
+ }
75
+ const wasOnline = person.connections.size > 0;
76
+ const returned = person.offlineSince !== undefined;
77
+ if (returned) {
78
+ this.clearTimer(person.graceTimer);
79
+ person.graceTimer = undefined;
80
+ person.offlineSince = undefined;
81
+ }
82
+ person.connections.add(connectionId);
83
+ person.lastSeen = at;
84
+ this.conns.set(connectionId, { key, lastSeen: at, idleTimer: this.armIdle(connectionId) });
85
+ if (!wasOnline)
86
+ this.emit({ type: 'online', key, at, returned });
87
+ }
88
+ /** The connection is alive. False when it is not tracked (closed, reaped, never connected). */
89
+ heartbeat(connectionId) {
90
+ const conn = this.conns.get(connectionId);
91
+ if (!conn)
92
+ return false;
93
+ const at = this.now();
94
+ conn.lastSeen = at;
95
+ this.clearTimer(conn.idleTimer);
96
+ conn.idleTimer = this.armIdle(connectionId);
97
+ const person = this.people.get(conn.key);
98
+ if (person)
99
+ person.lastSeen = at;
100
+ return true;
101
+ }
102
+ /** The connection closed. Idempotent: an unknown id is ignored. */
103
+ disconnect(connectionId) {
104
+ this.drop(connectionId);
105
+ }
106
+ /** Whether `key` has a live connection. */
107
+ isOnline(key) {
108
+ return (this.people.get(key)?.connections.size ?? 0) > 0;
109
+ }
110
+ /** Whether `key` is offline but inside the grace (not yet left). */
111
+ isInGrace(key) {
112
+ return this.people.get(key)?.offlineSince !== undefined;
113
+ }
114
+ /** When `key` was last heard from on any connection; undefined once they have left. */
115
+ lastSeen(key) {
116
+ return this.people.get(key)?.lastSeen;
117
+ }
118
+ /** `key`'s live connection ids. */
119
+ connections(key) {
120
+ return [...(this.people.get(key)?.connections ?? [])];
121
+ }
122
+ /** The person a connection belongs to, while it is live. */
123
+ keyOf(connectionId) {
124
+ return this.conns.get(connectionId)?.key;
125
+ }
126
+ /** Everyone with a live connection. */
127
+ online() {
128
+ return [...this.people].filter(([, p]) => p.connections.size > 0).map(([k]) => k);
129
+ }
130
+ /**
131
+ * Forget `key` at once, with NO events — for an app that removed the person
132
+ * itself (kicked, room deleted). Their connections stop being tracked.
133
+ */
134
+ forget(key) {
135
+ const person = this.people.get(key);
136
+ if (!person)
137
+ return;
138
+ for (const id of person.connections) {
139
+ const conn = this.conns.get(id);
140
+ if (conn)
141
+ this.clearTimer(conn.idleTimer);
142
+ this.conns.delete(id);
143
+ }
144
+ this.clearTimer(person.graceTimer);
145
+ this.people.delete(key);
146
+ }
147
+ /** Cancel every timer and forget everyone, with no events. For shutdown and room deletion. */
148
+ dispose() {
149
+ for (const key of [...this.people.keys()])
150
+ this.forget(key);
151
+ }
152
+ armIdle(connectionId) {
153
+ return this.setTimer(() => this.reapIdle(connectionId), this.idleMs);
154
+ }
155
+ reapIdle(connectionId) {
156
+ const conn = this.conns.get(connectionId);
157
+ if (!conn)
158
+ return;
159
+ this.emit({ type: 'idle', key: conn.key, connectionId, at: this.now(), lastSeen: conn.lastSeen });
160
+ // A listener may already have closed it (closing the transport calls disconnect).
161
+ this.drop(connectionId);
162
+ }
163
+ drop(connectionId) {
164
+ const conn = this.conns.get(connectionId);
165
+ if (!conn)
166
+ return;
167
+ this.clearTimer(conn.idleTimer);
168
+ this.conns.delete(connectionId);
169
+ const person = this.people.get(conn.key);
170
+ if (!person)
171
+ return;
172
+ person.connections.delete(connectionId);
173
+ if (person.connections.size > 0)
174
+ return;
175
+ const at = this.now();
176
+ person.offlineSince = at;
177
+ const key = conn.key;
178
+ this.emit({ type: 'offline', key, at });
179
+ // A listener may have reconnected or forgotten them synchronously.
180
+ if (this.people.get(key) !== person || person.offlineSince !== at || person.connections.size > 0)
181
+ return;
182
+ person.graceTimer = this.setTimer(() => this.leave(key, person), this.graceMs);
183
+ }
184
+ leave(key, person) {
185
+ if (this.people.get(key) !== person || person.offlineSince === undefined)
186
+ return;
187
+ this.people.delete(key);
188
+ this.emit({ type: 'left', key, at: this.now(), offlineSince: person.offlineSince, lastSeen: person.lastSeen });
189
+ }
190
+ emit(event) {
191
+ for (const l of [...this.listeners])
192
+ l(event);
193
+ }
194
+ }
@@ -0,0 +1,95 @@
1
+ /**
2
+ * Session claims: which browser tab a player plays a room from.
3
+ *
4
+ * A player opening the same room in a second tab (or on another device) must
5
+ * not end up with two tabs both acting for them. The rule, shared by every
6
+ * room app (`@wolffm/rooms-protocol`'s `session.ts` has the wire half):
7
+ *
8
+ * - **One holder per key.** A key is whatever the app scopes a session to,
9
+ * normally account × room. The holder is a TAB, not a connection: one tab
10
+ * may speak to a room over several sockets (a lobby socket and a match
11
+ * socket), and a reload or reconnect of the same tab is the same holder, so
12
+ * it never asks.
13
+ * - **A live holder is asked about, never silently replaced.** A claim from
14
+ * another tab answers `held`; only a claim with `take` (the player said yes)
15
+ * replaces it, and hands back the old tab's connections for the app to close.
16
+ * - **A stale holder is replaced without asking.** A connection is live while
17
+ * it beats (`heartbeat`); a holder none of whose connections has beaten for
18
+ * `idleMs` is gone in all but name (a closed laptop, a dropped network, a
19
+ * transport that has not timed out yet), so a new claim takes from it and
20
+ * says so (`stale: true`). Use the same window as your `PresenceTracker`.
21
+ * - **The last connection closing frees the key.** `release` on a closed
22
+ * connection; a tab with no connection left holds nothing.
23
+ *
24
+ * Pure arithmetic over keys, tab ids and connection ids: no sockets, no
25
+ * timers. Staleness is decided when a claim asks, from the clock, so nothing
26
+ * runs while nobody is claiming. Who counts as a player (and so claims at all)
27
+ * is the app's to decide; watchers should never be passed in.
28
+ */
29
+ export type SessionClaimDecision =
30
+ /** The tab holds the key now. `fresh`: nobody held it before; else this tab already did. */
31
+ {
32
+ type: 'granted';
33
+ fresh: boolean;
34
+ }
35
+ /** Another tab holds it and is live. Nothing changed; ask the player, then claim with `take`. */
36
+ | {
37
+ type: 'held';
38
+ holderTabId: string;
39
+ lastSeen: number;
40
+ }
41
+ /**
42
+ * The tab took the key from `fromTabId`. `stale`: that tab had gone silent, so nobody was
43
+ * asked. `retire`: its connections under this key, which no longer hold anything; close them.
44
+ */
45
+ | {
46
+ type: 'taken';
47
+ fromTabId: string;
48
+ stale: boolean;
49
+ retire: string[];
50
+ };
51
+ export interface SessionClaimsOptions {
52
+ /** A holder with no heartbeat on any connection for this long is stale. */
53
+ idleMs: number;
54
+ /** Clock. Defaults to `Date.now`. */
55
+ now?: () => number;
56
+ }
57
+ export declare class SessionClaims<K extends string = string> {
58
+ private readonly idleMs;
59
+ private readonly now;
60
+ private readonly claims;
61
+ /** Each connection's keys, and when it last beat. A connection appears only while it holds something. */
62
+ private readonly conns;
63
+ constructor(opts: SessionClaimsOptions);
64
+ /**
65
+ * `connectionId` of tab `tabId` claims `key`. A claim counts as a heartbeat
66
+ * for the connection. Pass `take` only once the player has said yes.
67
+ */
68
+ claim(key: K, tabId: string, connectionId: string, opts?: {
69
+ take?: boolean;
70
+ }): SessionClaimDecision;
71
+ /** The connection is alive. False when it holds nothing. */
72
+ heartbeat(connectionId: string): boolean;
73
+ /**
74
+ * The connection closed. Idempotent. Returns the keys it was the holder's
75
+ * last connection for, which nobody holds now.
76
+ */
77
+ release(connectionId: string): K[];
78
+ /** The tab holding `key`, if any. */
79
+ holder(key: K): string | undefined;
80
+ /** Whether `tabId` holds `key`. */
81
+ holds(key: K, tabId: string): boolean;
82
+ /** Whether `key`'s holder has gone silent past the idle window. False when nobody holds it. */
83
+ isStale(key: K): boolean;
84
+ /** The holder's connections under `key`. */
85
+ connections(key: K): string[];
86
+ /** The keys a connection holds. */
87
+ keysOf(connectionId: string): K[];
88
+ /** Drop `key`'s claim at once (the room was deleted). Its connections hold nothing under it after. */
89
+ forget(key: K): void;
90
+ private hold;
91
+ private attach;
92
+ private detach;
93
+ private lastSeenOf;
94
+ }
95
+ //# sourceMappingURL=session-claims.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"session-claims.d.ts","sourceRoot":"","sources":["../src/session-claims.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;GA2BG;AAEH,MAAM,MAAM,oBAAoB;AAC9B,4FAA4F;AAC1F;IAAE,IAAI,EAAE,SAAS,CAAC;IAAC,KAAK,EAAE,OAAO,CAAA;CAAE;AACrC,iGAAiG;GAC/F;IAAE,IAAI,EAAE,MAAM,CAAC;IAAC,WAAW,EAAE,MAAM,CAAC;IAAC,QAAQ,EAAE,MAAM,CAAA;CAAE;AACzD;;;GAGG;GACD;IAAE,IAAI,EAAE,OAAO,CAAC;IAAC,SAAS,EAAE,MAAM,CAAC;IAAC,KAAK,EAAE,OAAO,CAAC;IAAC,MAAM,EAAE,MAAM,EAAE,CAAA;CAAE,CAAC;AAE3E,MAAM,WAAW,oBAAoB;IACnC,2EAA2E;IAC3E,MAAM,EAAE,MAAM,CAAC;IACf,qCAAqC;IACrC,GAAG,CAAC,EAAE,MAAM,MAAM,CAAC;CACpB;AAOD,qBAAa,aAAa,CAAC,CAAC,SAAS,MAAM,GAAG,MAAM;IAClD,OAAO,CAAC,QAAQ,CAAC,MAAM,CAAS;IAChC,OAAO,CAAC,QAAQ,CAAC,GAAG,CAAe;IACnC,OAAO,CAAC,QAAQ,CAAC,MAAM,CAAuB;IAC9C,yGAAyG;IACzG,OAAO,CAAC,QAAQ,CAAC,KAAK,CAAyD;gBAEnE,IAAI,EAAE,oBAAoB;IAMtC;;;OAGG;IACH,KAAK,CAAC,GAAG,EAAE,CAAC,EAAE,KAAK,EAAE,MAAM,EAAE,YAAY,EAAE,MAAM,EAAE,IAAI,GAAE;QAAE,IAAI,CAAC,EAAE,OAAO,CAAA;KAAO,GAAG,oBAAoB;IAqBvG,4DAA4D;IAC5D,SAAS,CAAC,YAAY,EAAE,MAAM,GAAG,OAAO;IAOxC;;;OAGG;IACH,OAAO,CAAC,YAAY,EAAE,MAAM,GAAG,CAAC,EAAE;IAelC,qCAAqC;IACrC,MAAM,CAAC,GAAG,EAAE,CAAC,GAAG,MAAM,GAAG,SAAS;IAIlC,mCAAmC;IACnC,KAAK,CAAC,GAAG,EAAE,CAAC,EAAE,KAAK,EAAE,MAAM,GAAG,OAAO;IAIrC,+FAA+F;IAC/F,OAAO,CAAC,GAAG,EAAE,CAAC,GAAG,OAAO;IAKxB,4CAA4C;IAC5C,WAAW,CAAC,GAAG,EAAE,CAAC,GAAG,MAAM,EAAE;IAI7B,mCAAmC;IACnC,MAAM,CAAC,YAAY,EAAE,MAAM,GAAG,CAAC,EAAE;IAIjC,sGAAsG;IACtG,MAAM,CAAC,GAAG,EAAE,CAAC,GAAG,IAAI;IAOpB,OAAO,CAAC,IAAI;IAMZ,OAAO,CAAC,MAAM;IAWd,OAAO,CAAC,MAAM;IAQd,OAAO,CAAC,UAAU;CAKnB"}
@@ -0,0 +1,156 @@
1
+ /**
2
+ * Session claims: which browser tab a player plays a room from.
3
+ *
4
+ * A player opening the same room in a second tab (or on another device) must
5
+ * not end up with two tabs both acting for them. The rule, shared by every
6
+ * room app (`@wolffm/rooms-protocol`'s `session.ts` has the wire half):
7
+ *
8
+ * - **One holder per key.** A key is whatever the app scopes a session to,
9
+ * normally account × room. The holder is a TAB, not a connection: one tab
10
+ * may speak to a room over several sockets (a lobby socket and a match
11
+ * socket), and a reload or reconnect of the same tab is the same holder, so
12
+ * it never asks.
13
+ * - **A live holder is asked about, never silently replaced.** A claim from
14
+ * another tab answers `held`; only a claim with `take` (the player said yes)
15
+ * replaces it, and hands back the old tab's connections for the app to close.
16
+ * - **A stale holder is replaced without asking.** A connection is live while
17
+ * it beats (`heartbeat`); a holder none of whose connections has beaten for
18
+ * `idleMs` is gone in all but name (a closed laptop, a dropped network, a
19
+ * transport that has not timed out yet), so a new claim takes from it and
20
+ * says so (`stale: true`). Use the same window as your `PresenceTracker`.
21
+ * - **The last connection closing frees the key.** `release` on a closed
22
+ * connection; a tab with no connection left holds nothing.
23
+ *
24
+ * Pure arithmetic over keys, tab ids and connection ids: no sockets, no
25
+ * timers. Staleness is decided when a claim asks, from the clock, so nothing
26
+ * runs while nobody is claiming. Who counts as a player (and so claims at all)
27
+ * is the app's to decide; watchers should never be passed in.
28
+ */
29
+ export class SessionClaims {
30
+ idleMs;
31
+ now;
32
+ claims = new Map();
33
+ /** Each connection's keys, and when it last beat. A connection appears only while it holds something. */
34
+ conns = new Map();
35
+ constructor(opts) {
36
+ if (!(opts.idleMs > 0))
37
+ throw new RangeError(`idleMs must be > 0, got ${opts.idleMs}`);
38
+ this.idleMs = opts.idleMs;
39
+ this.now = opts.now ?? Date.now;
40
+ }
41
+ /**
42
+ * `connectionId` of tab `tabId` claims `key`. A claim counts as a heartbeat
43
+ * for the connection. Pass `take` only once the player has said yes.
44
+ */
45
+ claim(key, tabId, connectionId, opts = {}) {
46
+ if (tabId.length === 0)
47
+ throw new RangeError('tabId must not be empty');
48
+ const held = this.claims.get(key);
49
+ if (held === undefined) {
50
+ this.hold(key, tabId, connectionId);
51
+ return { type: 'granted', fresh: true };
52
+ }
53
+ if (held.tabId === tabId) {
54
+ this.attach(key, held, connectionId);
55
+ return { type: 'granted', fresh: false };
56
+ }
57
+ const lastSeen = this.lastSeenOf(held);
58
+ const stale = this.now() - lastSeen > this.idleMs;
59
+ if (!stale && opts.take !== true)
60
+ return { type: 'held', holderTabId: held.tabId, lastSeen };
61
+ const retire = [...held.connections];
62
+ for (const id of retire)
63
+ this.detach(key, id);
64
+ this.claims.delete(key);
65
+ this.hold(key, tabId, connectionId);
66
+ return { type: 'taken', fromTabId: held.tabId, stale, retire };
67
+ }
68
+ /** The connection is alive. False when it holds nothing. */
69
+ heartbeat(connectionId) {
70
+ const conn = this.conns.get(connectionId);
71
+ if (conn === undefined)
72
+ return false;
73
+ conn.lastSeen = this.now();
74
+ return true;
75
+ }
76
+ /**
77
+ * The connection closed. Idempotent. Returns the keys it was the holder's
78
+ * last connection for, which nobody holds now.
79
+ */
80
+ release(connectionId) {
81
+ const conn = this.conns.get(connectionId);
82
+ if (conn === undefined)
83
+ return [];
84
+ const freed = [];
85
+ for (const key of [...conn.keys]) {
86
+ this.detach(key, connectionId);
87
+ const claim = this.claims.get(key);
88
+ if (claim !== undefined && claim.connections.size === 0) {
89
+ this.claims.delete(key);
90
+ freed.push(key);
91
+ }
92
+ }
93
+ return freed;
94
+ }
95
+ /** The tab holding `key`, if any. */
96
+ holder(key) {
97
+ return this.claims.get(key)?.tabId;
98
+ }
99
+ /** Whether `tabId` holds `key`. */
100
+ holds(key, tabId) {
101
+ return this.claims.get(key)?.tabId === tabId;
102
+ }
103
+ /** Whether `key`'s holder has gone silent past the idle window. False when nobody holds it. */
104
+ isStale(key) {
105
+ const claim = this.claims.get(key);
106
+ return claim !== undefined && this.now() - this.lastSeenOf(claim) > this.idleMs;
107
+ }
108
+ /** The holder's connections under `key`. */
109
+ connections(key) {
110
+ return [...(this.claims.get(key)?.connections ?? [])];
111
+ }
112
+ /** The keys a connection holds. */
113
+ keysOf(connectionId) {
114
+ return [...(this.conns.get(connectionId)?.keys ?? [])];
115
+ }
116
+ /** Drop `key`'s claim at once (the room was deleted). Its connections hold nothing under it after. */
117
+ forget(key) {
118
+ const claim = this.claims.get(key);
119
+ if (claim === undefined)
120
+ return;
121
+ for (const id of [...claim.connections])
122
+ this.detach(key, id);
123
+ this.claims.delete(key);
124
+ }
125
+ hold(key, tabId, connectionId) {
126
+ const claim = { tabId, connections: new Set() };
127
+ this.claims.set(key, claim);
128
+ this.attach(key, claim, connectionId);
129
+ }
130
+ attach(key, claim, connectionId) {
131
+ claim.connections.add(connectionId);
132
+ const at = this.now();
133
+ const conn = this.conns.get(connectionId);
134
+ if (conn === undefined)
135
+ this.conns.set(connectionId, { keys: new Set([key]), lastSeen: at });
136
+ else {
137
+ conn.keys.add(key);
138
+ conn.lastSeen = at;
139
+ }
140
+ }
141
+ detach(key, connectionId) {
142
+ this.claims.get(key)?.connections.delete(connectionId);
143
+ const conn = this.conns.get(connectionId);
144
+ if (conn === undefined)
145
+ return;
146
+ conn.keys.delete(key);
147
+ if (conn.keys.size === 0)
148
+ this.conns.delete(connectionId);
149
+ }
150
+ lastSeenOf(claim) {
151
+ let latest = -Infinity;
152
+ for (const id of claim.connections)
153
+ latest = Math.max(latest, this.conns.get(id)?.lastSeen ?? -Infinity);
154
+ return latest;
155
+ }
156
+ }
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@hadoku/rooms-server",
3
- "version": "0.45.55",
4
- "gitHead": "4030a40dc8710a9ec7c1cb9d42d3afb185f329f9",
3
+ "version": "0.45.57",
4
+ "gitHead": "14172aa10cda73d19a6c845f77e0995a845fe5f8",
5
5
  "type": "module",
6
6
  "license": "MIT",
7
7
  "description": "Room lifecycle, membership, seating, identity and backpressure-aware emit for a socket.io server.",
@@ -23,7 +23,7 @@
23
23
  "directory": "packages/rooms-server"
24
24
  },
25
25
  "dependencies": {
26
- "@wolffm/rooms-protocol": "npm:@hadoku/rooms-protocol@0.45.55"
26
+ "@wolffm/rooms-protocol": "npm:@hadoku/rooms-protocol@0.45.57"
27
27
  },
28
28
  "peerDependencies": {
29
29
  "socket.io": "^4.8.3"