@hadoku/game-server 0.1.183 → 0.1.185

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.
@@ -24,33 +24,17 @@
24
24
  * person's userId. An end line names them by that exact string, so a file without it cannot name
25
25
  * them, and the screen costs a substring search.
26
26
  */
27
- import { readdir, readFile, rename, stat, utimes, writeFile } from 'node:fs/promises';
27
+ import { readdir, stat } from 'node:fs/promises';
28
28
  import { join } from 'node:path';
29
- import { promisify } from 'node:util';
30
- import { gunzip as gunzipCb, gzip as gzipCb } from 'node:zlib';
31
29
  import { UNNAMED } from '../room/constants.js';
32
30
  import { recordingChanged } from '../play/recording/changes.js';
33
31
  import { ACTIONS_SUFFIX, PUBLIC_SUFFIX, recordingOf } from '../play/recording/retention.js';
32
+ import { readLines, writeLines } from '../play/recording/writer.js';
34
33
  import { renameIds, replaceIds } from './anonymise.js';
35
- const gunzip = promisify(gunzipCb);
36
- const gzip = promisify(gzipCb);
37
- /** A recording file's text, read and unzipped off the event loop. */
38
- async function readText(path) {
39
- return (await gunzip(await readFile(path))).toString('utf8');
40
- }
41
- function parseLines(text) {
42
- return text
43
- .split('\n')
44
- .filter((l) => l.length > 0)
45
- .map((l) => JSON.parse(l));
46
- }
47
34
  /** Rewrite a recording file whole, keeping the mtime its retention reads. */
