@hadoku/game-server 0.1.268 → 0.1.270

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.
@@ -0,0 +1,279 @@
1
+ /**
2
+ * The match socket of a game whose rules run on this server (a `HostedMatch`), and the `/play` routes
3
+ * that start and describe one. Join and resync, watchers, one driving socket per seat, per-recipient
4
+ * emit, disconnect and online counts, the take-back asks, the start route with its queue and ceiling,
5
+ * adoption after a restart and the shutdown hand-over are here. What the game's wire carries is the
6
+ * game's ({@link MatchSocketGame}), and a game adds its own events on the hooks ({@link MatchSocketHooks}).
7
+ *
8
+ * ## The gate is re-applied
9
+ *
10
+ * The game's own gate (`deps.gate`, as `attachRelay` takes it) with the play socket's surface,
11
+ * installed here rather than relied on from whatever attached first: an ordering dependency on a
12
+ * gate is how a gate goes missing. The HTTP routes hang off the `api` router the caller already
13
+ * mounts behind its tier floor.
14
+ *
15
+ * ## Identity is derived, never accepted
16
+ *
17
+ * `identityFromHeaders` over the sanitized handshake. A payload never names who is speaking. The one
18
+ * exception is the caller's dev hatch (`devIdentity`, granted only on a bare local server with no edge
19
+ * secret): a browser cannot set `x-user-id` on a websocket handshake, so every local tab would be the
20
+ * same participant, and a handshake may name itself with `auth: { devUser }` or `?devUser=`.
21
+ *
22
+ * ## A refusal a player can read
23
+ *
24
+ * A join or resync for a match that is gone answers `{ error: 'unknown-match', outcome: 'match-gone',
25
+ * message }` in the game's words, so the client can say what happened rather than show a code. Every
26
+ * other refusal keeps the bare `{ error }`, which a client that reads only `error` already understands.
27
+ */
28
+ import { type Request, type Response, type Router } from 'express';
29
+ import type { Server as SocketIOServer, Socket } from 'socket.io';
30
+ import { type RateLimitConfig } from '@wolffm/rooms-server';
31
+ import { type ParticipantId } from '@wolffm/rooms-protocol';
32
+ import type { Gate } from '@wolffm/service-kernel/http';
33
+ import type { SessionHandle } from '../room/session.js';
34
+ import type { MatchRecord, ReapResult } from './match-host.js';
35
+ import type { MatchShell, RestartAct, TakeBackKind } from './match/shell.js';
36
+ /** The seat a socket that joined with no seat holds: it watches. */
37
+ export declare const WATCHER = -1;
38
+ /** What the socket asks of a match: the shell's seats, lifecycle and take-back, and the game's word to its seats when the server goes down. */
39
+ export type SocketMatch = Pick<MatchShell<{
40
+ t: string;
41
+ }, {
42
+ t: string;
43
+ }>, 'id' | 'epoch' | 'status' | 'failure' | 'unstartable' | 'queuePlace' | 'seats' | 'seatOf' | 'claim' | 'seatConnected' | 'seatDisconnected' | 'whenRunning' | 'restartAct' | 'restartState' | 'stop'> & {
44
+ serverStopping?(message: string): void;
45
+ };
46
+ /** What the registry still knows of a match it let go of. */
47
+ export interface FoundMatch {
48
+ id: string;
49
+ status: string;
50
+ failure: string | null;
51
+ winner?: unknown;
52
+ seats: readonly {
53
+ owner: ParticipantId | null;
54
+ }[];
55
+ }
56
+ /** The registry the socket runs on, typed by what it uses: the game's own registry is passed whole. */
57
+ export interface MatchSocketRegistry<M, Spec, From = never, Ended extends FoundMatch = FoundMatch> {
58
+ create(spec: Spec, from?: From): M;
59
+ get(id: string): M | undefined;
60
+ find(id: string): M | Ended | undefined;
61
+ adopt(record: MatchRecord): M | null;
62
+ full(): number | null;
63
+ handOver(): {
64
+ handed: M[];
65
+ ending: M[];
66
+ };
67
+ stopAll(): void;
68
+ }
69
+ /** The socket.io events the game's client speaks. */
70
+ export interface MatchSocketEvents {
71
+ join: string;
72
+ resync: string;
73
+ /** Which kind of connection this socket is for its seat, after every join and resync. */
74
+ role: string;
75
+ /** This server's build, on connect. */
76
+ build: string;
77
+ serverToClient: string;
78
+ clientToServer: string;
79
+ restartTurn: string;
80
+ restartState: string;
81
+ }
82
+ /** A payload read: its value, or the facts its `<name>-malformed` line carries. */
83
+ export type Read<T> = {
84
+ ok: true;
85
+ value: T;
86
+ } | {
87
+ ok: false;
88
+ facts: Record<string, unknown>;
89
+ };
90
+ /** A refusal of a join or resync: `match-gone` carries its outcome and words, the rest the bare code. */
91
+ export type MatchRefusal = {
92
+ error: string;
93
+ outcome?: 'match-gone';
94
+ message?: string;
95
+ };
96
+ /** {@link MatchSocketHandle.start}'s answer: the match the game opened, or why there is none, as an HTTP status and words. */
97
+ export type MatchStartOutcome<M> = {
98
+ ok: true;
99
+ match: M;
100
+ } | {
101
+ ok: false;
102
+ status: number;
103
+ error: string;
104
+ matchId?: string;
105
+ };
106
+ /** The game's part of its match socket. */
107
+ export interface MatchSocketGame<M, Spec, From, Input extends {
108
+ matchId: string;
109
+ }, Ended> {
110
+ events: MatchSocketEvents;
111
+ /** A join's or resync's payload: the match, and the tab the socket belongs to; or why it is malformed. */
112
+ readRequest(raw: unknown): {
113
+ ok: true;
114
+ value: {
115
+ matchId: string;
116
+ tabId?: string | undefined;
117
+ };
118
+ } | {
119
+ ok: false;
120
+ error: string;
121
+ };
122
+ /** `POST /play/matches`'s body, or why it is refused. */
123
+ parseStart(body: unknown): {
124
+ ok: true;
125
+ spec: Spec;
126
+ } | {
127
+ ok: false;
128
+ error: string;
129
+ };
130
+ /** The game's own refusals of a parsed start, and what it does once the match exists. */
131
+ admitStart?(spec: Spec, req: Request, res: Response): {
132
+ ok: true;
133
+ spec: Spec;
134
+ created?(m: M): void;
135
+ } | {
136
+ ok: false;
137
+ error: string;
138
+ };
139
+ /** What a start's `match-created` line says of it. */
140
+ startFacts?(spec: Spec, from?: From): Record<string, unknown>;
141
+ /** What a seat is sent on a join or a resync, or why there is nothing. */
142
+ snapshot(m: M, seat: number): object;
143
+ watcherSnapshot(m: M): object;
144
+ /** A seat's input on `events.clientToServer`, read. */
145
+ readInput(raw: unknown): Read<Input>;
146
+ /** What a dropped input's line names: one from no seat, or one from a socket that does not drive its seat. */
147
+ inputFacts?: {
148
+ notJoined?(input: Input): object;
149
+ refused?(input: Input): object;
150
+ };
151
+ /** A seat's input, from the socket that drives the seat. */
152
+ fromClient(m: M, seat: number, input: Input, conn: MatchConnection<M>): void;
153
+ /** A take-back act on `events.restartTurn`, read. */
154
+ readTakeBack(raw: unknown): Read<{
155
+ matchId: string;
156
+ act: RestartAct;
157
+ kind?: TakeBackKind | undefined;
158
+ }>;
159
+ /** The match's seats as `caller` may see them, for the start and describe routes. */
160
+ seatsSeenBy(m: M | Ended, caller: ParticipantId): object[];
161
+ /** What a player is told of a match that is gone: never heard of (`undefined`), or ended, with why when it failed. */
162
+ goneWords(failure: string | null | undefined): string;
163
+ }
164
+ /** One connection of the match socket, as the game's layer sees it. */
165
+ export interface MatchConnection<M> {
166
+ readonly socket: Socket;
167
+ readonly participantId: ParticipantId;
168
+ /** The socket's own sends. */
169
+ readonly ctx: MatchSocketContext<M>;
170
+ /**
171
+ * One seated event: its payload read (`<name>-malformed` when it is not), then the match and this
172
+ * socket's seat in it, then whether this socket drives that seat, and only then `act`. A seat's own
173
+ * input (`input` named) logs a send from no seat as `<name>-not-joined` and one from a socket not
174
+ * driving the seat as `c2s-watcher` or `c2s-elsewhere`; a relay (no `input`) drops both unlogged.
175
+ * `open` lets a send through that the seat's driver need not have made.
176
+ */
177
+ onSeated<T extends {
178
+ matchId: string;
179
+ }>(event: string, read: (raw: unknown) => Read<T>, how: {
180
+ name: string;
181
+ input?: string;
182
+ notJoined?: (value: T) => object;
183
+ refused?: (value: T) => object;
184
+ open?: (value: T, seat: number) => boolean;
185
+ }, act: (m: M, seat: number, value: T) => void): void;
186
+ }
187
+ /** The socket's own sends and bookkeeping, for the registry's hooks and the game's layer. */
188
+ export interface MatchSocketContext<M> {
189
+ /** Whether `owner` has any socket open on this server: a match, any role, or another of its screens. */
190
+ online(owner: ParticipantId): boolean;
191
+ /** The registry let go of `m`: its room goes with every socket still in it, and `onFreed` is told unless this server is going down. */
192
+ freed(m: M): void;
193
+ /** `payload` on `event` to the sockets of `seat` only; {@link WATCHER}: every watcher, encoded once. */
194
+ toSeat(m: M, seat: number, event: string, payload: object): void;
195
+ /** `payload` on `event` to every socket of `m`. */
196
+ toMatch(m: M, event: string, payload: unknown): void;
197
+ /** The socket.io room every socket of `m` is in. */
198
+ roomOf(m: M): string;
199
+ }
200
+ /** Where the game's own events hang off the socket. */
201
+ export interface MatchSocketHooks<M, R> {
202
+ /** Each connection, once, after the socket's own handlers. */
203
+ connection?(conn: MatchConnection<M>): void;
204
+ /** A socket joined `m` as `seat` (or {@link WATCHER}), before the seat is marked connected. */
205
+ onJoined?(m: M, seat: number, conn: MatchConnection<M>): void;
206
+ /** After a join's or resync's ack, before its role: what a fresh page needs that the snapshot does not carry. */
207
+ afterSnapshot?(m: M, seat: number, conn: MatchConnection<M>): void;
208
+ /** A socket stopped driving `seat` of `m`: it closed, or a newer window took the seat. */
209
+ onReleased?(m: M, seat: number, ctx: MatchSocketContext<M>): void;
210
+ /** The game's own `/play` routes, behind the same adoption gate. */
211
+ routes?(router: Router, matches: R): void;
212
+ }
213
+ export interface MatchSocketDeps<M, Spec, From, Input extends {
214
+ matchId: string;
215
+ }, Ended extends FoundMatch, R extends MatchSocketRegistry<M, Spec, From, Ended>> {
216
+ /** The tier floor. */
217
+ minTier: string;
218
+ gate: Pick<Gate, 'gateSocketIo'>;
219
+ log(entry: Record<string, unknown>): void;
220
+ game: MatchSocketGame<M, Spec, From, Input, Ended>;
221
+ /** The match registry, built on the socket's own sends. */
222
+ registry(ctx: MatchSocketContext<M>): R;
223
+ /** The game's own events and routes. */
224
+ hooks?: MatchSocketHooks<M, R>;
225
+ /** Why no match can start on this server at all (no engine to run one), or absent when one can. */
226
+ cannotStart?: string;
227
+ /** Per-handshake identity on a bare local server; the caller grants it only there. */
228
+ devIdentity: boolean;
229
+ /** This server's build, told to every socket on connect: a page whose bundle is older reloads. */
230
+ build?: string;
231
+ /** Every connection that passed the gate leaves its key here, from the same sanitized headers its identity comes from. */
232
+ keys?: {
233
+ learn(headers: Socket['request']['headers']): void;
234
+ };
235
+ /** One live tab per player per room: a seat's join names its tab and joins the tab's claim on the match's room. */
236
+ sessions?: {
237
+ handle: Pick<SessionHandle, 'attach'>;
238
+ room(matchId: string): string;
239
+ };
240
+ /** How long a join waits for a starting match. */
241
+ joinWaitMs: number;
242
+ /** How long a start waits for the game to open. */
243
+ startTimeoutMs: number;
244
+ startRateLimit: RateLimitConfig | null;
245
+ restartRateLimit: RateLimitConfig | null;
246
+ undoRateLimit: RateLimitConfig | null;
247
+ /** `GET /play/hosts`: where matches run. Absent: this machine only. */
248
+ hosts?(): unknown;
249
+ /** The registry let go of a match while this server is not going down. */
250
+ onFreed?(m: M): void;
251
+ /** Matches an earlier server left running, found asynchronously. */
252
+ orphans?(): Promise<readonly MatchRecord[]>;
253
+ /** Release the host's idle engines. */
254
+ closeHost?(): void;
255
+ /** The last word on the way out: stop every engine this process still owns. */
256
+ reapOnExit?(): ReapResult;
257
+ }
258
+ export interface MatchSocketHandle<M, Spec, From, R> {
259
+ matches: R;
260
+ /**
261
+ * Start a match the way `POST /play/matches` does: refused while draining, with no engine or at the
262
+ * ceiling, then waited for until the game opens, and stopped if it never does. `startedFor` can read
263
+ * its place in the queue; `from` is the registry's (a resumed game); `created` runs once the match exists.
264
+ */
265
+ start(req: Request, spec: Spec, startedFor: readonly ParticipantId[], from?: From, created?: (m: M) => void): Promise<MatchStartOutcome<M>>;
266
+ /** Settles once every match an earlier server left running is adopted or refused. Never rejects. */
267
+ adopted: Promise<void>;
268
+ /** Stop every match, and release the host's idle engines. */
269
+ close(): void;
270
+ /** Stop accepting matches, leave every live one running for the next process, and tell the seats of any that cannot be. */
271
+ shutdown(reason: string): {
272
+ handed: string[];
273
+ ended: string[];
274
+ reaped: ReapResult;
275
+ };
276
+ }
277
+ export declare function attachMatchSocket<M extends SocketMatch, Spec, From, Input extends {
278
+ matchId: string;
279
+ }, Ended extends FoundMatch, R extends MatchSocketRegistry<M, Spec, From, Ended>>(io: SocketIOServer, api: Router, deps: MatchSocketDeps<M, Spec, From, Input, Ended, R>): MatchSocketHandle<M, Spec, From, R>;
@@ -0,0 +1,462 @@
1
+ /**
2
+ * The match socket of a game whose rules run on this server (a `HostedMatch`), and the `/play` routes
3
+ * that start and describe one. Join and resync, watchers, one driving socket per seat, per-recipient
4
+ * emit, disconnect and online counts, the take-back asks, the start route with its queue and ceiling,
5
+ * adoption after a restart and the shutdown hand-over are here. What the game's wire carries is the
6
+ * game's ({@link MatchSocketGame}), and a game adds its own events on the hooks ({@link MatchSocketHooks}).
7
+ *
8
+ * ## The gate is re-applied
9
+ *
10
+ * The game's own gate (`deps.gate`, as `attachRelay` takes it) with the play socket's surface,
11
+ * installed here rather than relied on from whatever attached first: an ordering dependency on a
12
+ * gate is how a gate goes missing. The HTTP routes hang off the `api` router the caller already
13
+ * mounts behind its tier floor.
14
+ *
15
+ * ## Identity is derived, never accepted
16
+ *
17
+ * `identityFromHeaders` over the sanitized handshake. A payload never names who is speaking. The one
18
+ * exception is the caller's dev hatch (`devIdentity`, granted only on a bare local server with no edge
19
+ * secret): a browser cannot set `x-user-id` on a websocket handshake, so every local tab would be the
20
+ * same participant, and a handshake may name itself with `auth: { devUser }` or `?devUser=`.
21
+ *
22
+ * ## A refusal a player can read
23
+ *
24
+ * A join or resync for a match that is gone answers `{ error: 'unknown-match', outcome: 'match-gone',
25
+ * message }` in the game's words, so the client can say what happened rather than show a code. Every
26
+ * other refusal keeps the bare `{ error }`, which a client that reads only `error` already understands.
27
+ */
28
+ import express from 'express';
29
+ import { RoomRegistry, SKIP, emitPerRecipient, joinRoom, leaveRoom } from '@wolffm/rooms-server';
30
+ import { createSeatTable } from '@wolffm/rooms-protocol';
31
+ import { costlyActLimit, httpCaller, perCallerLimit } from '../http/request.js';
32
+ import { refuse } from '../http/room-core.js';
33
+ import { identityFromHeaders, participantHandle } from '../room/identity.js';
34
+ import { callerContext, report } from '../telemetry.js';
35
+ import { createSeatControl } from './seat-control.js';
36
+ /** The seat a socket that joined with no seat holds: it watches. */
37
+ export const WATCHER = -1;
38
+ const DEV_USER = /^[a-z0-9-]{1,32}$/;
39
+ /**
40
+ * Does this participant hold a seat in this match that has a board to return? A finished match is
41
+ * still worth rejoining for someone who was playing it: they get the board and the notice that ended
42
+ * it. For anyone else it is gone.
43
+ */
44
+ function hasBoard(match, participantId) {
45
+ const seat = match.seatOf(participantId);
46
+ return seat !== null && match.seats[seat]?.playerId !== null;
47
+ }
48
+ export function attachMatchSocket(io, api, deps) {
49
+ const { log, game } = deps;
50
+ const { events } = game;
51
+ // A game frame is never droppable: a dropped delta is a desynced board.
52
+ const policy = {
53
+ thresholdBytes: 1024 * 1024,
54
+ highPriority: new Set([events.serverToClient]),
55
+ lowPriorityOrder: [],
56
+ onDrop: (info) => log({ evt: 'emit-drop', ...info }),
57
+ onError: (info) => log({ evt: 'emit-error', event: info.event, socketId: info.socketId }),
58
+ };
59
+ const rooms = new RoomRegistry(() => ({ match: null }));
60
+ /** The socket.io room of a match's watchers, who are all sent one channel. */
61
+ const watchersOf = (matchId) => `${matchId}#watchers`;
62
+ const roomFor = (match) => {
63
+ const room = rooms.seed(match.id, match.id);
64
+ if (room.app.match === null) {
65
+ room.app.match = match;
66
+ // Membership only. Seat authority is the match's `claim`, which never transfers a seat; a
67
+ // capacity-0 table cannot be mistaken for it.
68
+ room.seats = createSeatTable(0);
69
+ }
70
+ return room;
71
+ };
72
+ /** One driving socket per seat, the newest: a tab is named `participant + tab id`, so only the same participant's same tab ever matches. */
73
+ const seats = createSeatControl();
74
+ const drives = (matchId, seat, socketId) => seat !== WATCHER && seats.holds(matchId, seat, socketId);
75
+ /** Each participant's open sockets on this server, any role: who `online` answers about. */
76
+ const online = new Map();
77
+ /** Set by `shutdown`: this process is going away, so it starts nothing new. */
78
+ let draining = null;
79
+ /** Set by `close`: nothing more is told to anyone. */
80
+ let closed = false;
81
+ const ctx = {
82
+ online: (owner) => (online.get(owner) ?? 0) > 0,
83
+ freed(match) {
84
+ // The room held the match itself: without this a stopped match stayed in memory for good.
85
+ rooms.delete(match.id);
86
+ io.in(match.id).socketsLeave(match.id);
87
+ io.in(watchersOf(match.id)).socketsLeave(watchersOf(match.id));
88
+ seats.forget(match.id);
89
+ // A match let go of because this process is going away is not gone: the next server may take it back.
90
+ if (draining === null && !closed)
91
+ deps.onFreed?.(match);
92
+ },
93
+ toSeat(match, seat, event, payload) {
94
+ if (seat === WATCHER) {
95
+ io.to(watchersOf(match.id)).emit(event, payload);
96
+ return;
97
+ }
98
+ emitPerRecipient(io, roomFor(match), event, (client) => (client.app.seat === seat ? payload : SKIP), policy);
99
+ },
100
+ toMatch: (match, event, payload) => io.to(roomFor(match).roomId).emit(event, payload),
101
+ roomOf: (match) => roomFor(match).roomId,
102
+ };
103
+ const matches = deps.registry(ctx);
104
+ const hooks = deps.hooks ?? {};
105
+ /* ── HTTP ───────────────────────────────────────────────────────── */
106
+ const router = express.Router();
107
+ router.use(express.json({ limit: '256kb' }));
108
+ // The server listens before every match an earlier one left running is adopted, so nothing here
109
+ // answers about a match until they are: one not adopted yet is not gone.
110
+ router.use((_req, _res, next) => {
111
+ if (adoptedYet)
112
+ next();
113
+ else
114
+ void adopted.then(() => next());
115
+ });
116
+ /** Starts still in flight, and who is waiting on each. */
117
+ const waitingOn = new Map();
118
+ const restartLimit = costlyActLimit(deps.restartRateLimit, { act: 'restart-turn', onRefused: () => log({ evt: 'restart-refused', reason: 'rate-limited' }) });
119
+ const undoLimit = costlyActLimit(deps.undoRateLimit, { act: 'undo', onRefused: () => log({ evt: 'undo-refused', reason: 'rate-limited' }) });
120
+ const startLimit = perCallerLimit(deps.startRateLimit, 'too many match starts; wait a little and try again', {
121
+ act: 'match-start',
122
+ onRefused: () => log({ evt: 'match-start-refused', reason: 'rate-limited' }),
123
+ });
124
+ router.post('/matches', async (req, res) => {
125
+ const parsed = game.parseStart(req.body);
126
+ if (!parsed.ok)
127
+ return refuse(res, 400, parsed.error);
128
+ if (!startLimit(req, res))
129
+ return;
130
+ const admitted = game.admitStart?.(parsed.spec, req, res) ?? { ok: true, spec: parsed.spec };
131
+ if (!admitted.ok)
132
+ return refuse(res, 400, admitted.error);
133
+ // Who is waiting on this start, for `GET /queue`: the caller, and the players a room start names
134
+ // (`res.locals`, this process's own scratch space, never the body).
135
+ const startedFor = res.locals.startedFor;
136
+ const started = await start(req, admitted.spec, [httpCaller(req), ...(Array.isArray(startedFor) ? startedFor : [])], undefined, admitted.created);
137
+ if (!started.ok) {
138
+ res.status(started.status).json({ ...(started.matchId === undefined ? {} : { matchId: started.matchId }), error: started.error });
139
+ return;
140
+ }
141
+ const { match } = started;
142
+ res.status(201).json({ matchId: match.id, epoch: match.epoch, seats: game.seatsSeenBy(match, httpCaller(req)) });
143
+ });
144
+ async function start(req, spec, startedFor, from, created) {
145
+ // A match started now would run on an engine this process is about to stop watching, and its
146
+ // seats would never be told. Refused in words instead.
147
+ if (draining !== null)
148
+ return { ok: false, status: 503, error: draining };
149
+ if (deps.cannotStart !== undefined)
150
+ return { ok: false, status: 503, error: deps.cannotStart };
151
+ const max = matches.full();
152
+ if (max !== null) {
153
+ report('capacity-refused', { act: 'match-start', max, ...callerContext(req.headers) });
154
+ return { ok: false, status: 503, error: `the server is already running ${max} matches` };
155
+ }
156
+ const match = matches.create(spec, from);
157
+ roomFor(match);
158
+ log({ evt: 'match-created', matchId: match.id, ...game.startFacts?.(spec, from) });
159
+ created?.(match);
160
+ waitingOn.set(match, new Set(startedFor));
161
+ const running = await match.whenRunning(deps.startTimeoutMs);
162
+ waitingOn.delete(match);
163
+ if (!running.ok) {
164
+ match.stop();
165
+ return { ok: false, status: match.unstartable === null ? 500 : 503, error: running.error, matchId: match.id };
166
+ }
167
+ return { ok: true, match };
168
+ }
169
+ /**
170
+ * The caller's place in the queue for an engine while a start they are waiting on waits its turn:
171
+ * the nearest, if several. `null` when none is waiting: booting, or no start.
172
+ */
173
+ router.get('/queue', (req, res) => {
174
+ const caller = httpCaller(req);
175
+ const places = [...waitingOn].flatMap(([match, who]) => (who.has(caller) && match.queuePlace !== null ? [match.queuePlace] : []));
176
+ res.json({ place: places.length === 0 ? null : Math.min(...places) });
177
+ });
178
+ /** Each host's eligibility, the bar that failed and why, its engines, matches and health. */
179
+ router.get('/hosts', (_req, res) => {
180
+ res.json(deps.hosts?.() ?? { mode: 'none' });
181
+ });
182
+ router.get('/matches/:id', (req, res) => {
183
+ const match = matches.find(String(req.params.id));
184
+ if (match === undefined)
185
+ return refuse(res, 404, 'no such match');
186
+ const seen = game.seatsSeenBy(match, httpCaller(req));
187
+ res.json({
188
+ matchId: match.id,
189
+ status: match.status,
190
+ failure: match.failure,
191
+ winner: match.winner ?? null,
192
+ // The digest handle only, never the id itself.
193
+ seats: match.seats.map((s, i) => ({ ...seen[i], claimedBy: s.owner === null ? null : participantHandle(s.owner) })),
194
+ });
195
+ });
196
+ hooks.routes?.(router, matches);
197
+ api.use('/play', router);
198
+ /* ── Socket ─────────────────────────────────────────────────────── */
199
+ deps.gate.gateSocketIo(io, { minTier: deps.minTier, surface: 'play-socket' });
200
+ function identityOf(socket) {
201
+ const headers = socket.request.headers;
202
+ if (deps.devIdentity) {
203
+ const auth = socket.handshake.auth;
204
+ const fromAuth = typeof auth?.devUser === 'string' ? auth.devUser : undefined;
205
+ const fromQuery = socket.handshake.query.devUser;
206
+ const devUser = fromAuth ?? (typeof fromQuery === 'string' ? fromQuery : undefined);
207
+ if (devUser !== undefined && DEV_USER.test(devUser)) {
208
+ // identity-model-disable-next-line G5: LEGITIMATE — the dev carve-out. The `local-dev-seat-<user>`
209
+ // identity is reached only when the caller grants `devIdentity`, which it does only with the bare-local
210
+ // hatch open and no edge secret, and the name is held to /^[a-z0-9-]{1,32}$/. Production sets the edge
211
+ // secret, so the branch is unreachable there, and a dev identity only ever reaches a local server's store.
212
+ return identityFromHeaders({ ...headers, 'x-user-id': `local-dev-seat-${devUser}` }, socket.id);
213
+ }
214
+ }
215
+ return identityFromHeaders(headers, socket.id);
216
+ }
217
+ /**
218
+ * `'elsewhere'` is a seat's socket a newer window of the same player took the seat from. `'watcher'`
219
+ * is a socket with no seat, on the shared public channel, refused every input.
220
+ */
221
+ const tellRole = (target, matchId, role) => {
222
+ target.emit(events.role, { matchId, role });
223
+ };
224
+ /** The log line a refused input gets: a watcher's, or a seat socket's that no longer drives the seat. */
225
+ const refusedInput = (seat) => (seat === WATCHER ? 'c2s-watcher' : 'c2s-elsewhere');
226
+ /** The `match-gone` refusal: the code the wire always carried, plus the outcome and the game's words. */
227
+ const matchGone = (failure) => ({ error: 'unknown-match', outcome: 'match-gone', message: game.goneWords(failure) });
228
+ io.on('connection', (socket) => {
229
+ if (deps.build !== undefined)
230
+ socket.emit(events.build, { build: deps.build });
231
+ const participantId = identityOf(socket);
232
+ deps.keys?.learn(socket.request.headers);
233
+ online.set(participantId, (online.get(participantId) ?? 0) + 1);
234
+ /** matchId → seat, for this connection. */
235
+ const joined = new Map();
236
+ const conn = { socket, participantId, ctx, onSeated };
237
+ async function snapshotFor(raw, isJoin) {
238
+ const request = game.readRequest(raw);
239
+ if (!request.ok)
240
+ return { reply: { error: request.error } };
241
+ // A seat back after a restart can ask before its match is adopted: it waits, and is not told
242
+ // the match is gone. Only then: an act sent right behind the join must find the seat already held.
243
+ if (!adoptedYet)
244
+ await adopted;
245
+ const { matchId, tabId } = request.value;
246
+ const match = matches.get(matchId);
247
+ if (match === undefined) {
248
+ // Ended and let go of: what is left of it says how it ended. Never heard of: it never
249
+ // existed, or, the case that actually happens, it died with an earlier process.
250
+ const ended = matches.find(matchId);
251
+ log({ evt: 'match-gone', matchId, ...(ended === undefined ? {} : { status: ended.status }), participantId, event: isJoin ? 'join' : 'resync' });
252
+ return { reply: matchGone(ended === undefined ? undefined : ended.failure) };
253
+ }
254
+ // Here and finished: a seat that has a board still gets it, with the notice the ending put on its
255
+ // stream. One that has none has nothing to come back to, and "starting" would be a lie.
256
+ if ((match.status === 'failed' || match.status === 'stopped') && !hasBoard(match, participantId)) {
257
+ log({ evt: 'match-gone', matchId: match.id, status: match.status, participantId, event: isJoin ? 'join' : 'resync' });
258
+ return { reply: matchGone(match.failure) };
259
+ }
260
+ let seat = joined.get(match.id) ?? null;
261
+ if (seat === null) {
262
+ if (!isJoin)
263
+ return { reply: { error: 'not-joined' } };
264
+ const claim = match.claim(participantId);
265
+ // Every seat held by other people: this socket watches. The same room, so it hears the
266
+ // public events; its own channel is the watcher one.
267
+ if (!claim.ok && claim.error !== 'match-full')
268
+ return { reply: { error: claim.error } };
269
+ seat = claim.ok ? claim.seat : WATCHER;
270
+ // Another live tab of this account holds the room: it is asked there, never taken from here.
271
+ if (seat !== WATCHER && tabId !== undefined && deps.sessions !== undefined && !deps.sessions.handle.attach(deps.sessions.room(match.id), participantId, tabId, socket)) {
272
+ return { reply: { error: 'session-elsewhere' } };
273
+ }
274
+ // The seat is this socket's before the first await: socket.io hands every packet of one read
275
+ // to its handler in that same tick, so an act the browser sent right behind its join is read
276
+ // before this function resumes, and would be dropped as `c2s-not-joined`.
277
+ joined.set(match.id, seat);
278
+ const { replaced, sameTab } = seat === WATCHER ? { replaced: null, sameTab: false } : seats.take(match.id, seat, socket.id, tabId === undefined ? null : `${participantId}\n${tabId}`);
279
+ const room = roomFor(match);
280
+ joinRoom(room, socket.id, socket.id, participantId, () => ({ seat: seat }));
281
+ if (replaced !== null) {
282
+ // Out of the line already, so its own `disconnect` marks no seat gone: this socket is in the room.
283
+ log({ evt: sameTab ? 'tab-rejoined' : 'seat-taken-over', matchId: match.id, seat, participantId, socketId: socket.id, replaced, role: 'player' });
284
+ const old = io.sockets.sockets.get(replaced);
285
+ if (old !== undefined && !sameTab) {
286
+ hooks.onReleased?.(match, seat, ctx);
287
+ tellRole(old, match.id, 'elsewhere');
288
+ }
289
+ old?.disconnect(true);
290
+ }
291
+ // A socket that watched and now holds a seat is sent its seat's channel only.
292
+ if (seat !== WATCHER)
293
+ await socket.leave(watchersOf(match.id));
294
+ await socket.join(seat === WATCHER ? [room.roomId, watchersOf(match.id)] : room.roomId);
295
+ log({ evt: 'joined', matchId: match.id, seat, participantId, fresh: claim.ok ? claim.fresh : false, role: seat === WATCHER ? 'watcher' : 'player' });
296
+ hooks.onJoined?.(match, seat, conn);
297
+ // A refresh: the old socket's close armed an abort of this seat's asks.
298
+ if (seat !== WATCHER)
299
+ match.seatConnected(seat);
300
+ }
301
+ if (match.status === 'starting') {
302
+ const running = await match.whenRunning(deps.joinWaitMs);
303
+ if (!running.ok)
304
+ return { reply: { error: running.error } };
305
+ }
306
+ return { reply: seat === WATCHER ? game.watcherSnapshot(match) : game.snapshot(match, seat), match };
307
+ }
308
+ function answer(event) {
309
+ return (raw, ack) => {
310
+ if (typeof ack !== 'function') {
311
+ log({ evt: 'no-ack', event, participantId });
312
+ return;
313
+ }
314
+ void snapshotFor(raw, event === 'join').then(({ reply, match }) => {
315
+ ack(reply);
316
+ if ('error' in reply) {
317
+ const matchId = typeof raw === 'object' && raw !== null ? raw.matchId : undefined;
318
+ log({ evt: `${event}-refused`, matchId: typeof matchId === 'string' ? matchId : null, participantId, error: reply.error });
319
+ return;
320
+ }
321
+ const seat = match === undefined ? undefined : joined.get(match.id);
322
+ // The registry's match for the id now: a restore since the ask replaced it.
323
+ const current = match === undefined ? undefined : matches.get(match.id);
324
+ if (current === undefined || seat === undefined)
325
+ return;
326
+ // After the ack, so the client has adopted the snapshot's cursor before the next frame reaches it.
327
+ hooks.afterSnapshot?.(current, seat, conn);
328
+ // And whether this socket drives the seat, every time: a newer window may have taken it since.
329
+ tellRole(socket, current.id, seat === WATCHER ? 'watcher' : drives(current.id, seat, socket.id) ? 'player' : 'elsewhere');
330
+ });
331
+ };
332
+ }
333
+ socket.on(events.join, answer('join'));
334
+ socket.on(events.resync, answer('resync'));
335
+ function onSeated(event, read, how, act) {
336
+ socket.on(event, (raw) => {
337
+ const parsed = read(raw);
338
+ if (!parsed.ok) {
339
+ log({ evt: `${how.name}-malformed`, participantId, ...parsed.facts });
340
+ return;
341
+ }
342
+ const { value } = parsed;
343
+ const match = matches.get(value.matchId);
344
+ const seat = match === undefined ? undefined : joined.get(match.id);
345
+ if (match === undefined || seat === undefined) {
346
+ if (how.input !== undefined)
347
+ log({ evt: `${how.name}-not-joined`, participantId, matchId: value.matchId, ...how.notJoined?.(value) });
348
+ return;
349
+ }
350
+ if (!drives(match.id, seat, socket.id) && how.open?.(value, seat) !== true) {
351
+ if (how.input !== undefined)
352
+ log({ evt: refusedInput(seat), participantId, matchId: match.id, seat, input: how.input, ...how.refused?.(value) });
353
+ return;
354
+ }
355
+ act(match, seat, value);
356
+ });
357
+ }
358
+ onSeated(events.clientToServer, game.readInput, { name: 'c2s', input: 'c2s', ...game.inputFacts }, (match, seat, input) => game.fromClient(match, seat, input, conn));
359
+ // A take-back, restarting the turn or undoing the last action: the seat is the claimed one, and the
360
+ // match's `restartAct` decides who may send which act. An ask is the costly one.
361
+ onSeated(events.restartTurn, game.readTakeBack, { name: 'restart', input: 'restart-turn' }, (match, seat, { act, kind = 'restart' }) => {
362
+ if (act === 'ask' && !(kind === 'undo' ? undoLimit : restartLimit)(participantId, socket.handshake.headers)) {
363
+ socket.emit(events.restartState, match.restartState());
364
+ return;
365
+ }
366
+ const outcome = match.restartAct(seat, act, kind);
367
+ if (!outcome.ok) {
368
+ log({ evt: `${kind}-refused`, participantId, matchId: match.id, seat, act, error: outcome.error });
369
+ // Whatever this socket drew on its own, the server's answer stands.
370
+ socket.emit(events.restartState, match.restartState());
371
+ }
372
+ });
373
+ hooks.connection?.(conn);
374
+ socket.on('disconnect', (reason) => {
375
+ const left = (online.get(participantId) ?? 1) - 1;
376
+ if (left <= 0)
377
+ online.delete(participantId);
378
+ else
379
+ online.set(participantId, left);
380
+ for (const [matchId, seat] of joined) {
381
+ // Before the match lookup: a socket lets go of the seat even when its match is gone, or a
382
+ // stale id would hold the control.
383
+ const wasDriver = seat !== WATCHER && seats.release(matchId, seat, socket.id);
384
+ const match = matches.get(matchId);
385
+ if (match === undefined)
386
+ continue;
387
+ const room = roomFor(match);
388
+ leaveRoom(room, socket.id);
389
+ const stillHere = [...room.clients.values()].some((c) => c.app.seat === seat);
390
+ if (wasDriver)
391
+ hooks.onReleased?.(match, seat, ctx);
392
+ log({ evt: 'left', matchId, seat, participantId, reason, stillHere });
393
+ // A watcher holds nothing: no seat to mark gone.
394
+ if (seat === WATCHER)
395
+ continue;
396
+ if (!stillHere)
397
+ match.seatDisconnected(seat);
398
+ }
399
+ });
400
+ });
401
+ /* ── Matches an earlier server left running ──────────────────────── */
402
+ // Here rather than in the caller, because an adopted match must be in the registry and have its room
403
+ // before a client can ask for it. The host finds them asynchronously (an engine may run on another
404
+ // machine), so a join and every `/play` route wait for `adopted`; the server listens without waiting.
405
+ // The host offers each orphan once and stops what is not taken on its own deadline, so an adopt that
406
+ // throws costs one match, not a leaked engine.
407
+ const adopted = (deps.orphans?.() ?? Promise.resolve([]))
408
+ .then((records) => {
409
+ for (const record of records) {
410
+ try {
411
+ const match = matches.adopt(record);
412
+ if (match === null) {
413
+ log({ evt: 'match-not-adopted', matchId: record.matchId, reason: 'the host cannot re-attach' });
414
+ continue;
415
+ }
416
+ roomFor(match);
417
+ log({
418
+ evt: 'match-adopted',
419
+ matchId: match.id,
420
+ hostId: record.hostId,
421
+ status: match.status,
422
+ orphanedAt: record.orphanedAt ?? null,
423
+ seats: match.seats.map((s) => ({ seat: s.seat, claimed: s.owner !== null, playerId: s.playerId })),
424
+ });
425
+ }
426
+ catch (err) {
427
+ log({ evt: 'match-adopt-failed', matchId: record.matchId, error: err.message });
428
+ }
429
+ }
430
+ })
431
+ .catch((err) => {
432
+ log({ evt: 'orphans-failed', error: err.message });
433
+ });
434
+ let adoptedYet = false;
435
+ void adopted.then(() => (adoptedYet = true));
436
+ return {
437
+ matches,
438
+ start,
439
+ adopted,
440
+ close() {
441
+ closed = true;
442
+ matches.stopAll();
443
+ deps.closeHost?.();
444
+ },
445
+ shutdown(reason) {
446
+ draining = reason;
447
+ // Every match that holds an engine is in one list or the other, a finished one inside its grace
448
+ // included: it is handed over like a running one, so its seats keep their result screens.
449
+ const { handed, ending } = matches.handOver();
450
+ for (const match of ending)
451
+ match.serverStopping?.(reason);
452
+ for (const match of ending)
453
+ match.stop();
454
+ // An idle engine holds no game, so it is stopped either way.
455
+ deps.closeHost?.();
456
+ // And then the last word, because asking is measurably not enough: an engine may take seconds to
457
+ // honour a stop and this process has about a millisecond left.
458
+ const reaped = deps.reapOnExit?.() ?? { killed: [], kept: [], left: [] };
459
+ return { handed: handed.map((m) => m.id), ended: ending.map((m) => m.id), reaped };
460
+ },
461
+ };
462
+ }
@@ -0,0 +1,15 @@
1
+ /**
2
+ * What a match socket keeps for each match, one entry per match: letting go of a match drops its
3
+ * entry, and a new epoch empties it, without reading any other match's keys. Every map a match
4
+ * keeps lives in its one entry, so a map added later cannot be left out of either.
5
+ */
6
+ export interface MatchKeyedMaps<T> {
7
+ /** `matchId`'s entry, made the first time it is asked for. */
8
+ of(matchId: string): T;
9
+ /** A new epoch: `matchId`'s entry starts afresh, and every other match's is untouched. */
10
+ reset(matchId: string): void;
11
+ /** The match is gone: its entry goes. */
12
+ forget(matchId: string): void;
13
+ }
14
+ /** One entry per match, each made by `make`. */
15
+ export declare function matchKeyedMaps<T>(make: () => T): MatchKeyedMaps<T>;
@@ -0,0 +1,21 @@
1
+ /** One entry per match, each made by `make`. */
2
+ export function matchKeyedMaps(make) {
3
+ const byMatch = new Map();
4
+ return {
5
+ of(matchId) {
6
+ const held = byMatch.get(matchId);
7
+ if (held !== undefined)
8
+ return held;
9
+ const made = make();
10
+ byMatch.set(matchId, made);
11
+ return made;
12
+ },
13
+ reset(matchId) {
14
+ if (byMatch.has(matchId))
15
+ byMatch.set(matchId, make());
16
+ },
17
+ forget(matchId) {
18
+ byMatch.delete(matchId);
19
+ },
20
+ };
21
+ }
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@hadoku/game-server",
3
- "version": "0.1.268",
4
- "gitHead": "7e4245c9b315269a20097fc89d20c3982b307e4a",
3
+ "version": "0.1.270",
4
+ "gitHead": "da8efa216c00e9fe86b62c692839a837155923c0",
5
5
  "type": "module",
