@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,89 @@
1
+ /**
2
+ * What is kept of `CARDTABLE_RECORDINGS_DIR` and for how long
3
+ * (`docs/planning/wave77-2026-10-27.md` §C): the public stream for 7 days, the
4
+ * action log for 90, and the whole directory capped at 2 GB — the oldest
5
+ * PUBLIC streams go first under the cap, because they are the rebuildable
6
+ * half (`recording/rebuild.ts`, lane D) and the action logs are a few KB each
7
+ * either way. Age is the file's own mtime: both files are written exactly
8
+ * once, at the match's end, so mtime IS "when this match ended" with nothing
9
+ * else ever touching it.
10
+ *
11
+ * Swept hourly (`recorder.ts`'s `watchRecordings`) and once at boot, same
12
+ * discipline as `host.ts`'s own run-directory sweep. Never throws: one bad
13
+ * stat or unlink is logged and skipped, not a reason to stop sweeping the rest.
14
+ */
15
+ import { readdirSync, rmSync, statSync } from 'node:fs';
16
+ import { join } from 'node:path';
17
+ export const PUBLIC_RETENTION_MS = 7 * 24 * 60 * 60 * 1000;
18
+ export const ACTIONS_RETENTION_MS = 90 * 24 * 60 * 60 * 1000;
19
+ /** See the module header: the oldest public streams are dropped first when the directory is over this. */
20
+ export const RECORDINGS_CAP_BYTES = 2 * 1024 * 1024 * 1024;
21
+ export const ACTIONS_SUFFIX = '.actions.jsonl.gz';
22
+ export const PUBLIC_SUFFIX = '.public.jsonl.gz';
23
+ function list(dir, errors) {
24
+ let names;
25
+ try {
26
+ names = readdirSync(dir);
27
+ }
28
+ catch (err) {
29
+ errors.push({ file: dir, error: err.message });
30
+ return [];
31
+ }
32
+ const out = [];
33
+ for (const name of names) {
34
+ if (!name.endsWith(ACTIONS_SUFFIX) && !name.endsWith(PUBLIC_SUFFIX))
35
+ continue;
36
+ try {
37
+ const st = statSync(join(dir, name));
38
+ out.push({ name, path: join(dir, name), size: st.size, mtimeMs: st.mtimeMs });
39
+ }
40
+ catch (err) {
41
+ errors.push({ file: name, error: err.message });
42
+ }
43
+ }
44
+ return out;
45
+ }
46
+ function remove(entry, log, evt, errors) {
47
+ try {
48
+ rmSync(entry.path, { force: true });
49
+ log({ evt, file: entry.name, ageMs: Date.now() - entry.mtimeMs, sizeBytes: entry.size });
50
+ }
51
+ catch (err) {
52
+ errors.push({ file: entry.name, error: err.message });
53
+ }
54
+ }
55
+ /** One pass over `dir`: age-based expiry, then the size cap. See the module header. `capBytes` is overridable for a test; production never passes one. */
56
+ export function sweepRecordings(dir, now = Date.now(), log = () => undefined, capBytes = RECORDINGS_CAP_BYTES) {
57
+ const errors = [];
58
+ const result = { expiredActions: [], expiredPublic: [], overCap: [], bytesAfter: 0, errors };
59
+ let entries = list(dir, errors);
60
+ const kept = [];
61
+ for (const entry of entries) {
62
+ const suffix = entry.name.endsWith(ACTIONS_SUFFIX) ? 'actions' : 'public';
63
+ const limit = suffix === 'actions' ? ACTIONS_RETENTION_MS : PUBLIC_RETENTION_MS;
64
+ if (now - entry.mtimeMs > limit) {
65
+ remove(entry, log, 'recording-expired', errors);
66
+ (suffix === 'actions' ? result.expiredActions : result.expiredPublic).push(entry.name);
67
+ }
68
+ else {
69
+ kept.push(entry);
70
+ }
71
+ }
72
+ entries = kept;
73
+ let total = entries.reduce((sum, e) => sum + e.size, 0);
74
+ if (total > capBytes) {
75
+ const publicOldestFirst = entries.filter((e) => e.name.endsWith(PUBLIC_SUFFIX)).sort((a, b) => a.mtimeMs - b.mtimeMs);
76
+ for (const entry of publicOldestFirst) {
77
+ if (total <= capBytes)
78
+ break;
79
+ remove(entry, log, 'recording-over-cap', errors);
80
+ result.overCap.push(entry.name);
81
+ total -= entry.size;
82
+ entries = entries.filter((e) => e !== entry);
83
+ }
84
+ }
85
+ result.bytesAfter = total;
86
+ if (errors.length > 0)
87
+ log({ evt: 'recording-sweep-errors', count: errors.length, errors });
88
+ return result;
89
+ }
@@ -0,0 +1,185 @@
1
+ /**
2
+ * One match's two recorded files (`docs/planning/wave77-2026-10-27.md` §C,
3
+ * contract 1): `<matchId>.actions.jsonl.gz` and `<matchId>.public.jsonl.gz`.
4
+ *
5
+ * Buffered, not streamed: every line is held in memory as it comes and both
6
+ * files are written once, gzipped, when the match ends. A long human game is
7
+ * a few hundred to a few thousand small JSON lines — a few hundred KB before
8
+ * gzip — so holding it costs nothing a match-sized process does not already
9
+ * spend on everything else, and it means recording never does disk I/O on the
10
+ * hot path: no write is on the way between Forge's line arriving and the next
11
+ * command being sent. The cost of this choice is the one named in the plan: a
12
+ * process that dies mid-match (not a clean end) loses that match's buffered
13
+ * lines, same as `host.ts`'s own `stream.jsonl` would need the run directory
14
+ * to survive the crash to replay — recording a match that outlives a restart
15
+ * is future work, not this wave's.
16
+ *
17
+ * Nothing here may fail a match. Every public method swallows its own errors
18
+ * into `log`; `finish` resolves even when the disk write failed.
19
+ */
20
+ import type { JsonLog } from '@wolffm/service-kernel/log';
21
+ /**
22
+ * Line 1 of the action log — contract 1, `v:2` since wave 78 §A. `spec` always carries a seed (the
23
+ * recorder assigns one if play did not).
24
+ *
25
+ * `v:1`'s `cmd` line carried `board`/`prompt`: a seat's folded-board digest and last prompt at
26
+ * `host.send` time, which `rebuild.ts` polled for before resending a command. Gone in `v:2` — see
27
+ * `ActionsCmdLine`'s own doc for why, and for what replaces it.
28
+ */
29
+ export interface ActionsHeader {
30
+ t: 'header';
31
+ v: 2;
32
+ matchId: string;
33
+ roomId: string | null;
34
+ pin: string | null;
35
+ bridge: string;
36
+ server: string;
37
+ startedAt: string;
38
+ spec: unknown;
39
+ }
40
+ /**
41
+ * One `cmd` line of the action log — contract 1, `v:2`. `cmd` is the raw `BridgeCommand`: a
42
+ * `reply`/`abort`, or an `act` built from the bridge's own `applied` echo (`PlayBridge.java`'s
43
+ * `SeatController.applied`, wired in `recorder.ts`'s `line` hook) rather than the browser's act at
44
+ * send time — `docs/planning/front-page-and-replay-plan.md`'s "Wave 77 results" is why: Forge can
45
+ * drop a sent act (no input was open) or apply two in a different order than they were sent, so a
46
+ * log of what was SENT is not a log of what the game did.
47
+ *
48
+ * No `board`/`prompt`. `v:1` carried them so `rebuild.ts` could poll for a seat reaching that
49
+ * position before resending its next command — dead now that an `act` line IS the applied act, in
50
+ * applied order, and a rebuild instead resends the next one once it sees ITS OWN `applied` echo
51
+ * (same ordinal, fresh JVM) for that seat. A `reply`/`abort` never used them either: it is gated on
52
+ * its own ask (`ask`, below), a separate channel from board/prompt that can read a different stage
53
+ * of the game depending on how Forge batches the two.
54
+ *
55
+ * Only `act`/`reply`/`abort`/`rewind` are ever logged: `stop`, `resend-pending`, `cancel-payment` and
56
+ * `probe` are connection/UI housekeeping, never part of the deterministic move sequence a rebuild
57
+ * replays, and `seat` is always a real seat, never null, for exactly that reason.
58
+ */
59
+ export interface ActionsCmdLine {
60
+ t: 'cmd';
61
+ seat: number;
62
+ /**
63
+ * For a `reply` or `abort`: which of that seat's asks it answers, counted from 0 in the order Forge
64
+ * sent them. The callId is the live run's own; a rebuild finds its own ask by this number. Not
65
+ * the reply's place among replies: the server answers some asks itself and lets others lapse.
66
+ */
67
+ ask?: number;
68
+ cmd: unknown;
69
+ }
70
+ export interface ActionsEndLine {
71
+ t: 'end';
72
+ endedAt: string;
73
+ reason: string;
74
+ /**
75
+ * Each seat's final board digest (`position.ts`), taken live. A rebuild that does not reach both
76
+ * is refused rather than served: the log alone does not yet reproduce every game (plan,
77
+ * "Wave 78 results"), so this is what keeps a wrong replay off the page.
78
+ */
79
+ boards?: [string, string];
80
+ /**
81
+ * Each seat holder's registry userId, by seat (null for the AI and an unheld seat), so a replay
82
+ * rebuilt from this log names its people as they are when watched (R12). The log keeps no name:
83
+ * its spec's human seats are `Player N` (`recorder.ts`'s `anonymousSpec`). Absent before #27.
84
+ */
85
+ users?: (string | null)[];
86
+ }
87
+ /**
88
+ * The public stream's version. `2` since wave 81: the stream is the watcher channel as every player
89
+ * (`visibility.ts`'s `EVERY_PLAYER`), so both hands are face up, and the header names the match's
90
+ * art. A `v:1` stream drew no hand, and is never served.
91
+ */
92
+ export declare const PUBLIC_VERSION = 2;
93
+ /** Line 1 of the public stream — contract 1. */
94
+ export interface PublicHeader {
95
+ t: 'header';
96
+ v: typeof PUBLIC_VERSION;
97
+ matchId: string;
98
+ roomId: string | null;
99
+ players: [string, string];
100
+ ai: [boolean, boolean];
101
+ decks: unknown[];
102
+ /** The art ids of every card both decks (or the scenario) name, as `forge:art` tells a live board (`art.ts`): what a replay warms. */
103
+ art: string[];
104
+ startedAt: string;
105
+ }
106
+ /** One `env` line of the public stream — contract 1. `env` is the watcher channel's own `ServerEnvelope`. */
107
+ export interface PublicEnvLine {
108
+ t: 'env';
109
+ at: number;
110
+ env: unknown;
111
+ }
112
+ /**
113
+ * The active seat's pointer, as `forge:presence` relayed it (`@hadoku/shared`'s `presence.ts`: it names no
114
+ * hidden card), so a replay draws their cursor and their drags. `playerId` is that seat's Forge player: the
115
+ * replay draws the seat at the bottom, from the player whose turn it is. Absent before wave 81 part 2.
116
+ */
117
+ export interface PublicPresenceLine {
118
+ t: 'presence';
119
+ at: number;
120
+ seat: number;
121
+ playerId: number;
122
+ presence: unknown;
123
+ }
124
+ /**
125
+ * A table message one seat relayed to the others (`@hadoku/shared`'s `relayed.ts`: a placement, a row
126
+ * order, a stack card's place), as its echo, so a replay lays the table out as the players saw it.
127
+ * Absent from a recording made before they were kept.
128
+ */
129
+ export interface PublicRelayLine {
130
+ t: 'relay';
131
+ at: number;
132
+ event: string;
133
+ echo: unknown;
134
+ }
135
+ /**
136
+ * A seat as the `end` line keeps it: the part of `forge:seats` (`SeatIdentity`) a replay draws faces
137
+ * from. A live board hears it on its own socket event, never through the watcher channel's envelopes,
138
+ * so without this a replay drew every player without an avatar.
139
+ */
140
+ export interface RecordedSeat {
141
+ seat: number;
142
+ claimed: boolean;
143
+ playerId: number | null;
144
+ /** Absent when the seat had none, as on the wire. */
145
+ avatarId?: string;
146
+ /**
147
+ * The holder's registry userId, so the replay draws them as they are when it is watched (R12):
148
+ * kept on disk, and replaced by their face and name before a replay leaves the server
149
+ * (`http/replays.ts`). Absent for the AI, and in a recording from before it was kept.
150
+ */
151
+ userId?: string;
152
+ }
153
+ export interface PublicEndLine {
154
+ t: 'end';
155
+ endedAt: string;
156
+ winner: 0 | 1 | null;
157
+ /** The roster as the match ended. Absent from a recording made before it was kept, or when the match was already gone. */
158
+ seats?: RecordedSeat[];
159
+ }
160
+ export interface MatchRecordingWriter {
161
+ /** Append one `cmd` line. Buffered — nothing is written to disk yet. */
162
+ actionCmd(line: Omit<ActionsCmdLine, 't'>): void;
163
+ /** Append one `env` line. Buffered. */
164
+ publicEnv(line: Omit<PublicEnvLine, 't'>): void;
165
+ /** Append one `presence` line. Buffered. */
166
+ publicPresence(line: Omit<PublicPresenceLine, 't'>): void;
167
+ /** Append one `relay` line. Buffered. */
168
+ publicRelay(line: Omit<PublicRelayLine, 't'>): void;
169
+ /** Both headers' `roomId`: a room links its match only after the match's host has started. */
170
+ room(roomId: string): void;
171
+ /**
172
+ * Write the `end` line onto both buffers, gzip each, and write both files.
173
+ * Never throws; a failed write is one `log` line, not a rejection. Resolves
174
+ * once both attempts (success or failure) are done.
175
+ */
176
+ finish(actionsEnd: Omit<ActionsEndLine, 't'>, publicEnd: Omit<PublicEndLine, 't'>): Promise<void>;
177
+ }
178
+ export interface MatchRecordingWriterDeps {
179
+ dir: string;
180
+ matchId: string;
181
+ actionsHeader: Omit<ActionsHeader, 't' | 'v'>;
182
+ publicHeader: Omit<PublicHeader, 't' | 'v'>;
183
+ log?: JsonLog;
184
+ }
185
+ export declare function createMatchRecordingWriter(deps: MatchRecordingWriterDeps): MatchRecordingWriter;
@@ -0,0 +1,90 @@
1
+ /**
2
+ * One match's two recorded files (`docs/planning/wave77-2026-10-27.md` §C,
3
+ * contract 1): `<matchId>.actions.jsonl.gz` and `<matchId>.public.jsonl.gz`.
4
+ *
5
+ * Buffered, not streamed: every line is held in memory as it comes and both
6
+ * files are written once, gzipped, when the match ends. A long human game is
7
+ * a few hundred to a few thousand small JSON lines — a few hundred KB before
8
+ * gzip — so holding it costs nothing a match-sized process does not already
9
+ * spend on everything else, and it means recording never does disk I/O on the
10
+ * hot path: no write is on the way between Forge's line arriving and the next
11
+ * command being sent. The cost of this choice is the one named in the plan: a
12
+ * process that dies mid-match (not a clean end) loses that match's buffered
13
+ * lines, same as `host.ts`'s own `stream.jsonl` would need the run directory
14
+ * to survive the crash to replay — recording a match that outlives a restart
15
+ * is future work, not this wave's.
16
+ *
17
+ * Nothing here may fail a match. Every public method swallows its own errors
18
+ * into `log`; `finish` resolves even when the disk write failed.
19
+ */
20
+ import { mkdirSync } from 'node:fs';
21
+ import { rename, writeFile } from 'node:fs/promises';
22
+ import { randomUUID } from 'node:crypto';
23
+ import { join } from 'node:path';
24
+ import { gzip as gzipCb } from 'node:zlib';
25
+ import { promisify } from 'node:util';
26
+ import { ACTIONS_SUFFIX, PUBLIC_SUFFIX } from './retention.js';
27
+ const gzip = promisify(gzipCb);
28
+ /**
29
+ * The public stream's version. `2` since wave 81: the stream is the watcher channel as every player
30
+ * (`visibility.ts`'s `EVERY_PLAYER`), so both hands are face up, and the header names the match's
31
+ * art. A `v:1` stream drew no hand, and is never served.
32
+ */
33
+ export const PUBLIC_VERSION = 2;
34
+ /** Write `bytes` to `path` whole or not at all: a temp file beside it, renamed over it. */
35
+ async function writeFileAtomic(path, bytes) {
36
+ const tmp = `${path}.${process.pid}.${randomUUID()}.tmp`;
37
+ await writeFile(tmp, bytes);
38
+ await rename(tmp, path);
39
+ }
40
+ async function flush(path, lines, log, which) {
41
+ try {
42
+ const text = lines.map((l) => JSON.stringify(l)).join('\n') + '\n';
43
+ const compressed = await gzip(Buffer.from(text, 'utf8'));
44
+ await writeFileAtomic(path, compressed);
45
+ }
46
+ catch (err) {
47
+ // A recording nobody can read is a loss, never a crash: the match this
48
+ // came from already finished by the time this runs.
49
+ log({ evt: 'recording-write-failed', which, path, error: err.message });
50
+ }
51
+ }
52
+ export function createMatchRecordingWriter(deps) {
53
+ const log = deps.log ?? (() => undefined);
54
+ try {
55
+ mkdirSync(deps.dir, { recursive: true });
56
+ }
57
+ catch (err) {
58
+ log({ evt: 'recording-dir-failed', dir: deps.dir, error: err.message });
59
+ }
60
+ const actionsHeader = { t: 'header', v: 2, ...deps.actionsHeader };
61
+ const publicHeader = { t: 'header', v: PUBLIC_VERSION, ...deps.publicHeader };
62
+ const actionLines = [actionsHeader];
63
+ const publicLines = [publicHeader];
64
+ return {
65
+ actionCmd(line) {
66
+ actionLines.push({ t: 'cmd', ...line });
67
+ },
68
+ publicEnv(line) {
69
+ publicLines.push({ t: 'env', ...line });
70
+ },
71
+ publicPresence(line) {
72
+ publicLines.push({ t: 'presence', ...line });
73
+ },
74
+ publicRelay(line) {
75
+ publicLines.push({ t: 'relay', ...line });
76
+ },
77
+ room(roomId) {
78
+ actionsHeader.roomId = roomId;
79
+ publicHeader.roomId = roomId;
80
+ },
81
+ async finish(actionsEnd, publicEnd) {
82
+ actionLines.push({ t: 'end', ...actionsEnd });
83
+ publicLines.push({ t: 'end', ...publicEnd });
84
+ await Promise.all([
85
+ flush(join(deps.dir, `${deps.matchId}${ACTIONS_SUFFIX}`), actionLines, log, 'actions'),
86
+ flush(join(deps.dir, `${deps.matchId}${PUBLIC_SUFFIX}`), publicLines, log, 'public'),
87
+ ]);
88
+ },
89
+ };
90
+ }
@@ -0,0 +1,128 @@
1
+ /**
2
+ * The relay's socket path: joins a seat's or a watcher's connection to a
3
+ * match's `RelaySession` (`runtimes/relay.ts`), and fans each relayed
4
+ * message out to the right live sockets. A real roster
5
+ * (`runtimes/relay-match.ts`'s `RelayMatch`, registered from a room's seats
6
+ * by `room/lobby.ts`'s one hook and read back by `plugins/relay.ts`'s
7
+ * `rosterOf`) now backs it — before that this file was proven only with a
8
+ * directly-injected test roster, refusing every join for lack of one.
9
+ *
10
+ * ## The gate is the play socket's, re-applied
11
+ *
12
+ * `../gate.ts`'s `gateSocketIo` (or the game's own, `RelayDeps.gate`) with the SAME `surface: 'play-socket'` the
13
+ * play socket itself uses (`play/socket.ts`) — not a new check, the
14
+ * identical one, installed again on the same `io` for the same reason
15
+ * `play/socket.ts`'s own header gives: an ordering dependency on who
16
+ * attaches first is how a gate goes missing.
17
+ *
18
+ * ## Identity is derived, never accepted
19
+ *
20
+ * `identityFromHeaders` over the sanitized handshake, exactly as the play
21
+ * socket does. `relay:join`'s `matchId` is read from the payload; nothing
22
+ * else about who is speaking is.
23
+ *
24
+ * ## One session per match, created on its first join
25
+ *
26
+ * A `RelaySession` has nothing to do until somebody joins it, so there is
27
+ * no reason to build one earlier. It is dropped from `live` once it ends.
28
+ *
29
+ * ## A room's next match is joined with the same `relay:join`
30
+ *
31
+ * When a match ends, its roster's owner has already put the room's next match under the same id
32
+ * (`runtimes/relay-match.ts`'s registry), and every live socket is told `relay:ended`. A screen
33
+ * rejoins by sending `relay:join` again on the socket it already has (`relay-channel.ts` does on
34
+ * every `relay:ended`): no new event and no reconnect. Until it does, that socket speaks for
35
+ * nothing — its sends and its disconnect belong to the match it joined, which is over.
36
+ */
37
+ import type { Server as SocketIOServer } from 'socket.io';
38
+ import type { ParticipantId } from '@wolffm/rooms-protocol';
39
+ import type { RateLimitConfig } from '@wolffm/rooms-server';
40
+ import type { Gate } from '@wolffm/service-kernel/http';
41
+ import { type RelayOutcome, type RelaySession, type RelaySink } from './runtimes/relay.js';
42
+ export declare const RELAY_EVENTS: {
43
+ readonly join: "relay:join";
44
+ readonly message: "relay:message";
45
+ /** The host's own word that the match ended: `{ winners }` (the `over` message's seat
46
+ * numbers), or `{ winners: null }` when every seat left. To every live socket of the match,
47
+ * the sender of `over` and every watcher included, so the room can show the result. */
48
+ readonly ended: "relay:ended";
49
+ };
50
+ /** Joins per caller: a burst of 10, then one every 10 s. A seat opens one
51
+ * relay connection per tab, so a burst covers a refresh storm without
52
+ * covering a scan. */
53
+ export declare const RELAY_JOIN_RATE_LIMIT: RateLimitConfig;
54
+ /**
55
+ * A match's own roster, read fresh on every join: how many seats it has,
56
+ * and which one (if any) a participant holds. Supplied by whoever owns the
57
+ * match's lifecycle — `runtimes/relay-match.ts`'s `RelayMatch`.
58
+ *
59
+ * `roleOf` answers `undefined` for a participant the match does not
60
+ * recognise at all — refused the same way `forge:join` refuses an unknown
61
+ * one — and `null` for a recognised watcher.
62
+ *
63
+ * **This file no longer builds the session itself.** `attach` is called at
64
+ * most once per roster, the first time anybody joins, and hands the
65
+ * lifecycle owner this file's own live-socket sink — the owner builds (or
66
+ * finishes building) its `RelaySession` AT THAT POINT, wired to sockets that
67
+ * did not exist a moment earlier, and returns it for this file to relay
68
+ * through. `seatConnected`/`seatDisconnected` are the same two hooks
69
+ * `play/match/shell.ts`'s `MatchShell` already exposes by those names; a
70
+ * roster backed by one simply forwards them, so its own rejoin-grace timers
71
+ * (RelaySession.seatLeft, past the grace) see the same socket transitions
72
+ * this file does.
73
+ */
74
+ export interface RelayRoster {
75
+ seatCount: number;
76
+ roleOf(participantId: ParticipantId): number | null | undefined;
77
+ /**
78
+ * How the room's previous match ended, while this one has not started: a join answers with it,
79
+ * so a screen that loads the room after an end still shows the result. Absent: nothing to tell.
80
+ */
81
+ lastEnded?(): {
82
+ winners: readonly number[] | null;
83
+ } | undefined;
84
+ /** This match's own session, wired to `sink`; `onEnded` is this file's own cleanup, called once. */
85
+ attach(sink: RelaySink, onEnded: (outcome: RelayOutcome | null) => void): RelaySession;
86
+ /** A seat's first live socket joined, or its last one went. Absent: nothing is told. */
87
+ seatConnected?(seat: number): void;
88
+ seatDisconnected?(seat: number): void;
89
+ }
90
+ export type RelayJoinAck = {
91
+ ok: true;
92
+ seat: number | null;
93
+ ended?: {
94
+ winners: readonly number[] | null;
95
+ };
96
+ } | {
97
+ ok: false;
98
+ error: 'bad-request' | 'unknown-match' | 'not-joined' | 'rate-limited';
99
+ };
100
+ export interface RelayDeps {
101
+ /** The tier floor; `CONFIG.minTier` in production. */
102
+ minTier: string;
103
+ /**
104
+ * The handshake gate: the game's own binding of the kernel's `createGate` (its edge secret, its
105
+ * bare-local hatch, its seal-refusal report). Absent: cardtable's (`../gate.ts`).
106
+ */
107
+ gate?: Pick<Gate, 'gateSocketIo'>;
108
+ /** This match's roster, or `undefined` for a matchId nothing is running — refused as `unknown-match`. */
109
+ rosterOf(matchId: string): RelayRoster | undefined;
110
+ /** The match ended: every seat left (`null`), or the leader's own bundle said `{ t: 'over', winners }`. */
111
+ onEnded?(matchId: string, outcome: RelayOutcome | null): void;
112
+ /** Overrides `RELAY_JOIN_RATE_LIMIT`; `null` is none. */
113
+ joinRateLimit?: RateLimitConfig | null;
114
+ log?(entry: Record<string, unknown>): void;
115
+ }
116
+ export interface RelayHandle {
117
+ /** The live session for a match that has at least one join — a test seam, and the composition seam once something builds on it. */
118
+ sessionOf(matchId: string): RelaySession | undefined;
119
+ /** Ends every live session (sweeps them as `every seat left`) and forgets them. */
120
+ close(): void;
121
+ }
122
+ /**
123
+ * Attaches the relay's `connection`/`relay:join`/`relay:message` handlers to
124
+ * `io`. Safe to call once per process; a second call on the same `io` would
125
+ * install the gate twice (harmless, same precedent as `play/socket.ts`) and
126
+ * a second, independent `live` map, so callers should not do that.
127
+ */
128
+ export declare function attachRelay(io: SocketIOServer, deps: RelayDeps): RelayHandle;