48
- async function writeLines(path, lines) {
35
+ async function rewrite(path, lines) {
49
36
  const { atime, mtime } = await stat(path);
50
- const tmp = `${path}.erase.tmp`;
51
- await writeFile(tmp, await gzip(Buffer.from(lines.map((l) => JSON.stringify(l)).join('\n') + '\n', 'utf8')));
52
- await utimes(tmp, atime, mtime);
53
- await rename(tmp, path);
37
+ await writeLines(path, lines, { times: { atime, mtime } });
54
38
  }
55
39
  /** The seats an end line names `userId` in: its recorded seats' `userId`, or its by-seat `users`. Drops each as it finds it. */
56
40
  function dropUser(end, userId) {
@@ -104,23 +88,23 @@ async function rewriteRecordings(dir, userId, change) {
104
88
  if (!files.includes(matchId + suffix))
105
89
  continue;
106
90
  const path = join(dir, matchId + suffix);
107
- const text = await readText(path).catch((err) => {
91
+ const lines = await readLines(path).catch((err) => {
108
92
  // Retention may age a file out between the listing and this read: it names no one now.
109
93
  if (err.code === 'ENOENT')
110
94
  return null;
111
95
  throw err;
112
96
  });
113
- if (text !== null)
114
- texts.push({ path, text });
97
+ if (lines !== null)
98
+ texts.push({ path, lines });
115
99
  }
116
- if (!texts.some(({ text }) => text.includes(userId)))
100
+ if (!texts.some(({ lines }) => lines.some((line) => line.includes(userId))))
117
101
  continue;
118
- const recording = texts.map(({ path, text }) => ({ path, lines: parseLines(text) }));
102
+ const recording = texts.map(({ path, lines }) => ({ path, lines: lines.map((l) => JSON.parse(l)) }));
119
103
  if (!change(recording))
120
104
  continue;
121
105
  try {
122
106
  for (const { path, lines } of recording)
123
- await writeLines(path, lines);
107
+ await rewrite(path, lines);
124
108
  }
125
109
  finally {
126
110
  recordingChanged(dir, matchId);
@@ -11,6 +11,10 @@
11
11
  * Swept hourly (`recorder.ts`'s `watchRecordings`) and once at boot, same
12
12
  * discipline as `host.ts`'s own run-directory sweep. Never throws: one bad
13
13
  * stat or unlink is logged and skipped, not a reason to stop sweeping the rest.
14
+ *
15
+ * A live match's files are written to temp files beside these (`writer.ts`) and
16
+ * renamed into place at its end. A process that dies, or hands its matches to
17
+ * the next, mid-match leaves its temp files: one a day old is removed.
14
18
  */
15
19
  import type { JsonLog } from '@wolffm/service-kernel/log';
16
20
  /**
@@ -23,6 +27,8 @@ export declare const PUBLIC_RETENTION_MS: number;
23
27
  export declare const ACTIONS_RETENTION_MS: number;
24
28
  /** See the module header: the oldest public streams are dropped first when the directory is over this. */
25
29
  export declare const RECORDINGS_CAP_BYTES: number;
30
+ /** A temp file not written for this long belonged to a match no process is recording: no game runs a day. */
31
+ export declare const TEMP_STALE_MS: number;
26
32
  export declare const ACTIONS_SUFFIX = ".actions.jsonl.gz";
27
33
  export declare const PUBLIC_SUFFIX = ".public.jsonl.gz";
28
34
  /** A file name in the recordings directory as the recording it belongs to; null for anything else. */
@@ -36,6 +42,8 @@ export interface SweepResult {
36
42
  expiredPublic: string[];
37
43
  /** Public streams removed to bring the directory back under {@link RECORDINGS_CAP_BYTES}. */
38
44
  overCap: string[];
45
+ /** Temp files a match left unfinished, removed after {@link TEMP_STALE_MS}. */
46
+ staleTemps: string[];
39
47
  /** Directory size after the sweep, best-effort (0 if it could not be read at all). */
40
48
  bytesAfter: number;
41
49
  errors: {
@@ -11,6 +11,10 @@
11
11
  * Swept hourly (`recorder.ts`'s `watchRecordings`) and once at boot, same
12
12
  * discipline as `host.ts`'s own run-directory sweep. Never throws: one bad
13
13
  * stat or unlink is logged and skipped, not a reason to stop sweeping the rest.
14
+ *
15
+ * A live match's files are written to temp files beside these (`writer.ts`) and
16
+ * renamed into place at its end. A process that dies, or hands its matches to
17
+ * the next, mid-match leaves its temp files: one a day old is removed.
14
18
  */
15
19
  import { readdirSync, rmSync, statSync } from 'node:fs';
16
20
  import { join } from 'node:path';
@@ -25,6 +29,8 @@ export const PUBLIC_RETENTION_MS = 365 * 24 * 60 * 60 * 1000;
25
29
  export const ACTIONS_RETENTION_MS = 2 * PUBLIC_RETENTION_MS;
26
30
  /** See the module header: the oldest public streams are dropped first when the directory is over this. */
27
31
  export const RECORDINGS_CAP_BYTES = 2 * 1024 * 1024 * 1024;
32
+ /** A temp file not written for this long belonged to a match no process is recording: no game runs a day. */
33
+ export const TEMP_STALE_MS = 24 * 60 * 60 * 1000;
28
34
  export const ACTIONS_SUFFIX = '.actions.jsonl.gz';
29
35
  export const PUBLIC_SUFFIX = '.public.jsonl.gz';
30
36
  /** A file name in the recordings directory as the recording it belongs to; null for anything else. */
@@ -42,15 +48,16 @@ function list(dir, errors) {
42
48
  }
43
49
  catch (err) {
44
50
  errors.push({ file: dir, error: err.message });
45
- return [];
51
+ return { recordings: [], temps: [] };
46
52
  }
47
- const out = [];
53
+ const out = { recordings: [], temps: [] };
48
54
  for (const name of names) {
49
- if (recordingOf(name) === null)
55
+ const into = recordingOf(name) !== null ? out.recordings : name.endsWith('.tmp') ? out.temps : null;
56
+ if (into === null)
50
57
  continue;
51
58
  try {
52
59
  const st = statSync(join(dir, name));
53
- out.push({ name, path: join(dir, name), size: st.size, mtimeMs: st.mtimeMs });
60
+ into.push({ name, path: join(dir, name), size: st.size, mtimeMs: st.mtimeMs });
54
61
  }
55
62
  catch (err) {
56
63
  errors.push({ file: name, error: err.message });
@@ -66,13 +73,21 @@ function remove(dir, entry, log, evt, errors) {
66
73
  catch (err) {
67
74
  errors.push({ file: entry.name, error: err.message });
68
75
  }
69
- recordingChanged(dir, recordingOf(entry.name).id);
76
+ const recording = recordingOf(entry.name);
77
+ if (recording !== null)
78
+ recordingChanged(dir, recording.id);
70
79
  }
71
80
  /** One pass over `dir`: age-based expiry, then the size cap. See the module header. `capBytes` is overridable for a test; production never passes one. */
72
81
  export function sweepRecordings(dir, now = Date.now(), log = () => undefined, capBytes = RECORDINGS_CAP_BYTES) {
73
82
  const errors = [];
74
- const result = { expiredActions: [], expiredPublic: [], overCap: [], bytesAfter: 0, errors };
75
- let entries = list(dir, errors);
83
+ const result = { expiredActions: [], expiredPublic: [], overCap: [], staleTemps: [], bytesAfter: 0, errors };
84
+ const { recordings: entries, temps } = list(dir, errors);
85
+ for (const temp of temps) {
86
+ if (now - temp.mtimeMs <= TEMP_STALE_MS)
87
+ continue;
88
+ remove(dir, temp, log, 'recording-temp-removed', errors);
89
+ result.staleTemps.push(temp.name);
90
+ }
76
91
  const kept = [];
77
92
  for (const entry of entries) {
78
93
  const suffix = entry.name.endsWith(ACTIONS_SUFFIX) ? 'actions' : 'public';
@@ -85,17 +100,15 @@ export function sweepRecordings(dir, now = Date.now(), log = () => undefined, ca
85
100
  kept.push(entry);
86
101
  }
87
102
  }
88
- entries = kept;
89
- let total = entries.reduce((sum, e) => sum + e.size, 0);
103
+ let total = kept.reduce((sum, e) => sum + e.size, 0);
90
104
  if (total > capBytes) {
91
- const publicOldestFirst = entries.filter((e) => e.name.endsWith(PUBLIC_SUFFIX)).sort((a, b) => a.mtimeMs - b.mtimeMs);
105
+ const publicOldestFirst = kept.filter((e) => e.name.endsWith(PUBLIC_SUFFIX)).sort((a, b) => a.mtimeMs - b.mtimeMs);
92
106
  for (const entry of publicOldestFirst) {
93
107
  if (total <= capBytes)
94
108
  break;
95
109
  remove(dir, entry, log, 'recording-over-cap', errors);
96
110
  result.overCap.push(entry.name);
97
111
  total -= entry.size;
98
- entries = entries.filter((e) => e !== entry);
99
112
  }
100
113
  }
101
114
  result.bytesAfter = total;
@@ -1,21 +1,24 @@
1
1
  /**
2
2
  * One match's two recorded files (`docs/planning/wave77-2026-10-27.md` §C,
3
- * contract 1): `<matchId>.actions.jsonl.gz` and `<matchId>.public.jsonl.gz`.
3
+ * contract 1): `<matchId>.actions.jsonl.gz` and `<matchId>.public.jsonl.gz`,
4
+ * and the one gzip JSONL writer and reader every user of the recordings
5
+ * directory goes through (the recorder, a rebuild, the replay routes, an erase).
4
6
  *
5
- * Buffered, not streamed: every line is held in memory as it comes and both
6
- * files are written once, gzipped, when the match ends. A long human game is
7
- * a few hundred to a few thousand small JSON lines — a few hundred KB before
8
- * gzip — so holding it costs nothing a match-sized process does not already
9
- * spend on everything else, and it means recording never does disk I/O on the
10
- * hot path: no write is on the way between Forge's line arriving and the next
11
- * command being sent. The cost of this choice is the one named in the plan: a
12
- * process that dies mid-match (not a clean end) loses that match's buffered
13
- * lines, same as `host.ts`'s own `stream.jsonl` would need the run directory
14
- * to survive the crash to replay — recording a match that outlives a restart
15
- * is future work, not this wave's.
7
+ * Streamed, not buffered: each line goes through gzip to a temp file beside the
8
+ * recording as it comes, and the file is put in place whole when the match ends.
9
+ * A long game's pointer alone is ten lines a second, and holding every line as a
10
+ * live object until the end kept ~10 MB per long match (and stringified all of it
11
+ * at once when it ended). What a match holds now is gzip's own state. Each
12
+ * header is still held until the end (the room links its match, and the art
13
+ * pins land, after the match starts), and is written then as the file's first
14
+ * gzip member: a gzip reader reads consecutive members as one stream, so the file
15
+ * reads as it always has. A process that dies mid-match leaves its temp files,
16
+ * which retention removes (`retention.ts`); recording a match that outlives a
17
+ * restart is still future work.
16
18
  *
17
- * Nothing here may fail a match. Every public method swallows its own errors
18
- * into `log`; `finish` resolves even when the disk write failed.
19
+ * Nothing here may fail a match. Every public method of the match writer
20
+ * swallows its own errors into `log`; `finish` resolves even when the disk
21
+ * write failed.
19
22
  */
20
23
  import type { JsonLog } from '@wolffm/service-kernel/log';
21
24
  /**
@@ -113,6 +116,8 @@ export interface PublicEnvLine {
113
116
  * The active seat's pointer, as `forge:presence` relayed it (`@hadoku/shared`'s `presence.ts`: it names no
114
117
  * hidden card), so a replay draws their cursor and their drags. `playerId` is that seat's Forge player: the
115
118
  * replay draws the seat at the bottom, from the player whose turn it is. Absent before wave 81 part 2.
119
+ * `presence` is kept without its `matchId` and with its coordinates at four places (the recorder's
120
+ * `recordedPresence`); a line written before that carries both, and a reader takes either.
116
121
  */
117
122
  export interface PublicPresenceLine {
118
123
  t: 'presence';
@@ -157,23 +162,52 @@ export interface PublicEndLine {
157
162
  /** The roster as the match ended. Absent from a recording made before it was kept, or when the match was already gone. */
158
163
  seats?: RecordedSeat[];
159
164
  }
165
+ /** Each non-empty line of a gzip JSONL file, in order, streamed: rejects on any read or gunzip error. */
166
+ export declare function eachLine(path: string, onLine: (line: string) => void): Promise<void>;
167
+ /** Every non-empty line of a gzip JSONL file, as text, in order. */
168
+ export declare function readLines(path: string): Promise<string[]>;
169
+ /** A gzip JSONL file being written: nothing is at its path until {@link JsonlGzWriter.close}. */
170
+ export interface JsonlGzWriter {
171
+ /** One line, gzipped on its way to the temp file. Never throws: a failure (and every line after it) is reported by `close`. */
172
+ line(value: unknown): void;
173
+ /**
174
+ * End the file and put it at `path` whole (a temp file renamed over it). `first`, when given, is its
175
+ * first line, written ahead of every {@link line}. `times` stamps the file before it lands (an erase
176
+ * keeps the mtime retention ages it by). Rejects on any write failure, and the temp files go.
177
+ */
178
+ close(path: string, opts?: {
179
+ first?: unknown;
180
+ times?: {
181
+ atime: Date;
182
+ mtime: Date;
183
+ };
184
+ }): Promise<void>;
185
+ }
186
+ /** Open a gzip JSONL file whose temp file sits beside `near` (a path in the directory it will land in). */
187
+ export declare function openJsonlGz(near: string): JsonlGzWriter;
188
+ /** Write `lines` to `path` as gzip JSONL, whole or not at all. */
189
+ export declare function writeLines(path: string, lines: readonly unknown[], opts?: {
190
+ times?: {
191
+ atime: Date;
192
+ mtime: Date;
193
+ };
194
+ }): Promise<void>;
160
195
  export interface MatchRecordingWriter {
161
- /** Append one `cmd` line. Buffered — nothing is written to disk yet. */
196
+ /** Append one `cmd` line, on its way to a temp file: nothing is at the recording's path until `finish`. */
162
197
  actionCmd(line: Omit<ActionsCmdLine, 't'>): void;
163
- /** Append one `env` line. Buffered. */
198
+ /** Append one `env` line. */
164
199
  publicEnv(line: Omit<PublicEnvLine, 't'>): void;
165
- /** Append one `presence` line. Buffered. */
200
+ /** Append one `presence` line. */
166
201
  publicPresence(line: Omit<PublicPresenceLine, 't'>): void;
167
- /** Append one `relay` line. Buffered. */
202
+ /** Append one `relay` line. */
168
203
  publicRelay(line: Omit<PublicRelayLine, 't'>): void;
169
204
  /** Both headers' `roomId`: a room links its match only after the match's host has started. */
170
205
  room(roomId: string): void;
171
206
  /**
172
- * Write the `end` line onto both buffers, gzip each, and write both files.
207
+ * Write the `end` line onto both files and put each in place, its header first.
173
208
  * Never throws; a failed write is one `log` line, not a rejection. Resolves
174
209
  * once both attempts (success or failure) are done.
175
- */
176
- /**
210
+ *
177
211
  * `aside`: this is an earlier epoch whose match already plays on under a new one (`MatchRegistry.restore`),
178
212
  * so it is written straight to the first free `<matchId>-e<N>`, never over the match's own name.
179
213
  */
@@ -1,29 +1,34 @@
1
1
  /**
2
2
  * One match's two recorded files (`docs/planning/wave77-2026-10-27.md` §C,
3
- * contract 1): `<matchId>.actions.jsonl.gz` and `<matchId>.public.jsonl.gz`.
3
+ * contract 1): `<matchId>.actions.jsonl.gz` and `<matchId>.public.jsonl.gz`,
4
+ * and the one gzip JSONL writer and reader every user of the recordings
5
+ * directory goes through (the recorder, a rebuild, the replay routes, an erase).
4
6
  *
5
- * Buffered, not streamed: every line is held in memory as it comes and both
6
- * files are written once, gzipped, when the match ends. A long human game is
7
- * a few hundred to a few thousand small JSON lines — a few hundred KB before
8
- * gzip — so holding it costs nothing a match-sized process does not already
9
- * spend on everything else, and it means recording never does disk I/O on the
10
- * hot path: no write is on the way between Forge's line arriving and the next
11
- * command being sent. The cost of this choice is the one named in the plan: a
12
- * process that dies mid-match (not a clean end) loses that match's buffered
13
- * lines, same as `host.ts`'s own `stream.jsonl` would need the run directory
14
- * to survive the crash to replay — recording a match that outlives a restart
15
- * is future work, not this wave's.
7
+ * Streamed, not buffered: each line goes through gzip to a temp file beside the
8
+ * recording as it comes, and the file is put in place whole when the match ends.
9
+ * A long game's pointer alone is ten lines a second, and holding every line as a
10
+ * live object until the end kept ~10 MB per long match (and stringified all of it
11
+ * at once when it ended). What a match holds now is gzip's own state. Each
12
+ * header is still held until the end (the room links its match, and the art
13
+ * pins land, after the match starts), and is written then as the file's first
14
+ * gzip member: a gzip reader reads consecutive members as one stream, so the file
15
+ * reads as it always has. A process that dies mid-match leaves its temp files,
16
+ * which retention removes (`retention.ts`); recording a match that outlives a
17
+ * restart is still future work.
16
18
  *
17
- * Nothing here may fail a match. Every public method swallows its own errors
18
- * into `log`; `finish` resolves even when the disk write failed.
19
+ * Nothing here may fail a match. Every public method of the match writer
20
+ * swallows its own errors into `log`; `finish` resolves even when the disk
21
+ * write failed.
19
22
  */
20
- import { existsSync, mkdirSync, readdirSync, renameSync } from 'node:fs';
21
- import { rename, writeFile } from 'node:fs/promises';
23
+ import { createReadStream, createWriteStream, existsSync, mkdirSync, readdirSync, renameSync } from 'node:fs';
24
+ import { rename, rm, utimes, writeFile } from 'node:fs/promises';
22
25
  import { randomUUID } from 'node:crypto';
23
- import { join } from 'node:path';
24
- import { gzip as gzipCb } from 'node:zlib';
26
+ import { createInterface } from 'node:readline';
27
+ import { join, resolve } from 'node:path';
28
+ import { pipeline } from 'node:stream/promises';
29
+ import { createGunzip, createGzip, gzip as gzipCb } from 'node:zlib';
25
30
  import { promisify } from 'node:util';
26
- import { recordingChanged } from './changes.js';
31
+ import { onRecordingChanged, recordingChanged } from './changes.js';
27
32
  import { ACTIONS_SUFFIX, PUBLIC_SUFFIX } from './retention.js';
28
33
  const gzip = promisify(gzipCb);
29
34
  /**
@@ -32,17 +37,83 @@ const gzip = promisify(gzipCb);
32
37
  * art. A `v:1` stream drew no hand, and is never served.
33
38
  */
34
39
  export const PUBLIC_VERSION = 2;
35
- /** Write `bytes` to `path` whole or not at all: a temp file beside it, renamed over it. */
36
- async function writeFileAtomic(path, bytes) {
37
- const tmp = `${path}.${process.pid}.${randomUUID()}.tmp`;
38
- await writeFile(tmp, bytes);
39
- await rename(tmp, path);
40
+ /* ── The gzip JSONL pair ─────────────────────────────────────────────────────────────────────── */
41
+ /** Each non-empty line of a gzip JSONL file, in order, streamed: rejects on any read or gunzip error. */
42
+ export function eachLine(path, onLine) {
43
+ return new Promise((resolve, reject) => {
44
+ const input = createReadStream(path);
45
+ const gunzip = createGunzip();
46
+ input.on('error', reject);
47
+ gunzip.on('error', reject);
48
+ const rl = createInterface({ input: input.pipe(gunzip), crlfDelay: Infinity });
49
+ // readline re-emits its input's error on itself: unheard, a corrupt file is an uncaught exception.
50
+ rl.on('error', reject);
51
+ rl.on('line', (line) => {
52
+ if (line !== '')
53
+ onLine(line);
54
+ });
55
+ rl.on('close', () => resolve());
56
+ });
57
+ }
58
+ /** Every non-empty line of a gzip JSONL file, as text, in order. */
59
+ export async function readLines(path) {
60
+ const lines = [];
61
+ await eachLine(path, (line) => lines.push(line));
62
+ return lines;
63
+ }
64
+ const tmpBeside = (path) => `${path}.${String(process.pid)}.${randomUUID()}.tmp`;
65
+ /** Open a gzip JSONL file whose temp file sits beside `near` (a path in the directory it will land in). */
66
+ export function openJsonlGz(near) {
67
+ const body = tmpBeside(near);
68
+ const gz = createGzip();
69
+ let failed = null;
70
+ // Heard at once: a failed open (a missing directory) must never be an unheard stream error.
71
+ const written = pipeline(gz, createWriteStream(body)).catch((err) => {
72
+ failed ??= err;
73
+ });
74
+ return {
75
+ line(value) {
76
+ if (failed !== null)
77
+ return;
78
+ try {
79
+ gz.write(JSON.stringify(value) + '\n');
80
+ }
81
+ catch (err) {
82
+ // A line that cannot be written spoils the file: `close` reports it, and nothing lands.
83
+ failed = err;
84
+ }
85
+ },
86
+ async close(path, opts = {}) {
87
+ gz.end();
88
+ await written;
89
+ const landing = opts.first === undefined ? body : tmpBeside(path);
90
+ try {
91
+ if (failed !== null)
92
+ throw failed;
93
+ if (opts.first !== undefined) {
94
+ await writeFile(landing, await gzip(Buffer.from(JSON.stringify(opts.first) + '\n', 'utf8')));
95
+ await pipeline(createReadStream(body), createWriteStream(landing, { flags: 'a' }));
96
+ }
97
+ if (opts.times !== undefined)
98
+ await utimes(landing, opts.times.atime, opts.times.mtime);
99
+ await rename(landing, path);
100
+ }
101
+ finally {
102
+ await Promise.all([rm(body, { force: true }), rm(landing, { force: true })]);
103
+ }
104
+ },
105
+ };
40
106
  }
41
- async function flush(path, lines, log, which) {
107
+ /** Write `lines` to `path` as gzip JSONL, whole or not at all. */
108
+ export async function writeLines(path, lines, opts = {}) {
109
+ const out = openJsonlGz(path);
110
+ for (const line of lines)
111
+ out.line(line);
112
+ await out.close(path, opts);
113
+ }
114
+ async function land(file, path, header, log, which) {
42
115
  try {
43
- const text = lines.map((l) => JSON.stringify(l)).join('\n') + '\n';
44
- const compressed = await gzip(Buffer.from(text, 'utf8'));
45
- await writeFileAtomic(path, compressed);
116
+ await file.close(path, { first: header });
46
117
  }
47
118
  catch (err) {
48
119
  // A recording nobody can read is a loss, never a crash: the match this
@@ -85,23 +156,43 @@ export function keepEarlierEpoch(dir, matchId, log) {
85
156
  recordingChanged(dir, matchId);
86
157
  recordingChanged(dir, `${matchId}-e${String(n)}`);
87
158
  }
88
- /** The recordings a match's earlier epochs left (`keepEarlierEpoch`), oldest first, by the id each is served under. */
89
- export function earlierEpochs(dir, matchId) {
159
+ const EPOCH_FILE = new RegExp(`^(.+)-e(\\d+)${PUBLIC_SUFFIX.replace(/\./g, '\\.')}$`);
160
+ /**
161
+ * Every earlier epoch in a recordings directory, by match id, from one listing: kept until a writer says
162
+ * a recording there changed (`changes.ts`), which is every way an epoch comes or goes. The tables'
163
+ * live view asks for each of a room's tables on every look.
164
+ */
165
+ const epochListings = new Map();
166
+ /** The directories whose changes already drop their listing. */
167
+ const epochWatched = new Set();
168
+ function epochListing(dir) {
169
+ const key = resolve(dir);
170
+ const cached = epochListings.get(key);
171
+ if (cached !== undefined)
172
+ return cached;
90
173
  let names;
91
174
  try {
92
175
  names = readdirSync(dir);
93
176
  }
94
177
  catch {
95
- return [];
178
+ return new Map();
96
179
  }
97
- const epoch = new RegExp(`^${matchId.replace(/[^A-Za-z0-9_-]/g, '')}-e(\\d+)${PUBLIC_SUFFIX.replace(/\./g, '\\.')}$`);
98
- return names
99
- .flatMap((n) => {
100
- const m = epoch.exec(n);
101
- return m === null ? [] : [Number(m[1])];
102
- })
103
- .sort((a, b) => a - b)
104
- .map((n) => `${matchId}-e${String(n)}`);
180
+ const listing = new Map();
181
+ for (const name of names) {
182
+ const m = EPOCH_FILE.exec(name);
183
+ if (m !== null)
184
+ listing.set(m[1], [...(listing.get(m[1]) ?? []), Number(m[2])]);
185
+ }
186
+ if (!epochWatched.has(key)) {
187
+ epochWatched.add(key);
188
+ onRecordingChanged(dir, () => epochListings.delete(key));
189
+ }
190
+ epochListings.set(key, listing);
191
+ return listing;
192
+ }
193
+ /** The recordings a match's earlier epochs left (`keepEarlierEpoch`), oldest first, by the id each is served under. */
194
+ export function earlierEpochs(dir, matchId) {
195
+ return [...(epochListing(dir).get(matchId) ?? [])].sort((a, b) => a - b).map((n) => `${matchId}-e${String(n)}`);
105
196
  }
106
197
  export function createMatchRecordingWriter(deps) {
107
198
  const log = deps.log ?? (() => undefined);
@@ -113,28 +204,29 @@ export function createMatchRecordingWriter(deps) {
113
204
  }
114
205
  const actionsHeader = { t: 'header', v: 2, ...deps.actionsHeader };
115
206
  const publicHeader = { t: 'header', v: PUBLIC_VERSION, ...deps.publicHeader };
116
- const actionLines = [actionsHeader];
117
- const publicLines = [publicHeader];
207
+ const [actionsPath, publicPath] = epochPaths(deps.dir, deps.matchId);
208
+ const actions = openJsonlGz(actionsPath);
209
+ const stream = openJsonlGz(publicPath);
118
210
  return {
119
211
  actionCmd(line) {
120
- actionLines.push({ t: 'cmd', ...line });
212
+ actions.line({ t: 'cmd', ...line });
121
213
  },
122
214
  publicEnv(line) {
123
- publicLines.push({ t: 'env', ...line });
215
+ stream.line({ t: 'env', ...line });
124
216
  },
125
217
  publicPresence(line) {
126
- publicLines.push({ t: 'presence', ...line });
218
+ stream.line({ t: 'presence', ...line });
127
219
  },
128
220
  publicRelay(line) {
129
- publicLines.push({ t: 'relay', ...line });
221
+ stream.line({ t: 'relay', ...line });
130
222
  },
131
223
  room(roomId) {
132
224
  actionsHeader.roomId = roomId;
133
225
  publicHeader.roomId = roomId;
134
226
  },
135
227
  async finish(actionsEnd, publicEnd, opts = {}) {
136
- actionLines.push({ t: 'end', ...actionsEnd });
137
- publicLines.push({ t: 'end', ...publicEnd });
228
+ actions.line({ t: 'end', ...actionsEnd });
229
+ stream.line({ t: 'end', ...publicEnd });
138
230
  let id = deps.matchId;
139
231
  if (opts.aside === true) {
140
232
  id = `${deps.matchId}-e${String(freeEpoch(deps.dir, deps.matchId))}`;
@@ -142,10 +234,8 @@ export function createMatchRecordingWriter(deps) {
142
234
  }
143
235
  else
144
236
  keepEarlierEpoch(deps.dir, deps.matchId, log);
145
- await Promise.all([
146
- flush(join(deps.dir, `${id}${ACTIONS_SUFFIX}`), actionLines, log, 'actions'),
147
- flush(join(deps.dir, `${id}${PUBLIC_SUFFIX}`), publicLines, log, 'public'),
148
- ]);
237
+ const [actionsAt, publicAt] = epochPaths(deps.dir, id);
238
+ await Promise.all([land(actions, actionsAt, actionsHeader, log, 'actions'), land(stream, publicAt, publicHeader, log, 'public')]);
149
239
  recordingChanged(deps.dir, id);
150
240
  },
151
241
  };
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@hadoku/game-server",
3
- "version": "0.1.183",
4
- "gitHead": "01148a983236975af19414ad2d04f7d5665864df",
3
+ "version": "0.1.185",
4
+ "gitHead": "99f54cf6886cd65c5712ca7c486f011e1b094054",
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,9 +17,9 @@
17
17
  "play/remote/"
18
18
  ],
19
19
  "dependencies": {
20
- "@wolffm/host-wire": "npm:@hadoku/host-wire@0.1.183",
21
- "@wolffm/platform-wire": "npm:@hadoku/platform-wire@0.1.183",
22
- "@wolffm/service-kernel": "npm:@hadoku/service-kernel@0.1.216",
20
+ "@wolffm/host-wire": "npm:@hadoku/host-wire@0.1.185",
21
+ "@wolffm/platform-wire": "npm:@hadoku/platform-wire@0.1.185",
22
+ "@wolffm/service-kernel": "npm:@hadoku/service-kernel@0.1.218",
23
23
  "@wolffm/prefs-client": "npm:@hadoku/prefs-client@^1.2.2",
24
24
  "@wolffm/rooms-protocol": "npm:@hadoku/rooms-protocol@^0.45.145",
25
25
  "@wolffm/rooms-server": "npm:@hadoku/rooms-server@^0.45.145",