6
6
  "license": "MIT",
7
7
  "description": "The server parts any hosted game shares, above the kernel: the app config and edge auth, the room core (identity, seats, sessions, membership, the room list, the generic room routes), match hosting (the host contract, local and remote JVMs, placement, the start queue, recordings, the in-process and relay runtimes), the match socket and the match registry, streams, erase, telemetry and usage. Knows no game; Magic plugs in from apps/server. MIT; imports only node built-ins, express, socket.io, @wolffm/* and the platform packages.",
@@ -16,12 +16,12 @@
16
16
  "play/remote/"
17
17
  ],
18
18
  "dependencies": {
19
- "@wolffm/host-wire": "npm:@hadoku/host-wire@0.1.268",
20
- "@wolffm/platform-wire": "npm:@hadoku/platform-wire@0.1.268",
21
- "@wolffm/service-kernel": "npm:@hadoku/service-kernel@0.1.301",
19
+ "@wolffm/host-wire": "npm:@hadoku/host-wire@0.1.270",
20
+ "@wolffm/platform-wire": "npm:@hadoku/platform-wire@0.1.270",
21
+ "@wolffm/service-kernel": "npm:@hadoku/service-kernel@0.1.303",
22
22
  "@wolffm/prefs-client": "npm:@hadoku/prefs-client@^1.2.4",
23
- "@wolffm/rooms-protocol": "npm:@hadoku/rooms-protocol@^0.45.158",
24
- "@wolffm/rooms-server": "npm:@hadoku/rooms-server@^0.45.158",
23
+ "@wolffm/rooms-protocol": "npm:@hadoku/rooms-protocol@^0.45.159",
24
+ "@wolffm/rooms-server": "npm:@hadoku/rooms-server@^0.45.159",
25
25
  "express": "^5.3.0",
26
26
  "socket.io": "^4.8.4",
27
27
  "zod": "^4.6.7"