@hadoku/game-server 0.1.156 → 0.1.158

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.
@@ -29,7 +29,8 @@ import { join } from 'node:path';
29
29
  import { promisify } from 'node:util';
30
30
  import { gunzip as gunzipCb, gzip as gzipCb } from 'node:zlib';
31
31
  import { UNNAMED } from '../room/constants.js';
32
- import { ACTIONS_SUFFIX, PUBLIC_SUFFIX } from '../play/recording/retention.js';
32
+ import { recordingChanged } from '../play/recording/changes.js';
33
+ import { ACTIONS_SUFFIX, PUBLIC_SUFFIX, recordingOf } from '../play/recording/retention.js';
33
34
  import { renameIds, replaceIds } from './anonymise.js';
34
35
  const gunzip = promisify(gunzipCb);
35
36
  const gzip = promisify(gzipCb);
@@ -95,7 +96,7 @@ async function rewriteRecordings(dir, userId, change) {
95
96
  return 0;
96
97
  throw err;
97
98
  }
98
- const matchIds = new Set(files.flatMap((f) => (f.endsWith(PUBLIC_SUFFIX) ? [f.slice(0, -PUBLIC_SUFFIX.length)] : f.endsWith(ACTIONS_SUFFIX) ? [f.slice(0, -ACTIONS_SUFFIX.length)] : [])));
99
+ const matchIds = new Set(files.flatMap((f) => recordingOf(f)?.id ?? []));
99
100
  let changed = 0;
100
101
  for (const matchId of matchIds) {
101
102
  const texts = [];
@@ -117,8 +118,13 @@ async function rewriteRecordings(dir, userId, change) {
117
118
  const recording = texts.map(({ path, text }) => ({ path, lines: parseLines(text) }));
118
119
  if (!change(recording))
119
120
  continue;
120
- for (const { path, lines } of recording)
121
- await writeLines(path, lines);
121
+ try {
122
+ for (const { path, lines } of recording)
123
+ await writeLines(path, lines);
124
+ }
125
+ finally {
126
+ recordingChanged(dir, matchId);
127
+ }
122
128
  changed++;
123
129
  }
124
130
  return changed;
@@ -128,6 +128,15 @@ export declare function pidIsStandingInRun(pid: number, run: string): boolean;
128
128
  * decides.
129
129
  */
130
130
  export declare function pidIsRunning(pid: number): boolean;
131
+ /**
132
+ * The work a process has done so far, as `/proc/<pid>/stat` counts it: CPU time (user + system,
133
+ * in clock ticks) and major page faults (pages it waited to read back, from swap or disk). Two
134
+ * readings apart say whether it is getting anywhere; `null` once it has exited, or without `/proc`.
135
+ */
136
+ export declare function pidWork(pid: number): {
137
+ cpuTicks: number;
138
+ majorFaults: number;
139
+ } | null;
131
140
  /** How long a kill will spin waiting for a SIGKILL to land. Measured at 0 ms. */
132
141
  export declare const REAP_CONFIRM_MS = 100;
133
142
  /** How often an attached process (which is nobody's child, so has no `exit` event) is checked for. */
@@ -209,6 +209,22 @@ export function pidIsRunning(pid) {
209
209
  return false; // no /proc entry: it has exited
210
210
  }
211
211
  }
212
+ /**
213
+ * The work a process has done so far, as `/proc/<pid>/stat` counts it: CPU time (user + system,
214
+ * in clock ticks) and major page faults (pages it waited to read back, from swap or disk). Two
215
+ * readings apart say whether it is getting anywhere; `null` once it has exited, or without `/proc`.
216
+ */
217
+ export function pidWork(pid) {
218
+ try {
219
+ const stat = readFileSync(`/proc/${pid}/stat`, 'utf8');
220
+ // After the `(comm)`, fields[0] is field 3 (state): majflt is field 12, utime 14, stime 15.
221
+ const fields = stat.slice(stat.lastIndexOf(')') + 2).split(' ');
222
+ return { cpuTicks: Number(fields[11]) + Number(fields[12]), majorFaults: Number(fields[9]) };
223
+ }
224
+ catch {
225
+ return null;
226
+ }
227
+ }
212
228
  /** How long a kill will spin waiting for a SIGKILL to land. Measured at 0 ms. */
