@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
@@ -0,0 +1,148 @@
1
+ /**
2
+ * The streamed desktop (Forge's own GUI, in a container — `../../stream/**`), described in the same
3
+ * vocabulary every other engine this host runs is: an `EngineRuntime` (`../engine-runtime.ts`), and
4
+ * the "start it, track it, a failed start is the match's fatal, tear it down" shape any engine's
5
+ * host needs. `stream/alloc.ts` already provisions and reclaims a room's containers; this file is
6
+ * what turns that into the same start/track/stop vocabulary, and `plugins/stream.ts` (the one
7
+ * caller, in `ensureRoomStreams`) is wired through it rather than calling `RoomStreams.allocate`
8
+ * directly.
9
+ *
10
+ * ## The Magic config
11
+ *
12
+ * `scripts/stream/container.sh` mounts one Forge jar and one `res/` into every container it
13
+ * starts; which jar and which res were, until now, resolved by the SCRIPT's own bash defaulting
14
+ * (`CARDTABLE_STREAM_FORGE_JAR`, falling back through `CARDTABLE_FORGE_RES`) — a Magic-specific
15
+ * concern baked into the one script every container goes through, and invisible to anything that
16
+ * does not read the script. {@link streamedEngineConfig} resolves and validates the same two paths
17
+ * in TypeScript instead, mirroring `local-jvm.ts`'s `jvmHostConfig`; `plugins/stream.ts` hands the
18
+ * result to `scriptRunner` as explicit `env`, so the jar/res a log line can name is what every `up`
19
+ * call actually mounts, never a different one the script's own bash default happened to find.
20
+ * `stream/alloc.ts` and `stream/index.ts` — the platform allocator — import neither this file's
21
+ * env names nor any Forge path; only this file and `plugins/stream.ts` (the composition point) do.
22
+ *
23
+ * ## Not a `child_process.spawn`
24
+ *
25
+ * A streamed desktop's "process" is a docker container `scripts/stream/container.sh` starts; this
26
+ * server never forks it directly, so {@link streamedEngineRuntime}'s `argv` returns nothing and it
27
+ * leaves `spawn` unset — `EngineRuntime.spawn` is optional for exactly this case (see
28
+ * `engine-runtime.ts`'s own doc). `perProcess` is 1: one container is one seat, with none of the
29
+ * Forge JVM pool's sharing (a streamed room gets one container per seat; a shared screen is
30
+ * cheaper and is not a game).
31
+ *
32
+ * ## Tracked, not pooled through `host.ts`
33
+ *
34
+ * `host.ts`/`match.ts` still place every Forge match through `localJvmLauncher`'s `JvmLauncher`;
35
+ * a streamed desktop has no bridge-line protocol for that coordinator to speak to in the first
36
+ * place (the player's input goes straight to Forge over noVNC, not through this server), so
37
+ * {@link streamedHost} is tracked by `plugins/stream.ts` itself (`state.streamedHosts`) rather than
38
+ * through `host.ts`'s match pool. `stream/alloc.ts`'s own `destroy()` — the one place a room's
39
+ * containers actually come down, whether asked for or reclaimed idle — reports back through
40
+ * `RoomStreamsOptions.onEnded`, which `plugins/stream.ts` wires to the matching host's `settled()`,
41
+ * so every ending reaches this file's vocabulary, not only an explicit `stop()`.
42
+ */
43
+ import { existsSync } from 'node:fs';
44
+ import { resolve } from 'node:path';
45
+ /** Measured 2026-09-19, `docs/spikes/streaming.md`, "the host" section: "Budget 1.3 GiB per streamed desktop." */
46
+ export const STREAMED_CONTAINER_MB = 1331;
47
+ /**
48
+ * Resolve the streamed desktop's Magic config from the environment, validated the way
49
+ * `jvmHostConfig` (`../local-jvm.ts`) validates the JVM pool's: a missing or malformed jar/res is a
50
+ * reason, not a guess. `CARDTABLE_STREAM_FORGE_JAR`/`_RES` name the container's own copy, falling
51
+ * back to the pool's `CARDTABLE_FORGE_JAR`/`_RES` when the container has none of its own — exactly
52
+ * the fallback chain `scripts/stream/container.sh`'s bash already encodes, so this and the script
53
+ * can never resolve a different jar from the same environment.
54
+ */
55
+ export function streamedEngineConfig(env = process.env) {
56
+ const jar = env.CARDTABLE_STREAM_FORGE_JAR ?? env.CARDTABLE_FORGE_JAR ?? '';
57
+ const res = env.CARDTABLE_STREAM_FORGE_RES ?? env.CARDTABLE_FORGE_RES ?? '';
58
+ if (jar === '')
59
+ return { ok: false, reason: 'neither CARDTABLE_STREAM_FORGE_JAR nor CARDTABLE_FORGE_JAR is set' };
60
+ if (!existsSync(jar))
61
+ return { ok: false, reason: `no Forge jar for the streamed desktop at ${jar}` };
62
+ if (res === '')
63
+ return { ok: false, reason: 'neither CARDTABLE_STREAM_FORGE_RES nor CARDTABLE_FORGE_RES is set' };
64
+ if (!existsSync(resolve(res, 'cardsfolder'))) {
65
+ return { ok: false, reason: `CARDTABLE_STREAM_FORGE_RES/CARDTABLE_FORGE_RES is not Forge's res/ (no cardsfolder): ${res}` };
66
+ }
67
+ return { ok: true, config: { forgeJar: resolve(jar), forgeRes: resolve(res) } };
68
+ }
69
+ /**
70
+ * What `scripts/stream/container.sh` reads to find the Forge it mounts, resolved HERE rather than
71
+ * left to its own bash fallback. `plugins/stream.ts` hands this to `scriptRunner`'s `env`, so the
72
+ * jar/res this process validated ({@link streamedEngineConfig}) is exactly what every `up` call
73
+ * mounts.
74
+ */
75
+ export function streamedContainerEnv(config) {
76
+ return { CARDTABLE_STREAM_FORGE_JAR: config.forgeJar, CARDTABLE_STREAM_FORGE_RES: config.forgeRes };
77
+ }
78
+ /**
79
+ * `EngineRuntime` (`../engine-runtime.ts`) for the streamed desktop: what it costs, in the same
80
+ * vocabulary the JVM pool's `forgeEngineRuntime` (`../local-jvm.ts`) uses, so a reader comparing
81
+ * the two engines this host runs sees one shape, not two. `argv`/`spawn` are left as the
82
+ * interface's own no-op/unset for an engine whose process is a container, not something this
83
+ * server forks — see the module header, "Not a `child_process.spawn`".
84
+ */
85
+ export function streamedEngineRuntime(config) {
86
+ return {
87
+ artifacts: { jar: config.forgeJar, res: config.forgeRes },
88
+ // Nothing here builds a java command line: the container's own entrypoint launches Forge's
89
+ // desktop itself from the jar/res it was handed as a mount, not an argv this process picks.
90
+ argv: () => [],
91
+ overheadMb: STREAMED_CONTAINER_MB,
92
+ // One seat, one container, always — unlike the JVM pool's `MATCHES_PER_JVM`, nothing shares.
93
+ perProcess: 1,
94
+ // `stream/alloc.ts`'s own idle/room-gone sweep is this engine's recycle policy; a crashed
95
+ // container looks the same as a reclaimed one to the allocator (both just stop answering
96
+ // `portOf`), so this hook has nothing further to add.
97
+ health: () => ({ recycle: false }),
98
+ };
99
+ }
100
+ /**
101
+ * Starts (or finds already-live) a room's seats' containers through `rooms`
102
+ * (`../../stream/alloc.ts`'s `RoomStreams`), and reports back in {@link StreamedHostEvents}'s
103
+ * vocabulary: a failed provision is `events.fatal`, exactly as a JVM's `{ t: 'fatal' }` line is
104
+ * `match.fail`'s trigger today. `stop()` releases them through `rooms.release` — `stream/alloc.ts`'s
105
+ * own teardown, never a second path that could disagree with it about what "torn down" means — and
106
+ * {@link StreamedMatchHost.settled} covers every OTHER way those same containers can end.
107
+ */
108
+ export function streamedHost(rooms, roomKey, seatCount, events) {
109
+ let ended = false;
110
+ let stopping = false;
111
+ const end = (reason) => {
112
+ if (ended)
113
+ return;
114
+ ended = true;
115
+ events.exit(reason);
116
+ };
117
+ void (async () => {
118
+ try {
119
+ const result = await rooms.allocate(roomKey, seatCount);
120
+ if (ended)
121
+ return;
122
+ if (!result.ok) {
123
+ events.fatal(`${result.reason}: ${result.detail}`);
124
+ end(`provisioning failed: ${result.detail}`);
125
+ return;
126
+ }
127
+ events.log({ evt: 'streamed-host-up', room: roomKey, seats: result.allocation.seats.length });
128
+ }
129
+ catch (err) {
130
+ if (ended)
131
+ return;
132
+ const message = err instanceof Error ? err.message : String(err);
133
+ events.fatal(message);
134
+ end(`provisioning failed: ${message}`);
135
+ }
136
+ })();
137
+ return {
138
+ stop() {
139
+ if (ended || stopping)
140
+ return;
141
+ stopping = true;
142
+ void rooms.release(roomKey, 'released').then(() => end('stopped'));
143
+ },
144
+ settled(reason) {
145
+ end(reason);
146
+ },
147
+ };
148
+ }
@@ -0,0 +1,65 @@
1
+ /**
2
+ * Match starts, held back while JVMs boot.
3
+ *
4
+ * A JVM boots in ~10 s alone, but boots share the box's CPU: ten started at once on a claw under
5
+ * CI load took 44.7–52.4 s each (hosting test C7, `docs/planning/hosting-test-plan.md`), the
6
+ * slowest within 8 s of the start timeout. A failover onto the claws is exactly that burst. Since
7
+ * many matches share one JVM (`host.ts`), what costs a boot is a JVM, not a match. So every start
8
+ * goes through here, wrapped around the host factory in `socket.ts`'s `attachPlay` — room starts,
9
+ * rematches, tournament tables, vs-AI and the dev routes all reach Forge through
10
+ * `MatchRegistry.create` → that one factory:
11
+ *
12
+ * - **A start that needs no boot goes at once**: a warm JVM with room starts it now, and one still
13
+ * booting with room starts it the moment it is warm (`room()`).
14
+ * - **A start that would launch a JVM waits while `limit` JVMs are booting already** (`booting()`).
15
+ * The pool's own warm JVM boots among them.
16
+ * - **A start no host may take waits too** (`room()` is `full`: placement found no eligible host,
17
+ * `placement/coordinator.ts`), until the factory's room changes.
18
+ * - **The rest wait in order**, and each is told its place (`StartEvents.queued`) whenever it
19
+ * moves; `Match` keeps it for `GET /play/queue`. A waiting start's host is a stand-in that holds
20
+ * what the match asks of it until the real one exists.
21
+ * - **The start timeout counts from the placement** (`StartEvents.booting`), not from the request:
22
+ * time in the queue is not Forge failing to start.
23
+ *
24
+ * A factory that says nothing about room (a test's replay host) boots nothing, and every start
25
+ * goes at once. Re-attach (`attach`) is not a start and passes straight through, as does
26
+ * everything else on the factory.
27
+ */
28
+ import type { HostEvents, MatchHostFactory } from './host.js';
29
+ /**
30
+ * JVMs booting at once before a start that needs another waits. A lone boot on a claw under CI
31
+ * load took 7.8–10.5 s and ten together ~50 s, so two keeps one well inside the 60 s start timeout
32
+ * while still overlapping the I/O-bound part of a boot.
33
+ */
34
+ export declare const COLD_STARTS = 2;
35
+ /** `CARDTABLE_PLAY_COLD_STARTS`, a whole number ≥ 1; anything else is the default. */
36
+ export declare function coldStartsFrom(env?: NodeJS.ProcessEnv): number;
37
+ /** What a start is told beyond a host's own events. Both optional: a host that boots at once says neither. */
38
+ export interface StartEvents<L extends {
39
+ t: string;
40
+ }, C extends {
41
+ t: string;
42
+ }> extends HostEvents<L, C> {
43
+ /** Waiting for a boot slot, at this 1-based place. Said again each time the place changes. */
44
+ queued?(place: number): void;
45
+ /** The match is being placed now: the start timeout runs from here. */
46
+ booting?(): void;
47
+ /** The factory threw for a start that had waited: the same failure a start that never waited throws to its caller. */
48
+ unstartable?(err: Error): void;
49
+ }
50
+ export type QueuedFactory<L extends {
51
+ t: string;
52
+ }, C extends {
53
+ t: string;
54
+ }> = MatchHostFactory<L, C> & {
55
+ /** JVMs booting now, and starts waiting, for diagnostics and tests. */
56
+ queue(): {
57
+ booting: number;
58
+ waiting: number;
59
+ };
60
+ };
61
+ export declare function queueColdStarts<L extends {
62
+ t: string;
63
+ }, C extends {
64
+ t: string;
65
+ }>(factory: MatchHostFactory<L, C>, limit: number, log: (entry: Record<string, unknown>) => void): QueuedFactory<L, C>;
@@ -0,0 +1,187 @@
1
+ /**
2
+ * Match starts, held back while JVMs boot.
3
+ *
4
+ * A JVM boots in ~10 s alone, but boots share the box's CPU: ten started at once on a claw under
5
+ * CI load took 44.7–52.4 s each (hosting test C7, `docs/planning/hosting-test-plan.md`), the
6
+ * slowest within 8 s of the start timeout. A failover onto the claws is exactly that burst. Since
7
+ * many matches share one JVM (`host.ts`), what costs a boot is a JVM, not a match. So every start
8
+ * goes through here, wrapped around the host factory in `socket.ts`'s `attachPlay` — room starts,
9
+ * rematches, tournament tables, vs-AI and the dev routes all reach Forge through
10
+ * `MatchRegistry.create` → that one factory:
11
+ *
12
+ * - **A start that needs no boot goes at once**: a warm JVM with room starts it now, and one still
13
+ * booting with room starts it the moment it is warm (`room()`).
14
+ * - **A start that would launch a JVM waits while `limit` JVMs are booting already** (`booting()`).
15
+ * The pool's own warm JVM boots among them.
16
+ * - **A start no host may take waits too** (`room()` is `full`: placement found no eligible host,
17
+ * `placement/coordinator.ts`), until the factory's room changes.
18
+ * - **The rest wait in order**, and each is told its place (`StartEvents.queued`) whenever it
19
+ * moves; `Match` keeps it for `GET /play/queue`. A waiting start's host is a stand-in that holds
20
+ * what the match asks of it until the real one exists.
21
+ * - **The start timeout counts from the placement** (`StartEvents.booting`), not from the request:
22
+ * time in the queue is not Forge failing to start.
23
+ *
24
+ * A factory that says nothing about room (a test's replay host) boots nothing, and every start
25
+ * goes at once. Re-attach (`attach`) is not a start and passes straight through, as does
26
+ * everything else on the factory.
27
+ */
28
+ import { positiveInt } from './engine-runtime.js';
29
+ /**
30
+ * JVMs booting at once before a start that needs another waits. A lone boot on a claw under CI
31
+ * load took 7.8–10.5 s and ten together ~50 s, so two keeps one well inside the 60 s start timeout
32
+ * while still overlapping the I/O-bound part of a boot.
33
+ */
34
+ export const COLD_STARTS = 2;
35
+ /** `CARDTABLE_PLAY_COLD_STARTS`, a whole number ≥ 1; anything else is the default. */
36
+ export function coldStartsFrom(env = process.env) {
37
+ return positiveInt(env.CARDTABLE_PLAY_COLD_STARTS, COLD_STARTS);
38
+ }
39
+ /** A waiting start's host until its JVM is asked for. */
40
+ class WaitingHost {
41
+ leave;
42
+ events;
43
+ host = null;
44
+ held = [];
45
+ remembered = null;
46
+ gone = false;
47
+ constructor(leave, events) {
48
+ this.leave = leave;
49
+ this.events = events;
50
+ }
51
+ /** The real host: everything held goes to it, in order. */
52
+ become(host) {
53
+ this.host = host;
54
+ if (this.remembered !== null)
55
+ host.remember?.(this.remembered);
56
+ for (const command of this.held.splice(0))
57
+ host.send(command);
58
+ }
59
+ /** Never booted: the queue was dropped (the server is closing or handing over). */
60
+ drop(reason) {
61
+ if (this.gone)
62
+ return;
63
+ this.gone = true;
64
+ this.events.exit(reason);
65
+ }
66
+ send(command) {
67
+ if (this.host !== null)
68
+ this.host.send(command);
69
+ else
70
+ this.held.push(command);
71
+ }
72
+ stop() {
73
+ if (this.host !== null) {
74
+ this.host.stop();
75
+ return;
76
+ }
77
+ if (this.gone)
78
+ return;
79
+ this.leave();
80
+ // A host's exit always comes after `stop` returns; so does this one.
81
+ queueMicrotask(() => this.drop('stopped before its JVM started'));
82
+ }
83
+ remember(state) {
84
+ if (this.host !== null)
85
+ this.host.remember?.(state);
86
+ else
87
+ this.remembered = state;
88
+ }
89
+ /** A start still waiting has no JVM to leave running. */
90
+ handOver() {
91
+ return this.host?.handOver?.() ?? false;
92
+ }
93
+ }
94
+ export function queueColdStarts(factory, limit, log) {
95
+ const waiting = [];
96
+ const booting = () => factory.booting?.() ?? 0;
97
+ /** A start may go now: some host may take it, and it needs no boot or another boot fits. */
98
+ const free = () => {
99
+ const room = factory.room?.() ?? 'warm';
100
+ return room !== 'full' && (room !== 'none' || booting() < limit);
101
+ };
102
+ let pumping = false;
103
+ /** Place this match now. Throws what the factory throws. */
104
+ function begin(matchId, spec, events, waitedMs) {
105
+ log({ evt: 'start-booting', matchId, room: factory.room?.() ?? 'warm', booting: booting(), ...(waitedMs === null ? {} : { waitedMs }) });
106
+ events.booting?.();
107
+ return factory(matchId, spec, events);
108
+ }
109
+ /** Start every waiter that may go, in order. Re-entered by a placement's own room change: once is enough. */
110
+ function pump() {
111
+ if (pumping)
112
+ return;
113
+ pumping = true;
114
+ try {
115
+ while (waiting.length > 0 && free()) {
116
+ const next = waiting.shift();
117
+ let host;
118
+ try {
119
+ host = begin(next.matchId, next.spec, next.events, Date.now() - next.since);
120
+ }
121
+ catch (err) {
122
+ next.events.unstartable?.(err);
123
+ next.host.drop(`Forge could not be started: ${err.message}`);
124
+ continue;
125
+ }
126
+ next.host.become(host);
127
+ }
128
+ }
129
+ finally {
130
+ pumping = false;
131
+ }
132
+ for (const [i, w] of waiting.entries()) {
133
+ if (w.place === i + 1)
134
+ continue;
135
+ w.place = i + 1;
136
+ w.events.queued?.(w.place);
137
+ }
138
+ }
139
+ function dropAll(reason) {
140
+ for (const w of waiting.splice(0))
141
+ w.host.drop(reason);
142
+ }
143
+ const queued = ((matchId, spec, events) => {
144
+ if (waiting.length === 0 && free())
145
+ return begin(matchId, spec, events, null);
146
+ const entry = {
147
+ matchId,
148
+ spec,
149
+ events,
150
+ place: 0,
151
+ since: Date.now(),
152
+ host: new WaitingHost(() => {
153
+ const i = waiting.indexOf(entry);
154
+ if (i >= 0)
155
+ waiting.splice(i, 1);
156
+ pump();
157
+ }, events),
158
+ };
159
+ waiting.push(entry);
160
+ log({ evt: 'start-queued', matchId, place: waiting.length, booting: booting(), limit });
161
+ pump();
162
+ return entry.host;
163
+ });
164
+ factory.watchRoom?.(pump);
165
+ queued.queue = () => ({ booting: booting(), waiting: waiting.length });
166
+ if (factory.room !== undefined)
167
+ queued.room = () => factory.room();
168
+ if (factory.booting !== undefined)
169
+ queued.booting = () => factory.booting();
170
+ if (factory.orphans !== undefined)
171
+ queued.orphans = () => factory.orphans();
172
+ if (factory.attach !== undefined)
173
+ queued.attach = (record, events) => factory.attach(record, events);
174
+ queued.close = () => {
175
+ dropAll('the server is closing');
176
+ factory.close?.();
177
+ };
178
+ if (factory.handOverAll !== undefined) {
179
+ queued.handOverAll = () => {
180
+ dropAll('the server is restarting');
181
+ factory.handOverAll();
182
+ };
183
+ }
184
+ if (factory.reapOnExit !== undefined)
185
+ queued.reapOnExit = () => factory.reapOnExit();
186
+ return queued;
187
+ }
@@ -0,0 +1 @@
1
+ export declare function avatarIdOf(v: unknown): string | undefined;
@@ -0,0 +1,28 @@
1
+ /**
2
+ * The one reading of an avatar id, in every direction. Generic to every room:
3
+ * nothing here depends on a game type, a pod or a draft.
4
+ *
5
+ * `@wolffm/rooms-protocol` types it `avatarId?: string | null` (`RosterIdentity`,
6
+ * `LocalIdentity`), so THREE states arrive — absent, explicitly null, a string —
7
+ * and exactly TWO ever leave this file: a non-blank string, or absent. `null`,
8
+ * `''`, whitespace, an over-long value and anything that is not a string all
9
+ * collapse to absent, because to whoever is drawing a face they all mean the
10
+ * same thing (draw the fallback) and a third state on the wire is a third branch
11
+ * in every consumer for no new fact.
12
+ *
13
+ * An EMPTY STRING reaching a client is the specific bug this function exists to
14
+ * stop. It survives a `!== undefined` check and then resolves to a sprite URL
15
+ * ending `square_.png`, which is a 404 drawn as a broken image rather than the
16
+ * fallback the absence would have produced.
17
+ *
18
+ * Split out of `room/lobby.ts` (wave 110 §L), importing `AVATAR_ID_MAX` straight
19
+ * from the platform package that defines it rather than through `@hadoku/shared`'s
20
+ * mixed barrel.
21
+ */
22
+ import { AVATAR_ID_MAX } from '@wolffm/platform-wire/look';
23
+ export function avatarIdOf(v) {
24
+ if (typeof v !== 'string')
25
+ return undefined;
26
+ const trimmed = v.trim();
27
+ return trimmed === '' || trimmed.length > AVATAR_ID_MAX ? undefined : trimmed;
28
+ }
@@ -0,0 +1,21 @@
1
+ /**
2
+ * Who is asking. Generic to every room, whatever it plays: `id` from
3
+ * `identityFromHeaders`, `name` from `userNameOf`, `userId` from
4
+ * `accountIdOf` — the registry userId `id` was minted from, which is what a
5
+ * saved room keeps (R12). null for a caller the edge named nobody, and for
6
+ * the testing seed.
7
+ *
8
+ * Split out of `room/lobby.ts` (wave 110 §L): nothing here names a game
9
+ * type, a pod, a draft or a format, so a non-Magic room (bomberman's) is
10
+ * exactly as much a `Caller` as a Magic one.
11
+ */
12
+ export interface Caller {
13
+ id: string;
14
+ name: string;
15
+ userId: string | null;
16
+ /**
17
+ * The edge's `X-Hadoku-Verified`: the operator verifies this person (`verifiedOf`). Absent is
18
+ * not verified, as the header's own absence is: a restored or synthetic caller verifies nobody.
19
+ */
20
+ verified?: boolean;
21
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,27 @@
1
+ /**
2
+ * Generic room-lifecycle constants, shared by nothing Magic-specific.
3
+ *
4
+ * Moved out of `room/lobby.ts` (split, wave 99 §L) so a platform file
5
+ * (`erase/recordings.ts`, `room/watching.ts`) can read them without an edge
6
+ * into the tangled lobby.
7
+ */
8
+ /**
9
+ * What a member is called before any request of theirs has named them: one restored from a saved
10
+ * room, which keeps no names (R12). The same word the HTTP layer gives a key the edge sent no
11
+ * name for.
12
+ */
13
+ export declare const UNNAMED = "friend";
14
+ /**
15
+ * How long a room may go without a touch before the front page stops
16
+ * OFFERING it (wave 31). The room is not deleted (`ROOM_IDLE_MS` does that, much
17
+ * later); it just stops advertising itself.
18
+ *
19
+ * The operator: *"why are 'hi there' and 'hi there2' still showing up?"* Rooms
20
+ * restore on boot and live twelve hours, and the list prints a room's STORED
21
+ * members, not who is connected, so a dead table looked alive with an Enter
22
+ * button. A room someone has open is touched by its screen's reads and, for as
23
+ * long as the screen stays open, by the room feed (`room/watching.ts`), so "nobody
24
+ * touched it for thirty minutes" means nobody is there. A room with a match or
25
+ * a draft under way is exempt: its players are on another screen.
26
+ */
27
+ export declare const ROOM_STALE_MS: number;
@@ -0,0 +1,27 @@
1
+ /**
2
+ * Generic room-lifecycle constants, shared by nothing Magic-specific.
3
+ *
4
+ * Moved out of `room/lobby.ts` (split, wave 99 §L) so a platform file
5
+ * (`erase/recordings.ts`, `room/watching.ts`) can read them without an edge
6
+ * into the tangled lobby.
7
+ */
8
+ /**
9
+ * What a member is called before any request of theirs has named them: one restored from a saved
10
+ * room, which keeps no names (R12). The same word the HTTP layer gives a key the edge sent no
11
+ * name for.
12
+ */
13
+ export const UNNAMED = 'friend';
14
+ /**
15
+ * How long a room may go without a touch before the front page stops
16
+ * OFFERING it (wave 31). The room is not deleted (`ROOM_IDLE_MS` does that, much
17
+ * later); it just stops advertising itself.
18
+ *
19
+ * The operator: *"why are 'hi there' and 'hi there2' still showing up?"* Rooms
20
+ * restore on boot and live twelve hours, and the list prints a room's STORED
21
+ * members, not who is connected, so a dead table looked alive with an Enter
22
+ * button. A room someone has open is touched by its screen's reads and, for as
23
+ * long as the screen stays open, by the room feed (`room/watching.ts`), so "nobody
24
+ * touched it for thirty minutes" means nobody is there. A room with a match or
25
+ * a draft under way is exempt: its players are on another screen.
26
+ */
27
+ export const ROOM_STALE_MS = 30 * 60_000;
@@ -0,0 +1,59 @@
1
+ import { z } from 'zod';
2
+ declare const EventRecordSchema: z.ZodObject<{
3
+ id: z.ZodString;
4
+ roomId: z.ZodString;
5
+ startsAt: z.ZodNumber;
6
+ organizerId: z.ZodString;
7
+ organizerUserId: z.ZodOptional<z.ZodNullable<z.ZodString>>;
8
+ organizerName: z.ZodOptional<z.ZodString>;
9
+ formId: z.ZodOptional<z.ZodString>;
10
+ createdAt: z.ZodNumber;
11
+ }, z.core.$strip>;
12
+ export type EventRecord = z.infer<typeof EventRecordSchema>;
13
+ declare const FormRecordSchema: z.ZodObject<{
14
+ formId: z.ZodString;
15
+ attachedById: z.ZodString;
16
+ attachedByUserId: z.ZodOptional<z.ZodNullable<z.ZodString>>;
17
+ attachedByName: z.ZodOptional<z.ZodString>;
18
+ attachedAt: z.ZodNumber;
19
+ }, z.core.$strip>;
20
+ export type FormRecord = z.infer<typeof FormRecordSchema>;
21
+ /** An event stays listed this long after it starts: it is still on while people play it. */
22
+ export declare const EVENT_LISTED_AFTER_START_MS: number;
23
+ export type NewEvent = Omit<EventRecord, 'id' | 'createdAt'>;
24
+ export type NewForm = Omit<FormRecord, 'attachedAt'>;
25
+ export type EventChange = {
26
+ ok: true;
27
+ event: EventRecord;
28
+ } | {
29
+ ok: false;
30
+ reason: 'no-event' | 'not-organizer';
31
+ };
32
+ export type FormChange = {
33
+ ok: true;
34
+ } | {
35
+ ok: false;
36
+ reason: 'no-form' | 'not-attacher';
37
+ };
38
+ export interface Events {
39
+ /** Every event not yet `EVENT_LISTED_AFTER_START_MS` past its start, soonest first. */
40
+ upcoming(now: number): EventRecord[];
41
+ get(id: string): EventRecord | undefined;
42
+ create(event: NewEvent, now: number): EventRecord;
43
+ reschedule(id: string, callerId: string, startsAt: number): EventChange;
44
+ cancel(id: string, callerId: string): EventChange;
45
+ /** Every attached form, oldest first. */
46
+ forms(): FormRecord[];
47
+ /** False when the form was already attached. */
48
+ attachForm(form: NewForm, now: number): boolean;
49
+ detachForm(formId: string, callerId: string): FormChange;
50
+ /** Forget forms Rally says are closed or gone: nobody lists them again. */
51
+ forgetForms(formIds: readonly string[]): void;
52
+ /** Account erase: an event they organised and a form they attached keep going under `to`, with no name. Answers how many changed, once saved. */
53
+ anonymise(ids: ReadonlySet<string>, to: string): Promise<{
54
+ events: number;
55
+ forms: number;
56
+ }>;
57
+ }
58
+ export declare function openEvents(file: string, log: (entry: Record<string, unknown>) => void, now?: () => number): Promise<Events>;
59
+ export {};