@hadoku/game-server 0.1.230 → 0.1.232

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.
@@ -3,7 +3,9 @@
3
3
  *
4
4
  * Scoped to GET/HEAD: a POST to a path that does not exist is a bug in the
5
5
  * caller, and answering it with an HTML page hides that. Mounted LAST, below
6
- * every route that owns a path, or it answers for them.
6
+ * every route that owns a path, or it answers for them. A missing `/embed/*`
7
+ * file is a 404, never the page: a module `import()` handed HTML fails with a
8
+ * MIME error that names nothing.
7
9
  *
8
10
  * Per caller, a page load is a costly act: each one boots the whole app, about
9
11
  * eight requests, each a line in this server's log and a row in the edge's. A
package/dist/http/page.js CHANGED
@@ -3,7 +3,9 @@
3
3
  *
4
4
  * Scoped to GET/HEAD: a POST to a path that does not exist is a bug in the
5
5
  * caller, and answering it with an HTML page hides that. Mounted LAST, below
6
- * every route that owns a path, or it answers for them.
6
+ * every route that owns a path, or it answers for them. A missing `/embed/*`
7
+ * file is a 404, never the page: a module `import()` handed HTML fails with a
8
+ * MIME error that names nothing.
7
9
  *
8
10
  * Per caller, a page load is a costly act: each one boots the whole app, about
9
11
  * eight requests, each a line in this server's log and a row in the edge's. A
@@ -23,6 +25,9 @@ export function attachPage(app, deps) {
23
25
  act: 'page-load',
24
26
  now: deps.now,
25
27
  });
