@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,240 @@
1
+ /**
2
+ * The relay's own `HostedMatch` — `RelaySession` (`./relay.ts`) composed with the same
3
+ * seat/rejoin-grace/watcher machinery every other hosted game runs on, so a relay match's end is
4
+ * recorded by the shell rather than only by `relay-socket.ts`'s bare `onEnded` callback, and a
5
+ * seat gone past its own grace is driven out of the game (`RelaySession.seatLeft`) — the first
6
+ * thing that ever drove one.
7
+ *
8
+ * There is no engine underneath a relay match — `RelaySession.command`/`fromSeat` are reached
9
+ * directly, never through a spawned process — so this file's own `MatchHostFactory` (below) is a
10
+ * trivial one, reused from `runtimes/in-process.ts` rather than written by hand: nothing ever
11
+ * calls `send`, nothing ever produces a line (`RelayLine` is `never`; see `./relay.ts`'s own
12
+ * header), and the match is `running` the instant {@link RelayMatch.attach} gives it somewhere to
13
+ * relay to — there is no boot to wait for.
14
+ *
15
+ * `RelayMatch` also implements `relay-socket.ts`'s own `RelayRoster`: it is both the match AND the
16
+ * roster a relay socket joins against (seating each socket where the room seats its owner), so
17
+ * `plugins/relay.ts`'s `rosterOf` can simply read one back
18
+ * out of {@link relayMatches} — the module singleton `plugins/relay.ts` registers into, from
19
+ * `room/lobby.ts`'s `onRelayRoomOpened` hook (kept out of this file's own importers; see
20
+ * {@link relayMatches}'s own doc).
21
+ */
22
+ import { HostedMatch } from '../match/hosted.js';
23
+ import { inProcessHost } from './in-process.js';
24
+ import { RelaySession } from './relay.js';
25
+ /** A `MatchSpec` with `seatCount` seats, none AI. `host.ts`'s own tuple-typed `seats` is Forge's;
26
+ * nothing here ever reads a relay match's `spec` back (there is no engine to configure), so the
27
+ * cast below is inert and stays local to this one file. */
28
+ function relaySpec(seatCount) {
29
+ const seats = Array.from({ length: seatCount }, (_, seat) => ({ ai: false, name: `Seat ${seat}`, deck: null }));
30
+ return { seats };
31
+ }
32
+ /**
33
+ * The host every `RelayMatch` runs on by default: nothing ever boots, nothing is ever sent down
34
+ * it, and stopping it is a no-op — reused from the generic `InProcessEngine` seam
35
+ * (`runtimes/in-process.ts`) rather than written by hand, so a relay match's "host" is proven
36
+ * generic the same way the toy game's engine is.
37
+ */
38
+ const relayNullHost = inProcessHost({
39
+ start: () => ({ send: () => { }, stop: () => { } }),
40
+ });
41
+ /**
42
+ * `RelaySession` composed with `HostedMatch`'s seat/rejoin-grace/watcher machinery — see this
43
+ * file's own header. A `RelayMatch` is also the `RelayRoster` `relay-socket.ts` joins against:
44
+ * `roleOf` seats a participant where the room seats them (every room auto-sits every joiner, the
45
+ * 2026-11-02 ruling, and the room's seats are the one record of who sat where) and `attach` is
46
+ * where its `RelaySession` is actually built, the moment it has live sockets to relay through.
47
+ */
48
+ export class RelayMatch extends HostedMatch {
49
+ seats;
50
+ /** Set once the match ends ({@link RelaySession}'s own `onEnded`) — mirrors `ToyMatch`'s own result field. */
51
+ result = null;
52
+ /** When the match ended; null until then. */
53
+ endedAt = null;
54
+ sessionRef = null;
55
+ seatGrace = new Map();
56
+ constructor(id, seatCount, deps, restore) {
57
+ super(id, relaySpec(seatCount), deps, restore);
58
+ this.seats = Array.from({ length: seatCount }, (_, seat) => ({ seat, ai: false, owner: null, playerId: seat, departure: null, here: false, away: false }));
59
+ for (const [seat, owner] of (restore?.owners ?? []).entries()) {
60
+ const s = this.seats[seat];
61
+ if (s !== undefined && owner !== null)
62
+ s.owner = owner;
63
+ }
64
+ }
65
+ /**
66
+ * `RelayRoster.lastEnded`: how the room's previous match ended, until this one is under way
67
+ * (its first message), so a screen that loads the room in between still shows the result.
68
+ * Undefined for a room's first match, and once this one has started.
69
+ */
70
+ lastEnded() {
71
+ return this.sessionRef?.started === true ? undefined : this.deps.previous;
72
+ }
73
+ /** `RelayRoster.seatCount`. */
74
+ get seatCount() {
75
+ return this.seats.length;
76
+ }
77
+ /**
78
+ * `RelayRoster.roleOf`: the seat the room has this participant in (`deps.roomSeatOf`), read
79
+ * fresh on every join, or null — a watcher — for one the room seats nowhere. The seat's owner
80
+ * follows the room: a member who moved seats, or a match restored with no owners, is seated
81
+ * where the room says, whichever socket reaches here first. Never `undefined` — this match
82
+ * keeps no membership list to refuse a stranger by, because the room's own join already settled
83
+ * that before any socket reached here.
84
+ */
85
+ roleOf(participantId) {
86
+ const roomSeat = this.deps.roomSeatOf(participantId);
87
+ const seat = roomSeat === null ? undefined : this.seats[roomSeat];
88
+ if (seat === undefined)
89
+ return null;
90
+ if (seat.owner !== participantId) {
91
+ for (const s of this.seats)
92
+ if (s.owner === participantId)
93
+ s.owner = null;
94
+ seat.owner = participantId;
95
+ this.remember();
96
+ this.deps.log({ evt: 'seat-claimed', matchId: this.id, seat: seat.seat, participantId });
97
+ }
98
+ return seat.seat;
99
+ }
100
+ /**
101
+ * `RelayRoster.attach`: this match's own `RelaySession`, built the moment it has somewhere to
102
+ * relay to (`relay-socket.ts`'s first join). A second call — should not happen, `relay-socket.ts`
103
+ * calls this at most once per roster — returns the session already built rather than replacing it.
104
+ */
105
+ attach(sink, onEnded) {
106
+ if (this.sessionRef !== null)
107
+ return this.sessionRef;
108
+ const session = new RelaySession(this.seats.length, sink, (outcome) => {
109
+ this.applyEnded(outcome);
110
+ onEnded(outcome);
111
+ }, (seat) => this.mayEnd(seat));
112
+ this.sessionRef = session;
113
+ this.game = session;
114
+ // A relay match has no engine underneath it to wait for: it is `running` from the instant
115
+ // it is given somewhere to relay to, the same way the toy game's own 'ready' line flips it
116
+ // (`fixtures/toy-game/match.ts`), except here there is no line to wait for at all.
117
+ this.status = 'running';
118
+ for (const done of this.runningWaiters.splice(0))
119
+ done({ ok: true });
120
+ this.armRejoinGrace();
121
+ return session;
122
+ }
123
+ /** Only the leader's seat ends the match; anyone else's `over` is refused and logged. */
124
+ mayEnd(seat) {
125
+ const leaderSeat = this.deps.leaderSeat();
126
+ if (seat === leaderSeat)
127
+ return true;
128
+ this.deps.log({ evt: 'relay-over-refused', matchId: this.id, seat, leaderSeat });
129
+ return false;
130
+ }
131
+ applyEnded(outcome) {
132
+ if (this.status !== 'running')
133
+ return;
134
+ this.status = 'over';
135
+ this.result = outcome;
136
+ this.endedAt = this.now();
137
+ this.syncClock();
138
+ for (const timer of this.seatGrace.values())
139
+ clearTimeout(timer);
140
+ this.seatGrace.clear();
141
+ this.tellEnded();
142
+ }
143
+ /**
144
+ * The shell's notice hook (see `runtimes/relay.ts`'s own `notice` method). `Match.serverStopping`'s
145
+ * own twin: the server is going down and this match cannot outlive it, so every seat is told
146
+ * in words.
147
+ */
148
+ serverStopping(message) {
149
+ this.deps.log({ evt: 'match-ending-with-server', matchId: this.id, status: this.status });
150
+ this.sessionRef?.notice('server-stopping', message);
151
+ }
152
+ /**
153
+ * Drives `RelaySession.seatLeft` after `seatRejoinGraceMs` — R's own "unverified" line settles
154
+ * here: nothing drove a rejoin-grace timer for a relay match before this file existed.
155
+ */
156
+ seatConnected(seat) {
157
+ super.seatConnected(seat);
158
+ const timer = this.seatGrace.get(seat);
159
+ if (timer !== undefined) {
160
+ clearTimeout(timer);
161
+ this.seatGrace.delete(seat);
162
+ this.deps.log({ evt: 'relay-seat-back', matchId: this.id, seat });
163
+ }
164
+ }
165
+ seatDisconnected(seat) {
166
+ super.seatDisconnected(seat);
167
+ const grace = this.deps.seatRejoinGraceMs ?? 0;
168
+ if (grace <= 0 || this.seatGrace.has(seat))
169
+ return;
170
+ const timer = setTimeout(() => {
171
+ this.seatGrace.delete(seat);
172
+ const s = this.seats[seat];
173
+ if (s === undefined || s.here)
174
+ return;
175
+ this.deps.log({ evt: 'relay-seat-left', matchId: this.id, seat });
176
+ this.game.command(this.concedeCommand(seat));
177
+ }, grace);
178
+ timer.unref();
179
+ this.seatGrace.set(seat, timer);
180
+ this.deps.log({ evt: 'relay-seat-held', matchId: this.id, seat, graceMs: grace });
181
+ }
182
+ onLine(_line) {
183
+ // `RelayLine` is `never` — no engine ever produces one (see `runtimes/relay.ts`'s module
184
+ // doc). Implemented only to satisfy `MatchShell`'s abstract contract.
185
+ }
186
+ concedeCommand(seat) {
187
+ return { t: 'concede', seat };
188
+ }
189
+ /**
190
+ * `MatchShell.forceConcede`: relay's own `command` is synchronous and unconditional
191
+ * (`RelaySession.command` → `seatLeft`), so there is nothing to wait on before forcing it —
192
+ * this IS the concede, the same one path that ever reaches it (a seat past its own grace, or
193
+ * the whole match's chess-clock flag, which a relay match never has).
194
+ */
195
+ forceConcede(seat) {
196
+ this.game.command(this.concedeCommand(seat));
197
+ }
198
+ }
199
+ /** Builds one `RelayMatch`, filling {@link relayNullHost} in when `deps.host` is left out. */
200
+ export function createRelayMatch(id, seatCount, deps, previous) {
201
+ return new RelayMatch(id, seatCount, { ...deps, host: deps.host ?? relayNullHost, ...(previous === undefined ? {} : { previous }) });
202
+ }
203
+ /**
204
+ * A registry of `RelayMatch`es, keyed by match (room) id. A match that ends is replaced by the
205
+ * room's next one at once, before `relay-socket.ts` tells any screen it ended, so every screen's
206
+ * rejoin (`relay-channel.ts` sends its join again on `relay:ended`) finds the new match. The next
207
+ * match carries how the last one ended (`RelayMatch.lastEnded`) until it is under way.
208
+ */
209
+ export function createRelayMatchRegistry() {
210
+ const matches = new Map();
211
+ function register(id, seatCount, deps, previous) {
212
+ const match = createRelayMatch(id, seatCount, {
213
+ ...deps,
214
+ ended: () => {
215
+ if (matches.get(id) === match)
216
+ register(id, seatCount, deps, { winners: match.result?.winners ?? null });
217
+ deps.ended?.();
218
+ },
219
+ }, previous);
220
+ matches.set(id, match);
221
+ return match;
222
+ }
223
+ return {
224
+ register: (id, seatCount, deps) => register(id, seatCount, deps),
225
+ get(id) {
226
+ return matches.get(id);
227
+ },
228
+ };
229
+ }
230
+ /**
231
+ * The one instance `plugins/relay.ts` shares between `ctx.state.lobby.onRelayRoomOpened`'s hook
232
+ * (what puts a `RelayMatch` in) and `rosterOf` (what reads one back out). `room/lobby.ts` never
233
+ * imports this module itself — see `Lobby.onRelayRoomOpened`'s own doc for the import cycle that
234
+ * would otherwise close back to `match.ts`'s `HostedMatch`. A plain module-level singleton rather
235
+ * than a field on `plugins/state.ts`'s `Cardtable` bag, which carries none for it this wave (that
236
+ * file is nobody's lane this wave). Unit tests build their own with
237
+ * {@link createRelayMatchRegistry} instead, so they never share state with this one or with each
238
+ * other.
239
+ */
240
+ export const relayMatches = createRelayMatchRegistry();
@@ -0,0 +1,128 @@
1
+ /**
2
+ * The relay runtime: a match with no engine. `RelaySession` is the
3
+ * `GameSession` (`../game-adapter.ts`) for a game that has no bridge of its
4
+ * own — the host's only job is to hand each seat's own message to every
5
+ * other seat, and to every watcher read-only, through the match's socket
6
+ * (`../relay-socket.ts`). Rooms, seats, rejoin and watchers come from
7
+ * `MatchShell`; this is the other half of that seam.
8
+ *
9
+ * A native game such as bomberman is this runtime plus the bundle's own
10
+ * `channel` (`@hadoku/rooms-protocol`'s `MatchChannel`), so the semantics
11
+ * here — ordering per sender, at-most-once delivery, a watcher's refused
12
+ * send — follow that reference exactly: a bundle on the other side of a
13
+ * relay match is already written against it.
14
+ *
15
+ * There is no bridge, so nothing ever produces a "line" for this session to
16
+ * read: `onLine` exists only to satisfy `GameSession` and is never called.
17
+ * What actually drives a relay match is `fromSeat`, called by
18
+ * `relay-socket.ts` whenever one seat's own connection sends a message —
19
+ * never through `GameSession` itself, because nothing upstream of a seat's
20
+ * own socket produces one.
21
+ */
22
+ import type { GameSession } from '../game-adapter.js';
23
+ /** A seat's or a watcher's message: opaque to the host, meaningful only to the game on both ends. */
24
+ export type RelayMessage = unknown;
25
+ /**
26
+ * `command()`'s one real case: a seat that must leave as a loss (a seat
27
+ * dropped past its grace, the shell's own concede). Nothing else goes down
28
+ * this sink — there is no engine underneath to send anything else to.
29
+ */
30
+ export type RelayCommand = {
31
+ t: 'concede';
32
+ seat: number;
33
+ };
34
+ /** `GameSession.onLine`'s parameter has nothing to carry: see the module doc. */
35
+ export type RelayLine = never;
36
+ /** What the match ended with: a ranking from the leader's own `{ t: 'over', winners }`
37
+ * message, or `null` when it ended because every seat left instead. */
38
+ export interface RelayOutcome {
39
+ winners: readonly number[];
40
+ }
41
+ /** Where a relayed message actually goes: wired to the live sockets by `relay-socket.ts`. */
42
+ export interface RelaySink {
43
+ toSeat(seat: number, msg: RelayMessage): void;
44
+ toWatchers(msg: RelayMessage): void;
45
+ }
46
+ export declare class RelaySession implements GameSession<RelayLine, RelayCommand> {
47
+ private readonly seatCount;
48
+ private readonly sink;
49
+ /** Called once, the first time the match ends — by `{ t: 'over', winners }` or by every seat leaving. */
50
+ private readonly onEnded?;
51
+ /**
52
+ * Whether `seat` may end the match with `{ t: 'over' }` — the protocol's host, the room's
53
+ * leader. An `over` it refuses is not relayed at all (every other seat would take it as
54
+ * final) and ends nothing. Absent: any seat may.
55
+ */
56
+ private readonly mayEnd?;
57
+ private readonly left;
58
+ private outcome;
59
+ private closed;
60
+ private relayedAny;
61
+ constructor(seatCount: number, sink: RelaySink,
62
+ /** Called once, the first time the match ends — by `{ t: 'over', winners }` or by every seat leaving. */
63
+ onEnded?: ((outcome: RelayOutcome | null) => void) | undefined,
64
+ /**
65
+ * Whether `seat` may end the match with `{ t: 'over' }` — the protocol's host, the room's
66
+ * leader. An `over` it refuses is not relayed at all (every other seat would take it as
67
+ * final) and ends nothing. Absent: any seat may.
68
+ */
69
+ mayEnd?: ((seat: number) => boolean) | undefined);
70
+ get isEnded(): boolean;
71
+ get result(): RelayOutcome | null;
72
+ /** Whether any seat has said anything in this match yet: the match is under way from its first message. */
73
+ get started(): boolean;
74
+ /**
75
+ * One seat's own connection sent `msg`: relay it to every OTHER seat and,
76
+ * read-only, to every watcher — never back to the sender. A seat already
77
+ * recorded as `left` cannot speak for it again; `relay-socket.ts` should
78
+ * never call this for a departed seat, but the guard is cheap insurance
79
+ * against exactly that race (a close and a late message crossing).
80
+ */
81
+ fromSeat(seat: number, msg: RelayMessage): void;
82
+ /**
83
+ * A watcher's own connection sent something: refused, always — a watcher
84
+ * has no seat to speak from (`MatchChannel`'s own doc has the same rule).
85
+ * `relay-socket.ts` must refuse this before it ever reaches here; this
86
+ * method exists only so a caller that forgets that guard fails safe
87
+ * (silently drops it) rather than failing loud.
88
+ */
89
+ fromWatcher(): void;
90
+ /**
91
+ * A seat's holder left for good — not a plain disconnect, which the
92
+ * socket layer alone tracks for rejoin. The match ends once every seat
93
+ * has.
94
+ */
95
+ seatLeft(seat: number): void;
96
+ private finish;
97
+ onLine(_line: RelayLine): void;
98
+ command(cmd: RelayCommand): void;
99
+ waitedOn(_seat: number): boolean;
100
+ tellRoster(): void;
101
+ turn(): number | null;
102
+ activeSeat(): {
103
+ seat: number;
104
+ playerId: number;
105
+ } | null;
106
+ openAsks(_seat: number): number;
107
+ /** A replayed command closes the session's own open ask. A relay match
108
+ * keeps no replay log and opens no asks of its own, so there is nothing
109
+ * to close. */
110
+ replayed(_command: RelayCommand): void;
111
+ /**
112
+ * The session's sweep at stop, fail or exit — `null` for a stop, same as
113
+ * the interface's own doc. `finish(null)` already covers "every seat
114
+ * left"; this is the same sweep from the OUTSIDE (the shell, or
115
+ * `relay-socket.ts`'s own `close()`, ending the match for reasons of its
116
+ * own). Idempotent, like every path into `finish`.
117
+ */
118
+ ended(_reason: string | null): void;
119
+ /**
120
+ * `GameSession.notice` (`game-adapter.ts`): the shell's own hook for words with no game state
121
+ * behind them. `Match.serverStopping` moves behind the same hook on Forge's side; here the
122
+ * server is going down and this match cannot outlive it, so every SEAT (never a watcher — the
123
+ * same "seats only" rule Forge's own `endNotice` follows) is told in words, as a relayed
124
+ * message shaped like any other: `{ t: 'notice', message }`. A match already ended has nothing
125
+ * left to tell.
126
+ */
127
+ notice(_kind: 'server-stopping', message: string): void;
128
+ }
@@ -0,0 +1,183 @@
1
+ /**
2
+ * The relay runtime: a match with no engine. `RelaySession` is the
3
+ * `GameSession` (`../game-adapter.ts`) for a game that has no bridge of its
4
+ * own — the host's only job is to hand each seat's own message to every
5
+ * other seat, and to every watcher read-only, through the match's socket
6
+ * (`../relay-socket.ts`). Rooms, seats, rejoin and watchers come from
7
+ * `MatchShell`; this is the other half of that seam.
8
+ *
9
+ * A native game such as bomberman is this runtime plus the bundle's own
10
+ * `channel` (`@hadoku/rooms-protocol`'s `MatchChannel`), so the semantics
11
+ * here — ordering per sender, at-most-once delivery, a watcher's refused
12
+ * send — follow that reference exactly: a bundle on the other side of a
13
+ * relay match is already written against it.
14
+ *
15
+ * There is no bridge, so nothing ever produces a "line" for this session to
16
+ * read: `onLine` exists only to satisfy `GameSession` and is never called.
17
+ * What actually drives a relay match is `fromSeat`, called by
18
+ * `relay-socket.ts` whenever one seat's own connection sends a message —
19
+ * never through `GameSession` itself, because nothing upstream of a seat's
20
+ * own socket produces one.
21
+ */
22
+ /** Whether `msg` is the leader's own end-of-game message. Read directly off
23
+ * the opaque content — the same way `GameAdapter.classify`'s `'over'` case
24
+ * reads Forge's own gameover line, except here the "line" is just one
25
+ * seat's relayed message. */
26
+ function isOverMessage(msg) {
27
+ if (typeof msg !== 'object' || msg === null)
28
+ return false;
29
+ const t = msg.t;
30
+ const winners = msg.winners;
31
+ return t === 'over' && Array.isArray(winners) && winners.every((w) => typeof w === 'number');
32
+ }
33
+ export class RelaySession {
34
+ seatCount;
35
+ sink;
36
+ onEnded;
37
+ mayEnd;
38
+ left = new Set();
39
+ outcome = null;
40
+ closed = false;
41
+ relayedAny = false;
42
+ constructor(seatCount, sink,
43
+ /** Called once, the first time the match ends — by `{ t: 'over', winners }` or by every seat leaving. */
44
+ onEnded,
45
+ /**
46
+ * Whether `seat` may end the match with `{ t: 'over' }` — the protocol's host, the room's
47
+ * leader. An `over` it refuses is not relayed at all (every other seat would take it as
48
+ * final) and ends nothing. Absent: any seat may.
49
+ */
50
+ mayEnd) {
51
+ this.seatCount = seatCount;
52
+ this.sink = sink;
53
+ this.onEnded = onEnded;
54
+ this.mayEnd = mayEnd;
55
+ }
56
+ get isEnded() {
57
+ return this.closed;
58
+ }
59
+ get result() {
60
+ return this.outcome;
61
+ }
62
+ /** Whether any seat has said anything in this match yet: the match is under way from its first message. */
63
+ get started() {
64
+ return this.relayedAny;
65
+ }
66
+ /**
67
+ * One seat's own connection sent `msg`: relay it to every OTHER seat and,
68
+ * read-only, to every watcher — never back to the sender. A seat already
69
+ * recorded as `left` cannot speak for it again; `relay-socket.ts` should
70
+ * never call this for a departed seat, but the guard is cheap insurance
71
+ * against exactly that race (a close and a late message crossing).
72
+ */
73
+ fromSeat(seat, msg) {
74
+ if (this.closed || this.left.has(seat))
75
+ return;
76
+ const over = isOverMessage(msg);
77
+ if (over && this.mayEnd !== undefined && !this.mayEnd(seat))
78
+ return;
79
+ this.relayedAny = true;
80
+ for (let other = 0; other < this.seatCount; other += 1) {
81
+ if (other !== seat)
82
+ this.sink.toSeat(other, msg);
83
+ }
84
+ this.sink.toWatchers(msg);
85
+ if (over)
86
+ this.finish({ winners: msg.winners });
87
+ }
88
+ /**
89
+ * A watcher's own connection sent something: refused, always — a watcher
90
+ * has no seat to speak from (`MatchChannel`'s own doc has the same rule).
91
+ * `relay-socket.ts` must refuse this before it ever reaches here; this
92
+ * method exists only so a caller that forgets that guard fails safe
93
+ * (silently drops it) rather than failing loud.
94
+ */
95
+ fromWatcher() {
96
+ // Deliberately empty.
97
+ }
98
+ /**
99
+ * A seat's holder left for good — not a plain disconnect, which the
100
+ * socket layer alone tracks for rejoin. The match ends once every seat
101
+ * has.
102
+ */
103
+ seatLeft(seat) {
104
+ if (this.closed || this.left.has(seat))
105
+ return;
106
+ this.left.add(seat);
107
+ if (this.left.size >= this.seatCount)
108
+ this.finish(null);
109
+ }
110
+ finish(outcome) {
111
+ if (this.closed)
112
+ return;
113
+ this.closed = true;
114
+ this.outcome = outcome;
115
+ this.onEnded?.(outcome);
116
+ }
117
+ /* ── GameSession ──────────────────────────────────────────────────── */
118
+ onLine(_line) {
119
+ // No bridge produces one; see the module doc.
120
+ }
121
+ command(cmd) {
122
+ if (cmd.t === 'concede')
123
+ this.seatLeft(cmd.seat);
124
+ }
125
+ waitedOn(_seat) {
126
+ // A relay match's clock is the game's own business, carried inside the
127
+ // opaque messages it relays; the shell has nothing to wait on here.
128
+ return false;
129
+ }
130
+ tellRoster() {
131
+ // The shell's own roster frame already reaches every seat; a relay
132
+ // session has nothing of its own to add to it.
133
+ }
134
+ turn() {
135
+ return null;
136
+ }
137
+ activeSeat() {
138
+ return null;
139
+ }
140
+ openAsks(_seat) {
141
+ return 0;
142
+ }
143
+ /*
144
+ * ── `GameSession`'s two optional hooks ───────────────────────────────
145
+ * Both now declared on `game-adapter.ts` (G's file), optional until
146
+ * every `GameSession` implements them. `MatchShell`/`HostedMatch` does
147
+ * not yet compose with a relay session, so nothing on the shell's side
148
+ * calls these yet, but `relay-socket.ts` already calls `ended` directly
149
+ * for its own sweep (see `close()`); implemented now so wiring the rest
150
+ * in is a no-op once something does.
151
+ */
152
+ /** A replayed command closes the session's own open ask. A relay match
153
+ * keeps no replay log and opens no asks of its own, so there is nothing
154
+ * to close. */
155
+ replayed(_command) {
156
+ // Deliberately empty.
157
+ }
158
+ /**
159
+ * The session's sweep at stop, fail or exit — `null` for a stop, same as
160
+ * the interface's own doc. `finish(null)` already covers "every seat
161
+ * left"; this is the same sweep from the OUTSIDE (the shell, or
162
+ * `relay-socket.ts`'s own `close()`, ending the match for reasons of its
163
+ * own). Idempotent, like every path into `finish`.
164
+ */
165
+ ended(_reason) {
166
+ this.finish(null);
167
+ }
168
+ /**
169
+ * `GameSession.notice` (`game-adapter.ts`): the shell's own hook for words with no game state
170
+ * behind them. `Match.serverStopping` moves behind the same hook on Forge's side; here the
171
+ * server is going down and this match cannot outlive it, so every SEAT (never a watcher — the
172
+ * same "seats only" rule Forge's own `endNotice` follows) is told in words, as a relayed
173
+ * message shaped like any other: `{ t: 'notice', message }`. A match already ended has nothing
174
+ * left to tell.
175
+ */
176
+ notice(_kind, message) {
177
+ if (this.closed)
178
+ return;
179
+ const msg = { t: 'notice', message };
180
+ for (let seat = 0; seat < this.seatCount; seat += 1)
181
+ this.sink.toSeat(seat, msg);
182
+ }
183
+ }
@@ -0,0 +1,116 @@
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 type { EngineRuntime } from '../engine-runtime.js';
44
+ import type { RoomStreams } from '../../stream/alloc.js';
45
+ /** Measured 2026-09-19, `docs/spikes/streaming.md`, "the host" section: "Budget 1.3 GiB per streamed desktop." */
46
+ export declare const STREAMED_CONTAINER_MB = 1331;
47
+ /** The two Magic-specific paths a streamed desktop's container mounts. See the module header. */
48
+ export interface StreamedMagicConfig {
49
+ forgeJar: string;
50
+ forgeRes: string;
51
+ }
52
+ export type StreamedAvailability = {
53
+ ok: true;
54
+ config: StreamedMagicConfig;
55
+ } | {
56
+ ok: false;
57
+ reason: string;
58
+ };
59
+ /**
60
+ * Resolve the streamed desktop's Magic config from the environment, validated the way
61
+ * `jvmHostConfig` (`../local-jvm.ts`) validates the JVM pool's: a missing or malformed jar/res is a
62
+ * reason, not a guess. `CARDTABLE_STREAM_FORGE_JAR`/`_RES` name the container's own copy, falling
63
+ * back to the pool's `CARDTABLE_FORGE_JAR`/`_RES` when the container has none of its own — exactly
64
+ * the fallback chain `scripts/stream/container.sh`'s bash already encodes, so this and the script
65
+ * can never resolve a different jar from the same environment.
66
+ */
67
+ export declare function streamedEngineConfig(env?: NodeJS.ProcessEnv): StreamedAvailability;
68
+ /**
69
+ * What `scripts/stream/container.sh` reads to find the Forge it mounts, resolved HERE rather than
70
+ * left to its own bash fallback. `plugins/stream.ts` hands this to `scriptRunner`'s `env`, so the
71
+ * jar/res this process validated ({@link streamedEngineConfig}) is exactly what every `up` call
72
+ * mounts.
73
+ */
74
+ export declare function streamedContainerEnv(config: StreamedMagicConfig): Record<string, string>;
75
+ /**
76
+ * `EngineRuntime` (`../engine-runtime.ts`) for the streamed desktop: what it costs, in the same
77
+ * vocabulary the JVM pool's `forgeEngineRuntime` (`../local-jvm.ts`) uses, so a reader comparing
78
+ * the two engines this host runs sees one shape, not two. `argv`/`spawn` are left as the
79
+ * interface's own no-op/unset for an engine whose process is a container, not something this
80
+ * server forks — see the module header, "Not a `child_process.spawn`".
81
+ */
82
+ export declare function streamedEngineRuntime(config: StreamedMagicConfig): EngineRuntime;
83
+ /**
84
+ * What a seat's containers coming up or going down tells the host, in the same three-part
85
+ * vocabulary `host.ts`'s `HostEvents` uses (a line, an exit, a log entry) without importing that
86
+ * file: this lane does not own `host.ts`, and a structural match costs nothing to keep. `fatal`
87
+ * stands in for `HostLifecycleLine`'s `{ t: 'fatal' }` case — a provisioning failure the match
88
+ * cannot recover from, same as a JVM's own fatal line.
89
+ */
90
+ export interface StreamedHostEvents {
91
+ /** A provision failed: the match's fatal. */
92
+ fatal(message: string): void;
93
+ /** The containers are gone for good — reclaimed, or asked to stop. */
94
+ exit(reason: string): void;
95
+ log(entry: Record<string, unknown>): void;
96
+ }
97
+ /** One streamed match's containers, from allocation through teardown. */
98
+ export interface StreamedMatchHost {
99
+ /** Ask every seat's container down. Idempotent, and safe even if they are already gone. */
100
+ stop(): void;
101
+ /**
102
+ * The containers went down some OTHER way — `stream/alloc.ts`'s own idle/room-gone sweep, or an
103
+ * orphan reclaim — so this host still reports it (`events.exit`) without releasing a second
104
+ * time. `plugins/stream.ts` calls this from `RoomStreamsOptions.onEnded`; idempotent with `stop`.
105
+ */
106
+ settled(reason: string): void;
107
+ }
108
+ /**
109
+ * Starts (or finds already-live) a room's seats' containers through `rooms`
110
+ * (`../../stream/alloc.ts`'s `RoomStreams`), and reports back in {@link StreamedHostEvents}'s
111
+ * vocabulary: a failed provision is `events.fatal`, exactly as a JVM's `{ t: 'fatal' }` line is
112
+ * `match.fail`'s trigger today. `stop()` releases them through `rooms.release` — `stream/alloc.ts`'s
113
+ * own teardown, never a second path that could disagree with it about what "torn down" means — and
114
+ * {@link StreamedMatchHost.settled} covers every OTHER way those same containers can end.
115
+ */
116
+ export declare function streamedHost(rooms: RoomStreams, roomKey: string, seatCount: number, events: StreamedHostEvents): StreamedMatchHost;