@hadoku/game-server 0.0.0-stage → 0.1.6

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.
Files changed (119) hide show
  1. package/LICENSE +21 -0
  2. package/dist/base-path.d.ts +29 -0
  3. package/dist/base-path.js +30 -0
  4. package/dist/busy.d.ts +40 -0
  5. package/dist/busy.js +23 -0
  6. package/dist/capacity.d.ts +9 -0
  7. package/dist/capacity.js +6 -0
  8. package/dist/config.d.ts +247 -0
  9. package/dist/config.js +271 -0
  10. package/dist/edge-auth.d.ts +43 -0
  11. package/dist/edge-auth.js +47 -0
  12. package/dist/erase/anonymise.d.ts +7 -0
  13. package/dist/erase/anonymise.js +7 -0
  14. package/dist/erase/index.d.ts +18 -0
  15. package/dist/erase/index.js +20 -0
  16. package/dist/erase/legacy-ids.d.ts +7 -0
  17. package/dist/erase/legacy-ids.js +24 -0
  18. package/dist/erase/recordings.d.ts +26 -0
  19. package/dist/erase/recordings.js +128 -0
  20. package/dist/erase/rooms.d.ts +63 -0
  21. package/dist/erase/rooms.js +67 -0
  22. package/dist/gate.d.ts +27 -0
  23. package/dist/gate.js +15 -0
  24. package/dist/http/client-events.d.ts +25 -0
  25. package/dist/http/client-events.js +15 -0
  26. package/dist/http/page.d.ts +26 -0
  27. package/dist/http/page.js +35 -0
  28. package/dist/http/prepared.d.ts +14 -0
  29. package/dist/http/prepared.js +16 -0
  30. package/dist/http/request.d.ts +59 -0
  31. package/dist/http/request.js +37 -0
  32. package/dist/http/room-core.d.ts +160 -0
  33. package/dist/http/room-core.js +278 -0
  34. package/dist/http/trim.d.ts +23 -0
  35. package/dist/http/trim.js +76 -0
  36. package/dist/http/usage.d.ts +22 -0
  37. package/dist/http/usage.js +16 -0
  38. package/dist/kernel.d.ts +4 -0
  39. package/dist/kernel.js +26 -0
  40. package/dist/log.d.ts +9 -0
  41. package/dist/log.js +9 -0
  42. package/dist/people.d.ts +105 -0
  43. package/dist/people.js +145 -0
  44. package/dist/play/clock.d.ts +39 -0
  45. package/dist/play/clock.js +81 -0
  46. package/dist/play/diagnostics.d.ts +21 -0
  47. package/dist/play/diagnostics.js +35 -0
  48. package/dist/play/engine-runtime.d.ts +200 -0
  49. package/dist/play/engine-runtime.js +309 -0
  50. package/dist/play/game-adapter.d.ts +158 -0
  51. package/dist/play/game-adapter.js +1 -0
  52. package/dist/play/host.d.ts +482 -0
  53. package/dist/play/host.js +950 -0
  54. package/dist/play/jvm-transport.d.ts +25 -0
  55. package/dist/play/jvm-transport.js +1 -0
  56. package/dist/play/local-jvm.d.ts +325 -0
  57. package/dist/play/local-jvm.js +829 -0
  58. package/dist/play/match/hosted.d.ts +92 -0
  59. package/dist/play/match/hosted.js +151 -0
  60. package/dist/play/match/outcome.d.ts +26 -0
  61. package/dist/play/match/outcome.js +21 -0
  62. package/dist/play/match/shell.d.ts +378 -0
  63. package/dist/play/match/shell.js +613 -0
  64. package/dist/play/recording/retention.d.ts +36 -0
  65. package/dist/play/recording/retention.js +89 -0
  66. package/dist/play/recording/writer.d.ts +185 -0
  67. package/dist/play/recording/writer.js +90 -0
  68. package/dist/play/relay-socket.d.ts +128 -0
  69. package/dist/play/relay-socket.js +194 -0
  70. package/dist/play/runtimes/in-process.d.ts +47 -0
  71. package/dist/play/runtimes/in-process.js +43 -0
  72. package/dist/play/runtimes/relay-match.d.ts +166 -0
  73. package/dist/play/runtimes/relay-match.js +240 -0
  74. package/dist/play/runtimes/relay.d.ts +128 -0
  75. package/dist/play/runtimes/relay.js +183 -0
  76. package/dist/play/runtimes/streamed.d.ts +116 -0
  77. package/dist/play/runtimes/streamed.js +148 -0
  78. package/dist/play/start-queue.d.ts +65 -0
  79. package/dist/play/start-queue.js +187 -0
  80. package/dist/room/avatar.d.ts +1 -0
  81. package/dist/room/avatar.js +28 -0
  82. package/dist/room/caller.d.ts +21 -0
  83. package/dist/room/caller.js +1 -0
  84. package/dist/room/constants.d.ts +27 -0
  85. package/dist/room/constants.js +27 -0
  86. package/dist/room/events.d.ts +59 -0
  87. package/dist/room/events.js +174 -0
  88. package/dist/room/identity.d.ts +89 -0
  89. package/dist/room/identity.js +98 -0
  90. package/dist/room/lobby.d.ts +426 -0
  91. package/dist/room/lobby.js +880 -0
  92. package/dist/room/membership.d.ts +64 -0
  93. package/dist/room/membership.js +76 -0
  94. package/dist/room/provisioning.d.ts +22 -0
  95. package/dist/room/provisioning.js +46 -0
  96. package/dist/room/record.d.ts +63 -0
  97. package/dist/room/record.js +39 -0
  98. package/dist/room/room-list.d.ts +67 -0
  99. package/dist/room/room-list.js +66 -0
  100. package/dist/room/seats.d.ts +39 -0
  101. package/dist/room/seats.js +58 -0
  102. package/dist/room/session.d.ts +91 -0
  103. package/dist/room/session.js +156 -0
  104. package/dist/room/socket-auth.d.ts +2 -0
  105. package/dist/room/socket-auth.js +10 -0
  106. package/dist/room/watching.d.ts +35 -0
  107. package/dist/room/watching.js +72 -0
  108. package/dist/room/watchparty-link.d.ts +1 -0
  109. package/dist/room/watchparty-link.js +17 -0
  110. package/dist/stream/alloc.d.ts +115 -0
  111. package/dist/stream/alloc.js +368 -0
  112. package/dist/stream/index.d.ts +66 -0
  113. package/dist/stream/index.js +293 -0
  114. package/dist/telemetry.d.ts +46 -0
  115. package/dist/telemetry.js +25 -0
  116. package/dist/testPort.d.ts +1 -0
  117. package/dist/testPort.js +28 -0
  118. package/package.json +35 -4
  119. package/README.md +0 -3