28
+ app.use('/embed', (_req, res) => {
29
+ res.status(404).type('text').send('no such embed file');
30
+ });
26
31
  app.get(/.*/, (req, res, next) => {
27
32
  if (!deps.basePath.ok) {
28
33
  res.status(503).type('html').send(diagnosticPage(deps.basePath, deps.basePrefix, deps.name));
@@ -233,6 +233,8 @@ export interface RoomCoreDeps<V extends RoomViewCore, C, P extends object, G = n
233
233
  * Absent: only the leader.
234
234
  */
235
235
  operator?: (req: Request) => boolean;
236
+ /** An operator's seat op, done or refused, as `act` (the route, `-` for `/`) and the body with `ok` and `reason`. Never a leader's own: filling a pod with the AI makes a dozen. */
237
+ audit?: (req: Request, act: string, roomId: string, outcome: Record<string, unknown>) => void;
236
238
  lobby: LobbyCore<V, C>;
237
239
  wire: RoomCoreWire<C, P>;
238
240
  /** Structured log lines. Never carries a password, hash or salt. */
@@ -369,7 +369,7 @@ export function attachRoomCore(api, deps, opts = {}) {
369
369
  });
370
370
  /**
371
371
  * One seat route. `leader`: the leader's op, so an operator (`deps.operator`) may act in the
372
- * leader's place; a member's own sit and stand are not. `limited`: it spends `SEAT_OP_RATE_LIMIT`
372
+ * leader's place, reported to `deps.audit`; a member's own sit and stand are not. `limited`: it spends `SEAT_OP_RATE_LIMIT`
373
373
  * (an op on another person or on the room's size); one that touches only the caller's own seat or
374
374
  * an open one never does, as a leader filling a pod with the AI makes a dozen of them in a row.
375
375
  */
@@ -382,7 +382,11 @@ export function attachRoomCore(api, deps, opts = {}) {
382
382
  const caller = callerOf(req);
383
383
  if (how.limited && !seatOpLimit(caller.id, res))
384
384
  return;
385
- const result = run(String(req.params.id), caller.id, body.value, how.leader && deps.operator?.(req) === true);
385
+ const id = String(req.params.id);
386
+ const override = how.leader && deps.operator?.(req) === true;
387
+ const result = run(id, caller.id, body.value, override);
388
+ if (override)
389
+ deps.audit?.(req, path.replaceAll('/', '-'), id, { ...body.value, ok: result.ok, ...(result.ok ? {} : { reason: result.reason }) });
386
390
  if (!result.ok)
387
391
  return seatOpStatus(res, result.reason);
388
392
  res.json({ ...roomBody(result.room, caller.id), ...('evicted' in result ? { evicted: result.evicted } : {}) });
@@ -3,7 +3,7 @@
3
3
  * match: a queued start's host until its JVM is asked for (`start-queue.ts`), and the host a
4
4
  * placed match talks to while a failed start is placed again (`placement/coordinator.ts`).
5
5
  */
6
- import type { MatchHost } from './host.js';
6
+ import type { MatchHost } from './match-host.js';
7
7
  type Remembered = Parameters<NonNullable<MatchHost<{
8
8
  t: string;
9
9
  }>['remember']>>[0];
@@ -45,7 +45,8 @@
45
45
  * cannot take the box.
46
46
  *
47
47
  * Nothing outside this file knows a JVM exists: `match.ts` sees a `MatchHost` — send a command,
48
- * get lines back, stop — and a `MatchHostFactory` makes one.
48
+ * get lines back, stop — and a `MatchHostFactory` makes one (`match-host.ts`, the contract every
49
+ * runtime speaks).
49
50
  *
50
51
  * ## A match outlives its server (Wave 22, §E)
51
52
  *
@@ -122,213 +123,7 @@
122
123
  */
123
124
  import type { JvmLauncher } from './jvm-transport.js';
124
125
  import { type JvmHostConfig } from './local-jvm.js';
125
- export interface SeatSpec {
126
- /** Forge's player name. Shown to both seats, so never an identity. */
127
- name: string;
128
- ai: boolean;
129
- }
130
- /**
131
- * A bot game: Forge's AI against Forge's AI, best of `bestOf`, each game drawn past `gameS` seconds
132
- * (`PlayBridge.java`'s `playHeadless`). It runs on the same JVMs as every match and is never a `Match`:
133
- * `play/botgames.ts` reads its lines.
134
- */
135
- export interface HeadlessRules {
136
- bestOf: 1 | 3;
137
- gameS: number;
138
- }
139
- /**
140
- * What a match needs to start, generic over the game `G`'s own extra fields (w119 §C, w120 §K).
141
- * Only `seats` (its length) and {@link MatchSpec.headless} (its presence) are read by this file's
142
- * own coordinator — everything else below is opaque to it: spread onto `config.json`
143
- * (`bridgeConfig`) and kept whole in `JvmRecord`, never interpreted here.
144
- *
145
- * `G`'s default, `unknown` (so `KnownFields & unknown` simplifies back to `KnownFields`), keeps every existing bare `MatchSpec` (no type
146
- * argument) call site reading exactly the shape below. w120 §K moved the four fields that were
147
- * Forge-only in principle AND in practice — `.dck` text (off {@link SeatSpec}), puzzle scenarios
148
- * (`scenario`/`skipOpening`/`restore`) and coin-toss rigging (`chooser`) — out of this base and
149
- * into Magic's own `games/magic/server/src/play/forge-spec.ts` (`ForgeMatchSpec`/`ForgeSeatSpec`),
150
- * which every Magic reader of a real match's spec now imports instead of this bare type:
151
- * `match.ts` (`SeatSpecWithIdentity`/`MatchSpecWithIdentity`), `botgames.ts`, `parked.ts`,
152
- * `deck-colors.ts`, `table-game.ts`, `art.ts`, `recording/{recorder,rebuild}.ts`,
153
- * `match/{registry,forge-session}.ts`, `socket.ts`, `http/routes.ts`. `format`, `handSmoothing`,
154
- * `clockMs`, `seed` and `headless` stay here: none of the four were named by the brief, each is
155
- * arguably generic to any room-hosted game (a format id, a clock, a seed, a bot game), and
156
- * `fixtures/toy-game/*` and `runtimes/relay-match.ts` build a bare `MatchSpec` directly, so moving
157
- * them would widen this change past what was asked. `seats` is a plain array, not the old 2-tuple
158
- * with "seat 0 is never AI" encoded in its type (that rule is `socket.ts`'s/the bridge's to
159
- * enforce, not this type's) — so `runtimes/relay-match.ts`'s pod-sized, no-AI roster needs no
160
- * `as unknown as MatchSpec` to fit it.
161
- */
162
- export type MatchSpec<G = unknown> = {
163
- /** Every seat this match starts with. */
164
- seats: SeatSpec[];
165
- /** A bot game ({@link HeadlessRules}); absent for every match a player plays or watches. */
166
- headless?: HeadlessRules;
167
- /** Seeds Forge's shuffles and the precon pick, for a repeatable test run. Omitted in play. */
168
- seed?: number;
169
- /**
170
- * Opaque per-game resume text, opened and written by `G`'s own `GameAdapter.restoreSpec`
171
- * (`game-adapter.ts`) — never read here. `fixtures/toy-game/rules.ts`'s `playToy` reads its own
172
- * JSON-encoded checkpoint back from this; Magic's `ForgeMatchSpec.scenario`
173
- * (`games/magic/server/src/play/forge-spec.ts`, w120 §K) is the Forge-shaped equivalent, kept
174
- * apart from this generic field because `PlayBridge.java`'s `configFrom` reads `scenario` by
175
- * that exact key, not whatever a non-Forge `G` happens to call its own resume data.
176
- */
177
- resumeData?: string;
178
- /**
179
- * The room's format id (`room/lobby.ts`'s `FormatId`): what a card-name ask is
180
- * narrowed to (`names.ts`). Inert in the JVM — `configFrom` never reads it — and
181
- * kept in `config.json` so a match taken back after a restart still has it.
182
- */
183
- format?: string;
184
- /**
185
- * The room's hand smoothing setting (`room/lobby.ts`'s `RoomSettings`): the
186
- * opening hand is the closer of two to the deck's land ratio, and each
187
- * mulligan's redraw is weighted toward it. `PlayBridge.java`'s `configFrom`
188
- * turns it into Forge's filtered hands. Absent is off, Forge's default — a
189
- * spec built directly, as the jvm suites build theirs, deals what it always did.
190
- */
191
- handSmoothing?: boolean;
192
- /**
193
- * The chess clock: each seat's time left, in ms, when this game starts — a room
194
- * with the clock on carries what the series' last game left (`play/clock.ts`).
195
- * Absent: no clock. Inert in the JVM, like `format`.
196
- */
197
- clockMs?: [number, number];
198
- /**
199
- * When the clock may first run: `'ready'` (absent) as soon as the game waits on a seat, the game
200
- * itself adding any grace; `'seated'` not before every seat's player has been at the game
201
- * (`MatchShell.clockSeated`). Inert in the JVM.
202
- */
203
- clockStart?: 'ready' | 'seated';
204
- } & G;
205
- /**
206
- * The four lines the host and placement read from any engine's own line type `L`; everything else
207
- * is the game's own (w103 §H's pinned shape). Forge's full `BridgeLine` (now `bridge-protocol.ts`)
208
- * narrows onto this through {@link isLifecycle} — TypeScript cannot narrow a generic `L extends {
209
- * t: string }` on its `t` member directly (w100 finding 3.2), so a caller holding an `L` checks
210
- * `isLifecycle(line)` first and reads the narrowed shape, never `line.t === 'ready'` on the bare `L`.
211
- */
212
- export type HostLifecycleLine = {
213
- t: 'ready';
214
- } | {
215
- t: 'fatal';
216
- message: string; /** Where it threw, top frames first, when the runtime knows. */
217
- frames?: readonly string[];
218
- } | {
219
- t: 'frame';
220
- } | {
221
- t: 'snapshot';
222
- };
223
- /** Narrows any engine's line onto the four the host itself understands. See {@link HostLifecycleLine}. */
224
- export declare function isLifecycle<L extends {
225
- t: string;
226
- }>(line: L): line is L & HostLifecycleLine;
227
- /** The latest `snapshot` line a match has had: what a restore starts it from. */
228
- export interface TurnSnapshot {
229
- turn: number;
230
- state: string;
231
- /** The engine's random as the turn began, so a restore replays the turn's shuffles and rolls; absent, the restore rolls afresh. */
232
- rng?: number;
233
- /** What the game held that {@link state} does not; absent or empty is the whole game. */
234
- lossy?: readonly string[];
235
- }
236
- /**
237
- * A bot game's (`MatchSpec.headless`) exit when Forge ended it on its own: the bridge plays the whole
238
- * best-of and stops, so this is the game finishing, never its host failing.
239
- */
240
- export declare const PLAYED_OUT = "played out";
241
- /**
242
- * What a match host tells its match, generic over the engine's own line type `L` (w103 §H's pinned
243
- * shape: Forge instantiates this `HostEvents<BridgeLine>`, `bridge-protocol.ts`).
244
- */
245
- export interface HostEvents<L extends {
246
- t: string;
247
- }, C extends {
248
- t: string;
249
- }> {
250
- line(line: L): void;
251
- /** The host is gone. `reason` says why, for the match's status. */
252
- exit(reason: string): void;
253
- log(entry: Record<string, unknown>): void;
254
- /**
255
- * Replay only (`attach`): a command an EARLIER server had already sent to this
256
- * JVM. Nothing the bridge says records that an ask was answered, so without
257
- * this a resumed match would re-open asks Forge has already returned from.
258
- */
259
- replayed?(command: C): void;
260
- }
261
- /** What a match sends its host, generic over the engine's own command type `C`. */
262
- export interface MatchHost<C extends {
263
- t: string;
264
- }> {
265
- send(command: C): void;
266
- /** Ask the match to stop; force it after a grace period. Idempotent. */
267
- stop(): void;
268
- /**
269
- * Write down what a re-attach or a restore of this match would need that only
270
- * the match knows: its epoch, which participant owns each seat, and its latest
271
- * turn-start snapshot. Absent on a host that cannot outlive the process (the
272
- * replay host in the tests).
273
- */
274
- remember?(state: Durable & {
275
- snapshot?: TurnSnapshot | null;
276
- clockMs?: [number, number];
277
- clockPaused?: boolean;
278
- clockSeated?: boolean;
279
- }): void;
280
- /**
281
- * The server is going down and this match is being LEFT RUNNING. Let go of
282
- * the transport without killing anything and without settling the run
283
- * directory, so the next process can `attach` to it. Absent on a host whose
284
- * JVM cannot outlive us, and false when there was nothing to hand over — the
285
- * caller then owes the seats an explanation instead.
286
- */
287
- handOver?(): boolean;
288
- }
289
- /**
290
- * What a restart needs to resume a match, independent of the engine (w103 §H's pinned shape):
291
- * its epoch, so a re-attached client resyncs on the cursor it holds, and which participant owns
292
- * each seat, so a re-attach cannot seat someone at the wrong hand. `checkpoint` is w105's: a
293
- * per-engine mid-game save, opaque to the host — whatever `GameAdapter.classify`'s `{ t:
294
- * 'checkpoint' }` line carried last (`match/shell.ts`'s `latestCheckpoint`), beside Forge's own
295
- * {@link TurnSnapshot} (`MatchRecord.snapshot`); when the two are the same value, `jvm.json` holds
296
- * it once (`recordEntry`). Absent before a match's first checkpoint. `readJvmRecord`/`hostFace`'s `remember`
297
- * pass through whatever the caller sent, never forcing it to `null` themselves.
298
- */
299
- export interface Durable {
300
- epoch: string;
301
- owners: (string | null)[];
302
- checkpoint?: unknown;
303
- /** What the game keeps beside its board across a restart (Magic's: each seat's own settings), opaque to the host as `checkpoint` is; absent when the game keeps nothing. */
304
- carry?: unknown;
305
- }
306
- /**
307
- * A match an earlier server left running, as `orphans()` offers it: everything a re-attach needs
308
- * and nothing a seat could not already see (`owners` are participant ids, which never leave this
309
- * host). `epoch`/`owners`/`checkpoint` are {@link Durable}'s; `epoch` widens to `null` here (unlike
310
- * `Durable`'s own, always-set `epoch`) because a freshly placed match has none yet — before its
311
- * first `remember()`, it has no durable identity to resume by.
312
- */
313
- export interface MatchRecord extends Pick<Durable, 'owners' | 'checkpoint' | 'carry'> {
314
- matchId: string;
315
- /** The JVM it runs in. */
316
- hostId: string;
317
- startedAt: string;
318
- /** The match's epoch, so a re-attached client resyncs on the cursor it holds. Null before its first `remember()`. */
319
- epoch: string | null;
320
- spec: MatchSpec;
321
- /** The match's latest turn-start snapshot, absent before its first turn. */
322
- snapshot?: TurnSnapshot | null;
323
- /** Each seat's chess-clock time left when the match last wrote this record; absent with no clock. */
324
- clockMs?: [number, number];
325
- /** The room's leader or an operator had paused the chess clock (`ChessClock.pause`); absent while it may run. */
326
- clockPaused?: true;
327
- /** Every seat's player had been at the game, so a `clockStart: 'seated'` clock may run (`MatchShell.clockSeated`). */
328
- clockSeated?: true;
329
- /** When the server that ran it handed its JVM over. */
330
- orphanedAt?: string;
331
- }
126
+ import { type HostEvents, type MatchHost, type MatchHostFactory, type MatchRecord, type ReapResult } from './match-host.js';
332
127
  /** One JVM's record, `<dir>/jvm.json`: what a later server re-attaches it and its matches by. */
333
128
  export interface JvmRecord {
334
129
  hostId: string;
@@ -337,49 +132,6 @@ export interface JvmRecord {
337
132
  orphanedAt?: string;
338
133
  matches: Omit<MatchRecord, 'hostId' | 'orphanedAt'>[];
339
134
  }
340
- /**
341
- * Makes a host for one match. `close`, when present, releases whatever the factory holds between
342
- * matches (an idle JVM); `attachPlay`'s `close()` calls it. `orphans`/`attach` are the re-attach
343
- * seam — a factory whose JVMs cannot outlive the process has neither.
344
- */
345
- export type MatchHostFactory<L extends {
346
- t: string;
347
- }, C extends {
348
- t: string;
349
- }> = ((matchId: string, spec: MatchSpec, events: HostEvents<L, C>) => MatchHost<C>) & {
350
- close?(): void;
351
- /** Matches still running from an earlier server, oldest first. Asked once, at boot. */
352
- orphans?(): Promise<MatchRecord[]>;
353
- /** Take one back: replay its stream into `events` before returning, then hand it live lines. */
354
- attach?(record: MatchRecord, events: HostEvents<L, C>): MatchHost<C>;
355
- /** Leave every live match running for the next process (SIGTERM). */
356
- handOverAll?(): void;
357
- /**
358
- * The last word before `process.exit`: kill every JVM this process still holds with no
359
- * handed-over match, and let go of the rest. Synchronous, immediate, and idempotent — see
360
- * "Going down" in the module header.
361
- */
362
- reapOnExit?(): ReapResult;
363
- /**
364
- * Where a match placed now would go, for `start-queue.ts`: into a warm JVM with room (it starts
365
- * at once), into one still booting, nowhere yet (placing it launches a JVM), or nowhere at all
366
- * (`full`: no host may take it now; it waits until `watchRoom` says otherwise).
367
- */
368
- room?(): 'warm' | 'booting' | 'none' | 'full';
369
- /** JVMs booting now. */
370
- booting?(): number;
371
- /** Called whenever `room()` or `booting()` may have changed. */
372
- watchRoom?(listener: () => void): void;
373
- };
374
- /** What `reapOnExit` did, by JVM host id, for the shutdown log. */
375
- export interface ReapResult {
376
- /** Confirmed gone because we killed them, and their run directories settled. */
377
- killed: string[];
378
- /** Already gone, or handed over. Nothing to do and nothing owed. */
379
- kept: string[];
380
- /** Still running after the kill. A leak, said out loud — the boot sweep is the next chance. */
381
- left: string[];
382
- }
383
135
  /** See "The ceiling" in the module header. Also `PlayDeps.maxMatches`'s default. */
384
136
  export declare const MAX_CONCURRENT_MATCHES = 50;
385
137
  /** See "Liveness" in the module header. */
package/dist/play/host.js CHANGED
@@ -45,7 +45,8 @@
45
45
  * cannot take the box.
46
46
  *
47
47
  * Nothing outside this file knows a JVM exists: `match.ts` sees a `MatchHost` — send a command,
48
- * get lines back, stop — and a `MatchHostFactory` makes one.
48
+ * get lines back, stop — and a `MatchHostFactory` makes one (`match-host.ts`, the contract every
49
+ * runtime speaks).
49
50
  *
50
51
  * ## A match outlives its server (Wave 22, §E)
51
52
  *
@@ -126,16 +127,7 @@ import { join } from 'node:path';
126
127
  import { writeFileAtomicSync } from '@wolffm/host-wire';
127
128
  import { jsonLogger } from '@wolffm/service-kernel/log';
128
129
  import { JVM_HEAP_MB, MATCHES_PER_JVM, RUN_DIR_NAME, localJvmLauncher } from './local-jvm.js';
129
- const LIFECYCLE_T = new Set(['ready', 'fatal', 'frame', 'snapshot']);
130
- /** Narrows any engine's line onto the four the host itself understands. See {@link HostLifecycleLine}. */
131
- export function isLifecycle(line) {
132
- return LIFECYCLE_T.has(line.t);
133
- }
134
- /**
135
- * A bot game's (`MatchSpec.headless`) exit when Forge ended it on its own: the bridge plays the whole
136
- * best-of and stops, so this is the game finishing, never its host failing.
137
- */
138
- export const PLAYED_OUT = 'played out';
130
+ import { PLAYED_OUT } from './match-host.js';
139
131
  /** See "The ceiling" in the module header. Also `PlayDeps.maxMatches`'s default. */
140
132
  export const MAX_CONCURRENT_MATCHES = 50;
141
133
  /** See "Liveness" in the module header. */
@@ -11,7 +11,7 @@
11
11
  * Moved out of `play/match.ts` (a pure move — no behaviour changed, every importer
12
12
  * rewritten, no shim): `match.ts` keeps `Match`, Forge's own `HostedMatch`.
13
13
  */
14
- import type { HostEvents, MatchHost, MatchHostFactory, MatchSpec, TurnSnapshot } from '../host.js';
14
+ import type { HostEvents, MatchHost, MatchHostFactory, MatchSpec, TurnSnapshot } from '../match-host.js';
15
15
  import type { StartEvents } from '../start-queue.js';
16
16
  import { MatchShell, type ShellDeps } from './shell.js';
17
17
  /** What any `HostedMatch` needs beyond {@link ShellDeps}: a factory for the host its own engine runs on. */
@@ -11,7 +11,7 @@
11
11
  import { type ParticipantId } from '@wolffm/rooms-protocol';
12
12
  import { ChessClock } from '../clock.js';
13
13
  import type { GameSession } from '../game-adapter.js';
14
- import type { MatchHost, MatchSpec, TurnSnapshot } from '../host.js';
14
+ import type { MatchHost, MatchSpec, TurnSnapshot } from '../match-host.js';
15
15
  import type { MatchStatus } from './outcome.js';
16
16
  export type ClaimOutcome = {
17
17
  ok: true;
@@ -0,0 +1,254 @@
1
+ /**
2
+ * The match runtime contract: what a match needs to start (`MatchSpec`), what its host tells it
3
+ * (`HostEvents`) and what it sends back (`MatchHost`), what a restart needs to resume it (`Durable`,
4
+ * `MatchRecord`), and the factory that makes a host for each match (`MatchHostFactory`).
5
+ *
6
+ * Every runtime speaks it: the Forge JVM pool (`host.ts`), the in-process host
7
+ * (`runtimes/in-process.ts`), the relay (`runtimes/relay-match.ts`) and the start queue's deferred
8
+ * host (`start-queue.ts`, `deferred-host.ts`). It lives apart from the pool so that none of them,
9
+ * nor the generic match code (`match/`), loads the JVM pool to read a type.
10
+ */
11
+ export interface SeatSpec {
12
+ /** Forge's player name. Shown to both seats, so never an identity. */
13
+ name: string;
14
+ ai: boolean;
15
+ }
16
+ /**
17
+ * A bot game: Forge's AI against Forge's AI, best of `bestOf`, each game drawn past `gameS` seconds
18
+ * (`PlayBridge.java`'s `playHeadless`). It runs on the same JVMs as every match and is never a `Match`:
19
+ * `play/botgames.ts` reads its lines.
20
+ */
21
+ export interface HeadlessRules {
22
+ bestOf: 1 | 3;
23
+ gameS: number;
24
+ }
25
+ /**
26
+ * What a match needs to start, generic over the game `G`'s own extra fields. Only `seats` (its
27
+ * length) and {@link MatchSpec.headless} (its presence) are read by the JVM pool (`host.ts`) —
28
+ * everything else below is opaque to it: spread onto `config.json` (`bridgeConfig`) and kept whole
29
+ * in `JvmRecord`, never interpreted there.
30
+ *
31
+ * `G`'s default, `unknown` (so `KnownFields & unknown` simplifies back to `KnownFields`), keeps every
32
+ * bare `MatchSpec` (no type argument) reading exactly the shape below. What only Forge reads — a
33
+ * seat's `.dck` text, puzzle scenarios (`scenario`/`skipOpening`/`restore`) and coin-toss rigging
34
+ * (`chooser`) — is Magic's own `games/magic/server/src/play/forge-spec.ts`
35
+ * (`ForgeMatchSpec`/`ForgeSeatSpec`), which every Magic reader of a real match's spec imports
36
+ * instead of this bare type. `format`, `handSmoothing`, `clockMs`, `seed` and `headless` are here
37
+ * because each is generic to any room-hosted game (a format id, a clock, a seed, a bot game), and
38
+ * `fixtures/toy-game/*` and `runtimes/relay-match.ts` build a bare `MatchSpec` directly. `seats` is
39
+ * a plain array, with no "seat 0 is never AI" in its type (that rule is `socket.ts`'s and the
40
+ * bridge's to enforce), so `runtimes/relay-match.ts`'s pod-sized, no-AI roster fits it as it is.
41
+ */
42
+ export type MatchSpec<G = unknown> = {
43
+ /** Every seat this match starts with. */
44
+ seats: SeatSpec[];
45
+ /** A bot game ({@link HeadlessRules}); absent for every match a player plays or watches. */
46
+ headless?: HeadlessRules;
47
+ /** Seeds Forge's shuffles and the precon pick, for a repeatable test run. Omitted in play. */
48
+ seed?: number;
49
+ /**
50
+ * Opaque per-game resume text, opened and written by `G`'s own `GameAdapter.restoreSpec`
51
+ * (`game-adapter.ts`) — never read here. `fixtures/toy-game/rules.ts`'s `playToy` reads its own
52
+ * JSON-encoded checkpoint back from this; Magic's `ForgeMatchSpec.scenario`
53
+ * (`games/magic/server/src/play/forge-spec.ts`) is the Forge-shaped equivalent, kept
54
+ * apart from this generic field because `PlayBridge.java`'s `configFrom` reads `scenario` by
55
+ * that exact key, not whatever a non-Forge `G` happens to call its own resume data.
56
+ */
57
+ resumeData?: string;
58
+ /**
59
+ * The room's format id (`room/format-id.ts`'s `FormatId`): what a card-name ask is
60
+ * narrowed to (`names.ts`). Inert in the JVM — `configFrom` never reads it — and
61
+ * kept in `config.json` so a match taken back after a restart still has it.
62
+ */
63
+ format?: string;
64
+ /**
65
+ * The room's hand smoothing setting (`@hadoku/shared`'s `RoomSettings`): the
66
+ * opening hand is the closer of two to the deck's land ratio, and each
67
+ * mulligan's redraw is weighted toward it. `PlayBridge.java`'s `configFrom`
68
+ * turns it into Forge's filtered hands. Absent is off, Forge's default — a
69
+ * spec built directly, as the jvm suites build theirs, deals what it always did.
70
+ */
71
+ handSmoothing?: boolean;
72
+ /**
73
+ * The chess clock: each seat's time left, in ms, when this game starts — a room
74
+ * with the clock on carries what the series' last game left (`play/clock.ts`).
75
+ * Absent: no clock. Inert in the JVM, like `format`.
76
+ */
77
+ clockMs?: [number, number];
78
+ /**
79
+ * When the clock may first run: `'ready'` (absent) as soon as the game waits on a seat, the game
80
+ * itself adding any grace; `'seated'` not before every seat's player has been at the game
81
+ * (`MatchShell.clockSeated`). Inert in the JVM.
82
+ */
83
+ clockStart?: 'ready' | 'seated';
84
+ } & G;
85
+ /**
86
+ * The four lines the host and placement read from any engine's own line type `L`; everything else
87
+ * is the game's own. Forge's full `BridgeLine` (`bridge-protocol.ts`) narrows onto this through
88
+ * {@link isLifecycle} — TypeScript cannot narrow a generic `L extends { t: string }` on its `t`
89
+ * member directly, so a caller holding an `L` checks `isLifecycle(line)` first and reads the
90
+ * narrowed shape, never `line.t === 'ready'` on the bare `L`.
91
+ */
92
+ export type HostLifecycleLine = {
93
+ t: 'ready';
94
+ } | {
95
+ t: 'fatal';
96
+ message: string; /** Where it threw, top frames first, when the runtime knows. */
97
+ frames?: readonly string[];
98
+ } | {
99
+ t: 'frame';
100
+ } | {
101
+ t: 'snapshot';
102
+ };
103
+ /** Narrows any engine's line onto the four the host itself understands. See {@link HostLifecycleLine}. */
104
+ export declare function isLifecycle<L extends {
105
+ t: string;
106
+ }>(line: L): line is L & HostLifecycleLine;
107
+ /** The latest `snapshot` line a match has had: what a restore starts it from. */
108
+ export interface TurnSnapshot {
109
+ turn: number;
110
+ state: string;
111
+ /** The engine's random as the turn began, so a restore replays the turn's shuffles and rolls; absent, the restore rolls afresh. */
112
+ rng?: number;
113
+ /** What the game held that {@link state} does not; absent or empty is the whole game. */
114
+ lossy?: readonly string[];
115
+ }
116
+ /**
117
+ * A bot game's (`MatchSpec.headless`) exit when Forge ended it on its own: the bridge plays the whole
118
+ * best-of and stops, so this is the game finishing, never its host failing.
119
+ */
120
+ export declare const PLAYED_OUT = "played out";
121
+ /**
122
+ * What a match host tells its match, generic over the engine's own line type `L` (Forge
123
+ * instantiates this `HostEvents<BridgeLine>`, `bridge-protocol.ts`).
124
+ */
125
+ export interface HostEvents<L extends {
126
+ t: string;
127
+ }, C extends {
128
+ t: string;
129
+ }> {
130
+ line(line: L): void;
131
+ /** The host is gone. `reason` says why, for the match's status. */
132
+ exit(reason: string): void;
133
+ log(entry: Record<string, unknown>): void;
134
+ /**
135
+ * Replay only (`attach`): a command an EARLIER server had already sent to this
136
+ * JVM. Nothing the bridge says records that an ask was answered, so without
137
+ * this a resumed match would re-open asks Forge has already returned from.
138
+ */
139
+ replayed?(command: C): void;
140
+ }
141
+ /** What a match sends its host, generic over the engine's own command type `C`. */
142
+ export interface MatchHost<C extends {
143
+ t: string;
144
+ }> {
145
+ send(command: C): void;
146
+ /** Ask the match to stop; force it after a grace period. Idempotent. */
147
+ stop(): void;
148
+ /**
149
+ * Write down what a re-attach or a restore of this match would need that only
150
+ * the match knows: its epoch, which participant owns each seat, and its latest
151
+ * turn-start snapshot. Absent on a host that cannot outlive the process (the
152
+ * replay host in the tests).
153
+ */
154
+ remember?(state: Durable & {
155
+ snapshot?: TurnSnapshot | null;
156
+ clockMs?: [number, number];
157
+ clockPaused?: boolean;
158
+ clockSeated?: boolean;
159
+ }): void;
160
+ /**
161
+ * The server is going down and this match is being LEFT RUNNING. Let go of
162
+ * the transport without killing anything and without settling the run
163
+ * directory, so the next process can `attach` to it. Absent on a host whose
164
+ * JVM cannot outlive us, and false when there was nothing to hand over — the
165
+ * caller then owes the seats an explanation instead.
166
+ */
167
+ handOver?(): boolean;
168
+ }
169
+ /**
170
+ * What a restart needs to resume a match, independent of the engine: its epoch, so a re-attached
171
+ * client resyncs on the cursor it holds, and which participant owns each seat, so a re-attach
172
+ * cannot seat someone at the wrong hand. `checkpoint` is a per-engine mid-game save, opaque to the
173
+ * host — whatever `GameAdapter.classify`'s `{ t: 'checkpoint' }` line carried last
174
+ * (`match/shell.ts`'s `latestCheckpoint`), beside Forge's own {@link TurnSnapshot}
175
+ * (`MatchRecord.snapshot`); when the two are the same value, `jvm.json` holds it once (`host.ts`'s
176
+ * `recordEntry`). Absent before a match's first checkpoint. `host.ts`'s `readJvmRecord` and
177
+ * `remember` pass through whatever the caller sent, never forcing it to `null` themselves.
178
+ */
179
+ export interface Durable {
180
+ epoch: string;
181
+ owners: (string | null)[];
182
+ checkpoint?: unknown;
183
+ /** What the game keeps beside its board across a restart (Magic's: each seat's own settings), opaque to the host as `checkpoint` is; absent when the game keeps nothing. */
184
+ carry?: unknown;
185
+ }
186
+ /**
187
+ * A match an earlier server left running, as `orphans()` offers it: everything a re-attach needs
188
+ * and nothing a seat could not already see (`owners` are participant ids, which never leave this
189
+ * host). `epoch`/`owners`/`checkpoint` are {@link Durable}'s; `epoch` widens to `null` here (unlike
190
+ * `Durable`'s own, always-set `epoch`) because a freshly placed match has none yet — before its
191
+ * first `remember()`, it has no durable identity to resume by.
192
+ */
193
+ export interface MatchRecord extends Pick<Durable, 'owners' | 'checkpoint' | 'carry'> {
194
+ matchId: string;
195
+ /** The JVM it runs in. */
196
+ hostId: string;
197
+ startedAt: string;
198
+ /** The match's epoch, so a re-attached client resyncs on the cursor it holds. Null before its first `remember()`. */
199
+ epoch: string | null;
200
+ spec: MatchSpec;
201
+ /** The match's latest turn-start snapshot, absent before its first turn. */
202
+ snapshot?: TurnSnapshot | null;
203
+ /** Each seat's chess-clock time left when the match last wrote this record; absent with no clock. */
204
+ clockMs?: [number, number];
205
+ /** The room's leader or an operator had paused the chess clock (`ChessClock.pause`); absent while it may run. */
206
+ clockPaused?: true;
207
+ /** Every seat's player had been at the game, so a `clockStart: 'seated'` clock may run (`MatchShell.clockSeated`). */
208
+ clockSeated?: true;
209
+ /** When the server that ran it handed its JVM over. */
210
+ orphanedAt?: string;
211
+ }
212
+ /**
213
+ * Makes a host for one match. `close`, when present, releases whatever the factory holds between
214
+ * matches (an idle JVM); `attachPlay`'s `close()` calls it. `orphans`/`attach` are the re-attach
215
+ * seam — a factory whose JVMs cannot outlive the process has neither.
216
+ */
217
+ export type MatchHostFactory<L extends {
218
+ t: string;
219
+ }, C extends {
220
+ t: string;
221
+ }> = ((matchId: string, spec: MatchSpec, events: HostEvents<L, C>) => MatchHost<C>) & {
222
+ close?(): void;
223
+ /** Matches still running from an earlier server, oldest first. Asked once, at boot. */
224
+ orphans?(): Promise<MatchRecord[]>;
225
+ /** Take one back: replay its stream into `events` before returning, then hand it live lines. */
226
+ attach?(record: MatchRecord, events: HostEvents<L, C>): MatchHost<C>;
227
+ /** Leave every live match running for the next process (SIGTERM). */
228
+ handOverAll?(): void;
229
+ /**
230
+ * The last word before `process.exit`: kill every JVM this process still holds with no
231
+ * handed-over match, and let go of the rest. Synchronous, immediate, and idempotent — see
232
+ * "Going down" in `host.ts`'s header.
233
+ */
234
+ reapOnExit?(): ReapResult;
235
+ /**
236
+ * Where a match placed now would go, for `start-queue.ts`: into a warm JVM with room (it starts
237
+ * at once), into one still booting, nowhere yet (placing it launches a JVM), or nowhere at all
238
+ * (`full`: no host may take it now; it waits until `watchRoom` says otherwise).
239
+ */
240
+ room?(): 'warm' | 'booting' | 'none' | 'full';
241
+ /** JVMs booting now. */
242
+ booting?(): number;
243
+ /** Called whenever `room()` or `booting()` may have changed. */
244
+ watchRoom?(listener: () => void): void;
245
+ };
246
+ /** What `reapOnExit` did, by JVM host id, for the shutdown log. */
247
+ export interface ReapResult {
248
+ /** Confirmed gone because we killed them, and their run directories settled. */
249
+ killed: string[];
250
+ /** Already gone, or handed over. Nothing to do and nothing owed. */
251
+ kept: string[];
252
+ /** Still running after the kill. A leak, said out loud — the boot sweep is the next chance. */
253
+ left: string[];
254
+ }
@@ -0,0 +1,20 @@
1
+ /**
2
+ * The match runtime contract: what a match needs to start (`MatchSpec`), what its host tells it
3
+ * (`HostEvents`) and what it sends back (`MatchHost`), what a restart needs to resume it (`Durable`,
4
+ * `MatchRecord`), and the factory that makes a host for each match (`MatchHostFactory`).
5
+ *
6
+ * Every runtime speaks it: the Forge JVM pool (`host.ts`), the in-process host
7
+ * (`runtimes/in-process.ts`), the relay (`runtimes/relay-match.ts`) and the start queue's deferred
8
+ * host (`start-queue.ts`, `deferred-host.ts`). It lives apart from the pool so that none of them,
9
+ * nor the generic match code (`match/`), loads the JVM pool to read a type.
10
+ */
11
+ const LIFECYCLE_T = new Set(['ready', 'fatal', 'frame', 'snapshot']);
12
+ /** Narrows any engine's line onto the four the host itself understands. See {@link HostLifecycleLine}. */
13
+ export function isLifecycle(line) {
14
+ return LIFECYCLE_T.has(line.t);
15
+ }
16
+ /**
17
+ * A bot game's (`MatchSpec.headless`) exit when Forge ended it on its own: the bridge plays the whole
18
+ * best-of and stops, so this is the game finishing, never its host failing.
19
+ */
20
+ export const PLAYED_OUT = 'played out';
@@ -12,7 +12,7 @@
12
12
  * own `MatchSpec`, because `host.ts` only ever hosts Forge. {@link GameHostFactory} is that one
13
13
  * further step, for a game whose config is not a `MatchSpec` at all.
14
14
  */
15
- import type { HostEvents, MatchHost } from '../host.js';
15
+ import type { HostEvents, MatchHost } from '../match-host.js';
16
16
  /** A line or a command from any engine: `t` is the one thing every engine's own vocabulary agrees on. */
17
17
  type EngineMsg = {
18
18
  t: string;
@@ -22,7 +22,7 @@
22
22
  import type { ParticipantId } from '@wolffm/rooms-protocol';
23
23
  import { HostedMatch, type HostedMatchDeps } from '../match/hosted.js';
24
24
  import type { ShellSeat } from '../match/shell.js';
25
- import type { MatchHostFactory } from '../host.js';
25
+ import type { MatchHostFactory } from '../match-host.js';
26
26
  import type { RelayRoster } from '../relay-socket.js';
27
27
  import { RelaySession, type RelayCommand, type RelayLine, type RelayOutcome, type RelaySink } from './relay.js';
28
28
  /** What `RelayMatch`'s own constructor is handed: {@link HostedMatchDeps} with `host` always
@@ -25,7 +25,7 @@
25
25
  * goes at once. Re-attach (`attach`) is not a start and passes straight through, as does
26
26
  * everything else on the factory.
27
27
  */
28
- import type { HostEvents, MatchHostFactory } from './host.js';
28
+ import type { HostEvents, MatchHostFactory } from './match-host.js';
29
29
  /**
30
30
  * JVMs booting at once before a start that needs another waits. A lone boot on a claw under CI
31
31
  * load took 7.8–10.5 s and ten together ~50 s, so two keeps one well inside the 60 s start timeout
@@ -226,10 +226,6 @@ export async function startRelayGame(options) {
226
226
  res.status(503).type('text').send(s.missing);
227
227
  });
228
228
  }
229
- // The embed's own files are the static bundle's; anything else under it is no page.
230
- ctx.app.use('/embed', (_req, res) => {
231
- res.status(404).type('text').send('no such embed file');
232
- });
233
229
  attachPage(ctx.app, {
234
230
  indexHtml: join(config.webDir, 'index.html'),
235
231
  basePath: ctx.bundle,
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@hadoku/game-server",
3
- "version": "0.1.230",
4
- "gitHead": "eff3ab2cbc75ee1d70fa3a3c7ad603d9e5fcfe5d",
3
+ "version": "0.1.232",
4
+ "gitHead": "9a4bbf57b928ce97f231236cd229ab27320e3095",
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.",
@@ -16,9 +16,9 @@
16
16
  "play/remote/"
17
17
  ],
18
18
  "dependencies": {
19
- "@wolffm/host-wire": "npm:@hadoku/host-wire@0.1.230",
20
- "@wolffm/platform-wire": "npm:@hadoku/platform-wire@0.1.230",
21
- "@wolffm/service-kernel": "npm:@hadoku/service-kernel@0.1.263",
19
+ "@wolffm/host-wire": "npm:@hadoku/host-wire@0.1.232",
20
+ "@wolffm/platform-wire": "npm:@hadoku/platform-wire@0.1.232",
21
+ "@wolffm/service-kernel": "npm:@hadoku/service-kernel@0.1.265",
22
22
  "@wolffm/prefs-client": "npm:@hadoku/prefs-client@^1.2.3",
23
23
  "@wolffm/rooms-protocol": "npm:@hadoku/rooms-protocol@^0.45.152",
24
24
  "@wolffm/rooms-server": "npm:@hadoku/rooms-server@^0.45.152",