213
229
  export const REAP_CONFIRM_MS = 100;
214
230
  /** How often an attached process (which is nobody's child, so has no `exit` event) is checked for. */
@@ -121,7 +121,7 @@
121
121
  export { bridgeDiagnostics } from './diagnostics.js';
122
122
  import type { JvmLauncher } from './jvm-transport.js';
123
123
  import { type JvmHostConfig } from './local-jvm.js';
124
- export { BRIDGE_CACHE_MAX_AGE_MS, BRIDGE_JVM_FLAGS, CRASH_RECORD_FILES, CRASH_RECORD_MAX_AGE_MS, CRASH_RECORDS_KEPT, FORGE_HEARTBEAT_TIMEOUT_S, FORGE_PREFERENCES, JVM_HEAP_MB, MATCHES_PER_JVM, bridgeLaunch, bridgeVersion, jvmHostConfig, liveJvmCount, stageRunDir, sweepRunDirs, writeFileAtomic, type JvmAvailability, type JvmHostConfig, } from './local-jvm.js';
124
+ export { BRIDGE_CACHE_MAX_AGE_MS, BRIDGE_JVM_FLAGS, CRASH_RECORD_FILES, CRASH_RECORD_MAX_AGE_MS, CRASH_RECORDS_KEPT, FORGE_HEARTBEAT_TIMEOUT_S, FORGE_JVM_FLAGS, FORGE_PREFERENCES, JVM_HEAP_MB, MATCHES_PER_JVM, bridgeLaunch, bridgeVersion, jvmHostConfig, liveJvmCount, stageRunDir, sweepRunDirs, writeFileAtomic, type JvmAvailability, type JvmHostConfig, } from './local-jvm.js';
125
125
  export interface SeatSpec {
126
126
  /** Forge's player name. Shown to both seats, so never an identity. */
127
127
  name: string;
package/dist/play/host.js CHANGED
@@ -124,7 +124,7 @@ import { join } from 'node:path';
124
124
  import { jsonLogger } from '@wolffm/service-kernel/log';
125
125
  export { bridgeDiagnostics } from './diagnostics.js';
126
126
  import { JVM_HEAP_MB, MATCHES_PER_JVM, localJvmLauncher, writeFileAtomic } from './local-jvm.js';
127
- export { BRIDGE_CACHE_MAX_AGE_MS, BRIDGE_JVM_FLAGS, CRASH_RECORD_FILES, CRASH_RECORD_MAX_AGE_MS, CRASH_RECORDS_KEPT, FORGE_HEARTBEAT_TIMEOUT_S, FORGE_PREFERENCES, JVM_HEAP_MB, MATCHES_PER_JVM, bridgeLaunch, bridgeVersion, jvmHostConfig, liveJvmCount, stageRunDir, sweepRunDirs, writeFileAtomic, } from './local-jvm.js';
127
+ export { BRIDGE_CACHE_MAX_AGE_MS, BRIDGE_JVM_FLAGS, CRASH_RECORD_FILES, CRASH_RECORD_MAX_AGE_MS, CRASH_RECORDS_KEPT, FORGE_HEARTBEAT_TIMEOUT_S, FORGE_JVM_FLAGS, FORGE_PREFERENCES, JVM_HEAP_MB, MATCHES_PER_JVM, bridgeLaunch, bridgeVersion, jvmHostConfig, liveJvmCount, stageRunDir, sweepRunDirs, writeFileAtomic, } from './local-jvm.js';
128
128
  const LIFECYCLE_T = new Set(['ready', 'fatal', 'frame', 'snapshot']);
129
129
  /** Narrows any engine's line onto the four the host itself understands. See {@link HostLifecycleLine}. */
130
130
  export function isLifecycle(line) {
@@ -87,12 +87,23 @@ import type { JvmLauncher } from './jvm-transport.js';
87
87
  */
88
88
  export declare const FORGE_HEARTBEAT_TIMEOUT_S = 86400;
89
89
  /**
90
- * Flags every bridge JVM gets, before the heap cap and the operator's `jvmOpts` (so a later flag
91
- * of theirs wins). `ExitOnOutOfMemoryError`: G1 has no GC-overhead limit, and without this a JVM
92
- * out of heap never exits — its games die of `OutOfMemoryError` and the JVM limps on
93
- * (hosting-test-plan B4: 62 % GC, act p99 14.6 s). With it the JVM exits (code 3), which fails
94
- * every match on it through the exit path.
90
+ * After this long without a GC, an idle JVM's G1 runs one on its own (JEP 346). That returns
91
+ * the committed heap a busy spell left behind, and walks the live set, so a quiet JVM keeps
92
+ * its live set paged in. Measured on the pool JVM, 2026-11-28: 190 MB live in 1.1–1.75 GB
93
+ * committed that was never handed back, and after a quiet spell 1.67 GB of it was in the
94
+ * cgroup's swap; with this, 340 MB committed, and one periodic GC paged 230 MB back from swap.
95
+ * A JVM doing work collects far more often than this, so it never fires there.
95
96
  */
97
+ export declare const JVM_IDLE_GC_MS = 300000;
98
+ /**
99
+ * Flags every Forge JVM gets (match bridges and the pool service), before its heap cap and the
100
+ * operator's `jvmOpts` (so a later flag of theirs wins). `ExitOnOutOfMemoryError`: G1 has no
101
+ * GC-overhead limit, and without this a JVM out of heap never exits — its games die of
102
+ * `OutOfMemoryError` and the JVM limps on (hosting-test-plan B4: 62 % GC, act p99 14.6 s). With
103
+ * it the JVM exits (code 3), which fails everything on it through the exit path.
104
+ */
105
+ export declare const FORGE_JVM_FLAGS: readonly string[];
106
+ /** {@link FORGE_JVM_FLAGS}, and Forge's client timeout far past any pause. */
96
107
  export declare const BRIDGE_JVM_FLAGS: readonly string[];
97
108
  export interface JvmHostConfig {
98
109
  java: string;
@@ -145,8 +156,9 @@ export declare const MATCHES_PER_JVM = 25;
145
156
  /**
146
157
  * Each JVM's heap cap: the budget for {@link MATCHES_PER_JVM} matches. A JVM is ~172 MB live idle
147
158
  * and ~10 MB per match (Wave 9 lane D; 4–9 MB in hosting-test-plan B3), so 25 matches live in
148
- * ~420 MB of a 2 GB heap. G1 does not hand committed heap back, so a JVM's RSS is budgeted at its
149
- * peak: ~2.3 GB with metaspace, code cache and Netty.
159
+ * ~420 MB of a 2 GB heap. G1 hands committed heap back only once the JVM is idle
160
+ * ({@link JVM_IDLE_GC_MS}), so a JVM's RSS is budgeted at its peak: ~2.3 GB with metaspace, code
161
+ * cache and Netty.
150
162
  */
151
163
  export declare const JVM_HEAP_MB = 2048;
152
164
  export type JvmAvailability = {
@@ -93,13 +93,24 @@ import { CRASH_MARKER, IN_FIFO, JVM_TMP_DIR, OUT_FIFO, PID_POLL_MS, REAP_CONFIRM
93
93
  */
94
94
  export const FORGE_HEARTBEAT_TIMEOUT_S = 86_400;
95
95
  /**
96
- * Flags every bridge JVM gets, before the heap cap and the operator's `jvmOpts` (so a later flag
97
- * of theirs wins). `ExitOnOutOfMemoryError`: G1 has no GC-overhead limit, and without this a JVM
98
- * out of heap never exits — its games die of `OutOfMemoryError` and the JVM limps on
99
- * (hosting-test-plan B4: 62 % GC, act p99 14.6 s). With it the JVM exits (code 3), which fails
100
- * every match on it through the exit path.
96
+ * After this long without a GC, an idle JVM's G1 runs one on its own (JEP 346). That returns
97
+ * the committed heap a busy spell left behind, and walks the live set, so a quiet JVM keeps
98
+ * its live set paged in. Measured on the pool JVM, 2026-11-28: 190 MB live in 1.1–1.75 GB
99
+ * committed that was never handed back, and after a quiet spell 1.67 GB of it was in the
100
+ * cgroup's swap; with this, 340 MB committed, and one periodic GC paged 230 MB back from swap.
101
+ * A JVM doing work collects far more often than this, so it never fires there.
101
102
  */
102
- export const BRIDGE_JVM_FLAGS = ['-XX:+ExitOnOutOfMemoryError', `-Dforge.net.heartbeatTimeout=${FORGE_HEARTBEAT_TIMEOUT_S}`];
103
+ export const JVM_IDLE_GC_MS = 300_000;
104
+ /**
105
+ * Flags every Forge JVM gets (match bridges and the pool service), before its heap cap and the
106
+ * operator's `jvmOpts` (so a later flag of theirs wins). `ExitOnOutOfMemoryError`: G1 has no
107
+ * GC-overhead limit, and without this a JVM out of heap never exits — its games die of
108
+ * `OutOfMemoryError` and the JVM limps on (hosting-test-plan B4: 62 % GC, act p99 14.6 s). With
109
+ * it the JVM exits (code 3), which fails everything on it through the exit path.
110
+ */
111
+ export const FORGE_JVM_FLAGS = ['-XX:+ExitOnOutOfMemoryError', `-XX:G1PeriodicGCInterval=${JVM_IDLE_GC_MS}`];
112
+ /** {@link FORGE_JVM_FLAGS}, and Forge's client timeout far past any pause. */
113
+ export const BRIDGE_JVM_FLAGS = [...FORGE_JVM_FLAGS, `-Dforge.net.heartbeatTimeout=${FORGE_HEARTBEAT_TIMEOUT_S}`];
103
114
  const AI_FLAT_MC_LEVELS = ['off', 'base', 'lite', 'max'];
104
115
  /** `CARDTABLE_AI_FLAT_MC`'s default. See docs/planning/flat-mc-ai.md for the measurement behind it. */
105
116
  export const AI_FLAT_MC = 'off';
@@ -123,8 +134,9 @@ export const MATCHES_PER_JVM = 25;
123
134
  /**
124
135
  * Each JVM's heap cap: the budget for {@link MATCHES_PER_JVM} matches. A JVM is ~172 MB live idle
125
136
  * and ~10 MB per match (Wave 9 lane D; 4–9 MB in hosting-test-plan B3), so 25 matches live in
126
- * ~420 MB of a 2 GB heap. G1 does not hand committed heap back, so a JVM's RSS is budgeted at its
127
- * peak: ~2.3 GB with metaspace, code cache and Netty.
137
+ * ~420 MB of a 2 GB heap. G1 hands committed heap back only once the JVM is idle
138
+ * ({@link JVM_IDLE_GC_MS}), so a JVM's RSS is budgeted at its peak: ~2.3 GB with metaspace, code
139
+ * cache and Netty.
128
140
  */
129
141
  export const JVM_HEAP_MB = 2048;
130
142
  /** Where compiled bridges are kept, shared by every tree on the host (keyed by `bridgeVersion`). */
@@ -0,0 +1,5 @@
1
+ type Listener = (id: string) => void;
2
+ /** `id` is the recording's own (`<matchId>` or `<matchId>-e<N>`): its files were written, moved or removed. */
3
+ export declare function recordingChanged(dir: string, id: string): void;
4
+ export declare function onRecordingChanged(dir: string, listener: Listener): () => void;
5
+ export {};
@@ -0,0 +1,22 @@
1
+ /**
2
+ * Who hears that a recording changed on disk. Every writer of the recordings directory says so here
3
+ * once its write has landed: the recorder finishing a match and moving an earlier epoch aside
4
+ * (`writer.ts`), retention removing a file (`retention.ts`), an account erase rewriting one
5
+ * (`erase/recordings.ts`), a rebuild writing its stream back. A reader that keeps the directory in
6
+ * memory (the replay list's index) listens and reads that one recording again. Nothing watches the
7
+ * directory, so a file put there by anything else is seen at the next boot, never before.
8
+ */
9
+ import { resolve } from 'node:path';
10
+ const listeners = new Map();
11
+ /** `id` is the recording's own (`<matchId>` or `<matchId>-e<N>`): its files were written, moved or removed. */
12
+ export function recordingChanged(dir, id) {
13
+ for (const listener of listeners.get(resolve(dir)) ?? [])
14
+ listener(id);
15
+ }
16
+ export function onRecordingChanged(dir, listener) {
17
+ const key = resolve(dir);
18
+ const set = listeners.get(key) ?? new Set();
19
+ set.add(listener);
20
+ listeners.set(key, set);
21
+ return () => set.delete(listener);
22
+ }
@@ -19,6 +19,11 @@ export declare const ACTIONS_RETENTION_MS: number;
19
19
  export declare const RECORDINGS_CAP_BYTES: number;
20
20
  export declare const ACTIONS_SUFFIX = ".actions.jsonl.gz";
21
21
  export declare const PUBLIC_SUFFIX = ".public.jsonl.gz";
22
+ /** A file name in the recordings directory as the recording it belongs to; null for anything else. */
23
+ export declare function recordingOf(name: string): {
24
+ id: string;
25
+ kind: 'public' | 'actions';
26
+ } | null;
22
27
  export interface SweepResult {
23
28
  /** Files removed for being past their own retention window, by suffix. */
24
29
  expiredActions: string[];
@@ -14,12 +14,21 @@
14
14
  */
15
15
  import { readdirSync, rmSync, statSync } from 'node:fs';
16
16
  import { join } from 'node:path';
17
+ import { recordingChanged } from './changes.js';
17
18
  export const PUBLIC_RETENTION_MS = 7 * 24 * 60 * 60 * 1000;
18
19
  export const ACTIONS_RETENTION_MS = 90 * 24 * 60 * 60 * 1000;
19
20
  /** See the module header: the oldest public streams are dropped first when the directory is over this. */
20
21
  export const RECORDINGS_CAP_BYTES = 2 * 1024 * 1024 * 1024;
21
22
  export const ACTIONS_SUFFIX = '.actions.jsonl.gz';
22
23
  export const PUBLIC_SUFFIX = '.public.jsonl.gz';
24
+ /** A file name in the recordings directory as the recording it belongs to; null for anything else. */
25
+ export function recordingOf(name) {
26
+ if (name.endsWith(PUBLIC_SUFFIX))
27
+ return { id: name.slice(0, -PUBLIC_SUFFIX.length), kind: 'public' };
28
+ if (name.endsWith(ACTIONS_SUFFIX))
29
+ return { id: name.slice(0, -ACTIONS_SUFFIX.length), kind: 'actions' };
30
+ return null;
31
+ }
23
32
  function list(dir, errors) {
24
33
  let names;
25
34
  try {
@@ -31,7 +40,7 @@ function list(dir, errors) {
31
40
  }
32
41
  const out = [];
33
42
  for (const name of names) {
34
- if (!name.endsWith(ACTIONS_SUFFIX) && !name.endsWith(PUBLIC_SUFFIX))
43
+ if (recordingOf(name) === null)
35
44
  continue;
36
45
  try {
37
46
  const st = statSync(join(dir, name));
@@ -43,7 +52,7 @@ function list(dir, errors) {
43
52
  }
44
53
  return out;
45
54
  }
46
- function remove(entry, log, evt, errors) {
55
+ function remove(dir, entry, log, evt, errors) {
47
56
  try {
48
57
  rmSync(entry.path, { force: true });
49
58
  log({ evt, file: entry.name, ageMs: Date.now() - entry.mtimeMs, sizeBytes: entry.size });
@@ -51,6 +60,7 @@ function remove(entry, log, evt, errors) {
51
60
  catch (err) {
52
61
  errors.push({ file: entry.name, error: err.message });
53
62
  }
63
+ recordingChanged(dir, recordingOf(entry.name).id);
54
64
  }
55
65
  /** 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. */
56
66
  export function sweepRecordings(dir, now = Date.now(), log = () => undefined, capBytes = RECORDINGS_CAP_BYTES) {
@@ -62,7 +72,7 @@ export function sweepRecordings(dir, now = Date.now(), log = () => undefined, ca
62
72
  const suffix = entry.name.endsWith(ACTIONS_SUFFIX) ? 'actions' : 'public';
63
73
  const limit = suffix === 'actions' ? ACTIONS_RETENTION_MS : PUBLIC_RETENTION_MS;
64
74
  if (now - entry.mtimeMs > limit) {
65
- remove(entry, log, 'recording-expired', errors);
75
+ remove(dir, entry, log, 'recording-expired', errors);
66
76
  (suffix === 'actions' ? result.expiredActions : result.expiredPublic).push(entry.name);
67
77
  }
68
78
  else {
@@ -76,7 +86,7 @@ export function sweepRecordings(dir, now = Date.now(), log = () => undefined, ca
76
86
  for (const entry of publicOldestFirst) {
77
87
  if (total <= capBytes)
78
88
  break;
79
- remove(entry, log, 'recording-over-cap', errors);
89
+ remove(dir, entry, log, 'recording-over-cap', errors);
80
90
  result.overCap.push(entry.name);
81
91
  total -= entry.size;
82
92
  entries = entries.filter((e) => e !== entry);
@@ -23,6 +23,7 @@ import { randomUUID } from 'node:crypto';
23
23
  import { join } from 'node:path';
24
24
  import { gzip as gzipCb } from 'node:zlib';
25
25
  import { promisify } from 'node:util';
26
+ import { recordingChanged } from './changes.js';
26
27
  import { ACTIONS_SUFFIX, PUBLIC_SUFFIX } from './retention.js';
27
28
  const gzip = promisify(gzipCb);
28
29
  /**
@@ -81,6 +82,8 @@ export function keepEarlierEpoch(dir, matchId, log) {
81
82
  catch (err) {
82
83
  log({ evt: 'recording-epoch-keep-failed', matchId, epoch: n, error: err.message });
83
84
  }
85
+ recordingChanged(dir, matchId);
86
+ recordingChanged(dir, `${matchId}-e${String(n)}`);
84
87
  }
85
88
  /** The recordings a match's earlier epochs left (`keepEarlierEpoch`), oldest first, by the id each is served under. */
86
89
  export function earlierEpochs(dir, matchId) {
@@ -143,6 +146,7 @@ export function createMatchRecordingWriter(deps) {
143
146
  flush(join(deps.dir, `${id}${ACTIONS_SUFFIX}`), actionLines, log, 'actions'),
144
147
  flush(join(deps.dir, `${id}${PUBLIC_SUFFIX}`), publicLines, log, 'public'),
145
148
  ]);
149
+ recordingChanged(deps.dir, id);
146
150
  },
147
151
  };
148
152
  }
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@hadoku/game-server",
3
- "version": "0.1.156",
4
- "gitHead": "cf53f245d940318677658882201155d883e1ab2b",
3
+ "version": "0.1.158",
4
+ "gitHead": "c0edfe5c5672ea00e058c777deeccc8963eba558",
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.156",
21
- "@wolffm/platform-wire": "npm:@hadoku/platform-wire@0.1.156",
22
- "@wolffm/service-kernel": "npm:@hadoku/service-kernel@0.1.189",
20
+ "@wolffm/host-wire": "npm:@hadoku/host-wire@0.1.158",
21
+ "@wolffm/platform-wire": "npm:@hadoku/platform-wire@0.1.158",
22
+ "@wolffm/service-kernel": "npm:@hadoku/service-kernel@0.1.191",
23
23
  "@wolffm/prefs-client": "npm:@hadoku/prefs-client@^1.2.2",
24
24
  "@wolffm/rooms-protocol": "npm:@hadoku/rooms-protocol@^0.45.143",
25
25
  "@wolffm/rooms-server": "npm:@hadoku/rooms-server@^0.45.143",