@hadoku/rooms-server 0.45.56 → 0.45.58
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 +5 -2
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +5 -2
- package/dist/session-claims.d.ts +95 -0
- package/dist/session-claims.d.ts.map +1 -0
- package/dist/session-claims.js +156 -0
- package/dist/store/fileStore.d.ts +46 -0
- package/dist/store/fileStore.d.ts.map +1 -0
- package/dist/store/fileStore.js +151 -0
- package/dist/store/index.d.ts +4 -0
- package/dist/store/index.d.ts.map +1 -0
- package/dist/store/index.js +21 -0
- package/dist/store/snapshot.d.ts +192 -0
- package/dist/store/snapshot.d.ts.map +1 -0
- package/dist/store/snapshot.js +306 -0
- package/dist/store/store.d.ts +55 -0
- package/dist/store/store.d.ts.map +1 -0
- package/dist/store/store.js +61 -0
- package/package.json +8 -4
package/dist/index.d.ts
CHANGED
|
@@ -3,8 +3,10 @@
|
|
|
3
3
|
*
|
|
4
4
|
* Room lifecycle and membership, stable participant identity, seating, avatar
|
|
5
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.
|
|
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. Durable room storage (snapshot codec, memory and file
|
|
8
|
+
* tiers) is the `./store` subpath, kept out of this entry because it reaches
|
|
9
|
+
* `node:fs`.
|
|
8
10
|
*
|
|
9
11
|
* Carries no hosting-app vocabulary and no opinion about what a room is FOR —
|
|
10
12
|
* that lives in `CoreRoomState<TApp>`'s `app`. Three things a hosting app
|
|
@@ -19,4 +21,5 @@ export * from './emit.js';
|
|
|
19
21
|
export * from './gc.js';
|
|
20
22
|
export * from './rateLimiter.js';
|
|
21
23
|
export * from './presence.js';
|
|
24
|
+
export * from './session-claims.js';
|
|
22
25
|
//# sourceMappingURL=index.d.ts.map
|
package/dist/index.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;GAgBG;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
|
@@ -3,8 +3,10 @@
|
|
|
3
3
|
*
|
|
4
4
|
* Room lifecycle and membership, stable participant identity, seating, avatar
|
|
5
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.
|
|
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. Durable room storage (snapshot codec, memory and file
|
|
8
|
+
* tiers) is the `./store` subpath, kept out of this entry because it reaches
|
|
9
|
+
* `node:fs`.
|
|
8
10
|
*
|
|
9
11
|
* Carries no hosting-app vocabulary and no opinion about what a room is FOR —
|
|
10
12
|
* that lives in `CoreRoomState<TApp>`'s `app`. Three things a hosting app
|
|
@@ -19,6 +21,7 @@ export * from './emit.js';
|
|
|
19
21
|
export * from './gc.js';
|
|
20
22
|
export * from './rateLimiter.js';
|
|
21
23
|
export * from './presence.js';
|
|
24
|
+
export * from './session-claims.js';
|
|
22
25
|
// NOT `export * from '@wolffm/rooms-protocol'`. Re-exporting it would give
|
|
23
26
|
// every symbol two import paths, and the first thing that drifts is which one
|
|
24
27
|
// a file happens to use. Consumers depend on both packages explicitly.
|
|
@@ -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
|
+
}
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
import type { RoomSnapshot } from './snapshot.js';
|
|
2
|
+
import type { RoomStore } from './store.js';
|
|
3
|
+
export interface FileRoomStoreOptions {
|
|
4
|
+
/**
|
|
5
|
+
* Overrides the clock used to name quarantine files. Only there so a test can
|
|
6
|
+
* make the name deterministic; the store itself has no other use for time.
|
|
7
|
+
*/
|
|
8
|
+
now?: () => number;
|
|
9
|
+
}
|
|
10
|
+
export declare class FileRoomStore implements RoomStore {
|
|
11
|
+
#private;
|
|
12
|
+
readonly dir: string;
|
|
13
|
+
readonly quarantineDir: string;
|
|
14
|
+
constructor(dir: string, opts?: FileRoomStoreOptions);
|
|
15
|
+
/**
|
|
16
|
+
* Read a snapshot, or null when there is none.
|
|
17
|
+
*
|
|
18
|
+
* THROWS on a file that exists and does not parse. Deliberately: returning
|
|
19
|
+
* null there would make an unreadable snapshot indistinguishable from a room
|
|
20
|
+
* that was never persisted, and the room would boot empty and then be
|
|
21
|
+
* overwritten by the next debounced save — losing the bytes that a human could
|
|
22
|
+
* still have recovered something from. The caller catches and quarantines.
|
|
23
|
+
*/
|
|
24
|
+
load(roomId: string): Promise<RoomSnapshot | null>;
|
|
25
|
+
save(snapshot: RoomSnapshot): Promise<void>;
|
|
26
|
+
saveSync(snapshot: RoomSnapshot): void;
|
|
27
|
+
remove(roomId: string): Promise<void>;
|
|
28
|
+
removeSync(roomId: string): void;
|
|
29
|
+
list(): Promise<string[]>;
|
|
30
|
+
/**
|
|
31
|
+
* Move the record aside by RENAME, so the bytes are preserved exactly.
|
|
32
|
+
*
|
|
33
|
+
* Not "read, re-serialise, write elsewhere": the thing being set aside is by
|
|
34
|
+
* definition something this build could not parse, so anything that goes
|
|
35
|
+
* through a parser would lose whatever a human might still recover. A rename
|
|
36
|
+
* also makes the room invisible to the next `load` in the same operation,
|
|
37
|
+
* rather than leaving a window where it boots twice.
|
|
38
|
+
*/
|
|
39
|
+
quarantine(roomId: string, reason: string): Promise<void>;
|
|
40
|
+
listQuarantined(): Promise<string[]>;
|
|
41
|
+
/** The raw bytes of a quarantined record, exactly as they were set aside. */
|
|
42
|
+
readQuarantined(name: string): string;
|
|
43
|
+
/** Every room id this store holds, read synchronously. For the exit flush. */
|
|
44
|
+
listSync(): string[];
|
|
45
|
+
}
|
|
46
|
+
//# sourceMappingURL=fileStore.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"fileStore.d.ts","sourceRoot":"","sources":["../../src/store/fileStore.ts"],"names":[],"mappings":"AAuCA,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,eAAe,CAAC;AAClD,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,YAAY,CAAC;AAa5C,MAAM,WAAW,oBAAoB;IACnC;;;OAGG;IACH,GAAG,CAAC,EAAE,MAAM,MAAM,CAAC;CACpB;AAED,qBAAa,aAAc,YAAW,SAAS;;IAC7C,QAAQ,CAAC,GAAG,EAAE,MAAM,CAAC;IACrB,QAAQ,CAAC,aAAa,EAAE,MAAM,CAAC;gBAGnB,GAAG,EAAE,MAAM,EAAE,IAAI,GAAE,oBAAyB;IAWxD;;;;;;;;OAQG;IACG,IAAI,CAAC,MAAM,EAAE,MAAM,GAAG,OAAO,CAAC,YAAY,GAAG,IAAI,CAAC;IAWlD,IAAI,CAAC,QAAQ,EAAE,YAAY,GAAG,OAAO,CAAC,IAAI,CAAC;IAIjD,QAAQ,CAAC,QAAQ,EAAE,YAAY,GAAG,IAAI;IAchC,MAAM,CAAC,MAAM,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC;IAI3C,UAAU,CAAC,MAAM,EAAE,MAAM,GAAG,IAAI;IAI1B,IAAI,IAAI,OAAO,CAAC,MAAM,EAAE,CAAC;IAc/B;;;;;;;;OAQG;IACG,UAAU,CAAC,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC;IASzD,eAAe,IAAI,OAAO,CAAC,MAAM,EAAE,CAAC;IAW1C,6EAA6E;IAC7E,eAAe,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM;IAIrC,8EAA8E;IAC9E,QAAQ,IAAI,MAAM,EAAE;CAOrB"}
|
|
@@ -0,0 +1,151 @@
|
|
|
1
|
+
/*
|
|
2
|
+
* The file tier.
|
|
3
|
+
*
|
|
4
|
+
* One JSON file per room in a directory, written atomically, with a
|
|
5
|
+
* `quarantine/` subdirectory for records this build cannot read.
|
|
6
|
+
*
|
|
7
|
+
* ## Room ids are base64url, not the room id
|
|
8
|
+
*
|
|
9
|
+
* A room id arrives from a join payload. `<dir>/<roomId>.json` with a roomId of
|
|
10
|
+
* `../../.ssh/authorized_keys` writes outside the directory, and a roomId of
|
|
11
|
+
* `CON` or one containing `:` is unwriteable on some filesystems and fine on
|
|
12
|
+
* others — which is the worst kind of bug, because it only appears in
|
|
13
|
+
* production. base64url of the id removes the whole class: the alphabet is
|
|
14
|
+
* `A-Za-z0-9-_`, it is reversible so `list()` still returns real room ids, and
|
|
15
|
+
* it cannot contain a separator or a dot.
|
|
16
|
+
*
|
|
17
|
+
* ## Writes are atomic
|
|
18
|
+
*
|
|
19
|
+
* Write a temp file, `fsync` it, rename over the target. A rename within a
|
|
20
|
+
* directory is atomic on POSIX, so a reader never sees half a snapshot and a
|
|
21
|
+
* crash mid-write leaves the previous snapshot intact rather than a truncated
|
|
22
|
+
* file. Without it, the failure mode is precisely the one §4.5 is about: a file
|
|
23
|
+
* that parses far enough to look plausible.
|
|
24
|
+
*/
|
|
25
|
+
import { closeSync, existsSync, fsyncSync, mkdirSync, openSync, readFileSync, readdirSync, renameSync, rmSync, writeSync, } from 'node:fs';
|
|
26
|
+
import { mkdir, readFile, readdir, rename, rm, writeFile } from 'node:fs/promises';
|
|
27
|
+
import { join } from 'node:path';
|
|
28
|
+
const SUFFIX = '.json';
|
|
29
|
+
const QUARANTINE_DIR = 'quarantine';
|
|
30
|
+
function keyFor(roomId) {
|
|
31
|
+
return Buffer.from(roomId, 'utf8').toString('base64url');
|
|
32
|
+
}
|
|
33
|
+
function roomIdFor(key) {
|
|
34
|
+
return Buffer.from(key, 'base64url').toString('utf8');
|
|
35
|
+
}
|
|
36
|
+
export class FileRoomStore {
|
|
37
|
+
dir;
|
|
38
|
+
quarantineDir;
|
|
39
|
+
#now;
|
|
40
|
+
constructor(dir, opts = {}) {
|
|
41
|
+
this.dir = dir;
|
|
42
|
+
this.quarantineDir = join(dir, QUARANTINE_DIR);
|
|
43
|
+
this.#now = opts.now ?? (() => Date.now());
|
|
44
|
+
mkdirSync(this.dir, { recursive: true });
|
|
45
|
+
}
|
|
46
|
+
#path(roomId) {
|
|
47
|
+
return join(this.dir, keyFor(roomId) + SUFFIX);
|
|
48
|
+
}
|
|
49
|
+
/**
|
|
50
|
+
* Read a snapshot, or null when there is none.
|
|
51
|
+
*
|
|
52
|
+
* THROWS on a file that exists and does not parse. Deliberately: returning
|
|
53
|
+
* null there would make an unreadable snapshot indistinguishable from a room
|
|
54
|
+
* that was never persisted, and the room would boot empty and then be
|
|
55
|
+
* overwritten by the next debounced save — losing the bytes that a human could
|
|
56
|
+
* still have recovered something from. The caller catches and quarantines.
|
|
57
|
+
*/
|
|
58
|
+
async load(roomId) {
|
|
59
|
+
let text;
|
|
60
|
+
try {
|
|
61
|
+
text = await readFile(this.#path(roomId), 'utf8');
|
|
62
|
+
}
|
|
63
|
+
catch (err) {
|
|
64
|
+
if (err.code === 'ENOENT')
|
|
65
|
+
return null;
|
|
66
|
+
throw err;
|
|
67
|
+
}
|
|
68
|
+
return JSON.parse(text);
|
|
69
|
+
}
|
|
70
|
+
async save(snapshot) {
|
|
71
|
+
this.saveSync(snapshot);
|
|
72
|
+
}
|
|
73
|
+
saveSync(snapshot) {
|
|
74
|
+
mkdirSync(this.dir, { recursive: true });
|
|
75
|
+
const target = this.#path(snapshot.roomId);
|
|
76
|
+
const tmp = `${target}.${process.pid}.${this.#now()}.tmp`;
|
|
77
|
+
const fd = openSync(tmp, 'w');
|
|
78
|
+
try {
|
|
79
|
+
writeSync(fd, JSON.stringify(snapshot));
|
|
80
|
+
fsyncSync(fd);
|
|
81
|
+
}
|
|
82
|
+
finally {
|
|
83
|
+
closeSync(fd);
|
|
84
|
+
}
|
|
85
|
+
renameSync(tmp, target);
|
|
86
|
+
}
|
|
87
|
+
async remove(roomId) {
|
|
88
|
+
await rm(this.#path(roomId), { force: true });
|
|
89
|
+
}
|
|
90
|
+
removeSync(roomId) {
|
|
91
|
+
rmSync(this.#path(roomId), { force: true });
|
|
92
|
+
}
|
|
93
|
+
async list() {
|
|
94
|
+
let entries;
|
|
95
|
+
try {
|
|
96
|
+
entries = await readdir(this.dir);
|
|
97
|
+
}
|
|
98
|
+
catch (err) {
|
|
99
|
+
if (err.code === 'ENOENT')
|
|
100
|
+
return [];
|
|
101
|
+
throw err;
|
|
102
|
+
}
|
|
103
|
+
return entries
|
|
104
|
+
.filter((n) => n.endsWith(SUFFIX) && !n.endsWith('.tmp'))
|
|
105
|
+
.map((n) => roomIdFor(n.slice(0, -SUFFIX.length)))
|
|
106
|
+
.sort();
|
|
107
|
+
}
|
|
108
|
+
/**
|
|
109
|
+
* Move the record aside by RENAME, so the bytes are preserved exactly.
|
|
110
|
+
*
|
|
111
|
+
* Not "read, re-serialise, write elsewhere": the thing being set aside is by
|
|
112
|
+
* definition something this build could not parse, so anything that goes
|
|
113
|
+
* through a parser would lose whatever a human might still recover. A rename
|
|
114
|
+
* also makes the room invisible to the next `load` in the same operation,
|
|
115
|
+
* rather than leaving a window where it boots twice.
|
|
116
|
+
*/
|
|
117
|
+
async quarantine(roomId, reason) {
|
|
118
|
+
const source = this.#path(roomId);
|
|
119
|
+
if (!existsSync(source))
|
|
120
|
+
return;
|
|
121
|
+
await mkdir(this.quarantineDir, { recursive: true });
|
|
122
|
+
const name = `${keyFor(roomId)}.${this.#now()}${SUFFIX}`;
|
|
123
|
+
await rename(source, join(this.quarantineDir, name));
|
|
124
|
+
await writeFile(join(this.quarantineDir, `${name}.reason.txt`), `${reason}\n`, 'utf8');
|
|
125
|
+
}
|
|
126
|
+
async listQuarantined() {
|
|
127
|
+
let entries;
|
|
128
|
+
try {
|
|
129
|
+
entries = await readdir(this.quarantineDir);
|
|
130
|
+
}
|
|
131
|
+
catch (err) {
|
|
132
|
+
if (err.code === 'ENOENT')
|
|
133
|
+
return [];
|
|
134
|
+
throw err;
|
|
135
|
+
}
|
|
136
|
+
return entries.filter((n) => n.endsWith(SUFFIX)).sort();
|
|
137
|
+
}
|
|
138
|
+
/** The raw bytes of a quarantined record, exactly as they were set aside. */
|
|
139
|
+
readQuarantined(name) {
|
|
140
|
+
return readFileSync(join(this.quarantineDir, name), 'utf8');
|
|
141
|
+
}
|
|
142
|
+
/** Every room id this store holds, read synchronously. For the exit flush. */
|
|
143
|
+
listSync() {
|
|
144
|
+
if (!existsSync(this.dir))
|
|
145
|
+
return [];
|
|
146
|
+
return readdirSync(this.dir)
|
|
147
|
+
.filter((n) => n.endsWith(SUFFIX) && !n.endsWith('.tmp'))
|
|
148
|
+
.map((n) => roomIdFor(n.slice(0, -SUFFIX.length)))
|
|
149
|
+
.sort();
|
|
150
|
+
}
|
|
151
|
+
}
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
export { applySnapshot, decodeSnapshot, jsonCodec, pruneNonDurable, snapshotRoom, SnapshotUnreadableError, STORE_VERSION, type AppCodec, type DecodedSnapshot, type RestoreContext, type RestoredMember, type RoomCodec, type RoomSnapshot, type SerializedMember, type UnreadableReason, } from './snapshot.js';
|
|
2
|
+
export { MemoryRoomStore, type RoomStore } from './store.js';
|
|
3
|
+
export { FileRoomStore, type FileRoomStoreOptions } from './fileStore.js';
|
|
4
|
+
//# sourceMappingURL=index.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/store/index.ts"],"names":[],"mappings":"AAmBA,OAAO,EACL,aAAa,EACb,cAAc,EACd,SAAS,EACT,eAAe,EACf,YAAY,EACZ,uBAAuB,EACvB,aAAa,EACb,KAAK,QAAQ,EACb,KAAK,eAAe,EACpB,KAAK,cAAc,EACnB,KAAK,cAAc,EACnB,KAAK,SAAS,EACd,KAAK,YAAY,EACjB,KAAK,gBAAgB,EACrB,KAAK,gBAAgB,GACtB,MAAM,eAAe,CAAC;AAEvB,OAAO,EAAE,eAAe,EAAE,KAAK,SAAS,EAAE,MAAM,YAAY,CAAC;AAC7D,OAAO,EAAE,aAAa,EAAE,KAAK,oBAAoB,EAAE,MAAM,gBAAgB,CAAC"}
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
/*
|
|
2
|
+
* @wolffm/rooms-server/store — a room snapshot's codec, and where it is stored.
|
|
3
|
+
*
|
|
4
|
+
* Moved here from hadoku-cardtable `packages/room-store` (`@hadoku/room-store`,
|
|
5
|
+
* MIT since cardtable `b4f826d9b`), unchanged in behaviour: a file written by
|
|
6
|
+
* that package's `FileRoomStore` loads through this one
|
|
7
|
+
* (`apps/server/test/room-store-compat.test.ts`). The § numbers in these files
|
|
8
|
+
* point at the spec it grew from, hadoku-cardtable
|
|
9
|
+
* `docs/requests/P6_PERSISTENCE.md`; cardtable#2 and #25 are provenance too.
|
|
10
|
+
*
|
|
11
|
+
* A SUBPATH, not part of the package root, because `fileStore.ts` imports
|
|
12
|
+
* `node:fs`: a host that never persists a room should not load the filesystem
|
|
13
|
+
* tier by importing `RoomRegistry`.
|
|
14
|
+
*
|
|
15
|
+
* Transport-free and socket-free: nothing here imports `socket.io`, and only
|
|
16
|
+
* `fileStore.ts` touches the filesystem. `MemoryRoomStore` is the default tier,
|
|
17
|
+
* so a host that has not opted in changes no behaviour.
|
|
18
|
+
*/
|
|
19
|
+
export { applySnapshot, decodeSnapshot, jsonCodec, pruneNonDurable, snapshotRoom, SnapshotUnreadableError, STORE_VERSION, } from './snapshot.js';
|
|
20
|
+
export { MemoryRoomStore } from './store.js';
|
|
21
|
+
export { FileRoomStore } from './fileStore.js';
|
|
@@ -0,0 +1,192 @@
|
|
|
1
|
+
import { type ParticipantId, type SeatTable } from '@wolffm/rooms-protocol';
|
|
2
|
+
import type { CoreRoomState } from '../state.js';
|
|
3
|
+
/**
|
|
4
|
+
* Bumped when the shape in THIS file changes, or what its ids mean does.
|
|
5
|
+
*
|
|
6
|
+
* A snapshot whose `storeVersion` this build does not recognise is quarantined,
|
|
7
|
+
* never guessed at (§4.5). The host's own blob versions independently through
|
|
8
|
+
* `appVersion`, so a host migrating its app state does not need us to bump.
|
|
9
|
+
*
|
|
10
|
+
* 2 (2026-10-31): participant ids are minted from the userId, not the key
|
|
11
|
+
* (cardtable#2, #25). A version-1 snapshot names people by key-derived ids no
|
|
12
|
+
* caller can present any more, and they cannot be mapped without the keys, so
|
|
13
|
+
* it is quarantined like any other unknown version (the operator chose a reset).
|
|
14
|
+
*/
|
|
15
|
+
export declare const STORE_VERSION = 2;
|
|
16
|
+
/** One durable participant, flattened out of `CoreRoomState.clients`. */
|
|
17
|
+
export interface SerializedMember {
|
|
18
|
+
/** Durable tiers only — see §4.2 and `pruneNonDurable`. */
|
|
19
|
+
participantId: ParticipantId;
|
|
20
|
+
joinedAt: number;
|
|
21
|
+
lastSeen: number;
|
|
22
|
+
/** The registry userId `participantId` was minted from; what the person is looked up by. */
|
|
23
|
+
accountId?: string;
|
|
24
|
+
/** `ClientMeta<TClient>.app`, through the host's client codec. */
|
|
25
|
+
app: unknown;
|
|
26
|
+
}
|
|
27
|
+
/** Wire form. Maps and Sets are not JSON; this is the flattened room. */
|
|
28
|
+
export interface RoomSnapshot {
|
|
29
|
+
storeVersion: number;
|
|
30
|
+
roomId: string;
|
|
31
|
+
roomKey: string;
|
|
32
|
+
lastEventSeq: number;
|
|
33
|
+
createdAt: number;
|
|
34
|
+
updatedAt: number;
|
|
35
|
+
members: SerializedMember[];
|
|
36
|
+
usedAvatars: string[];
|
|
37
|
+
seats: SeatTable;
|
|
38
|
+
/** Opaque to the store. Goes through `AppCodec`. */
|
|
39
|
+
app: unknown;
|
|
40
|
+
/** The host's own schema version, echoed back to its `deserialize`. */
|
|
41
|
+
appVersion?: number;
|
|
42
|
+
}
|
|
43
|
+
/**
|
|
44
|
+
* Context handed to a codec on the way back in.
|
|
45
|
+
*
|
|
46
|
+
* `restoreId` is the reason this exists. `@wolffm/rooms-protocol`'s `SeqCursor`
|
|
47
|
+
* says an epoch is *"any value … as long as it changes when the room is rebuilt
|
|
48
|
+
* and not otherwise"*, and a restore rebuilds the room. A host whose app state
|
|
49
|
+
* carries an epoch stamps this one on it
|
|
50
|
+
* during `deserialize`, so a client holding a pre-restart cursor gets
|
|
51
|
+
* `epoch-change` from `classifySeq` and refetches, instead of reading a room
|
|
52
|
+
* counting from a restored `seq` as a flood of duplicates and discarding live
|
|
53
|
+
* events forever.
|
|
54
|
+
*/
|
|
55
|
+
export interface RestoreContext {
|
|
56
|
+
roomId: string;
|
|
57
|
+
/** Unique to this restore. Never equal to the value the room had before. */
|
|
58
|
+
restoreId: string;
|
|
59
|
+
/** The clock's time at restore, for a host that stamps its own timestamps. */
|
|
60
|
+
restoredAt: number;
|
|
61
|
+
}
|
|
62
|
+
/** How the host's `TApp` (and `TClient`) go in and out. P6 §3. */
|
|
63
|
+
export interface AppCodec<T> {
|
|
64
|
+
version: number;
|
|
65
|
+
serialize(value: T): unknown;
|
|
66
|
+
/**
|
|
67
|
+
* `raw` is whatever `serialize` produced, and `version` is the `appVersion`
|
|
68
|
+
* it was written under — so a host migrates its own blob without the store
|
|
69
|
+
* bumping `STORE_VERSION`. Throwing here is a quarantine (§4.5), not a crash.
|
|
70
|
+
*/
|
|
71
|
+
deserialize(raw: unknown, version: number, ctx: RestoreContext): T;
|
|
72
|
+
}
|
|
73
|
+
export interface RoomCodec<TApp, TClient = unknown> {
|
|
74
|
+
app: AppCodec<TApp>;
|
|
75
|
+
/** For `ClientMeta.app`. Omitted means the per-client blob is plain JSON. */
|
|
76
|
+
client?: AppCodec<TClient>;
|
|
77
|
+
}
|
|
78
|
+
/** A codec for state that is already plain JSON. Round-trips by structure. */
|
|
79
|
+
export declare function jsonCodec<T>(version?: number): AppCodec<T>;
|
|
80
|
+
/** Why a snapshot could not be read. Each arm is a quarantine reason (§4.5). */
|
|
81
|
+
export type UnreadableReason =
|
|
82
|
+
/** `storeVersion` is not one this build understands. */
|
|
83
|
+
'store-version'
|
|
84
|
+
/** The record is not shaped like a snapshot at all. */
|
|
85
|
+
| 'malformed'
|
|
86
|
+
/** The host's `deserialize` threw. */
|
|
87
|
+
| 'codec';
|
|
88
|
+
/**
|
|
89
|
+
* A snapshot that must be set aside rather than applied.
|
|
90
|
+
*
|
|
91
|
+
* Thrown by `decodeSnapshot` *before* anything touches a room, which is what
|
|
92
|
+
* makes §4.5's "never half-applied" a structural property rather than a promise:
|
|
93
|
+
* the decode either produces a complete set of fields or it produces nothing.
|
|
94
|
+
* Half-restoring is the worse failure — a room back with seats but not its app
|
|
95
|
+
* state looks fine and is unrecoverable, where one that does not come back at all is
|
|
96
|
+
* obvious in the first second.
|
|
97
|
+
*/
|
|
98
|
+
export declare class SnapshotUnreadableError extends Error {
|
|
99
|
+
readonly reason: UnreadableReason;
|
|
100
|
+
readonly roomId: string;
|
|
101
|
+
constructor(reason: UnreadableReason, roomId: string, detail: string);
|
|
102
|
+
}
|
|
103
|
+
/**
|
|
104
|
+
* Drop everything a non-durable participant held, in place, on a CLONE.
|
|
105
|
+
*
|
|
106
|
+
* §4.2. `isDurableParticipantId` is the predicate and its own doc comment names
|
|
107
|
+
* this as its purpose — *"the check for 'may hold a seat / may have a pending
|
|
108
|
+
* request replayed'"*. An `eph:` id **is** a socket id, so restoring one would
|
|
109
|
+
* hold a seat that no future connection can ever claim. The roster comes back
|
|
110
|
+
* smaller than it went in, and the seat comes back claimable. That is correct,
|
|
111
|
+
* not lossy.
|
|
112
|
+
*
|
|
113
|
+
* Applied on the way out (nothing ephemeral reaches disk) and again on the way
|
|
114
|
+
* in (a snapshot written by another build is not trusted to have done it).
|
|
115
|
+
*/
|
|
116
|
+
export declare function pruneNonDurable(table: SeatTable): SeatTable;
|
|
117
|
+
/**
|
|
118
|
+
* Flatten a live room into its wire form.
|
|
119
|
+
*
|
|
120
|
+
* Pure: the room is read, never written. Everything that comes out is a clone,
|
|
121
|
+
* so a caller holding the snapshot cannot reach back into room state — and, more
|
|
122
|
+
* to the point, a debounced save that is serialised now and written later cannot
|
|
123
|
+
* be changed out from under itself by the next change to the room.
|
|
124
|
+
*
|
|
125
|
+
* `clients` is keyed by the ephemeral `clientId`, so two live sockets for one
|
|
126
|
+
* refreshing participant appear as two entries. They collapse to one member,
|
|
127
|
+
* keeping the most recently seen — a snapshot describes people, not connections.
|
|
128
|
+
*/
|
|
129
|
+
export declare function snapshotRoom<TApp, TClient>(room: CoreRoomState<TApp, TClient>, codec: RoomCodec<TApp, TClient>): RoomSnapshot;
|
|
130
|
+
/** A durable member, back from the snapshot. Not a `ClientMeta`: it has no socket. */
|
|
131
|
+
export interface RestoredMember<TClient> {
|
|
132
|
+
participantId: ParticipantId;
|
|
133
|
+
joinedAt: number;
|
|
134
|
+
lastSeen: number;
|
|
135
|
+
accountId?: string;
|
|
136
|
+
app: TClient;
|
|
137
|
+
}
|
|
138
|
+
/** Everything a restore produces, assembled before any of it is applied. */
|
|
139
|
+
export interface DecodedSnapshot<TApp, TClient> {
|
|
140
|
+
roomId: string;
|
|
141
|
+
roomKey: string;
|
|
142
|
+
lastEventSeq: number;
|
|
143
|
+
createdAt: number;
|
|
144
|
+
usedAvatars: Set<string>;
|
|
145
|
+
seats: SeatTable;
|
|
146
|
+
app: TApp;
|
|
147
|
+
members: Array<RestoredMember<TClient>>;
|
|
148
|
+
}
|
|
149
|
+
/**
|
|
150
|
+
* Turn a snapshot back into room fields, or throw.
|
|
151
|
+
*
|
|
152
|
+
* Nothing in here touches a room. That is the §4.5 guarantee in one sentence:
|
|
153
|
+
* every way this can fail — an unknown `storeVersion`, a record that is not
|
|
154
|
+
* shaped like a snapshot, a host codec that throws — fails before a single field
|
|
155
|
+
* has been assigned anywhere, so there is no state to be left half-applied.
|
|
156
|
+
*
|
|
157
|
+
* **`leaderId` is not restored, and nothing here produces one.**
|
|
158
|
+
* `CoreRoomState.leaderId` is documented as *"The room's authority, by
|
|
159
|
+
* clientId"*, and `clientId` is the ephemeral per-connection id — so a persisted
|
|
160
|
+
* `leaderId` names a socket that certainly does not exist after a restart. P6 §2
|
|
161
|
+
* offered three ways out and this package takes (b): persist nothing, and let
|
|
162
|
+
* leadership be re-established on the first qualifying join after restore. It is
|
|
163
|
+
* the least surprising behaviour for a host that has not asked for any of this,
|
|
164
|
+
* it is roughly what an unpersisted server already does when a leader
|
|
165
|
+
* disconnects, and many apps have no leader concept at all.
|
|
166
|
+
*/
|
|
167
|
+
export declare function decodeSnapshot<TApp, TClient>(snapshot: RoomSnapshot, codec: RoomCodec<TApp, TClient>, ctx: RestoreContext): DecodedSnapshot<TApp, TClient>;
|
|
168
|
+
/**
|
|
169
|
+
* Write a decoded snapshot onto a freshly seeded room, all at once.
|
|
170
|
+
*
|
|
171
|
+
* Separate from `decodeSnapshot` on purpose: everything that can fail has
|
|
172
|
+
* already happened by the time this runs, so this function cannot leave a room
|
|
173
|
+
* half-restored.
|
|
174
|
+
*
|
|
175
|
+
* Two fields come from `now` rather than from the snapshot:
|
|
176
|
+
*
|
|
177
|
+
* - **`updatedAt`** — §4.6. `evaluateRoom` computes `now - room.updatedAt` and
|
|
178
|
+
* destroys an empty room once that exceeds `emptyGraceMs`. Inheriting the
|
|
179
|
+
* snapshot's `updatedAt` would make a room restored after a long outage
|
|
180
|
+
* instantly reap-eligible, before anybody has had a chance to reconnect. A
|
|
181
|
+
* restore stamps a FRESH emptiness clock. (`gc.ts`'s own comment concedes
|
|
182
|
+
* that `updatedAt` "stands in for last emptied — coarse but conservative",
|
|
183
|
+
* which is true while rooms are born empty and false the moment one is born
|
|
184
|
+
* 45 minutes old.)
|
|
185
|
+
* - **`leaderId`** — null. See `decodeSnapshot`.
|
|
186
|
+
*
|
|
187
|
+
* `clients` stays empty: §4.3. The restored participants have no sockets at all
|
|
188
|
+
* and their seats are still theirs. Seat tenure is a function of participant
|
|
189
|
+
* identity and time, never of socket liveness.
|
|
190
|
+
*/
|
|
191
|
+
export declare function applySnapshot<TApp, TClient>(room: CoreRoomState<TApp, TClient>, decoded: DecodedSnapshot<TApp, TClient>, now: number): void;
|
|
192
|
+
//# sourceMappingURL=snapshot.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"snapshot.d.ts","sourceRoot":"","sources":["../../src/store/snapshot.ts"],"names":[],"mappings":"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"}
|
|
@@ -0,0 +1,306 @@
|
|
|
1
|
+
/*
|
|
2
|
+
* The wire form of a room, and the two pure functions that get in and out of it.
|
|
3
|
+
*
|
|
4
|
+
* This is the hard half of room persistence (P6 §3; `index.ts` says where the
|
|
5
|
+
* § numbers point). Not the storage — storage is `store.ts` and it is twenty
|
|
6
|
+
* lines per tier. The hard part is that `JSON.stringify` renders a `Map` and a
|
|
7
|
+
* `Set` as `{}`, so a room written out naively comes back with an empty roster
|
|
8
|
+
* and nobody notices until the restore.
|
|
9
|
+
*
|
|
10
|
+
* ## What actually needs flattening
|
|
11
|
+
*
|
|
12
|
+
* Three containers, and only three, verified against `../state.ts`: `clients`
|
|
13
|
+
* (a `Map`), `usedAvatars` (a `Set`) and `clientNames` (a `Map`). Every other field on `CoreRoomState` is a scalar,
|
|
14
|
+
* and `seats` is a `SeatTable`, which `@wolffm/rooms-protocol`'s `seats.ts`
|
|
15
|
+
* made plain JSON-safe arrays and records *specifically so this would be a
|
|
16
|
+
* matter of writing it out* — its header says so and asks that it be kept that
|
|
17
|
+
* way. So `SeatTable` goes into the snapshot verbatim.
|
|
18
|
+
*
|
|
19
|
+
* ## Three fields are deliberately absent
|
|
20
|
+
*
|
|
21
|
+
* `SerializedMember` carries neither `clientId` nor `socketId` nor `friendKey`,
|
|
22
|
+
* and each absence is load-bearing rather than an oversight:
|
|
23
|
+
*
|
|
24
|
+
* - `clientId` and `socketId` are transport identifiers (`state.ts`'s own
|
|
25
|
+
* comment: *"Ephemeral per-connection id. In practice the socket id."*).
|
|
26
|
+
* Neither survives a restart, so persisting one would restore a room whose
|
|
27
|
+
* roster names sockets that certainly do not exist. The stable identity IS
|
|
28
|
+
* `participantId` — the whole point of the tiered id scheme.
|
|
29
|
+
* - `friendKey` is **auth material**. `ClientMeta.friendKey`'s own doc comment
|
|
30
|
+
* says *"Server-internal: it IS the auth material, so it must never reach a
|
|
31
|
+
* payload"*, and a snapshot on disk is a payload — a longer-lived one than
|
|
32
|
+
* anything on a socket. Writing it out would put every friend's credential
|
|
33
|
+
* in a file, looking entirely normal.
|
|
34
|
+
*
|
|
35
|
+
* ## No names, no faces: a person is their userId (R12)
|
|
36
|
+
*
|
|
37
|
+
* A member is written as their `participantId` and, beside it, `accountId`: the
|
|
38
|
+
* registry userId the id was minted from. Never a display name, never an avatar
|
|
39
|
+
* id, and no `clientNames` (hadoku_site IDENTITY_MODEL R12, cardtable#25). A
|
|
40
|
+
* name or face on disk is a copy an account delete never reaches and a rename
|
|
41
|
+
* never updates; the userId is what a name or face is looked up by when shown,
|
|
42
|
+
* and an erased account's userId simply stops resolving. A live member brings
|
|
43
|
+
* both back on their next request.
|
|
44
|
+
*
|
|
45
|
+
* `leaderId` is absent too, for a different reason; see `decodeSnapshot`.
|
|
46
|
+
*/
|
|
47
|
+
import { isDurableParticipantId, } from '@wolffm/rooms-protocol';
|
|
48
|
+
/**
|
|
49
|
+
* Bumped when the shape in THIS file changes, or what its ids mean does.
|
|
50
|
+
*
|
|
51
|
+
* A snapshot whose `storeVersion` this build does not recognise is quarantined,
|
|
52
|
+
* never guessed at (§4.5). The host's own blob versions independently through
|
|
53
|
+
* `appVersion`, so a host migrating its app state does not need us to bump.
|
|
54
|
+
*
|
|
55
|
+
* 2 (2026-10-31): participant ids are minted from the userId, not the key
|
|
56
|
+
* (cardtable#2, #25). A version-1 snapshot names people by key-derived ids no
|
|
57
|
+
* caller can present any more, and they cannot be mapped without the keys, so
|
|
58
|
+
* it is quarantined like any other unknown version (the operator chose a reset).
|
|
59
|
+
*/
|
|
60
|
+
export const STORE_VERSION = 2;
|
|
61
|
+
/** A codec for state that is already plain JSON. Round-trips by structure. */
|
|
62
|
+
export function jsonCodec(version = 1) {
|
|
63
|
+
return {
|
|
64
|
+
version,
|
|
65
|
+
serialize: (value) => clone(value),
|
|
66
|
+
deserialize: (raw) => clone(raw),
|
|
67
|
+
};
|
|
68
|
+
}
|
|
69
|
+
/**
|
|
70
|
+
* A snapshot that must be set aside rather than applied.
|
|
71
|
+
*
|
|
72
|
+
* Thrown by `decodeSnapshot` *before* anything touches a room, which is what
|
|
73
|
+
* makes §4.5's "never half-applied" a structural property rather than a promise:
|
|
74
|
+
* the decode either produces a complete set of fields or it produces nothing.
|
|
75
|
+
* Half-restoring is the worse failure — a room back with seats but not its app
|
|
76
|
+
* state looks fine and is unrecoverable, where one that does not come back at all is
|
|
77
|
+
* obvious in the first second.
|
|
78
|
+
*/
|
|
79
|
+
export class SnapshotUnreadableError extends Error {
|
|
80
|
+
reason;
|
|
81
|
+
roomId;
|
|
82
|
+
constructor(reason, roomId, detail) {
|
|
83
|
+
super(`snapshot for room ${roomId} is unreadable (${reason}): ${detail}`);
|
|
84
|
+
this.name = 'SnapshotUnreadableError';
|
|
85
|
+
this.reason = reason;
|
|
86
|
+
this.roomId = roomId;
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
function clone(value) {
|
|
90
|
+
return structuredClone(value);
|
|
91
|
+
}
|
|
92
|
+
/**
|
|
93
|
+
* Drop everything a non-durable participant held, in place, on a CLONE.
|
|
94
|
+
*
|
|
95
|
+
* §4.2. `isDurableParticipantId` is the predicate and its own doc comment names
|
|
96
|
+
* this as its purpose — *"the check for 'may hold a seat / may have a pending
|
|
97
|
+
* request replayed'"*. An `eph:` id **is** a socket id, so restoring one would
|
|
98
|
+
* hold a seat that no future connection can ever claim. The roster comes back
|
|
99
|
+
* smaller than it went in, and the seat comes back claimable. That is correct,
|
|
100
|
+
* not lossy.
|
|
101
|
+
*
|
|
102
|
+
* Applied on the way out (nothing ephemeral reaches disk) and again on the way
|
|
103
|
+
* in (a snapshot written by another build is not trusted to have done it).
|
|
104
|
+
*/
|
|
105
|
+
export function pruneNonDurable(table) {
|
|
106
|
+
for (const seat of table.seats) {
|
|
107
|
+
const occ = seat.occupant;
|
|
108
|
+
if (occ && occ.kind === 'human' && !isDurableParticipantId(occ.participantId)) {
|
|
109
|
+
seat.occupant = null;
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
for (const pid of Object.keys(table.remembered)) {
|
|
113
|
+
if (!isDurableParticipantId(pid))
|
|
114
|
+
delete table.remembered[pid];
|
|
115
|
+
}
|
|
116
|
+
for (const [seatId, reservation] of Object.entries(table.reservations)) {
|
|
117
|
+
if (!isDurableParticipantId(reservation.participantId)) {
|
|
118
|
+
delete table.reservations[Number(seatId)];
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
return table;
|
|
122
|
+
}
|
|
123
|
+
/**
|
|
124
|
+
* Flatten a live room into its wire form.
|
|
125
|
+
*
|
|
126
|
+
* Pure: the room is read, never written. Everything that comes out is a clone,
|
|
127
|
+
* so a caller holding the snapshot cannot reach back into room state — and, more
|
|
128
|
+
* to the point, a debounced save that is serialised now and written later cannot
|
|
129
|
+
* be changed out from under itself by the next change to the room.
|
|
130
|
+
*
|
|
131
|
+
* `clients` is keyed by the ephemeral `clientId`, so two live sockets for one
|
|
132
|
+
* refreshing participant appear as two entries. They collapse to one member,
|
|
133
|
+
* keeping the most recently seen — a snapshot describes people, not connections.
|
|
134
|
+
*/
|
|
135
|
+
export function snapshotRoom(room, codec) {
|
|
136
|
+
const byParticipant = new Map();
|
|
137
|
+
for (const meta of room.clients.values()) {
|
|
138
|
+
if (!isDurableParticipantId(meta.participantId))
|
|
139
|
+
continue;
|
|
140
|
+
const existing = byParticipant.get(meta.participantId);
|
|
141
|
+
if (existing === undefined || meta.lastSeen >= existing.lastSeen) {
|
|
142
|
+
byParticipant.set(meta.participantId, meta);
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
const members = [];
|
|
146
|
+
for (const meta of byParticipant.values()) {
|
|
147
|
+
const member = {
|
|
148
|
+
participantId: meta.participantId,
|
|
149
|
+
joinedAt: meta.joinedAt,
|
|
150
|
+
lastSeen: meta.lastSeen,
|
|
151
|
+
app: codec.client ? codec.client.serialize(meta.app) : clone(meta.app),
|
|
152
|
+
};
|
|
153
|
+
if (meta.accountId !== undefined)
|
|
154
|
+
member.accountId = meta.accountId;
|
|
155
|
+
members.push(member);
|
|
156
|
+
}
|
|
157
|
+
members.sort((a, b) => (a.participantId < b.participantId ? -1 : 1));
|
|
158
|
+
return {
|
|
159
|
+
storeVersion: STORE_VERSION,
|
|
160
|
+
roomId: room.roomId,
|
|
161
|
+
roomKey: room.roomKey,
|
|
162
|
+
lastEventSeq: room.lastEventSeq,
|
|
163
|
+
createdAt: room.createdAt,
|
|
164
|
+
updatedAt: room.updatedAt,
|
|
165
|
+
members,
|
|
166
|
+
usedAvatars: [...room.usedAvatars].sort(),
|
|
167
|
+
seats: pruneNonDurable(clone(room.seats)),
|
|
168
|
+
app: codec.app.serialize(room.app),
|
|
169
|
+
appVersion: codec.app.version,
|
|
170
|
+
};
|
|
171
|
+
}
|
|
172
|
+
function isRecord(v) {
|
|
173
|
+
return typeof v === 'object' && v !== null;
|
|
174
|
+
}
|
|
175
|
+
function looksLikeSeatTable(v) {
|
|
176
|
+
if (!isRecord(v))
|
|
177
|
+
return false;
|
|
178
|
+
if (!Array.isArray(v.seats))
|
|
179
|
+
return false;
|
|
180
|
+
if (!isRecord(v.remembered) || !isRecord(v.reservations))
|
|
181
|
+
return false;
|
|
182
|
+
if (typeof v.reservationTtlMs !== 'number')
|
|
183
|
+
return false;
|
|
184
|
+
return v.capacity === null || typeof v.capacity === 'number';
|
|
185
|
+
}
|
|
186
|
+
/**
|
|
187
|
+
* Turn a snapshot back into room fields, or throw.
|
|
188
|
+
*
|
|
189
|
+
* Nothing in here touches a room. That is the §4.5 guarantee in one sentence:
|
|
190
|
+
* every way this can fail — an unknown `storeVersion`, a record that is not
|
|
191
|
+
* shaped like a snapshot, a host codec that throws — fails before a single field
|
|
192
|
+
* has been assigned anywhere, so there is no state to be left half-applied.
|
|
193
|
+
*
|
|
194
|
+
* **`leaderId` is not restored, and nothing here produces one.**
|
|
195
|
+
* `CoreRoomState.leaderId` is documented as *"The room's authority, by
|
|
196
|
+
* clientId"*, and `clientId` is the ephemeral per-connection id — so a persisted
|
|
197
|
+
* `leaderId` names a socket that certainly does not exist after a restart. P6 §2
|
|
198
|
+
* offered three ways out and this package takes (b): persist nothing, and let
|
|
199
|
+
* leadership be re-established on the first qualifying join after restore. It is
|
|
200
|
+
* the least surprising behaviour for a host that has not asked for any of this,
|
|
201
|
+
* it is roughly what an unpersisted server already does when a leader
|
|
202
|
+
* disconnects, and many apps have no leader concept at all.
|
|
203
|
+
*/
|
|
204
|
+
export function decodeSnapshot(snapshot, codec, ctx) {
|
|
205
|
+
const roomId = ctx.roomId;
|
|
206
|
+
if (!isRecord(snapshot)) {
|
|
207
|
+
throw new SnapshotUnreadableError('malformed', roomId, 'record is not an object');
|
|
208
|
+
}
|
|
209
|
+
if (snapshot.storeVersion !== STORE_VERSION) {
|
|
210
|
+
throw new SnapshotUnreadableError('store-version', roomId, `have ${STORE_VERSION}, found ${String(snapshot.storeVersion)}`);
|
|
211
|
+
}
|
|
212
|
+
if (typeof snapshot.roomId !== 'string' || typeof snapshot.roomKey !== 'string') {
|
|
213
|
+
throw new SnapshotUnreadableError('malformed', roomId, 'roomId/roomKey missing');
|
|
214
|
+
}
|
|
215
|
+
if (typeof snapshot.lastEventSeq !== 'number' || typeof snapshot.createdAt !== 'number') {
|
|
216
|
+
throw new SnapshotUnreadableError('malformed', roomId, 'lastEventSeq/createdAt missing');
|
|
217
|
+
}
|
|
218
|
+
if (!Array.isArray(snapshot.members) || !Array.isArray(snapshot.usedAvatars)) {
|
|
219
|
+
throw new SnapshotUnreadableError('malformed', roomId, 'members/usedAvatars missing');
|
|
220
|
+
}
|
|
221
|
+
if (!looksLikeSeatTable(snapshot.seats)) {
|
|
222
|
+
throw new SnapshotUnreadableError('malformed', roomId, 'seats is not a SeatTable');
|
|
223
|
+
}
|
|
224
|
+
const appVersion = snapshot.appVersion ?? codec.app.version;
|
|
225
|
+
let app;
|
|
226
|
+
try {
|
|
227
|
+
app = codec.app.deserialize(snapshot.app, appVersion, ctx);
|
|
228
|
+
}
|
|
229
|
+
catch (err) {
|
|
230
|
+
throw new SnapshotUnreadableError('codec', roomId, `app codec threw: ${String(err)}`);
|
|
231
|
+
}
|
|
232
|
+
const members = [];
|
|
233
|
+
for (const raw of snapshot.members) {
|
|
234
|
+
if (!isRecord(raw) || typeof raw.participantId !== 'string') {
|
|
235
|
+
throw new SnapshotUnreadableError('malformed', roomId, 'member without a participantId');
|
|
236
|
+
}
|
|
237
|
+
// §4.2 again, on the way in. A snapshot written by another build is not
|
|
238
|
+
// trusted to have pruned; restoring an `eph:` member would hand a seat to an
|
|
239
|
+
// id that is a dead socket.
|
|
240
|
+
if (!isDurableParticipantId(raw.participantId))
|
|
241
|
+
continue;
|
|
242
|
+
let clientApp;
|
|
243
|
+
try {
|
|
244
|
+
clientApp = codec.client
|
|
245
|
+
? codec.client.deserialize(raw.app, appVersion, ctx)
|
|
246
|
+
: clone(raw.app);
|
|
247
|
+
}
|
|
248
|
+
catch (err) {
|
|
249
|
+
throw new SnapshotUnreadableError('codec', roomId, `client codec threw: ${String(err)}`);
|
|
250
|
+
}
|
|
251
|
+
const member = {
|
|
252
|
+
participantId: raw.participantId,
|
|
253
|
+
joinedAt: typeof raw.joinedAt === 'number' ? raw.joinedAt : ctx.restoredAt,
|
|
254
|
+
lastSeen: typeof raw.lastSeen === 'number' ? raw.lastSeen : ctx.restoredAt,
|
|
255
|
+
app: clientApp,
|
|
256
|
+
};
|
|
257
|
+
// A name or avatar id a snapshot still carries is not read back (see the header).
|
|
258
|
+
if (typeof raw.accountId === 'string' && raw.accountId !== '')
|
|
259
|
+
member.accountId = raw.accountId;
|
|
260
|
+
members.push(member);
|
|
261
|
+
}
|
|
262
|
+
return {
|
|
263
|
+
roomId: snapshot.roomId,
|
|
264
|
+
roomKey: snapshot.roomKey,
|
|
265
|
+
lastEventSeq: snapshot.lastEventSeq,
|
|
266
|
+
createdAt: snapshot.createdAt,
|
|
267
|
+
usedAvatars: new Set(snapshot.usedAvatars.filter((a) => typeof a === 'string')),
|
|
268
|
+
seats: pruneNonDurable(clone(snapshot.seats)),
|
|
269
|
+
app,
|
|
270
|
+
members,
|
|
271
|
+
};
|
|
272
|
+
}
|
|
273
|
+
/**
|
|
274
|
+
* Write a decoded snapshot onto a freshly seeded room, all at once.
|
|
275
|
+
*
|
|
276
|
+
* Separate from `decodeSnapshot` on purpose: everything that can fail has
|
|
277
|
+
* already happened by the time this runs, so this function cannot leave a room
|
|
278
|
+
* half-restored.
|
|
279
|
+
*
|
|
280
|
+
* Two fields come from `now` rather than from the snapshot:
|
|
281
|
+
*
|
|
282
|
+
* - **`updatedAt`** — §4.6. `evaluateRoom` computes `now - room.updatedAt` and
|
|
283
|
+
* destroys an empty room once that exceeds `emptyGraceMs`. Inheriting the
|
|
284
|
+
* snapshot's `updatedAt` would make a room restored after a long outage
|
|
285
|
+
* instantly reap-eligible, before anybody has had a chance to reconnect. A
|
|
286
|
+
* restore stamps a FRESH emptiness clock. (`gc.ts`'s own comment concedes
|
|
287
|
+
* that `updatedAt` "stands in for last emptied — coarse but conservative",
|
|
288
|
+
* which is true while rooms are born empty and false the moment one is born
|
|
289
|
+
* 45 minutes old.)
|
|
290
|
+
* - **`leaderId`** — null. See `decodeSnapshot`.
|
|
291
|
+
*
|
|
292
|
+
* `clients` stays empty: §4.3. The restored participants have no sockets at all
|
|
293
|
+
* and their seats are still theirs. Seat tenure is a function of participant
|
|
294
|
+
* identity and time, never of socket liveness.
|
|
295
|
+
*/
|
|
296
|
+
export function applySnapshot(room, decoded, now) {
|
|
297
|
+
room.leaderId = null;
|
|
298
|
+
room.lastEventSeq = decoded.lastEventSeq;
|
|
299
|
+
room.createdAt = decoded.createdAt;
|
|
300
|
+
room.updatedAt = now;
|
|
301
|
+
room.clients.clear();
|
|
302
|
+
room.usedAvatars = decoded.usedAvatars;
|
|
303
|
+
room.clientNames = new Map();
|
|
304
|
+
room.seats = decoded.seats;
|
|
305
|
+
room.app = decoded.app;
|
|
306
|
+
}
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
import type { RoomSnapshot } from './snapshot.js';
|
|
2
|
+
export interface RoomStore {
|
|
3
|
+
load(roomId: string): Promise<RoomSnapshot | null>;
|
|
4
|
+
save(snapshot: RoomSnapshot): Promise<void>;
|
|
5
|
+
remove(roomId: string): Promise<void>;
|
|
6
|
+
/** Room ids known to the store, for an eager restore at boot. */
|
|
7
|
+
list(): Promise<string[]>;
|
|
8
|
+
/**
|
|
9
|
+
* Set a room's record aside INTACT under a distinct key, and make `load`
|
|
10
|
+
* behave as if it were not there. §4.5.
|
|
11
|
+
*
|
|
12
|
+
* On the interface rather than bolted on per tier, because a tier that cannot
|
|
13
|
+
* quarantine cannot implement the one rule that keeps a half-read snapshot
|
|
14
|
+
* from being applied — and that is the rule the whole store is refused over.
|
|
15
|
+
*/
|
|
16
|
+
quarantine(roomId: string, reason: string): Promise<void>;
|
|
17
|
+
/** Quarantine keys. Diagnostic; the boot path never reads them. */
|
|
18
|
+
listQuarantined(): Promise<string[]>;
|
|
19
|
+
/**
|
|
20
|
+
* Optional synchronous write, used by the SIGTERM flush (§4.4).
|
|
21
|
+
*
|
|
22
|
+
* A signal handler that awaits a promise races the process exit. A tier that
|
|
23
|
+
* can write synchronously says so here; the flush falls back to the async path
|
|
24
|
+
* under a deadline for one that cannot.
|
|
25
|
+
*/
|
|
26
|
+
saveSync?(snapshot: RoomSnapshot): void;
|
|
27
|
+
}
|
|
28
|
+
/**
|
|
29
|
+
* The default tier. Survives nothing, which is the point: it changes no
|
|
30
|
+
* behaviour for a host that never asked for persistence, while still exercising
|
|
31
|
+
* every code path a real tier does — so the load-or-create logic, the debounce
|
|
32
|
+
* and the quarantine are not untested in the default configuration.
|
|
33
|
+
*
|
|
34
|
+
* Stores clones, so a caller mutating a room after `save` cannot reach into what
|
|
35
|
+
* was written. A file tier gets that for free from serialisation; the memory
|
|
36
|
+
* tier has to do it on purpose, and a memory tier that aliased would make the
|
|
37
|
+
* two tiers behave differently under exactly the debounce this package exists
|
|
38
|
+
* to make safe.
|
|
39
|
+
*/
|
|
40
|
+
export declare class MemoryRoomStore implements RoomStore {
|
|
41
|
+
#private;
|
|
42
|
+
load(roomId: string): Promise<RoomSnapshot | null>;
|
|
43
|
+
save(snapshot: RoomSnapshot): Promise<void>;
|
|
44
|
+
saveSync(snapshot: RoomSnapshot): void;
|
|
45
|
+
remove(roomId: string): Promise<void>;
|
|
46
|
+
list(): Promise<string[]>;
|
|
47
|
+
quarantine(roomId: string, reason: string): Promise<void>;
|
|
48
|
+
listQuarantined(): Promise<string[]>;
|
|
49
|
+
/** The record set aside under `key`, exactly as it was stored. */
|
|
50
|
+
quarantinedRecord(key: string): {
|
|
51
|
+
snapshot: RoomSnapshot;
|
|
52
|
+
reason: string;
|
|
53
|
+
} | undefined;
|
|
54
|
+
}
|
|
55
|
+
//# sourceMappingURL=store.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"store.d.ts","sourceRoot":"","sources":["../../src/store/store.ts"],"names":[],"mappings":"AAaA,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,eAAe,CAAC;AAElD,MAAM,WAAW,SAAS;IACxB,IAAI,CAAC,MAAM,EAAE,MAAM,GAAG,OAAO,CAAC,YAAY,GAAG,IAAI,CAAC,CAAC;IACnD,IAAI,CAAC,QAAQ,EAAE,YAAY,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;IAC5C,MAAM,CAAC,MAAM,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;IACtC,iEAAiE;IACjE,IAAI,IAAI,OAAO,CAAC,MAAM,EAAE,CAAC,CAAC;IAC1B;;;;;;;OAOG;IACH,UAAU,CAAC,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;IAC1D,mEAAmE;IACnE,eAAe,IAAI,OAAO,CAAC,MAAM,EAAE,CAAC,CAAC;IACrC;;;;;;OAMG;IACH,QAAQ,CAAC,CAAC,QAAQ,EAAE,YAAY,GAAG,IAAI,CAAC;CACzC;AAMD;;;;;;;;;;;GAWG;AACH,qBAAa,eAAgB,YAAW,SAAS;;IAIzC,IAAI,CAAC,MAAM,EAAE,MAAM,GAAG,OAAO,CAAC,YAAY,GAAG,IAAI,CAAC;IAKlD,IAAI,CAAC,QAAQ,EAAE,YAAY,GAAG,OAAO,CAAC,IAAI,CAAC;IAIjD,QAAQ,CAAC,QAAQ,EAAE,YAAY,GAAG,IAAI;IAIhC,MAAM,CAAC,MAAM,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC;IAIrC,IAAI,IAAI,OAAO,CAAC,MAAM,EAAE,CAAC;IAIzB,UAAU,CAAC,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC;IAOzD,eAAe,IAAI,OAAO,CAAC,MAAM,EAAE,CAAC;IAI1C,kEAAkE;IAClE,iBAAiB,CAAC,GAAG,EAAE,MAAM,GAAG;QAAE,QAAQ,EAAE,YAAY,CAAC;QAAC,MAAM,EAAE,MAAM,CAAA;KAAE,GAAG,SAAS;CAGvF"}
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
/*
|
|
2
|
+
* The store interface and its in-memory tier.
|
|
3
|
+
*
|
|
4
|
+
* Shaped after watchparty's own `chatRepo` pattern — an interface with a memory
|
|
5
|
+
* tier, a file tier and room for a Redis tier behind it, chosen by config, with
|
|
6
|
+
* the memory tier as the always-present base. **Nothing in the interface names a
|
|
7
|
+
* backend**, which is the property that makes a third tier someone else's twenty
|
|
8
|
+
* lines rather than a change here.
|
|
9
|
+
*
|
|
10
|
+
* In-memory is the default, so a host that does not opt in gets exactly what it
|
|
11
|
+
* had: no filesystem, no network, no behaviour change.
|
|
12
|
+
*/
|
|
13
|
+
function clone(snapshot) {
|
|
14
|
+
return structuredClone(snapshot);
|
|
15
|
+
}
|
|
16
|
+
/**
|
|
17
|
+
* The default tier. Survives nothing, which is the point: it changes no
|
|
18
|
+
* behaviour for a host that never asked for persistence, while still exercising
|
|
19
|
+
* every code path a real tier does — so the load-or-create logic, the debounce
|
|
20
|
+
* and the quarantine are not untested in the default configuration.
|
|
21
|
+
*
|
|
22
|
+
* Stores clones, so a caller mutating a room after `save` cannot reach into what
|
|
23
|
+
* was written. A file tier gets that for free from serialisation; the memory
|
|
24
|
+
* tier has to do it on purpose, and a memory tier that aliased would make the
|
|
25
|
+
* two tiers behave differently under exactly the debounce this package exists
|
|
26
|
+
* to make safe.
|
|
27
|
+
*/
|
|
28
|
+
export class MemoryRoomStore {
|
|
29
|
+
#rooms = new Map();
|
|
30
|
+
#quarantined = new Map();
|
|
31
|
+
async load(roomId) {
|
|
32
|
+
const found = this.#rooms.get(roomId);
|
|
33
|
+
return found ? clone(found) : null;
|
|
34
|
+
}
|
|
35
|
+
async save(snapshot) {
|
|
36
|
+
this.saveSync(snapshot);
|
|
37
|
+
}
|
|
38
|
+
saveSync(snapshot) {
|
|
39
|
+
this.#rooms.set(snapshot.roomId, clone(snapshot));
|
|
40
|
+
}
|
|
41
|
+
async remove(roomId) {
|
|
42
|
+
this.#rooms.delete(roomId);
|
|
43
|
+
}
|
|
44
|
+
async list() {
|
|
45
|
+
return [...this.#rooms.keys()].sort();
|
|
46
|
+
}
|
|
47
|
+
async quarantine(roomId, reason) {
|
|
48
|
+
const found = this.#rooms.get(roomId);
|
|
49
|
+
if (found === undefined)
|
|
50
|
+
return;
|
|
51
|
+
this.#rooms.delete(roomId);
|
|
52
|
+
this.#quarantined.set(`${roomId}#${this.#quarantined.size}`, { snapshot: found, reason });
|
|
53
|
+
}
|
|
54
|
+
async listQuarantined() {
|
|
55
|
+
return [...this.#quarantined.keys()].sort();
|
|
56
|
+
}
|
|
57
|
+
/** The record set aside under `key`, exactly as it was stored. */
|
|
58
|
+
quarantinedRecord(key) {
|
|
59
|
+
return this.#quarantined.get(key);
|
|
60
|
+
}
|
|
61
|
+
}
|
package/package.json
CHANGED
|
@@ -1,16 +1,20 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@hadoku/rooms-server",
|
|
3
|
-
"version": "0.45.
|
|
4
|
-
"gitHead": "
|
|
3
|
+
"version": "0.45.58",
|
|
4
|
+
"gitHead": "f29f3a0ffaf16ad7785bced1f0032096b061ab2d",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"license": "MIT",
|
|
7
|
-
"description": "Room lifecycle, membership, seating, identity
|
|
7
|
+
"description": "Room lifecycle, membership, seating, identity, presence, backpressure-aware emit and durable room storage for a socket.io server.",
|
|
8
8
|
"main": "./dist/index.js",
|
|
9
9
|
"types": "./dist/index.d.ts",
|
|
10
10
|
"exports": {
|
|
11
11
|
".": {
|
|
12
12
|
"types": "./dist/index.d.ts",
|
|
13
13
|
"import": "./dist/index.js"
|
|
14
|
+
},
|
|
15
|
+
"./store": {
|
|
16
|
+
"types": "./dist/store/index.d.ts",
|
|
17
|
+
"import": "./dist/store/index.js"
|
|
14
18
|
}
|
|
15
19
|
},
|
|
16
20
|
"files": [
|
|
@@ -23,7 +27,7 @@
|
|
|
23
27
|
"directory": "packages/rooms-server"
|
|
24
28
|
},
|
|
25
29
|
"dependencies": {
|
|
26
|
-
"@wolffm/rooms-protocol": "npm:@hadoku/rooms-protocol@0.45.
|
|
30
|
+
"@wolffm/rooms-protocol": "npm:@hadoku/rooms-protocol@0.45.58"
|
|
27
31
|
},
|
|
28
32
|
"peerDependencies": {
|
|
29
33
|
"socket.io": "^4.8.3"
|