@hadoku/rooms-server 0.45.55 → 0.45.56

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), 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,5 @@ 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';
20
22
  //# 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"}
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), 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,7 @@ 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';
20
22
  // NOT `export * from '@wolffm/rooms-protocol'`. Re-exporting it would give
21
23
  // every symbol two import paths, and the first thing that drifts is which one
22
24
  // 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,MAAM,CAAC;IAAC,QAAQ,EAAE,OAAO,CAAA;CAAE;AAC3D,oEAAoE;GAClE;IAAE,IAAI,EAAE,SAAS,CAA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,CAAC,MAAM,CAAwB;IAC/C,OAAO,CAAC,QAAQ,CAAC,KAAK,CAAoC;IAC1D,OAAO,CAAC,QAAQ,CAAC,SAAS,CAAkC;gBAEhD,IAAI,EAAE,eAAe;IAUjC,iFAAiF;IACjF,EAAE,CAAC,QAAQ,EAAE,gBAAgB,CAAC,CAAC,CAAC,GAAG,MAAM,IAAI;IAK7C;;;OAGG;IACH,OAAO,CAAC,GAAG,EAAE,CAAC,EAAE,YAAY,EAAE,MAAM,GAAG,IAAI;IAyB3C,+FAA+F;IAC/F,SAAS,CAAC,YAAY,EAAE,MAAM,GAAG,OAAO;IAYxC,mEAAmE;IACnE,UAAU,CAAC,YAAY,EAAE,MAAM,GAAG,IAAI;IAItC,2CAA2C;IAC3C,QAAQ,CAAC,GAAG,EAAE,CAAC,GAAG,OAAO;IAIzB,oEAAoE;IACpE,SAAS,CAAC,GAAG,EAAE,CAAC,GAAG,OAAO;IAI1B,uFAAuF;IACvF,QAAQ,CAAC,GAAG,EAAE,CAAC,GAAG,MAAM,GAAG,SAAS;IAIpC,mCAAmC;IACnC,WAAW,CAAC,GAAG,EAAE,CAAC,GAAG,MAAM,EAAE;IAI7B,4DAA4D;IAC5D,KAAK,CAAC,YAAY,EAAE,MAAM,GAAG,CAAC,GAAG,SAAS;IAI1C,uCAAuC;IACvC,MAAM,IAAI,CAAC,EAAE;IAIb;;;OAGG;IACH,MAAM,CAAC,GAAG,EAAE,CAAC,GAAG,IAAI;IAYpB,8FAA8F;IAC9F,OAAO,IAAI,IAAI;IAIf,OAAO,CAAC,OAAO;IAIf,OAAO,CAAC,QAAQ;IAQhB,OAAO,CAAC,IAAI;IAkBZ,OAAO,CAAC,KAAK;IAMb,OAAO,CAAC,IAAI;CAGb"}
@@ -0,0 +1,194 @@
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
+ 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
+ }
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.56",
4
+ "gitHead": "69d5ce6b957f1e1b8eb3b16448367d5f3b4714eb",
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.56"
27
27
  },
28
28
  "peerDependencies": {
29
29
  "socket.io": "^4.8.3"