package/dist/people.js ADDED
@@ -0,0 +1,145 @@
1
+ /**
2
+ * Who a person is and what they look like, from hadoku_site's prefs-api: their
3
+ * live display name, their avatar picture and the cosmetics they wear. One
4
+ * batched call (`resolveAvatars`) answers all three by userId.
5
+ *
6
+ * The operator, 2026-11-05: *"picture/character are the same thing and all
7
+ * over the entire site it's the same avatar. we must display all
8
+ * customizations everywhere."* A person picks all of it in the fleet's avatar
9
+ * settings, never here; this module only reads it.
10
+ *
11
+ * Resolved with this server's own service key. A failure answers nobody and
12
+ * is logged, never thrown: a missing look costs a face its dressing, not a
13
+ * join. Cached a minute, so a room's joins share one lookup; a person who has
14
+ * just changed theirs is read `fresh` (the served room's `account`, `room/serve.ts`).
15
+ * The picture URL is relayed, never fetched: the browser loads it from
16
+ * Discord, Steam or cdn.hadoku.me, all inside hadoku.me's img-src.
17
+ */
18
+ import { resolveAvatars } from '@wolffm/prefs-client/avatar';
19
+ import { cleanWorn } from '@wolffm/prefs-client/cosmetics';
20
+ import { AVATAR_ID_MAX, LOOK_PICTURE_MAX, lookOrNone } from '@wolffm/platform-wire/look';
21
+ const CACHE_TTL_MS = 60_000;
22
+ const CACHE_PRUNE_THRESHOLD = 1024;
23
+ const LOOKUP_TIMEOUT_MS = 5000;
24
+ /** What one resolved entry means here. Exported for its test. */
25
+ export function personOf(r) {
26
+ const picture = r !== undefined && r.source !== 'sprite' && typeof r.url === 'string' && r.url.startsWith('https://') && r.url.length <= LOOK_PICTURE_MAX ? r.url : undefined;
27
+ const cosmetics = cleanWorn(r?.cosmetics);
28
+ return {
29
+ name: typeof r?.name === 'string' && r.name.trim() !== '' ? r.name : null,
30
+ sprite: typeof r?.sprite === 'string' && r.sprite.trim() !== '' && r.sprite.length <= AVATAR_ID_MAX ? r.sprite : null,
31
+ look: lookOrNone({ ...(picture === undefined ? {} : { picture }), ...(cosmetics === undefined ? {} : { cosmetics }) }),
32
+ };
33
+ }
34
+ /** No key, no lookups: every answer is empty and nothing is called. */
35
+ export function createPeople(opts) {
36
+ const now = opts.now ?? Date.now;
37
+ const cache = new Map();
38
+ const baseUrl = opts.baseUrl.replace(/\/+$/, '');
39
+ // hadoku.me's WAF challenges a bare client user-agent, and a lookup that
40
+ // never answers must not hold a join's promise open.
41
+ const lookupFetch = (input, init) => (opts.fetch ?? fetch)(input, {
42
+ ...init,
43
+ headers: { ...init?.headers, 'User-Agent': 'hadoku-cardtable-people/1' },
44
+ signal: AbortSignal.timeout(LOOKUP_TIMEOUT_MS),
45
+ });
46
+ let inflight = Promise.resolve();
47
+ const peek = (userId) => {
48
+ const hit = cache.get(userId);
49
+ return hit !== undefined && hit.expiresAt > now() ? hit.person : undefined;
50
+ };
51
+ return {
52
+ peek,
53
+ forget: (userId) => (cache.delete(userId) ? 1 : 0),
54
+ async resolve(userIds, { fresh = false } = {}) {
55
+ const out = new Map();
56
+ const missing = [];
57
+ for (const id of new Set(userIds)) {
58
+ const hit = fresh ? undefined : peek(id);
59
+ if (hit !== undefined)
60
+ out.set(id, hit);
61
+ else
62
+ missing.push(id);
63
+ }
64
+ if (missing.length === 0 || (opts.serviceKey === '' && opts.keyless !== true))
65
+ return out;
66
+ // One lookup at a time: a burst of joins after a restart asks once per
67
+ // id rather than once per join.
68
+ const run = inflight.then(async () => {
69
+ const still = fresh ? missing : missing.filter((id) => peek(id) === undefined);
70
+ if (still.length === 0)
71
+ return;
72
+ try {
73
+ const answer = await resolveAvatars({ baseUrl, serviceKey: opts.serviceKey, fetch: lookupFetch }, still);
74
+ const at = now();
75
+ for (const id of still)
76
+ cache.set(id, { person: personOf(answer[id]), expiresAt: at + CACHE_TTL_MS });
77
+ if (cache.size > CACHE_PRUNE_THRESHOLD)
78
+ for (const [k, e] of cache)
79
+ if (e.expiresAt <= at)
80
+ cache.delete(k);
81
+ }
82
+ catch (err) {
83
+ opts.log({ evt: 'people-resolve-failed', ids: still.length, error: err.message });
84
+ }
85
+ });
86
+ inflight = run;
87
+ await run;
88
+ for (const id of missing) {
89
+ const hit = cache.get(id);
90
+ if (hit !== undefined)
91
+ out.set(id, hit.person);
92
+ }
93
+ return out;
94
+ },
95
+ };
96
+ }
97
+ /**
98
+ * Write `person` onto member `memberId` of `roomId`: their name in every room they are in, their
99
+ * character and their look in this one. The account is the one source of all three (the operator,
100
+ * 2026-11-05: *"all over the entire site it's the same avatar"*); a field the lookup has no answer
101
+ * for leaves what the room already holds.
102
+ */
103
+ export function applyPerson(rooms, roomId, memberId, person) {
104
+ if (rooms.get(roomId)?.members.some((m) => m.id === memberId) !== true)
105
+ return;
106
+ if (person.name !== null)
107
+ rooms.rename({ id: memberId, name: person.name });
108
+ if (person.sprite !== null)
109
+ rooms.setAvatar(roomId, memberId, person.sprite);
110
+ rooms.setLook(roomId, memberId, person.look);
111
+ }
112
+ /**
113
+ * Every member of a room that changes is written from their account (`applyPerson`, from the
114
+ * cache mostly), so a joiner and a member a restart left unnamed (R12) are named and dressed
115
+ * whether or not they have the room open. A change made while the room IS open reaches it live
116
+ * through the served room (`room/serve.ts`); `sweep` is the boot's one read of the restored rooms,
117
+ * and `arrived` reads one person fresh as they come into a room, so a change made since the
118
+ * cache's last answer is what the room gets (as the served room re-reads an account on its join).
119
+ */
120
+ export function attachPeople(rooms, people) {
121
+ const write = async (open) => {
122
+ const users = open.map((roomId) => ({ roomId, users: rooms.usersOf(roomId) }));
123
+ const found = await people.resolve(users.flatMap((r) => r.users.map((u) => u.userId)));
124
+ for (const r of users) {
125
+ for (const { memberId, userId } of r.users) {
126
+ const person = found.get(userId);
127
+ if (person !== undefined)
128
+ applyPerson(rooms, r.roomId, memberId, person);
129
+ }
130
+ }
131
+ };
132
+ const stop = rooms.onChange((roomId) => void write([roomId]));
133
+ const arrived = async (roomId, memberId, userId) => {
134
+ const person = (await people.resolve([userId], { fresh: true })).get(userId);
135
+ if (person !== undefined)
136
+ applyPerson(rooms, roomId, memberId, person);
137
+ };
138
+ return { sweep: () => write(rooms.offered().map((r) => r.id)), arrived, stop };
139
+ }
140
+ /** How a person is drawn in a record of the past: their character and their look, as they are now. */
141
+ export function faceOfPerson(person) {
142
+ if (person === undefined)
143
+ return {};
144
+ return { ...(person.sprite === null ? {} : { avatarId: person.sprite }), ...(person.look === undefined ? {} : { look: person.look }) };
145
+ }
@@ -0,0 +1,39 @@
1
+ /**
2
+ * The chess clock: each seat's time left in one game (`GAME_CLOCK_MS`,
3
+ * `@hadoku/shared`), spent only while the game is waiting on that seat.
4
+ *
5
+ * Pure arithmetic over the times it is handed — no timers and no wall clock of
6
+ * its own — so `match.ts` decides WHEN a seat is being waited on (its
7
+ * `waitingOnFor`, the fact the other seat's banner already reads) and this file
8
+ * only adds up how long. Both seats can run at once: a mulligan is decided on
9
+ * both sides together.
10
+ *
11
+ * What it does not see is what it does not charge: a window the server
12
+ * auto-passes never reaches the seat as a live bar, so it never starts the
13
+ * seat's clock, and sideboarding happens between two matches, while no clock
14
+ * exists. Every game of a series starts from the whole clock.
15
+ */
16
+ export type Pair<T> = [T, T];
17
+ /** One seat's clock as a screen draws it: `ms` left as of the moment it was read, and whether it is running. */
18
+ export interface ClockReading {
19
+ ms: number;
20
+ running: boolean;
21
+ }
22
+ export declare class ChessClock {
23
+ #private;
24
+ constructor(left: readonly [number, number]);
25
+ /** Which seats the game is waiting on from `now`. True when that changed which seats run. */
26
+ set(running: readonly [boolean, boolean], now: number): boolean;
27
+ /** Stop both seats: the game is over, or the server is letting go of it. */
28
+ stop(now: number): void;
29
+ /** Each seat's time left at `now`. */
30
+ left(now: number): Pair<number>;
31
+ reading(now: number): Pair<ClockReading>;
32
+ /** The running seat whose time runs out first, and in how long from `now`; null while no seat runs. */
33
+ nextFlag(now: number): {
34
+ seat: 0 | 1;
35
+ inMs: number;
36
+ } | null;
37
+ /** A seat that ran out of time: running, with nothing left. */
38
+ flagged(now: number): 0 | 1 | null;
39
+ }
@@ -0,0 +1,81 @@
1
+ /**
2
+ * The chess clock: each seat's time left in one game (`GAME_CLOCK_MS`,
3
+ * `@hadoku/shared`), spent only while the game is waiting on that seat.
4
+ *
5
+ * Pure arithmetic over the times it is handed — no timers and no wall clock of
6
+ * its own — so `match.ts` decides WHEN a seat is being waited on (its
7
+ * `waitingOnFor`, the fact the other seat's banner already reads) and this file
8
+ * only adds up how long. Both seats can run at once: a mulligan is decided on
9
+ * both sides together.
10
+ *
11
+ * What it does not see is what it does not charge: a window the server
12
+ * auto-passes never reaches the seat as a live bar, so it never starts the
13
+ * seat's clock, and sideboarding happens between two matches, while no clock
14
+ * exists. Every game of a series starts from the whole clock.
15
+ */
16
+ export class ChessClock {
17
+ #left;
18
+ /** When each running seat last started (or was last read), null while it is stopped. */
19
+ #since = [null, null];
20
+ constructor(left) {
21
+ this.#left = [Math.max(0, left[0]), Math.max(0, left[1])];
22
+ }
23
+ /** Charge every running seat up to `now`. */
24
+ #settle(now) {
25
+ for (const seat of [0, 1]) {
26
+ const since = this.#since[seat];
27
+ if (since === null)
28
+ continue;
29
+ this.#left[seat] = Math.max(0, this.#left[seat] - Math.max(0, now - since));
30
+ this.#since[seat] = now;
31
+ }
32
+ }
33
+ /** Which seats the game is waiting on from `now`. True when that changed which seats run. */
34
+ set(running, now) {
35
+ this.#settle(now);
36
+ let moved = false;
37
+ for (const seat of [0, 1]) {
38
+ const on = running[seat] && this.#left[seat] > 0;
39
+ if (on === (this.#since[seat] !== null))
40
+ continue;
41
+ this.#since[seat] = on ? now : null;
42
+ moved = true;
43
+ }
44
+ return moved;
45
+ }
46
+ /** Stop both seats: the game is over, or the server is letting go of it. */
47
+ stop(now) {
48
+ this.set([false, false], now);
49
+ }
50
+ /** Each seat's time left at `now`. */
51
+ left(now) {
52
+ this.#settle(now);
53
+ return [this.#left[0], this.#left[1]];
54
+ }
55
+ reading(now) {
56
+ const left = this.left(now);
57
+ return [
58
+ { ms: left[0], running: this.#since[0] !== null },
59
+ { ms: left[1], running: this.#since[1] !== null },
60
+ ];
61
+ }
62
+ /** The running seat whose time runs out first, and in how long from `now`; null while no seat runs. */
63
+ nextFlag(now) {
64
+ const left = this.left(now);
65
+ let next = null;
66
+ for (const seat of [0, 1]) {
67
+ if (this.#since[seat] === null)
68
+ continue;
69
+ if (next === null || left[seat] < next.inMs)
70
+ next = { seat, inMs: left[seat] };
71
+ }
72
+ return next;
73
+ }
74
+ /** A seat that ran out of time: running, with nothing left. */
75
+ flagged(now) {
76
+ const left = this.left(now);
77
+ if (this.#since[0] !== null && left[0] === 0)
78
+ return 0;
79
+ return this.#since[1] !== null && left[1] === 0 ? 1 : null;
80
+ }
81
+ }
@@ -0,0 +1,21 @@
1
+ /**
2
+ * What a bridge JVM said about itself on stderr, as opposed to Forge's own log chatter. One rule for
3
+ * both places that read a dead JVM's stderr: this machine's pool (`local-jvm.ts`, logged before a
4
+ * clean end removes the file) and the host agent on a claw (`apps/agent`, the reason a JVM exited,
5
+ * which becomes the failover alert's cause). Kept free of imports so the agent's bundle can take it.
6
+ */
7
+ /** At most this many distinct diagnostic lines, each cut to {@link DIAGNOSTIC_CHARS}, logged for one JVM. */
8
+ export declare const DIAGNOSTICS_KEPT = 40;
9
+ /**
10
+ * What the bridge said about itself on stderr: every line it tagged `[bridge]` and the headline of every
11
+ * Java throwable with its first frame, each kept once with how many times it came, in first-seen order.
12
+ *
13
+ * A clean end removes the run directory, and with it `bridge.stderr.txt`, which is where the bridge says a
14
+ * read of Forge failed (`PlayBridge.java`'s `decoration`, `[bridge] … could not read …`). So the operator's
15
+ * dredge window, 2026-10-23 — a prompt whose read threw and never went out — left nothing in the logs to
16
+ * find it by. This is what is kept of it.
17
+ */
18
+ export declare function bridgeDiagnostics(stderr: string): {
19
+ line: string;
20
+ count: number;
21
+ }[];
@@ -0,0 +1,35 @@
1
+ /**
2
+ * What a bridge JVM said about itself on stderr, as opposed to Forge's own log chatter. One rule for
3
+ * both places that read a dead JVM's stderr: this machine's pool (`local-jvm.ts`, logged before a
4
+ * clean end removes the file) and the host agent on a claw (`apps/agent`, the reason a JVM exited,
5
+ * which becomes the failover alert's cause). Kept free of imports so the agent's bundle can take it.
6
+ */
7
+ /** At most this many distinct diagnostic lines, each cut to {@link DIAGNOSTIC_CHARS}, logged for one JVM. */
8
+ export const DIAGNOSTICS_KEPT = 40;
9
+ const DIAGNOSTIC_CHARS = 400;
10
+ /** A line the bridge tagged as its own, or the headline of a Java throwable (`Exception in thread …`, `java.lang.X: …`). */
11
+ const DIAGNOSTIC_LINE = /^(\[bridge\]|Exception in thread |(?:[\w$]+\.)+[\w$]*(?:Exception|Error)(?::|$))/;
12
+ /**
13
+ * What the bridge said about itself on stderr: every line it tagged `[bridge]` and the headline of every
14
+ * Java throwable with its first frame, each kept once with how many times it came, in first-seen order.
15
+ *
16
+ * A clean end removes the run directory, and with it `bridge.stderr.txt`, which is where the bridge says a
17
+ * read of Forge failed (`PlayBridge.java`'s `decoration`, `[bridge] … could not read …`). So the operator's
18
+ * dredge window, 2026-10-23 — a prompt whose read threw and never went out — left nothing in the logs to
19
+ * find it by. This is what is kept of it.
20
+ */
21
+ export function bridgeDiagnostics(stderr) {
22
+ const seen = new Map();
23
+ const lines = stderr.split('\n');
24
+ for (let i = 0; i < lines.length; i++) {
25
+ const raw = (lines[i] ?? '').trimEnd();
26
+ if (!DIAGNOSTIC_LINE.test(raw))
27
+ continue;
28
+ const frame = raw.startsWith('[bridge]') ? undefined : lines[i + 1]?.trim();
29
+ const line = (frame?.startsWith('at ') ? `${raw} ${frame}` : raw).slice(0, DIAGNOSTIC_CHARS);
30
+ if (!seen.has(line) && seen.size >= DIAGNOSTICS_KEPT)
31
+ continue;
32
+ seen.set(line, (seen.get(line) ?? 0) + 1);
33
+ }
34
+ return [...seen].map(([line, count]) => ({ line, count }));
35
+ }
@@ -0,0 +1,200 @@
1
+ /**
2
+ * Generic process hosting for a game engine run as a long-lived subprocess: a run directory
3
+ * reached over named pipes that outlive the server, pid-based liveness (a recycled pid is some
4
+ * other program, never ours to claim), and the crash-record bookkeeping a boot sweep prunes.
5
+ * `local-jvm.ts` is the one caller today — Forge's bridge JVM, hosted through this file's
6
+ * primitives — and `EngineRuntime` below is the seam a later lane (L2, `host.ts` going generic)
7
+ * can rewire the coordinator through, so a non-JVM engine fits the same host.
8
+ *
9
+ * Nothing here knows about Forge, bridges, or `.dck` files. See `local-jvm.ts`'s own header for
10
+ * the run directory's on-disk shape and why a JVM outlives its server.
11
+ */
12
+ import { type ChildProcess } from 'node:child_process';
13
+ /**
14
+ * A process `EngineRuntime.spawn` handed back: just the pid and the two edges `local-jvm.ts`'s
15
+ * `LocalJvm` needs to watch — nothing of `node:child_process`'s own shape leaks past this, so an
16
+ * engine that is not a `child_process` at all (a streamed desktop's "process" is a docker
17
+ * container `scripts/stream/container.sh` starts, not a pid this server forks) can still describe
18
+ * itself this way without pretending to BE a `ChildProcess`.
19
+ */
20
+ export interface EngineProcess {
21
+ readonly pid: number;
22
+ /** The process ended on its own — exited, or never started (`onError` instead). */
23
+ onExit(cb: (code: number | null, signal: NodeJS.Signals | null) => void): void;
24
+ /** The process could not be started at all. */
25
+ onError(cb: (err: Error) => void): void;
26
+ /** Stop listening: called once `onExit`/`onError` has fired, so nothing later touches a settled match. */
27
+ dispose(): void;
28
+ }
29
+ /**
30
+ * What the host asks of any engine it runs matches through: the process it spawns and what that
31
+ * process costs. `local-jvm.ts`'s `LocalJvm` launches through `forgeEngineRuntime`'s `spawn`
32
+ * (the actual `child_process.spawn` call lives there, not in `LocalJvm`, which only builds the
33
+ * argv and hands it over) instead of building the child process itself. The coordinator itself
34
+ * (`host.ts`) still places matches through `localJvmLauncher`'s `JvmLauncher`, never through
35
+ * `EngineRuntime` directly — lifting the POOL onto this seam, so a non-JVM engine shares the same
36
+ * coordinator, is still ahead of this.
37
+ */
38
+ export interface EngineRuntime {
39
+ /** Paths (or other identifiers) of what the process needs, keyed for logging. */
40
+ artifacts: Record<string, string>;
41
+ /** The full argv (after the executable) to launch one process in run directory `dir`, sized to `size`. */
42
+ argv(dir: string, size: {
43
+ memoryMb: number;
44
+ }): string[];
45
+ /** RAM one idle process costs beyond what it hosts. */
46
+ overheadMb: number;
47
+ /** Matches (or jobs) one process hosts at most. */
48
+ perProcess: number;
49
+ /** Is the process in `dir` still healthy, or due for a recycle? */
50
+ health?(dir: string): {
51
+ recycle: boolean;
52
+ };
53
+ /**
54
+ * Launch `argv` (after the executable) with `cwd` and these three stdio fds — never a Node
55
+ * pipe; `local-jvm.ts`'s header says why a JVM's stdio has to be fds on named pipes, not
56
+ * something that dies with this process. Optional: an engine whose "process" is not one this
57
+ * server forks at all (a container another script starts) leaves it unset and is launched some
58
+ * other way.
59
+ */
60
+ spawn?(argv: string[], cwd: string, io: {
61
+ stdin: number;
62
+ stdout: number;
63
+ stderr: number;
64
+ }): EngineProcess;
65
+ }
66
+ /** An `EngineProcess` over a real `child_process` — what every `spawn` implementation here wraps. */
67
+ export declare function wrapChildProcess(child: ChildProcess): EngineProcess;
68
+ /** A whole number of at least 1 from `raw`, else `fallback`. */
69
+ export declare function positiveInt(raw: string | undefined, fallback: number): number;
70
+ /**
71
+ * The `java` to run when nothing names one, as an ABSOLUTE path whenever one can be found: a
72
+ * caller that also wants `javac` (to compile a bridge, say) looks beside it, and beside a bare
73
+ * `java` is `./javac`, which never exists.
74
+ *
75
+ * In order: `$JAVA_HOME/bin/java`, then the first `java` on `PATH` with its symlinks followed
76
+ * (`/usr/local/bin/java` is a link into the fleet's JDK, and `javac` sits beside the real file,
77
+ * not the link). A bare `java` only when neither exists.
78
+ */
79
+ export declare function defaultJava(env?: NodeJS.ProcessEnv): string;
80
+ /** A process's stdin, opened by both ends. */
81
+ export declare const IN_FIFO = "in.fifo";
82
+ /** A process's stdout, same treatment. */
83
+ export declare const OUT_FIFO = "out.fifo";
84
+ /** Where a process's own `java.io.tmpdir`-style scratch space goes, inside the run dir. */
85
+ export declare const JVM_TMP_DIR = "tmp";
86
+ /**
87
+ * Two named pipes in the run dir. `mkfifo(3)` has no binding in `node:fs`, so
88
+ * this shells out — once per run directory, at staging time.
89
+ */
90
+ export declare function makeFifos(run: string): void;
91
+ /**
92
+ * The transport to one process over its fifos, either end of which may be opened by a process
93
+ * that did not create it. Both fds are `O_RDWR` so neither side ever reads EOF — the engine would
94
+ * exit on one, and we could not tell a handed-over process from a dead one.
95
+ */
96
+ export interface JvmIo {
97
+ /** Queue one line for the process's stdin; never blocks. See {@link openJvmIo}. */
98
+ write(line: string): void;
99
+ lines: NodeJS.ReadableStream;
100
+ close(): void;
101
+ }
102
+ /**
103
+ * The read end is a `net.Socket` over the fd, **not** `fs.createReadStream`.
104
+ * That is not a style choice: `fs.read` on a blocking fifo fd parks a libuv
105
+ * THREADPOOL thread for as long as the fifo is empty, and the pool is four
106
+ * threads by default. Two matches and a spare is three readers waiting on a
107
+ * quiet Forge, and the fourth thread is every other piece of async file work
108
+ * this process does — which is how the first version of this deadlocked
109
+ * `host.test.ts` outright. `net.Socket` puts the fd in libuv's event loop
110
+ * (`uv_pipe_open`, epoll) and occupies no thread at all.
111
+ */
112
+ export declare function openJvmIo(run: string, log: (entry: Record<string, unknown>) => void): JvmIo;
113
+ /**
114
+ * Is `pid` still the process standing in `run`? The cwd check is what makes
115
+ * this safe against pid reuse: a recycled pid is some other program, in some
116
+ * other directory. Null when `/proc` cannot answer.
117
+ */
118
+ export declare function pidIsStandingIn(pid: number, run: string): boolean | null;
119
+ /**
120
+ * `pidIsStandingIn`, tolerant of a run dir reached through a symlink: `/proc`
121
+ * answers with the resolved path and a run dir is not always resolved first, so the
122
+ * two spellings can differ.
123
+ */
124
+ export declare function pidIsStandingInRun(pid: number, run: string): boolean;
125
+ /**
126
+ * Alive, and not a zombie waiting to be reaped. A zombie still answers signal 0
127
+ * — it has a pid until its parent collects it — so `/proc/<pid>/stat` is what
128
+ * decides.
129
+ */
130
+ export declare function pidIsRunning(pid: number): boolean;
131
+ /** How long a kill will spin waiting for a SIGKILL to land. Measured at 0 ms. */
132
+ export declare const REAP_CONFIRM_MS = 100;
133
+ /** How often an attached process (which is nobody's child, so has no `exit` event) is checked for. */
134
+ export declare const PID_POLL_MS = 1000;
135
+ /**
136
+ * Block this thread for `ms`. Only ever used confirming a kill before the caller
137
+ * stops existing (`process.exit` a statement away), where there is no later tick to confirm in.
138
+ */
139
+ export declare function sleepSync(ms: number): void;
140
+ /** SIGKILL a pid we own, or say nothing: it may have gone between the check and here. */
141
+ export declare function killPid(pid: number): void;
142
+ /** One run directory under a `workDir`, as a real path. */
143
+ export interface RunDirEntry {
144
+ name: string;
145
+ dir: string;
146
+ mtimeMs: number;
147
+ }
148
+ /** Marks a pruned-down run directory as a crash record rather than scaffolding to remove outright. */
149
+ export declare const CRASH_MARKER = "crash.json";
150
+ /** Our run directories directly under `workDir`, as real paths, matching `namePattern`. */
151
+ export declare function runDirs(workDir: string, namePattern: RegExp): RunDirEntry[];
152
+ /** When a crash record (named `marker`, inside `dir`) was written: its own `at`, else `fallbackMtimeMs`. */
153
+ export declare function crashTime(dir: string, marker: string, fallbackMtimeMs: number): number;
154
+ /**
155
+ * Enforce a crash-record bound over directories matching `namePattern` under `workDir`: the
156
+ * newest `keep` within `maxAgeMs` stay, the rest are removed outright. Returns what it removed.
157
+ */
158
+ export declare function pruneCrashRecords(workDir: string, namePattern: RegExp, marker: string, keep: number, maxAgeMs: number, now?: number): {
159
+ kept: string[];
160
+ removed: string[];
161
+ };
162
+ /**
163
+ * The working directory of every process on this host that we can see, or
164
+ * null when `/proc` cannot say (not Linux). A process that exits between the
165
+ * listing and the readlink, or belongs to another user, is not standing in one
166
+ * of our directories.
167
+ */
168
+ export declare function processCwds(): string[] | null;
169
+ /** Is `cwd` this directory, or somewhere under it? */
170
+ export declare function cwdIsUnder(cwd: string, dir: string): boolean;
171
+ export interface SweepResult {
172
+ /** Directories removed: dead, not fresh, not a crash record within the bound. */
173
+ removed: string[];
174
+ /** Spared: some process is standing in it — a running process, ours or another server's. */
175
+ live: string[];
176
+ /** Spared: changed within the sweep's freshness window. */
177
+ fresh: string[];
178
+ /** Crash records kept, and those the bound removed. */
179
+ crashes: {
180
+ kept: string[];
181
+ removed: string[];
182
+ };
183
+ /**
184
+ * Live processes of ours: the directory's own launch record names the very process standing in it.
185
+ * A subset of `live`, oldest first.
186
+ */
187
+ running: {
188
+ hostId: string;
189
+ pid: number;
190
+ run: string;
191
+ startedAt: string;
192
+ }[];
193
+ /**
194
+ * Live directories the sweep ENDED: a legacy one-process-per-run-dir layout nothing re-attaches
195
+ * any more, named by its own record's pid.
196
+ */
197
+ killed: string[];
198
+ /** Set when the sweep did nothing, and why. */
199
+ skipped?: string;
200
+ }