@hadoku/game-server 0.1.136 → 0.1.146
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/erase/rooms.d.ts +2 -1
- package/dist/erase/rooms.js +13 -4
- package/dist/external-game-manifests.js +10 -9
- package/dist/fetch-trace.d.ts +35 -0
- package/dist/fetch-trace.js +123 -0
- package/dist/people.d.ts +18 -4
- package/dist/people.js +27 -6
- package/dist/persist/snapshot-writer.d.ts +55 -0
- package/dist/persist/snapshot-writer.js +162 -0
- package/dist/play/clock.d.ts +5 -1
- package/dist/play/clock.js +6 -2
- package/dist/play/host.js +6 -0
- package/dist/play/jvm-transport.d.ts +6 -0
- package/dist/play/match/shell.d.ts +3 -1
- package/dist/play/match/shell.js +3 -1
- package/dist/relay-game.js +3 -2
- package/dist/room/lobby.d.ts +6 -3
- package/dist/room/lobby.js +23 -5
- package/dist/room/off-loop-store.d.ts +26 -0
- package/dist/room/off-loop-store.js +43 -0
- package/package.json +7 -7
package/dist/erase/rooms.d.ts
CHANGED
|
@@ -62,7 +62,8 @@ interface RoomsLobby {
|
|
|
62
62
|
anonymise(ids: ReadonlySet<string>, to: string): number;
|
|
63
63
|
/** Account merge: every room naming the merged-away account, and not the kept one, names the kept one. */
|
|
64
64
|
merge(move: IdMove): number;
|
|
65
|
-
|
|
65
|
+
/** Every room written or deleted so far is on disk: a step answers only once what it changed is. */
|
|
66
|
+
flushed(): Promise<void>;
|
|
66
67
|
}
|
|
67
68
|
export interface RoomsEraseDeps<M extends LiveMatch> {
|
|
68
69
|
lobby: RoomsLobby;
|
package/dist/erase/rooms.js
CHANGED
|
@@ -57,7 +57,7 @@ export function roomsEraseSteps(deps) {
|
|
|
57
57
|
n++;
|
|
58
58
|
}
|
|
59
59
|
// A closed room's file names them until it is deleted: answer only once it is.
|
|
60
|
-
await deps.lobby.
|
|
60
|
+
await deps.lobby.flushed();
|
|
61
61
|
return n;
|
|
62
62
|
},
|
|
63
63
|
// A merge closes nothing: a room they were alone in moves to the kept account whole (`roomsMoved`).
|
|
@@ -65,7 +65,7 @@ export function roomsEraseSteps(deps) {
|
|
|
65
65
|
},
|
|
66
66
|
{
|
|
67
67
|
what: 'roomsLeft',
|
|
68
|
-
erase: ({ participantId }) => {
|
|
68
|
+
erase: async ({ participantId }) => {
|
|
69
69
|
let n = 0;
|
|
70
70
|
for (const room of deps.lobby.list()) {
|
|
71
71
|
if (!room.members.some((m) => m.id === participantId))
|
|
@@ -77,6 +77,7 @@ export function roomsEraseSteps(deps) {
|
|
|
77
77
|
deps.forfeited(room.id, left.forfeited.tableId, participantId, left.forfeited.matchIds);
|
|
78
78
|
n++;
|
|
79
79
|
}
|
|
80
|
+
await deps.lobby.flushed();
|
|
80
81
|
return n;
|
|
81
82
|
},
|
|
82
83
|
// A merge leaves nothing: their place moves to the kept account (`roomsMoved`), and a room the
|
|
@@ -85,8 +86,16 @@ export function roomsEraseSteps(deps) {
|
|
|
85
86
|
},
|
|
86
87
|
{
|
|
87
88
|
what: 'roomsAnonymised',
|
|
88
|
-
erase: ({ ids, placeholder }) =>
|
|
89
|
-
|
|
89
|
+
erase: async ({ ids, placeholder }) => {
|
|
90
|
+
const n = deps.lobby.anonymise(ids, placeholder);
|
|
91
|
+
await deps.lobby.flushed();
|
|
92
|
+
return n;
|
|
93
|
+
},
|
|
94
|
+
merge: async (accounts) => {
|
|
95
|
+
const roomsMoved = deps.lobby.merge(accounts);
|
|
96
|
+
await deps.lobby.flushed();
|
|
97
|
+
return { roomsMoved };
|
|
98
|
+
},
|
|
90
99
|
},
|
|
91
100
|
];
|
|
92
101
|
}
|
|
@@ -8,7 +8,7 @@
|
|
|
8
8
|
* that cannot be fetched or read never unregisters a game that was read once: the copy on disk
|
|
9
9
|
* stands in, and the reason is logged. Only a game never read anywhere has no manifest.
|
|
10
10
|
*/
|
|
11
|
-
import {
|
|
11
|
+
import { mkdir, readFile, rename, writeFile } from 'node:fs/promises';
|
|
12
12
|
import { join } from 'node:path';
|
|
13
13
|
import { externalGameManifest, manifestPathOf, } from '@wolffm/platform-wire/external-game-manifest';
|
|
14
14
|
const DEFAULT_TIMEOUT_MS = 5_000;
|
|
@@ -36,10 +36,11 @@ export function manifestReader(opts) {
|
|
|
36
36
|
throw new Error(`${url} answered ${res.status}`);
|
|
37
37
|
return parsed(await res.json());
|
|
38
38
|
};
|
|
39
|
-
|
|
39
|
+
// Both off the event loop: a refresh every few minutes must never wait on the disk with the server held.
|
|
40
|
+
const readCache = async (id) => {
|
|
40
41
|
let text;
|
|
41
42
|
try {
|
|
42
|
-
text =
|
|
43
|
+
text = await readFile(cacheFile(id), 'utf8');
|
|
43
44
|
}
|
|
44
45
|
catch (err) {
|
|
45
46
|
if (err.code === 'ENOENT')
|
|
@@ -48,11 +49,11 @@ export function manifestReader(opts) {
|
|
|
48
49
|
}
|
|
49
50
|
return parsed(JSON.parse(text));
|
|
50
51
|
};
|
|
51
|
-
const writeCache = (id, manifest) => {
|
|
52
|
-
|
|
52
|
+
const writeCache = async (id, manifest) => {
|
|
53
|
+
await mkdir(opts.cacheDir, { recursive: true });
|
|
53
54
|
const tmp = `${cacheFile(id)}.tmp`;
|
|
54
|
-
|
|
55
|
-
|
|
55
|
+
await writeFile(tmp, `${JSON.stringify(manifest, null, 2)}\n`, 'utf8');
|
|
56
|
+
await rename(tmp, cacheFile(id));
|
|
56
57
|
};
|
|
57
58
|
return async (game) => {
|
|
58
59
|
if (game.manifest !== undefined)
|
|
@@ -60,7 +61,7 @@ export function manifestReader(opts) {
|
|
|
60
61
|
let cached = null;
|
|
61
62
|
let cacheProblem = null;
|
|
62
63
|
try {
|
|
63
|
-
cached = readCache(game.id);
|
|
64
|
+
cached = await readCache(game.id);
|
|
64
65
|
}
|
|
65
66
|
catch (err) {
|
|
66
67
|
cacheProblem = describe(err);
|
|
@@ -68,7 +69,7 @@ export function manifestReader(opts) {
|
|
|
68
69
|
try {
|
|
69
70
|
const manifest = await fetchOne(game);
|
|
70
71
|
if (JSON.stringify(manifest) !== JSON.stringify(cached))
|
|
71
|
-
writeCache(game.id, manifest);
|
|
72
|
+
await writeCache(game.id, manifest);
|
|
72
73
|
return { manifest, source: 'fetched' };
|
|
73
74
|
}
|
|
74
75
|
catch (err) {
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* How far an outbound `fetch` got before it failed, read from undici's diagnostics channels
|
|
3
|
+
* (Node's own fetch publishes them). A lookup that times out says only "aborted due to timeout";
|
|
4
|
+
* this says whether it was still waiting for a socket, opening one, had sent its request on a new
|
|
5
|
+
* or a reused socket (and how long that socket had sat idle), or had its response headers.
|
|
6
|
+
*
|
|
7
|
+
* Only a fetch made through `tracedFetch` is followed: its context is carried to undici's request
|
|
8
|
+
* by `AsyncLocalStorage`, and every later event is tied to it through the request and its socket.
|
|
9
|
+
* Every other fetch in the process costs one map lookup per event.
|
|
10
|
+
*/
|
|
11
|
+
/** How far one fetch got, each step in ms since it began; a step it never reached is absent. */
|
|
12
|
+
export interface FetchPhases {
|
|
13
|
+
/** undici took the request. */
|
|
14
|
+
queuedMs?: number;
|
|
15
|
+
/** The socket it was sent on: opened for it, or reused from the pool. */
|
|
16
|
+
socket?: 'new' | 'reused';
|
|
17
|
+
/** A new socket: how long its TCP and TLS connect took. */
|
|
18
|
+
connectMs?: number;
|
|
19
|
+
/** A reused socket: how long it had sat idle since its last response finished. */
|
|
20
|
+
idleMs?: number;
|
|
21
|
+
/** Its request headers were written. */
|
|
22
|
+
sentMs?: number;
|
|
23
|
+
/** Its body was written. */
|
|
24
|
+
bodySentMs?: number;
|
|
25
|
+
/** Its response headers arrived. */
|
|
26
|
+
headersMs?: number;
|
|
27
|
+
/** How long it ran before it failed. */
|
|
28
|
+
failedMs?: number;
|
|
29
|
+
/** Connects to the same origin still open when it failed. */
|
|
30
|
+
connectsPending?: number;
|
|
31
|
+
}
|
|
32
|
+
/** `base` (the global fetch by default), followed: a call that rejects leaves how far it got for `phasesOf`. */
|
|
33
|
+
export declare function tracedFetch(base?: typeof fetch): typeof fetch;
|
|
34
|
+
/** How far the traced fetch that failed with `err` got, when one did. */
|
|
35
|
+
export declare function phasesOf(err: unknown): FetchPhases | undefined;
|
|
@@ -0,0 +1,123 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* How far an outbound `fetch` got before it failed, read from undici's diagnostics channels
|
|
3
|
+
* (Node's own fetch publishes them). A lookup that times out says only "aborted due to timeout";
|
|
4
|
+
* this says whether it was still waiting for a socket, opening one, had sent its request on a new
|
|
5
|
+
* or a reused socket (and how long that socket had sat idle), or had its response headers.
|
|
6
|
+
*
|
|
7
|
+
* Only a fetch made through `tracedFetch` is followed: its context is carried to undici's request
|
|
8
|
+
* by `AsyncLocalStorage`, and every later event is tied to it through the request and its socket.
|
|
9
|
+
* Every other fetch in the process costs one map lookup per event.
|
|
10
|
+
*/
|
|
11
|
+
import { AsyncLocalStorage } from 'node:async_hooks';
|
|
12
|
+
import { subscribe } from 'node:diagnostics_channel';
|
|
13
|
+
const now = () => performance.now();
|
|
14
|
+
const context = new AsyncLocalStorage();
|
|
15
|
+
const byRequest = new WeakMap();
|
|
16
|
+
const socketOf = new WeakMap();
|
|
17
|
+
const sockets = new WeakMap();
|
|
18
|
+
/** Connects begun and not yet done, oldest first, by origin (undici hands each end a fresh params object, so they pair in order). */
|
|
19
|
+
const connecting = new Map();
|
|
20
|
+
const byError = new WeakMap();
|
|
21
|
+
const originOf = (p) => `${p?.protocol ?? ''}//${p?.hostname ?? ''}${p?.port === undefined || p.port === '' ? '' : `:${String(p.port)}`}`;
|
|
22
|
+
const since = (t) => Math.round(now() - t.start);
|
|
23
|
+
const failed = (t, err) => {
|
|
24
|
+
if (t.phases.failedMs === undefined) {
|
|
25
|
+
t.phases.failedMs = since(t);
|
|
26
|
+
const origin = t.origin;
|
|
27
|
+
if (origin !== undefined)
|
|
28
|
+
t.phases.connectsPending = connecting.get(origin)?.length ?? 0;
|
|
29
|
+
}
|
|
30
|
+
if (typeof err === 'object' && err !== null)
|
|
31
|
+
byError.set(err, t.phases);
|
|
32
|
+
return t.phases;
|
|
33
|
+
};
|
|
34
|
+
let installed = false;
|
|
35
|
+
function install() {
|
|
36
|
+
if (installed)
|
|
37
|
+
return;
|
|
38
|
+
installed = true;
|
|
39
|
+
subscribe('undici:request:create', (m) => {
|
|
40
|
+
const { request } = m;
|
|
41
|
+
const t = context.getStore();
|
|
42
|
+
if (request === undefined || t === undefined)
|
|
43
|
+
return;
|
|
44
|
+
byRequest.set(request, t);
|
|
45
|
+
t.phases.queuedMs = since(t);
|
|
46
|
+
if (typeof request.origin === 'string')
|
|
47
|
+
t.origin = new URL(request.origin).origin;
|
|
48
|
+
});
|
|
49
|
+
subscribe('undici:client:beforeConnect', (m) => {
|
|
50
|
+
const origin = originOf(m.connectParams);
|
|
51
|
+
connecting.set(origin, [...(connecting.get(origin) ?? []), now()]);
|
|
52
|
+
});
|
|
53
|
+
const connectDone = (m) => {
|
|
54
|
+
const { connectParams, socket } = m;
|
|
55
|
+
const origin = originOf(connectParams);
|
|
56
|
+
const [at, ...rest] = connecting.get(origin) ?? [];
|
|
57
|
+
if (rest.length === 0)
|
|
58
|
+
connecting.delete(origin);
|
|
59
|
+
else
|
|
60
|
+
connecting.set(origin, rest);
|
|
61
|
+
if (at !== undefined && socket !== undefined)
|
|
62
|
+
sockets.set(socket, { connectMs: Math.round(now() - at), used: false });
|
|
63
|
+
};
|
|
64
|
+
subscribe('undici:client:connected', connectDone);
|
|
65
|
+
subscribe('undici:client:connectError', connectDone);
|
|
66
|
+
subscribe('undici:client:sendHeaders', (m) => {
|
|
67
|
+
const { request, socket } = m;
|
|
68
|
+
if (request === undefined || socket === undefined)
|
|
69
|
+
return;
|
|
70
|
+
socketOf.set(request, socket);
|
|
71
|
+
const s = sockets.get(socket);
|
|
72
|
+
const t = byRequest.get(request);
|
|
73
|
+
if (t !== undefined) {
|
|
74
|
+
t.phases.sentMs = since(t);
|
|
75
|
+
t.phases.socket = s?.used === false ? 'new' : 'reused';
|
|
76
|
+
if (s !== undefined && !s.used)
|
|
77
|
+
t.phases.connectMs = s.connectMs;
|
|
78
|
+
if (s?.idleSince !== undefined)
|
|
79
|
+
t.phases.idleMs = Math.round(now() - s.idleSince);
|
|
80
|
+
}
|
|
81
|
+
if (s !== undefined) {
|
|
82
|
+
s.used = true;
|
|
83
|
+
delete s.idleSince;
|
|
84
|
+
}
|
|
85
|
+
});
|
|
86
|
+
subscribe('undici:request:bodySent', (m) => {
|
|
87
|
+
const t = byRequest.get(m.request ?? {});
|
|
88
|
+
if (t !== undefined)
|
|
89
|
+
t.phases.bodySentMs = since(t);
|
|
90
|
+
});
|
|
91
|
+
subscribe('undici:request:headers', (m) => {
|
|
92
|
+
const t = byRequest.get(m.request ?? {});
|
|
93
|
+
if (t !== undefined)
|
|
94
|
+
t.phases.headersMs = since(t);
|
|
95
|
+
});
|
|
96
|
+
subscribe('undici:request:trailers', (m) => {
|
|
97
|
+
const socket = socketOf.get(m.request ?? {});
|
|
98
|
+
const s = socket === undefined ? undefined : sockets.get(socket);
|
|
99
|
+
if (s !== undefined)
|
|
100
|
+
s.idleSince = now();
|
|
101
|
+
});
|
|
102
|
+
subscribe('undici:request:error', (m) => {
|
|
103
|
+
const { request, error } = m;
|
|
104
|
+
const t = request === undefined ? undefined : byRequest.get(request);
|
|
105
|
+
if (t !== undefined)
|
|
106
|
+
failed(t, error);
|
|
107
|
+
});
|
|
108
|
+
}
|
|
109
|
+
/** `base` (the global fetch by default), followed: a call that rejects leaves how far it got for `phasesOf`. */
|
|
110
|
+
export function tracedFetch(base) {
|
|
111
|
+
install();
|
|
112
|
+
return (input, init) => {
|
|
113
|
+
const t = { start: now(), phases: {} };
|
|
114
|
+
return context.run(t, () => (base ?? fetch)(input, init)).catch((err) => {
|
|
115
|
+
failed(t, err);
|
|
116
|
+
throw err;
|
|
117
|
+
});
|
|
118
|
+
};
|
|
119
|
+
}
|
|
120
|
+
/** How far the traced fetch that failed with `err` got, when one did. */
|
|
121
|
+
export function phasesOf(err) {
|
|
122
|
+
return typeof err === 'object' && err !== null ? byError.get(err) : undefined;
|
|
123
|
+
}
|
package/dist/people.d.ts
CHANGED
|
@@ -10,7 +10,8 @@
|
|
|
10
10
|
*
|
|
11
11
|
* Resolved with this server's own service key, through prefs-client's shared
|
|
12
12
|
* people lookup (`createPeopleLookup`). A failure answers nobody and is logged,
|
|
13
|
-
* never thrown: a missing look costs a face its dressing, not a join.
|
|
13
|
+
* never thrown: a missing look costs a face its dressing, not a join. The failure's line says how
|
|
14
|
+
* far the request got (`fetch-trace.ts`). Cached a
|
|
14
15
|
* minute, so a room's joins share one lookup; a person who has
|
|
15
16
|
* just changed theirs is read `fresh` (the served room's `account`, `room/serve.ts`).
|
|
16
17
|
* The picture URL is relayed, never fetched: the browser loads it from
|
|
@@ -29,11 +30,19 @@ export interface Person {
|
|
|
29
30
|
sprite: string | null;
|
|
30
31
|
look: Look | undefined;
|
|
31
32
|
}
|
|
33
|
+
export interface ResolveOptions {
|
|
34
|
+
/** Skip the cache: the person has just changed theirs. */
|
|
35
|
+
fresh?: boolean;
|
|
36
|
+
/**
|
|
37
|
+
* Wait at most this long, then answer with what is cached now. A screen passes `SCREEN_WAIT_MS`:
|
|
38
|
+
* it shows a name it does not have yet as it would an unreachable one, and the lookup carries on
|
|
39
|
+
* and fills the cache for the next read.
|
|
40
|
+
*/
|
|
41
|
+
within?: number;
|
|
42
|
+
}
|
|
32
43
|
export interface People {
|
|
33
44
|
/** Every id in the answer; one the lookup could not reach is absent, not a default. */
|
|
34
|
-
resolve(userIds: readonly string[], opts?:
|
|
35
|
-
fresh?: boolean;
|
|
36
|
-
}): Promise<Map<string, Person>>;
|
|
45
|
+
resolve(userIds: readonly string[], opts?: ResolveOptions): Promise<Map<string, Person>>;
|
|
37
46
|
/** The cached answer for one id, or undefined when there is none fresh. */
|
|
38
47
|
peek(userId: string): Person | undefined;
|
|
39
48
|
}
|
|
@@ -51,6 +60,11 @@ export interface PeopleOptions {
|
|
|
51
60
|
now?: () => number;
|
|
52
61
|
fetch?: typeof fetch;
|
|
53
62
|
}
|
|
63
|
+
/**
|
|
64
|
+
* How long a request a person is waiting on waits for names (`ResolveOptions.within`). prefs-api's
|
|
65
|
+
* answers to this server, 2026-11-24..26: p50 561 ms, p99 1004 ms, p99.5 1105 ms.
|
|
66
|
+
*/
|
|
67
|
+
export declare const SCREEN_WAIT_MS = 1200;
|
|
54
68
|
/** What one resolved entry means here. Exported for its test. */
|
|
55
69
|
export declare function personOf(r: ResolvedPerson | undefined): Person;
|
|
56
70
|
/**
|
package/dist/people.js
CHANGED
|
@@ -10,7 +10,8 @@
|
|
|
10
10
|
*
|
|
11
11
|
* Resolved with this server's own service key, through prefs-client's shared
|
|
12
12
|
* people lookup (`createPeopleLookup`). A failure answers nobody and is logged,
|
|
13
|
-
* never thrown: a missing look costs a face its dressing, not a join.
|
|
13
|
+
* never thrown: a missing look costs a face its dressing, not a join. The failure's line says how
|
|
14
|
+
* far the request got (`fetch-trace.ts`). Cached a
|
|
14
15
|
* minute, so a room's joins share one lookup; a person who has
|
|
15
16
|
* just changed theirs is read `fresh` (the served room's `account`, `room/serve.ts`).
|
|
16
17
|
* The picture URL is relayed, never fetched: the browser loads it from
|
|
@@ -19,8 +20,14 @@
|
|
|
19
20
|
import { createPeopleLookup } from '@wolffm/prefs-client/people';
|
|
20
21
|
import { cleanWorn } from '@wolffm/prefs-client/cosmetics';
|
|
21
22
|
import { AVATAR_ID_MAX, LOOK_PICTURE_MAX, lookOrNone } from '@wolffm/platform-wire/look';
|
|
23
|
+
import { phasesOf, tracedFetch } from './fetch-trace.js';
|
|
22
24
|
const CACHE_TTL_MS = 60_000;
|
|
23
25
|
const LOOKUP_TIMEOUT_MS = 5000;
|
|
26
|
+
/**
|
|
27
|
+
* How long a request a person is waiting on waits for names (`ResolveOptions.within`). prefs-api's
|
|
28
|
+
* answers to this server, 2026-11-24..26: p50 561 ms, p99 1004 ms, p99.5 1105 ms.
|
|
29
|
+
*/
|
|
30
|
+
export const SCREEN_WAIT_MS = 1200;
|
|
24
31
|
/** What one resolved entry means here. Exported for its test. */
|
|
25
32
|
export function personOf(r) {
|
|
26
33
|
const picture = r !== undefined && r.source !== 'sprite' && typeof r.url === 'string' && r.url.startsWith('https://') && r.url.length <= LOOK_PICTURE_MAX ? r.url : undefined;
|
|
@@ -45,8 +52,8 @@ export function createPeople(opts) {
|
|
|
45
52
|
userAgent: 'hadoku-cardtable-people/1',
|
|
46
53
|
ttlMs: CACHE_TTL_MS,
|
|
47
54
|
timeoutMs: LOOKUP_TIMEOUT_MS,
|
|
48
|
-
onError: (err, ids) => opts.log({ evt: 'people-resolve-failed', ids: ids.length, error: err.message }),
|
|
49
|
-
|
|
55
|
+
onError: (err, ids) => opts.log({ evt: 'people-resolve-failed', ids: ids.length, error: err.message, ...phasesOf(err) }),
|
|
56
|
+
fetch: tracedFetch(opts.fetch),
|
|
50
57
|
...(opts.now === undefined ? {} : { now: opts.now }),
|
|
51
58
|
});
|
|
52
59
|
const peek = (userId) => {
|
|
@@ -56,10 +63,24 @@ export function createPeople(opts) {
|
|
|
56
63
|
return {
|
|
57
64
|
peek,
|
|
58
65
|
forget: (userId) => lookup.forget(userId),
|
|
59
|
-
async resolve(userIds, options = {}) {
|
|
66
|
+
async resolve(userIds, { within, ...options } = {}) {
|
|
67
|
+
const answer = lookup.resolve(userIds, options);
|
|
68
|
+
let late;
|
|
69
|
+
const found = await (within === undefined
|
|
70
|
+
? answer
|
|
71
|
+
: Promise.race([answer, new Promise((r) => (late = setTimeout(() => r(undefined), within)))]).finally(() => clearTimeout(late)));
|
|
60
72
|
const out = new Map();
|
|
61
|
-
|
|
62
|
-
|
|
73
|
+
if (found === undefined) {
|
|
74
|
+
opts.log({ evt: 'people-shown-early', ids: userIds.length, waitedMs: within });
|
|
75
|
+
for (const id of new Set(userIds)) {
|
|
76
|
+
const person = peek(id);
|
|
77
|
+
if (person !== undefined)
|
|
78
|
+
out.set(id, person);
|
|
79
|
+
}
|
|
80
|
+
return out;
|
|
81
|
+
}
|
|
82
|
+
for (const [id, a] of found)
|
|
83
|
+
out.set(id, personOf(a ?? undefined));
|
|
63
84
|
return out;
|
|
64
85
|
},
|
|
65
86
|
};
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Every snapshot file the server keeps (a room, a draft) is written here, OFF the event loop.
|
|
3
|
+
*
|
|
4
|
+
* ## Why
|
|
5
|
+
*
|
|
6
|
+
* A synchronous write on the event loop stops everything the server does until the disk answers:
|
|
7
|
+
* the claws' heartbeats, every socket, every request. On the production host's btrfs root under another
|
|
8
|
+
* workload's writes, `fsyncSync` of a 10 kB room file can force a whole transaction commit and
|
|
9
|
+
* take tens of seconds (2026-11-27 06:07–06:12Z: the process in D state with its CPU idle, a POST
|
|
10
|
+
* that wrote three rooms 28.7 s, and every claw fencing its JVMs because this server said nothing
|
|
11
|
+
* for 10 s). Writing through `fs/promises` moves the wait onto libuv's pool, where it delays only
|
|
12
|
+
* the next snapshot.
|
|
13
|
+
*
|
|
14
|
+
* ## What a write is
|
|
15
|
+
*
|
|
16
|
+
* The same atomic recipe `FileRoomStore` uses: a temp file, `fsync`ed, renamed over the target, so a
|
|
17
|
+
* reader never sees half a snapshot and a crash leaves the previous one.
|
|
18
|
+
*
|
|
19
|
+
* ## Order and memory
|
|
20
|
+
*
|
|
21
|
+
* One file is in flight at a time, across the whole process: a stalled disk ties up one pool thread,
|
|
22
|
+
* never all four (`dns.lookup`, zlib and the rest share them). A file written again before its
|
|
23
|
+
* last write has started keeps only the newest text, so a stall costs one pending snapshot per file,
|
|
24
|
+
* however many mutations it sat through. A remove waits behind the writes queued before it, so a
|
|
25
|
+
* late write can never bring a removed file back.
|
|
26
|
+
*
|
|
27
|
+
* ## Going down
|
|
28
|
+
*
|
|
29
|
+
* A deploy's SIGTERM awaits {@link SnapshotWriter.idle} before the process exits (the kernel's
|
|
30
|
+
* `drain`). An exit that does not wait (a crash, `process.exit`) writes whatever is still queued
|
|
31
|
+
* synchronously in an `exit` handler, without `fsync` (a process exit keeps the page cache); a
|
|
32
|
+
* file whose write was already in flight then lands as whichever rename the kernel takes last.
|
|
33
|
+
*/
|
|
34
|
+
import { type JsonLog } from '@wolffm/service-kernel/log';
|
|
35
|
+
/** A write slower than this is logged (`snapshot-write-slow`): the disk stalled, and nothing else did. */
|
|
36
|
+
export declare const SLOW_WRITE_MS = 1000;
|
|
37
|
+
export declare class SnapshotWriter {
|
|
38
|
+
#private;
|
|
39
|
+
constructor(opts?: {
|
|
40
|
+
log?: JsonLog;
|
|
41
|
+
now?: () => number;
|
|
42
|
+
});
|
|
43
|
+
/** Write `text` to `file` atomically, soon. Returns at once. */
|
|
44
|
+
write(file: string, text: string): void;
|
|
45
|
+
/** Remove `file` once every write queued before this has landed. A write queued after it wins. */
|
|
46
|
+
remove(file: string): Promise<void>;
|
|
47
|
+
/** Resolves once nothing is queued or in flight. */
|
|
48
|
+
idle(): Promise<void>;
|
|
49
|
+
/** How many files have a write or a remove still to land. */
|
|
50
|
+
pending(): number;
|
|
51
|
+
/** The exit path: everything still queued, written now, synchronously. */
|
|
52
|
+
drainSync(): void;
|
|
53
|
+
}
|
|
54
|
+
/** The process's one writer: every store shares it, so one stalled disk ties up one pool thread. */
|
|
55
|
+
export declare function snapshotWriter(): SnapshotWriter;
|
|
@@ -0,0 +1,162 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Every snapshot file the server keeps (a room, a draft) is written here, OFF the event loop.
|
|
3
|
+
*
|
|
4
|
+
* ## Why
|
|
5
|
+
*
|
|
6
|
+
* A synchronous write on the event loop stops everything the server does until the disk answers:
|
|
7
|
+
* the claws' heartbeats, every socket, every request. On the production host's btrfs root under another
|
|
8
|
+
* workload's writes, `fsyncSync` of a 10 kB room file can force a whole transaction commit and
|
|
9
|
+
* take tens of seconds (2026-11-27 06:07–06:12Z: the process in D state with its CPU idle, a POST
|
|
10
|
+
* that wrote three rooms 28.7 s, and every claw fencing its JVMs because this server said nothing
|
|
11
|
+
* for 10 s). Writing through `fs/promises` moves the wait onto libuv's pool, where it delays only
|
|
12
|
+
* the next snapshot.
|
|
13
|
+
*
|
|
14
|
+
* ## What a write is
|
|
15
|
+
*
|
|
16
|
+
* The same atomic recipe `FileRoomStore` uses: a temp file, `fsync`ed, renamed over the target, so a
|
|
17
|
+
* reader never sees half a snapshot and a crash leaves the previous one.
|
|
18
|
+
*
|
|
19
|
+
* ## Order and memory
|
|
20
|
+
*
|
|
21
|
+
* One file is in flight at a time, across the whole process: a stalled disk ties up one pool thread,
|
|
22
|
+
* never all four (`dns.lookup`, zlib and the rest share them). A file written again before its
|
|
23
|
+
* last write has started keeps only the newest text, so a stall costs one pending snapshot per file,
|
|
24
|
+
* however many mutations it sat through. A remove waits behind the writes queued before it, so a
|
|
25
|
+
* late write can never bring a removed file back.
|
|
26
|
+
*
|
|
27
|
+
* ## Going down
|
|
28
|
+
*
|
|
29
|
+
* A deploy's SIGTERM awaits {@link SnapshotWriter.idle} before the process exits (the kernel's
|
|
30
|
+
* `drain`). An exit that does not wait (a crash, `process.exit`) writes whatever is still queued
|
|
31
|
+
* synchronously in an `exit` handler, without `fsync` (a process exit keeps the page cache); a
|
|
32
|
+
* file whose write was already in flight then lands as whichever rename the kernel takes last.
|
|
33
|
+
*/
|
|
34
|
+
import { mkdirSync, renameSync, rmSync, writeFileSync } from 'node:fs';
|
|
35
|
+
import { mkdir, open, rename, rm } from 'node:fs/promises';
|
|
36
|
+
import { dirname } from 'node:path';
|
|
37
|
+
import { jsonLogger } from '@wolffm/service-kernel/log';
|
|
38
|
+
/** A write slower than this is logged (`snapshot-write-slow`): the disk stalled, and nothing else did. */
|
|
39
|
+
export const SLOW_WRITE_MS = 1000;
|
|
40
|
+
export class SnapshotWriter {
|
|
41
|
+
/** Not started yet, oldest first; a file's position is its first unstarted job's. */
|
|
42
|
+
#queued = new Map();
|
|
43
|
+
#inFlight = null;
|
|
44
|
+
#idleWaiters = [];
|
|
45
|
+
#log;
|
|
46
|
+
#now;
|
|
47
|
+
#seq = 0;
|
|
48
|
+
constructor(opts = {}) {
|
|
49
|
+
this.#log = opts.log ?? jsonLogger('cardtable-snapshots');
|
|
50
|
+
this.#now = opts.now ?? Date.now;
|
|
51
|
+
}
|
|
52
|
+
/** Write `text` to `file` atomically, soon. Returns at once. */
|
|
53
|
+
write(file, text) {
|
|
54
|
+
const queued = this.#queued.get(file);
|
|
55
|
+
this.#queued.set(file, { kind: 'write', text, waiters: queued?.waiters ?? [] });
|
|
56
|
+
this.#pump();
|
|
57
|
+
}
|
|
58
|
+
/** Remove `file` once every write queued before this has landed. A write queued after it wins. */
|
|
59
|
+
remove(file) {
|
|
60
|
+
return new Promise((resolve, reject) => {
|
|
61
|
+
const queued = this.#queued.get(file);
|
|
62
|
+
this.#queued.set(file, { kind: 'remove', waiters: [...(queued?.waiters ?? []), { resolve, reject }] });
|
|
63
|
+
this.#pump();
|
|
64
|
+
});
|
|
65
|
+
}
|
|
66
|
+
/** Resolves once nothing is queued or in flight. */
|
|
67
|
+
idle() {
|
|
68
|
+
if (this.#inFlight === null && this.#queued.size === 0)
|
|
69
|
+
return Promise.resolve();
|
|
70
|
+
return new Promise((resolve) => this.#idleWaiters.push(resolve));
|
|
71
|
+
}
|
|
72
|
+
/** How many files have a write or a remove still to land. */
|
|
73
|
+
pending() {
|
|
74
|
+
return this.#queued.size + (this.#inFlight === null ? 0 : 1);
|
|
75
|
+
}
|
|
76
|
+
/** The exit path: everything still queued, written now, synchronously. */
|
|
77
|
+
drainSync() {
|
|
78
|
+
for (const [file, job] of this.#queued) {
|
|
79
|
+
this.#queued.delete(file);
|
|
80
|
+
try {
|
|
81
|
+
if (job.kind === 'write') {
|
|
82
|
+
mkdirSync(dirname(file), { recursive: true });
|
|
83
|
+
const tmp = this.#tmpOf(file);
|
|
84
|
+
writeFileSync(tmp, job.text);
|
|
85
|
+
renameSync(tmp, file);
|
|
86
|
+
}
|
|
87
|
+
else {
|
|
88
|
+
rmSync(file, { force: true });
|
|
89
|
+
}
|
|
90
|
+
for (const w of job.waiters)
|
|
91
|
+
w.resolve();
|
|
92
|
+
}
|
|
93
|
+
catch (err) {
|
|
94
|
+
this.#log({ evt: 'snapshot-write-failed', level: 'error', file, at: 'exit', error: err.message });
|
|
95
|
+
for (const w of job.waiters)
|
|
96
|
+
w.reject(err);
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
#tmpOf(file) {
|
|
101
|
+
this.#seq += 1;
|
|
102
|
+
return `${file}.${process.pid}.${this.#now()}.${this.#seq}.tmp`;
|
|
103
|
+
}
|
|
104
|
+
#pump() {
|
|
105
|
+
if (this.#inFlight !== null)
|
|
106
|
+
return;
|
|
107
|
+
const next = this.#queued.entries().next();
|
|
108
|
+
if (next.done === true) {
|
|
109
|
+
const waiters = this.#idleWaiters;
|
|
110
|
+
this.#idleWaiters = [];
|
|
111
|
+
for (const w of waiters)
|
|
112
|
+
w();
|
|
113
|
+
return;
|
|
114
|
+
}
|
|
115
|
+
const [file, job] = next.value;
|
|
116
|
+
this.#queued.delete(file);
|
|
117
|
+
this.#inFlight = file;
|
|
118
|
+
const started = this.#now();
|
|
119
|
+
const run = job.kind === 'write' ? this.#writeAsync(file, job.text) : rm(file, { force: true });
|
|
120
|
+
run.then(() => {
|
|
121
|
+
const ms = this.#now() - started;
|
|
122
|
+
if (ms > SLOW_WRITE_MS)
|
|
123
|
+
this.#log({ evt: 'snapshot-write-slow', level: 'warn', file, kind: job.kind, ms, queued: this.#queued.size });
|
|
124
|
+
for (const w of job.waiters)
|
|
125
|
+
w.resolve();
|
|
126
|
+
}, (err) => {
|
|
127
|
+
this.#log({ evt: job.kind === 'write' ? 'snapshot-write-failed' : 'snapshot-remove-failed', level: 'error', file, error: err.message });
|
|
128
|
+
for (const w of job.waiters)
|
|
129
|
+
w.reject(err);
|
|
130
|
+
}).finally(() => {
|
|
131
|
+
this.#inFlight = null;
|
|
132
|
+
this.#pump();
|
|
133
|
+
});
|
|
134
|
+
}
|
|
135
|
+
async #writeAsync(file, text) {
|
|
136
|
+
await mkdir(dirname(file), { recursive: true });
|
|
137
|
+
const tmp = this.#tmpOf(file);
|
|
138
|
+
const handle = await open(tmp, 'w');
|
|
139
|
+
try {
|
|
140
|
+
await handle.writeFile(text);
|
|
141
|
+
await handle.sync();
|
|
142
|
+
}
|
|
143
|
+
finally {
|
|
144
|
+
await handle.close();
|
|
145
|
+
}
|
|
146
|
+
await rename(tmp, file);
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
/** On `globalThis`, not in this module: a second copy of the module (a bundle, a test's fresh import) shares it. */
|
|
150
|
+
const SHARED = Symbol.for('hadoku.game-server.snapshotWriter');
|
|
151
|
+
/** The process's one writer: every store shares it, so one stalled disk ties up one pool thread. */
|
|
152
|
+
export function snapshotWriter() {
|
|
153
|
+
const holder = globalThis;
|
|
154
|
+
let writer = holder[SHARED];
|
|
155
|
+
if (writer === undefined) {
|
|
156
|
+
const made = new SnapshotWriter();
|
|
157
|
+
process.on('exit', () => made.drainSync());
|
|
158
|
+
holder[SHARED] = made;
|
|
159
|
+
writer = made;
|
|
160
|
+
}
|
|
161
|
+
return writer;
|
|
162
|
+
}
|
package/dist/play/clock.d.ts
CHANGED
|
@@ -22,7 +22,11 @@ export interface ClockReading {
|
|
|
22
22
|
export declare class ChessClock {
|
|
23
23
|
#private;
|
|
24
24
|
constructor(left: readonly [number, number]);
|
|
25
|
-
/**
|
|
25
|
+
/**
|
|
26
|
+
* Which seats the game is waiting on from `now`. True when that changed which seats run. A seat with
|
|
27
|
+
* nothing left still runs while it is waited on: that is what {@link flagged} and {@link nextFlag}
|
|
28
|
+
* look for, and a seat stopped at zero would sit at 0:00 and never lose.
|
|
29
|
+
*/
|
|
26
30
|
set(running: readonly [boolean, boolean], now: number): boolean;
|
|
27
31
|
/** Stop both seats: the game is over, or the server is letting go of it. */
|
|
28
32
|
stop(now: number): void;
|
package/dist/play/clock.js
CHANGED
|
@@ -30,12 +30,16 @@ export class ChessClock {
|
|
|
30
30
|
this.#since[seat] = now;
|
|
31
31
|
}
|
|
32
32
|
}
|
|
33
|
-
/**
|
|
33
|
+
/**
|
|
34
|
+
* Which seats the game is waiting on from `now`. True when that changed which seats run. A seat with
|
|
35
|
+
* nothing left still runs while it is waited on: that is what {@link flagged} and {@link nextFlag}
|
|
36
|
+
* look for, and a seat stopped at zero would sit at 0:00 and never lose.
|
|
37
|
+
*/
|
|
34
38
|
set(running, now) {
|
|
35
39
|
this.#settle(now);
|
|
36
40
|
let moved = false;
|
|
37
41
|
for (const seat of [0, 1]) {
|
|
38
|
-
const on = running[seat]
|
|
42
|
+
const on = running[seat];
|
|
39
43
|
if (on === (this.#since[seat] !== null))
|
|
40
44
|
continue;
|
|
41
45
|
this.#since[seat] = on ? now : null;
|
package/dist/play/host.js
CHANGED
|
@@ -397,6 +397,9 @@ export function jvmHostFactory(config, options = {}) {
|
|
|
397
397
|
}
|
|
398
398
|
/** Boot a new JVM. Throws what the launcher throws. */
|
|
399
399
|
function launch() {
|
|
400
|
+
const down = launcher.unavailable?.() ?? null;
|
|
401
|
+
if (down !== null)
|
|
402
|
+
throw new Error(`no JVM can be launched here: ${down}`);
|
|
400
403
|
const hostId = `h-${randomBytes(6).toString('hex')}`;
|
|
401
404
|
const transport = launcher.launch(hostId, { xmxMb: config.xmxMb ?? JVM_HEAP_MB });
|
|
402
405
|
const dir = join(config.workDir, hostId);
|
|
@@ -634,6 +637,9 @@ export function jvmHostFactory(config, options = {}) {
|
|
|
634
637
|
return;
|
|
635
638
|
if (liveJvms().some((j) => hasRoom(j) || !j.warm) || jvms.size >= maxJvms())
|
|
636
639
|
return;
|
|
640
|
+
// Gone, not failing: what follows a lost link is its pool's abandonment, never a boot.
|
|
641
|
+
if ((launcher.unavailable?.() ?? null) !== null)
|
|
642
|
+
return;
|
|
637
643
|
try {
|
|
638
644
|
launch();
|
|
639
645
|
}
|
|
@@ -22,4 +22,10 @@ export interface JvmLauncher {
|
|
|
22
22
|
running(): Promise<string[]>;
|
|
23
23
|
/** Take one back. Lines it printed while nobody was attached are replayed first, in order. */
|
|
24
24
|
attach(hostId: string): JvmTransport;
|
|
25
|
+
/**
|
|
26
|
+
* Why nothing can be launched here now (a claw whose link is lost), or null. A pool asks before it
|
|
27
|
+
* stages a launch: staging is sync disk writes, and on the production host's contended disk a relaunch onto a lost
|
|
28
|
+
* claw held the event loop past every other claw's fencing window.
|
|
29
|
+
*/
|
|
30
|
+
unavailable?(): string | null;
|
|
25
31
|
}
|
|
@@ -252,7 +252,9 @@ export declare abstract class MatchShell<Line extends {
|
|
|
252
252
|
* still on that seat's clock, it is armed again for what is left. Node fires a timer by the event
|
|
253
253
|
* loop's own clock, cut to the millisecond, and `now` reads the wall clock, so a timer armed for the
|
|
254
254
|
* 20 000 ms left can fire when the wall clock has moved 19 999: that seat then has 1 ms left, nothing
|
|
255
|
-
* about who runs has changed, and without the re-arm the seat sat at 0:00 and never lost.
|
|
255
|
+
* about who runs has changed, and without the re-arm the seat sat at 0:00 and never lost. The wall
|
|
256
|
+
* clock can reach zero between this timer's read and the settle after it; the clock keeps a seat
|
|
257
|
+
* with nothing left running ({@link ChessClock.set}), so the re-arm finds it at 0 ms.
|
|
256
258
|
*/
|
|
257
259
|
private armFlag;
|
|
258
260
|
/** Nobody's time runs any more: the match is letting go of its game. */
|
package/dist/play/match/shell.js
CHANGED
|
@@ -187,7 +187,9 @@ export class MatchShell {
|
|
|
187
187
|
* still on that seat's clock, it is armed again for what is left. Node fires a timer by the event
|
|
188
188
|
* loop's own clock, cut to the millisecond, and `now` reads the wall clock, so a timer armed for the
|
|
189
189
|
* 20 000 ms left can fire when the wall clock has moved 19 999: that seat then has 1 ms left, nothing
|
|
190
|
-
* about who runs has changed, and without the re-arm the seat sat at 0:00 and never lost.
|
|
190
|
+
* about who runs has changed, and without the re-arm the seat sat at 0:00 and never lost. The wall
|
|
191
|
+
* clock can reach zero between this timer's read and the settle after it; the clock keeps a seat
|
|
192
|
+
* with nothing left running ({@link ChessClock.set}), so the re-arm finds it at 0 ms.
|
|
191
193
|
*/
|
|
192
194
|
armFlag(now) {
|
|
193
195
|
if (this.flagTimer !== null)
|
package/dist/relay-game.js
CHANGED
|
@@ -29,7 +29,7 @@ import { existsSync, mkdirSync } from 'node:fs';
|
|
|
29
29
|
import { join } from 'node:path';
|
|
30
30
|
import express from 'express';
|
|
31
31
|
import { PresenceTracker } from '@wolffm/rooms-server';
|
|
32
|
-
import {
|
|
32
|
+
import { OffLoopRoomStore } from './room/off-loop-store.js';
|
|
33
33
|
import { jsonLogger } from '@wolffm/service-kernel/log';
|
|
34
34
|
import { diagnosticPage, sendIndex } from '@wolffm/service-kernel/http';
|
|
35
35
|
import { createGameServer } from '@wolffm/service-kernel/server';
|
|
@@ -109,7 +109,7 @@ export async function startRelayGame(options) {
|
|
|
109
109
|
phase: 'stores',
|
|
110
110
|
async setup(ctx) {
|
|
111
111
|
const lobby = new RelayLobby({
|
|
112
|
-
store: new
|
|
112
|
+
store: new OffLoopRoomStore(config.roomsDir),
|
|
113
113
|
now: Date.now,
|
|
114
114
|
log: roomsLog,
|
|
115
115
|
typeOf: (gameType) => (gameType === options.gameType ? roomType : undefined),
|
|
@@ -161,6 +161,7 @@ export async function startRelayGame(options) {
|
|
|
161
161
|
accounts.stop();
|
|
162
162
|
void lobby.removed();
|
|
163
163
|
},
|
|
164
|
+
drain: () => lobby.flushed(),
|
|
164
165
|
erase: roomsEraseSteps({ lobby, liveMatches: () => [], forfeit: () => { }, closed: () => { }, forfeited: () => { } }),
|
|
165
166
|
};
|
|
166
167
|
},
|
package/dist/room/lobby.d.ts
CHANGED
|
@@ -7,9 +7,10 @@
|
|
|
7
7
|
*
|
|
8
8
|
* ## Persistence: write-through, through `@wolffm/rooms-server/store`
|
|
9
9
|
*
|
|
10
|
-
* A deploy restarts the server several times a day, so every mutation
|
|
11
|
-
*
|
|
12
|
-
*
|
|
10
|
+
* A deploy restarts the server several times a day, so every mutation queues that room's snapshot
|
|
11
|
+
* before the call returns (`FileRoomStore`'s atomic temp-file-fsync-rename, which production's
|
|
12
|
+
* `OffLoopRoomStore` runs off the event loop: a stalled disk must never stop the server). No
|
|
13
|
+
* debounce: the write starts at once, and the kernel's shutdown drain awaits it (`flushed`). Rooms are stored in the store's
|
|
13
14
|
* own snapshot format (`STORE_VERSION`) and read back through `decodeSnapshot`, so an unreadable or
|
|
14
15
|
* future-format record is QUARANTINED (moved aside intact), never half-applied or silently dropped.
|
|
15
16
|
*
|
|
@@ -584,6 +585,8 @@ export declare class RoomLobby<V extends PlatformRoomView, I extends RoomCreateI
|
|
|
584
585
|
sweep(idleMs?: number): string[];
|
|
585
586
|
/** Resolves once every room forgotten so far is gone from disk too (a failed delete is logged as `room-forget-failed`). */
|
|
586
587
|
removed(): Promise<void>;
|
|
588
|
+
/** Resolves once every room written or forgotten so far is on disk (`OffLoopRoomStore`); at once for a store that writes in the call. */
|
|
589
|
+
flushed(): Promise<void>;
|
|
587
590
|
/**
|
|
588
591
|
* Account erase: every room that still names one of `ids` names `to` instead, and is saved. Answers
|
|
589
592
|
* how many rooms changed. The person leaves first (`leave`), so leadership has passed on.
|
package/dist/room/lobby.js
CHANGED
|
@@ -7,9 +7,10 @@
|
|
|
7
7
|
*
|
|
8
8
|
* ## Persistence: write-through, through `@wolffm/rooms-server/store`
|
|
9
9
|
*
|
|
10
|
-
* A deploy restarts the server several times a day, so every mutation
|
|
11
|
-
*
|
|
12
|
-
*
|
|
10
|
+
* A deploy restarts the server several times a day, so every mutation queues that room's snapshot
|
|
11
|
+
* before the call returns (`FileRoomStore`'s atomic temp-file-fsync-rename, which production's
|
|
12
|
+
* `OffLoopRoomStore` runs off the event loop: a stalled disk must never stop the server). No
|
|
13
|
+
* debounce: the write starts at once, and the kernel's shutdown drain awaits it (`flushed`). Rooms are stored in the store's
|
|
13
14
|
* own snapshot format (`STORE_VERSION`) and read back through `decodeSnapshot`, so an unreadable or
|
|
14
15
|
* future-format record is QUARANTINED (moved aside intact), never half-applied or silently dropped.
|
|
15
16
|
*
|
|
@@ -33,6 +34,7 @@
|
|
|
33
34
|
* ephemeral caller (the HTTP layer answers 403) rather than seat a member who vanishes on restart.
|
|
34
35
|
*/
|
|
35
36
|
import { STORE_VERSION, SnapshotUnreadableError, decodeSnapshot, } from '@wolffm/rooms-server/store';
|
|
37
|
+
import { OffLoopRoomStore } from './off-loop-store.js';
|
|
36
38
|
import { createSeatTable, isDurableParticipantId } from '@wolffm/rooms-protocol';
|
|
37
39
|
import { addMember, createMembershipLedger, setReady as ledgerSetReady } from '@wolffm/rooms-server';
|
|
38
40
|
import { seatsOpenAt } from '@wolffm/platform-wire/events';
|
|
@@ -369,9 +371,17 @@ export class RoomLobby {
|
|
|
369
371
|
const how = hooks.autoSeat?.(room, memberId) ?? 'game-seat';
|
|
370
372
|
if (how !== 'game-seat')
|
|
371
373
|
return;
|
|
372
|
-
|
|
373
|
-
if (
|
|
374
|
+
// A member back in still holds the seat they left in: never a second one.
|
|
375
|
+
if (room.seats.includes(memberId))
|
|
374
376
|
return;
|
|
377
|
+
// None open: grow the room by one past the last, as a Sit press does (`sitSeat`), up to the type's ceiling.
|
|
378
|
+
let open = room.seats.indexOf(null);
|
|
379
|
+
if (open === -1) {
|
|
380
|
+
if (room.seats.length >= hooks.seatCeiling(room))
|
|
381
|
+
return;
|
|
382
|
+
open = room.seats.length;
|
|
383
|
+
hooks.growSeats(room, open);
|
|
384
|
+
}
|
|
375
385
|
setGameSeat(room, open, memberId);
|
|
376
386
|
// As every other seat op does: a type that keeps a seat open (`plainRoomType`'s `keepOneOpen`) grows here.
|
|
377
387
|
hooks.trimSeats(room);
|
|
@@ -983,6 +993,12 @@ export class RoomLobby {
|
|
|
983
993
|
async removed() {
|
|
984
994
|
await Promise.all([...this.#removing]);
|
|
985
995
|
}
|
|
996
|
+
/** Resolves once every room written or forgotten so far is on disk (`OffLoopRoomStore`); at once for a store that writes in the call. */
|
|
997
|
+
async flushed() {
|
|
998
|
+
await this.removed();
|
|
999
|
+
if (this.store instanceof OffLoopRoomStore)
|
|
1000
|
+
await this.store.flushed();
|
|
1001
|
+
}
|
|
986
1002
|
/**
|
|
987
1003
|
* Account erase: every room that still names one of `ids` names `to` instead, and is saved. Answers
|
|
988
1004
|
* how many rooms changed. The person leaves first (`leave`), so leadership has passed on.
|
|
@@ -1070,6 +1086,8 @@ export class RoomLobby {
|
|
|
1070
1086
|
async open() {
|
|
1071
1087
|
const store = this.store;
|
|
1072
1088
|
const codec = this.#codec;
|
|
1089
|
+
// What this process has already written to the directory is read back, not the bytes before it.
|
|
1090
|
+
await this.flushed();
|
|
1073
1091
|
for (const roomId of await store.list()) {
|
|
1074
1092
|
const quarantine = async (reason) => {
|
|
1075
1093
|
await store.quarantine(roomId, reason);
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `FileRoomStore` with its writes off the event loop: the same files, the same format, the same
|
|
3
|
+
* atomic temp-file-fsync-rename, through the process's {@link snapshotWriter} instead of
|
|
4
|
+
* `fsyncSync` on the loop (`persist/snapshot-writer.ts` has the measured why). Reads (`load`,
|
|
5
|
+
* `list`, `quarantine`) happen at boot and stay the base class's.
|
|
6
|
+
*
|
|
7
|
+
* `saveSync` keeps its name because the lobby calls it from every mutation and must not await; it
|
|
8
|
+
* returns once the snapshot is queued. A save then a remove of one room land in that order.
|
|
9
|
+
*/
|
|
10
|
+
import { FileRoomStore, type RoomSnapshot } from '@wolffm/rooms-server/store';
|
|
11
|
+
import { type SnapshotWriter } from '../persist/snapshot-writer.js';
|
|
12
|
+
export declare class OffLoopRoomStore extends FileRoomStore {
|
|
13
|
+
#private;
|
|
14
|
+
constructor(dir: string, opts?: {
|
|
15
|
+
writer?: SnapshotWriter;
|
|
16
|
+
now?: () => number;
|
|
17
|
+
});
|
|
18
|
+
/** `FileRoomStore`'s own file for a room: base64url of the id, so a join payload never names a path. */
|
|
19
|
+
fileOf(roomId: string): string;
|
|
20
|
+
saveSync(snapshot: RoomSnapshot): void;
|
|
21
|
+
save(snapshot: RoomSnapshot): Promise<void>;
|
|
22
|
+
remove(roomId: string): Promise<void>;
|
|
23
|
+
removeSync(roomId: string): void;
|
|
24
|
+
/** Resolves once every save and remove asked of this process's writer so far has landed. */
|
|
25
|
+
flushed(): Promise<void>;
|
|
26
|
+
}
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `FileRoomStore` with its writes off the event loop: the same files, the same format, the same
|
|
3
|
+
* atomic temp-file-fsync-rename, through the process's {@link snapshotWriter} instead of
|
|
4
|
+
* `fsyncSync` on the loop (`persist/snapshot-writer.ts` has the measured why). Reads (`load`,
|
|
5
|
+
* `list`, `quarantine`) happen at boot and stay the base class's.
|
|
6
|
+
*
|
|
7
|
+
* `saveSync` keeps its name because the lobby calls it from every mutation and must not await; it
|
|
8
|
+
* returns once the snapshot is queued. A save then a remove of one room land in that order.
|
|
9
|
+
*/
|
|
10
|
+
import { join } from 'node:path';
|
|
11
|
+
import { FileRoomStore } from '@wolffm/rooms-server/store';
|
|
12
|
+
import { snapshotWriter } from '../persist/snapshot-writer.js';
|
|
13
|
+
const SUFFIX = '.json';
|
|
14
|
+
export class OffLoopRoomStore extends FileRoomStore {
|
|
15
|
+
#writer;
|
|
16
|
+
constructor(dir, opts = {}) {
|
|
17
|
+
super(dir, opts.now === undefined ? {} : { now: opts.now });
|
|
18
|
+
this.#writer = opts.writer ?? snapshotWriter();
|
|
19
|
+
}
|
|
20
|
+
/** `FileRoomStore`'s own file for a room: base64url of the id, so a join payload never names a path. */
|
|
21
|
+
fileOf(roomId) {
|
|
22
|
+
return join(this.dir, `${Buffer.from(roomId, 'utf8').toString('base64url')}${SUFFIX}`);
|
|
23
|
+
}
|
|
24
|
+
saveSync(snapshot) {
|
|
25
|
+
this.#writer.write(this.fileOf(snapshot.roomId), JSON.stringify(snapshot));
|
|
26
|
+
}
|
|
27
|
+
save(snapshot) {
|
|
28
|
+
this.saveSync(snapshot);
|
|
29
|
+
return Promise.resolve();
|
|
30
|
+
}
|
|
31
|
+
remove(roomId) {
|
|
32
|
+
return this.#writer.remove(this.fileOf(roomId));
|
|
33
|
+
}
|
|
34
|
+
removeSync(roomId) {
|
|
35
|
+
void this.#writer.remove(this.fileOf(roomId)).catch(() => {
|
|
36
|
+
// The writer has logged it (`snapshot-remove-failed`); a sync caller has nobody to tell.
|
|
37
|
+
});
|
|
38
|
+
}
|
|
39
|
+
/** Resolves once every save and remove asked of this process's writer so far has landed. */
|
|
40
|
+
flushed() {
|
|
41
|
+
return this.#writer.idle();
|
|
42
|
+
}
|
|
43
|
+
}
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@hadoku/game-server",
|
|
3
|
-
"version": "0.1.
|
|
4
|
-
"gitHead": "
|
|
3
|
+
"version": "0.1.146",
|
|
4
|
+
"gitHead": "f801fb0993e84eaed7c4472993a11b21276052c1",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"license": "MIT",
|
|
7
7
|
"description": "The server parts any hosted game shares, above the kernel: the app config and edge auth, the room core (identity, seats, sessions, membership, the room list, the generic room routes), match hosting (the host contract, local and remote JVMs, placement, the start queue, recordings, the in-process and relay runtimes), streams, erase, telemetry and usage. Knows no game; Magic plugs in from apps/server. MIT; imports only node built-ins, express, socket.io, @wolffm/* and the platform packages.",
|
|
@@ -17,12 +17,12 @@
|
|
|
17
17
|
"play/remote/"
|
|
18
18
|
],
|
|
19
19
|
"dependencies": {
|
|
20
|
-
"@wolffm/host-wire": "npm:@hadoku/host-wire@0.1.
|
|
21
|
-
"@wolffm/platform-wire": "npm:@hadoku/platform-wire@0.1.
|
|
22
|
-
"@wolffm/service-kernel": "npm:@hadoku/service-kernel@0.1.
|
|
20
|
+
"@wolffm/host-wire": "npm:@hadoku/host-wire@0.1.146",
|
|
21
|
+
"@wolffm/platform-wire": "npm:@hadoku/platform-wire@0.1.146",
|
|
22
|
+
"@wolffm/service-kernel": "npm:@hadoku/service-kernel@0.1.179",
|
|
23
23
|
"@wolffm/prefs-client": "npm:@hadoku/prefs-client@^1.2.2",
|
|
24
|
-
"@wolffm/rooms-protocol": "npm:@hadoku/rooms-protocol@^0.45.
|
|
25
|
-
"@wolffm/rooms-server": "npm:@hadoku/rooms-server@^0.45.
|
|
24
|
+
"@wolffm/rooms-protocol": "npm:@hadoku/rooms-protocol@^0.45.143",
|
|
25
|
+
"@wolffm/rooms-server": "npm:@hadoku/rooms-server@^0.45.143",
|
|
26
26
|
"express": "^5.1.0",
|
|
27
27
|
"socket.io": "^4.8.3",
|
|
28
28
|
"zod": "4.5.4"
|