@hadoku/game-server 0.1.40 → 0.1.42

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.
package/dist/auth.d.ts ADDED
@@ -0,0 +1,24 @@
1
+ /**
2
+ * A game's edge auth and tier gate, built from its own config: the one pair every game server
3
+ * needs (provenance on every request and socket handshake, the floor below `/health`), so no game
4
+ * wires `createEdgeAuth`/`createGate` by hand. Cardtable's own binding (`kernel.ts`) is this,
5
+ * over its `CONFIG`.
6
+ */
7
+ import { type EdgeAuth } from '@wolffm/service-kernel/auth';
8
+ import { type Gate, type SealRefusedReporter } from '@wolffm/service-kernel/http';
9
+ import type { GameServerConfig } from './config.js';
10
+ export interface GameAuth {
11
+ edgeAuth: EdgeAuth;
12
+ /** The gate at the game's own floor: the HTTP floor, and every socket's handshake. */
13
+ gate: Gate;
14
+ }
15
+ export interface GameAuthOptions {
16
+ /** Told of every request or handshake the seal refused. Default: logged under `svc`. */
17
+ reportSealRefused?: SealRefusedReporter;
18
+ /** The log's `svc` for the default reporter. */
19
+ svc?: string;
20
+ }
21
+ type AuthConfig = Pick<GameServerConfig, 'edgeAuthSecret' | 'allowUnverifiedEdge' | 'devTier' | 'minTier'>;
22
+ /** Read lazily: a config built on first access (`lazyConfig`) is not forced by building this. */
23
+ export declare function createGameAuth(config: AuthConfig, options?: GameAuthOptions): GameAuth;
24
+ export {};
package/dist/auth.js ADDED
@@ -0,0 +1,31 @@
1
+ /**
2
+ * A game's edge auth and tier gate, built from its own config: the one pair every game server
3
+ * needs (provenance on every request and socket handshake, the floor below `/health`), so no game
4
+ * wires `createEdgeAuth`/`createGate` by hand. Cardtable's own binding (`kernel.ts`) is this,
5
+ * over its `CONFIG`.
6
+ */
7
+ import { createEdgeAuth, rankOf, tierOf } from '@wolffm/service-kernel/auth';
8
+ import { createGate } from '@wolffm/service-kernel/http';
9
+ /** Read lazily: a config built on first access (`lazyConfig`) is not forced by building this. */
10
+ export function createGameAuth(config, options = {}) {
11
+ const edgeAuth = createEdgeAuth({
12
+ edgeAuthSecret: () => config.edgeAuthSecret,
13
+ allowUnverifiedEdge: () => config.allowUnverifiedEdge,
14
+ devTier: () => config.devTier,
15
+ });
16
+ const svc = options.svc ?? 'game-server';
17
+ const report = options.reportSealRefused ??
18
+ ((surface, headers, path) => {
19
+ const tier = headers['x-hadoku-tier'];
20
+ console.log(JSON.stringify({ t: new Date().toISOString(), svc, evt: 'seal-refused', surface, tier: typeof tier === 'string' ? tier : 'public', path }));
21
+ });
22
+ const gate = createGate({
23
+ sanitizeHeaders: edgeAuth.sanitizeHeaders,
24
+ edgeProvenance: edgeAuth.edgeProvenance,
25
+ tierOf,
26
+ rankOf,
27
+ reportSealRefused: report,
28
+ minTier: () => config.minTier,
29
+ });
30
+ return { edgeAuth, gate };
31
+ }
package/dist/config.d.ts CHANGED
@@ -37,6 +37,7 @@ import { type Tier } from '@wolffm/service-kernel/auth';
37
37
  * tsx) it is `packages/game-server/src/`, and the app it configures is `apps/server` beside it.
38
38
  */
39
39
  export declare const APP_ROOT: string;
40
+ /** Resolve a configured path against the package root unless it is absolute. */
40
41
  /** The in-clone paths a state dir replaces, for the boot move (`state-dir.ts`). */
41
42
  export declare const LEGACY_STATE: {
42
43
  readonly dataDir: string;
@@ -47,6 +48,13 @@ export interface CreateConfigOptions {
47
48
  envPrefix?: string;
48
49
  /** The environment to read. Default `process.env` — override to build a second config in one process (a test, or a second game). */
49
50
  env?: NodeJS.ProcessEnv;
51
+ /** What a relative directory resolves against: the game server's own package root. Default: cardtable's `apps/server`. */
52
+ root?: string;
53
+ /**
54
+ * A game's own defaults, by unprefixed name (`PORT: '9010'`, `BASE_PREFIX: '/bomberman'`,
55
+ * `ROOMS_DIR: 'state/rooms'`): what a variable the environment leaves unset reads as.
56
+ */
57
+ defaults?: Readonly<Record<string, string>>;
50
58
  }
51
59
  export interface GameServerConfig {
52
60
  /** Port this server listens on. cloudflared points the tunnel hostname here. */
package/dist/config.js CHANGED
@@ -41,14 +41,15 @@ const HERE = dirname(fileURLToPath(import.meta.url));
41
41
  */
42
42
  export const APP_ROOT = basename(HERE) === 'dist' ? dirname(HERE) : resolve(HERE, '../../../apps/server');
43
43
  /** Resolve a configured path against the package root unless it is absolute. */
44
- const resolveDir = (value) => (isAbsolute(value) ? value : resolve(APP_ROOT, value));
45
44
  /** The in-clone paths a state dir replaces, for the boot move (`state-dir.ts`). */
46
45
  export const LEGACY_STATE = { dataDir: resolve(APP_ROOT, 'data'), logDir: resolve(APP_ROOT, 'logs') };
47
46
  /** Everything a game-server app needs that is not specific to any one game (w119 §C). */
48
47
  export function createConfig(options = {}) {
49
48
  const prefix = options.envPrefix ?? 'CARDTABLE';
50
49
  const env = options.env ?? process.env;
51
- const read = (name) => env[`${prefix}_${name}`];
50
+ const read = (name) => env[`${prefix}_${name}`] ?? options.defaults?.[name];
51
+ const root = options.root ?? APP_ROOT;
52
+ const resolveDir = (value) => (isAbsolute(value) ? value : resolve(root, value));
52
53
  const stateDirRaw = read('STATE_DIR');
53
54
  const stateDir = stateDirRaw ? resolveDir(stateDirRaw) : '';
54
55
  const logDir = resolveDir(read('LOG_DIR') || (stateDir ? join(stateDir, 'logs') : 'logs'));
@@ -72,13 +73,13 @@ export function createConfig(options = {}) {
72
73
  prefsBaseUrl: read('PREFS_BASE_URL') || 'https://hadoku.me/prefs',
73
74
  monitoringBaseUrl: read('MONITORING_BASE_URL') || 'https://hadoku.me',
74
75
  watchpartyBaseUrl: read('WATCHPARTY_BASE_URL') || 'https://hadoku.me/watchparty',
75
- callersSeenFile: read('CALLERS_SEEN_FILE') ?? join(dataDir, 'callers-seen.json'),
76
+ callersSeenFile: resolveDir(read('CALLERS_SEEN_FILE') ?? join(dataDir, 'callers-seen.json')),
76
77
  statsBaseUrl: read('STATS_BASE_URL') || 'https://hadoku.me/prefs',
77
78
  stateDir,
78
79
  logDir,
79
80
  dataDir,
80
81
  eventsFile: read('EVENTS_FILE') ?? join(dataDir, 'events.json'),
81
- roomsDir: read('ROOMS_DIR') ?? join(dataDir, 'rooms'),
82
+ roomsDir: resolveDir(read('ROOMS_DIR') ?? join(dataDir, 'rooms')),
82
83
  alertWebhook: env[`DISCORD_${prefix}_ALERT_WEBHOOK`] || '',
83
84
  backstopForceFile: read('BACKSTOP_FORCE_FILE') ?? join(dataDir, 'backstop-force.json'),
84
85
  testNoRateLimits: read('E2E_NO_RATE_LIMITS') === '1',
package/dist/kernel.js CHANGED
@@ -1,26 +1,13 @@
1
- /**
2
- * cardtable's binding of `@hadoku/service-kernel`'s auth and gate: the env prefix and the one
3
- * `createEdgeAuth`/`createGate` pair that `edge-auth.ts` and `gate.ts` share, built from `CONFIG`.
4
- */
5
- import { createEdgeAuth, rankOf, tierOf } from '@wolffm/service-kernel/auth';
6
- import { createGate } from '@wolffm/service-kernel/http';
1
+ import { createGameAuth } from './auth.js';
7
2
  import { CONFIG } from './config.js';
8
3
  import { reportSealRefused } from './telemetry.js';
9
4
  /** `assertFloor`'s env prefix (`edge-auth.ts`) — hadoku_site's wrapper sets `CARDTABLE_MIN_TIER`. */
10
5
  export const ENV_PREFIX = 'CARDTABLE';
11
- export const edgeAuth = createEdgeAuth({
12
- edgeAuthSecret: () => CONFIG.edgeAuthSecret,
13
- allowUnverifiedEdge: () => CONFIG.allowUnverifiedEdge,
14
- devTier: () => CONFIG.devTier,
15
- });
16
- export const gate = createGate({
17
- sanitizeHeaders: edgeAuth.sanitizeHeaders,
18
- edgeProvenance: edgeAuth.edgeProvenance,
19
- tierOf,
20
- rankOf,
6
+ const auth = createGameAuth(CONFIG, {
21
7
  // `reportSealRefused`'s own surface type is cardtable's closed set (`telemetry.ts`); the
22
8
  // kernel's is an open `string` so it knows no game's surface names. Every surface this gate
23
9
  // ever reports is in that set.
24
10
  reportSealRefused: reportSealRefused,
25
- minTier: () => CONFIG.minTier,
26
11
  });
12
+ export const edgeAuth = auth.edgeAuth;
13
+ export const gate = auth.gate;
@@ -0,0 +1,118 @@
1
+ /**
2
+ * A relay game's whole server: `startRelayGame({...})`, and the game is its config.
3
+ *
4
+ * A relay game runs its match in one browser, its host's, and the relay carries it to the others
5
+ * (`play/relay-socket.ts`): the server keeps no game state, only the rooms around it. Every such
6
+ * game needs the same server, so it is here, once — bomberman's `index.ts` and the game
7
+ * template's plugins each built it by hand before.
8
+ *
9
+ * the kernel `@hadoku/service-kernel/server`'s `createGameServer`: express, socket.io,
10
+ * provenance and the tier floor, `/health`, telemetry, account erase, listen, the
11
+ * deploy handover and shutdown
12
+ * config + auth `createConfig` under the game's env prefix and defaults; `createGameAuth`
13
+ * lobby the rooms, restored from disk (`plainRoomType`: marked seats, one kept open,
14
+ * a persona per bot), swept when idle, and each one's relay match
15
+ * people every member named and dressed from their account (`attachPeople`)
16
+ * rooms `/api/rooms*` (room-core, with its seat routes) and `/:id/start`, the
17
+ * countdown every page counts to (`room/starts.ts`)
18
+ * page the game's own static directories, then index.html for every client route
19
+ * /room chat, roster and presence (`room/serve.ts`)
20
+ * relay + feed the match socket, and the room list pushed to the front page
21
+ *
22
+ * A game adds only what is its own, as more kernel plugins (bomberman's round results), reading
23
+ * the shared parts from `ctx.state`.
24
+ */
25
+ import { type GamePlugin, type GameServer, type GameServerConfig as KernelConfig } from '@wolffm/service-kernel/server';
26
+ import { type GameAuth } from './auth.js';
27
+ import { type GameServerConfig } from './config.js';
28
+ import { type People } from './people.js';
29
+ import { RoomLobby, type PlainRoomSize, type PlainRoomView, type PlatformRoomView, type RoomCreateInput } from './room/lobby.js';
30
+ import { type Starts } from './room/starts.js';
31
+ import { type ReportOutcome, type RoundContext } from './stats/relay-results.js';
32
+ /** A relay room: the platform's view, its bots and, while one is pending, its start. */
33
+ export type RelayRoomView = PlatformRoomView & PlainRoomView & {
34
+ start: ReturnType<Starts['view']>;
35
+ };
36
+ /** The lobby a relay game's rooms live in: a room IS its match, and there is one game type. */
37
+ export declare class RelayLobby extends RoomLobby<RelayRoomView, RoomCreateInput> {
38
+ #private;
39
+ constructor(deps: ConstructorParameters<typeof RoomLobby<RelayRoomView, RoomCreateInput>>[0], gameType: string);
40
+ /** A relay room's match id is its room id. */
41
+ roomOfMatch(matchId: string): RelayRoomView | undefined;
42
+ setGameType(roomId: string, _callerId: string, gameType: string): {
43
+ ok: true;
44
+ room: RelayRoomView;
45
+ } | {
46
+ ok: false;
47
+ reason: string;
48
+ };
49
+ }
50
+ /** What every plugin of a relay game reads: the shared parts, built in the kit's own phases. */
51
+ export interface RelayGameState {
52
+ config: GameServerConfig;
53
+ auth: GameAuth;
54
+ /** From the `stores` phase on. */
55
+ lobby: RelayLobby;
56
+ people: People;
57
+ starts: Starts;
58
+ /** Each `/room` connection's friend key, by participant id: the key its round results are reported under. */
59
+ userKeys: Map<string, string>;
60
+ }
61
+ export type RelayGamePlugin = GamePlugin<Record<string, never>, RelayGameState>;
62
+ /** A directory served beside the bundle (bomberman's `/game`, its WASM build). */
63
+ export interface StaticDir {
64
+ /** The URL path it is served at, `/game`. */
65
+ path: string;
66
+ dir: string;
67
+ /** Files that never change under their name (a hashed build): cached a year. Everything else revalidates. */
68
+ immutable?: RegExp;
69
+ /** Its index, which must exist for the directory to count as built. Default `index.html`. */
70
+ index?: string;
71
+ /** What a request under `path` answers while it is not built (503). */
72
+ missing: string;
73
+ /** A directory that is not built degrades `/health`, saying this, with `field: 'missing'`. */
74
+ health?: {
75
+ field: string;
76
+ problem: string;
77
+ };
78
+ }
79
+ export interface RelayGameOptions {
80
+ /** The game's id: its log services (`<id>-rooms`, …), its restart event, the `/room` app id. */
81
+ id: string;
82
+ /** Its name, as the page that stands in for a broken bundle says it. */
83
+ name: string;
84
+ /** Its env vars are `<envPrefix>_<NAME>`. */
85
+ envPrefix: string;
86
+ /** The server package's root: what a relative directory resolves against. */
87
+ root: string;
88
+ /** The checkout, for `/health`'s commit. */
89
+ repoRoot: string;
90
+ /** The game's own config defaults by unprefixed name (`PORT`, `BASE_PREFIX`, `ROOMS_DIR`, …). */
91
+ defaults: Readonly<Record<string, string>>;
92
+ /** The participant-id domain, so ids are this game's own and never another's (`room/identity.ts`). */
93
+ participantDomain: string;
94
+ gameType: string;
95
+ /** A room id as this game's wire admits it. */
96
+ roomIdRe: RegExp;
97
+ /** The room's seats: how many it opens with, the most it grows to, and the relay match's seat count. */
98
+ seats: Pick<PlainRoomSize, 'seats' | 'max' | 'relaySeats'>;
99
+ /** The bundle's fixed-name embed entries; everything else it emits is hashed. */
100
+ embedEntries?: readonly string[];
101
+ statics?: readonly StaticDir[];
102
+ /** The countdown a Start counts down (ms). Default `COUNTDOWN_MS`. */
103
+ countdownMs?: number;
104
+ /**
105
+ * The game's round results, reported to the game-stats store under the game's id
106
+ * (`stats/relay-results.ts`): its bundle's payload as the store's report. Absent: no `/result` route.
107
+ */
108
+ results?: {
109
+ toReport(raw: unknown, ctx: RoundContext): ReportOutcome;
110
+ /** The match roster's id for a bot in `seat`. Default `ai:<seat>`. */
111
+ botClientId?: (seat: number) => string;
112
+ };
113
+ /** More of the game's own plugins, run in their phases after the kit's own of the same phase. */
114
+ plugins?: readonly RelayGamePlugin[];
115
+ /** Kernel config to override (a test's port, signals off). */
116
+ kernel?: Partial<KernelConfig>;
117
+ }
118
+ export declare function startRelayGame(options: RelayGameOptions): Promise<GameServer<Record<string, never>, RelayGameState>>;
@@ -0,0 +1,359 @@
1
+ /**
2
+ * A relay game's whole server: `startRelayGame({...})`, and the game is its config.
3
+ *
4
+ * A relay game runs its match in one browser, its host's, and the relay carries it to the others
5
+ * (`play/relay-socket.ts`): the server keeps no game state, only the rooms around it. Every such
6
+ * game needs the same server, so it is here, once — bomberman's `index.ts` and the game
7
+ * template's plugins each built it by hand before.
8
+ *
9
+ * the kernel `@hadoku/service-kernel/server`'s `createGameServer`: express, socket.io,
10
+ * provenance and the tier floor, `/health`, telemetry, account erase, listen, the
11
+ * deploy handover and shutdown
12
+ * config + auth `createConfig` under the game's env prefix and defaults; `createGameAuth`
13
+ * lobby the rooms, restored from disk (`plainRoomType`: marked seats, one kept open,
14
+ * a persona per bot), swept when idle, and each one's relay match
15
+ * people every member named and dressed from their account (`attachPeople`)
16
+ * rooms `/api/rooms*` (room-core, with its seat routes) and `/:id/start`, the
17
+ * countdown every page counts to (`room/starts.ts`)
18
+ * page the game's own static directories, then index.html for every client route
19
+ * /room chat, roster and presence (`room/serve.ts`)
20
+ * relay + feed the match socket, and the room list pushed to the front page
21
+ *
22
+ * A game adds only what is its own, as more kernel plugins (bomberman's round results), reading
23
+ * the shared parts from `ctx.state`.
24
+ */
25
+ import { existsSync, mkdirSync } from 'node:fs';
26
+ import { join } from 'node:path';
27
+ import express from 'express';
28
+ import { PresenceTracker } from '@wolffm/rooms-server';
29
+ import { FileRoomStore } from '@wolffm/rooms-server/store';
30
+ import { jsonLogger } from '@wolffm/service-kernel/log';
31
+ import { diagnosticPage, sendIndex } from '@wolffm/service-kernel/http';
32
+ import { createGameServer } from '@wolffm/service-kernel/server';
33
+ import { monitoringSink, siteOf } from '@wolffm/service-kernel/telemetry';
34
+ import { createGameAuth } from './auth.js';
35
+ import { createConfig } from './config.js';
36
+ import { fkOf } from './erase/index.js';
37
+ import { roomsEraseSteps } from './erase/rooms.js';
38
+ import { attachRoomCore, badRequest, noMatch } from './http/room-core.js';
39
+ import { callerOf } from './http/request.js';
40
+ import { attachPeople, createPeople } from './people.js';
41
+ import { attachRelay } from './play/relay-socket.js';
42
+ import { relayMatches } from './play/runtimes/relay-match.js';
43
+ import { configureParticipantIdDomain, identityFromHeaders } from './room/identity.js';
44
+ import { RoomLobby, plainRoomType } from './room/lobby.js';
45
+ import { attachServedRoom } from './room/serve.js';
46
+ import { COUNTDOWN_MS, createStarts } from './room/starts.js';
47
+ import { attachRoomFeed } from './room/watching.js';
48
+ import { createStatsReporter } from './stats/reporter.js';
49
+ import { attachResultRoute } from './stats/relay-results.js';
50
+ /** The lobby a relay game's rooms live in: a room IS its match, and there is one game type. */
51
+ export class RelayLobby extends RoomLobby {
52
+ #gameType;
53
+ constructor(deps, gameType) {
54
+ super(deps);
55
+ this.#gameType = gameType;
56
+ }
57
+ /** A relay room's match id is its room id. */
58
+ roomOfMatch(matchId) {
59
+ return this.get(matchId);
60
+ }
61
+ setGameType(roomId, _callerId, gameType) {
62
+ const room = this.get(roomId);
63
+ if (room === undefined)
64
+ return { ok: false, reason: 'no-room' };
65
+ return gameType === this.#gameType ? { ok: true, room } : { ok: false, reason: 'mode-locked' };
66
+ }
67
+ }
68
+ /** A non-negative int setting: the env's, else the game's default, else `fallback`. */
69
+ function intSetting(raw, fallback) {
70
+ const n = Number.parseInt(raw ?? '', 10);
71
+ return Number.isFinite(n) && n >= 0 ? n : fallback;
72
+ }
73
+ export async function startRelayGame(options) {
74
+ // Before anything derives an id: every room, relay and HTTP surface below mints them.
75
+ configureParticipantIdDomain(options.participantDomain);
76
+ const { id, envPrefix } = options;
77
+ const env = process.env;
78
+ const config = createConfig({ envPrefix, root: options.root, defaults: options.defaults });
79
+ const auth = createGameAuth(config, { svc: id });
80
+ mkdirSync(config.logDir, { recursive: true });
81
+ const setting = (name) => env[`${envPrefix}_${name}`] ?? options.defaults[name];
82
+ const seatHoldMs = intSetting(setting('SEAT_HOLD_MS'), 120_000);
83
+ const disconnectGraceMs = intSetting(setting('DISCONNECT_GRACE_MS'), 5_000);
84
+ // Never below the seat hold: a room whose seats are still held for returning players must
85
+ // outlive the hold, or the sweep loses a game in progress.
86
+ const roomIdleMs = Math.max(intSetting(setting('ROOM_IDLE_MS'), 6 * 60 * 60 * 1000), seatHoldMs + 30_000);
87
+ const log = jsonLogger(id);
88
+ const roomsLog = jsonLogger(`${id}-rooms`);
89
+ const relayLog = jsonLogger(`${id}-relay`);
90
+ const statics = (options.statics ?? []).map((s) => ({ ...s, built: existsSync(join(s.dir, s.index ?? 'index.html')) }));
91
+ const starts = createStarts({ countdownMs: options.countdownMs ?? COUNTDOWN_MS });
92
+ const base = plainRoomType({ ...options.seats, markedSeats: true, keepOneOpen: true });
93
+ const roomType = {
94
+ ...base,
95
+ /** A pending start rides on every room body: every page counts down to it. */
96
+ view: (room) => ({ ...base.view(room), start: starts.view(room.id) }),
97
+ };
98
+ const state = { config, auth, starts, userKeys: new Map() };
99
+ const lobbyPlugin = {
100
+ name: 'lobby',
101
+ phase: 'stores',
102
+ async setup(ctx) {
103
+ const lobby = new RelayLobby({
104
+ store: new FileRoomStore(config.roomsDir),
105
+ now: Date.now,
106
+ log: roomsLog,
107
+ typeOf: (gameType) => (gameType === options.gameType ? roomType : undefined),
108
+ watchpartyRoom: { name: 'Room', gameType: options.gameType },
109
+ }, options.gameType);
110
+ const restored = await lobby.open();
111
+ roomsLog({ evt: 'lobby-open', rooms: restored });
112
+ ctx.state.lobby = lobby;
113
+ ctx.gauge('rooms', () => lobby.list().length);
114
+ lobby.onChange((roomId) => {
115
+ if (lobby.get(roomId) === undefined)
116
+ starts.forget(roomId);
117
+ });
118
+ // A room IS its match: one relay match per room, opened as the room is.
119
+ lobby.onRelayRoomOpened((roomId, seatCount) => {
120
+ relayMatches.register(roomId, seatCount, {
121
+ log: relayLog,
122
+ roomSeatOf: (participantId) => lobby.gameSeatOf(roomId, participantId),
123
+ // A round's end is taken from the HOST of the room's match (whom `starts` named),
124
+ // falling back to the leader's seat while nobody hosts or the host left theirs.
125
+ leaderSeat: () => {
126
+ const host = starts.hostOf(roomId);
127
+ const hostSeat = host === null ? null : lobby.gameSeatOf(roomId, host);
128
+ if (hostSeat !== null)
129
+ return hostSeat;
130
+ const leader = lobby.get(roomId)?.leader;
131
+ return leader === undefined ? null : lobby.gameSeatOf(roomId, leader);
132
+ },
133
+ seatRejoinGraceMs: seatHoldMs,
134
+ });
135
+ });
136
+ const sweep = setInterval(() => lobby.sweep(roomIdleMs), 60_000);
137
+ sweep.unref();
138
+ const people = createPeople({
139
+ baseUrl: config.prefsBaseUrl,
140
+ serviceKey: config.serviceKey,
141
+ keyless: config.testPeopleStandIn,
142
+ log: jsonLogger(`${id}-people`),
143
+ });
144
+ ctx.state.people = people;
145
+ // Every member named and dressed from their account: as a room changes, once over the
146
+ // restored rooms now, and fresh as each one arrives (room-core's `arrived`, below).
147
+ const accounts = attachPeople(lobby, people);
148
+ void accounts.sweep();
149
+ arrived = (roomId, memberId, userId) => void accounts.arrived(roomId, memberId, userId);
150
+ return {
151
+ shutdown: () => {
152
+ clearInterval(sweep);
153
+ accounts.stop();
154
+ void lobby.removed();
155
+ },
156
+ erase: roomsEraseSteps({ lobby, liveMatches: () => [], forfeit: () => { }, closed: () => { }, forfeited: () => { } }),
157
+ };
158
+ },
159
+ };
160
+ let arrived = () => { };
161
+ const roomsPlugin = {
162
+ name: 'rooms',
163
+ phase: 'routes',
164
+ setup(ctx) {
165
+ const lobby = ctx.state.lobby;
166
+ const roomCore = attachRoomCore(ctx.api, {
167
+ lobby,
168
+ wire: relayWire(options.gameType, options.roomIdRe),
169
+ seatRoutes: lobby,
170
+ arrived: (roomId, caller) => {
171
+ if (caller.userId !== null)
172
+ arrived(roomId, caller.id, caller.userId);
173
+ },
174
+ log: roomsLog,
175
+ });
176
+ // The leader's (seated or watching) or a seated player's Start: a pending start every
177
+ // page counts down to, and its host. Answers the room, as every seat route does.
178
+ roomCore.router.post('/:id/start', (req, res) => {
179
+ if (typeof req.body !== 'object' || req.body === null || Object.keys(req.body).length > 0)
180
+ return badRequest(res, 'expected an empty body');
181
+ const caller = callerOf(req);
182
+ const roomId = String(req.params.id);
183
+ if (!options.roomIdRe.test(roomId))
184
+ return noMatch(res);
185
+ const room = lobby.get(roomId);
186
+ if (room === undefined || !lobby.isMember(roomId, caller.id))
187
+ return noMatch(res);
188
+ const result = starts.request(room, caller.id);
189
+ if (!result.ok)
190
+ return badRequest(res, result.reason);
191
+ // Read again: the view is built per read, and this one now carries the start.
192
+ res.json(roomCore.roomBody(lobby.get(roomId) ?? room, caller.id));
193
+ });
194
+ const results = options.results;
195
+ if (results !== undefined) {
196
+ const statsLog = jsonLogger(`${id}-stats`);
197
+ const stats = createStatsReporter({ gameId: id, serviceKey: config.serviceKey, serviceKeyEnvVar: `${envPrefix}_SERVICE_KEY`, log: statsLog });
198
+ attachResultRoute(ctx.api, {
199
+ lobby,
200
+ userKeys: ctx.state.userKeys,
201
+ stats,
202
+ toReport: results.toReport,
203
+ ...(results.botClientId === undefined ? {} : { botClientId: results.botClientId }),
204
+ log: statsLog,
205
+ });
206
+ return { shutdown: () => void stats.idle() };
207
+ }
208
+ },
209
+ };
210
+ const pagePlugin = {
211
+ name: 'page',
212
+ phase: 'routes',
213
+ setup(ctx) {
214
+ for (const s of statics) {
215
+ if (s.built) {
216
+ ctx.app.use(s.path, express.static(s.dir, {
217
+ index: s.index ?? 'index.html',
218
+ redirect: false,
219
+ setHeaders: (res, filePath) => {
220
+ res.setHeader('Cache-Control', s.immutable?.test(filePath) === true ? 'public, max-age=31536000, immutable' : 'no-cache');
221
+ },
222
+ }));
223
+ }
224
+ ctx.app.use(s.path, (_req, res) => {
225
+ if (s.built)
226
+ res.status(404).type('text').send('Not found');
227
+ else
228
+ res.status(503).type('text').send(s.missing);
229
+ });
230
+ }
231
+ // The embed's own files are the static bundle's; anything else under it is no page.
232
+ ctx.app.use('/embed', (_req, res) => {
233
+ res.status(404).type('text').send('no such embed file');
234
+ });
235
+ ctx.app.get(/.*/, (_req, res, next) => {
236
+ if (!ctx.bundle.ok) {
237
+ res.status(503).type('html').send(diagnosticPage(ctx.bundle, config.basePrefix, options.name));
238
+ return;
239
+ }
240
+ sendIndex(res, join(config.webDir, 'index.html'), (err) => err && next(err));
241
+ });
242
+ },
243
+ };
244
+ const socketsPlugin = {
245
+ name: 'sockets',
246
+ phase: 'sockets',
247
+ async setup(ctx) {
248
+ const lobby = ctx.state.lobby;
249
+ // The relay first: it installs the engine-wide provenance sanitizer `/room`'s admit relies on.
250
+ const relay = attachRelay(ctx.io, {
251
+ minTier: config.minTier,
252
+ gate: auth.gate,
253
+ rosterOf: (matchId) => relayMatches.get(matchId),
254
+ log: relayLog,
255
+ });
256
+ // The room's own presence: its grace is not the relay seat's hold.
257
+ const presence = new PresenceTracker({ idleMs: 2_000_000_000, graceMs: disconnectGraceMs });
258
+ const roomLog = jsonLogger(`${id}-room`);
259
+ await attachServedRoom(ctx.io, {
260
+ lobby,
261
+ presence,
262
+ people: ctx.state.people,
263
+ isMatch: (matchId) => relayMatches.get(matchId) !== undefined,
264
+ minTier: config.minTier,
265
+ stateDir: () => config.roomsDir,
266
+ appId: id,
267
+ roomIdRe: options.roomIdRe,
268
+ namespace: '/room',
269
+ // Every refusal on `/room` is logged; a silent one looks like dead chat.
270
+ onEvent: (level, event, fields) => {
271
+ if (level !== 'debug')
272
+ roomLog({ level, evt: event, ...fields });
273
+ },
274
+ });
275
+ // Each connection's own friend key, from ITS handshake (sanitized by the relay's provenance
276
+ // check above): the key its round results are reported under.
277
+ ctx.io.of('/room').on('connection', (socket) => {
278
+ const key = socket.request.headers['x-user-key'];
279
+ if (typeof key !== 'string' || key === '')
280
+ return;
281
+ ctx.state.userKeys.set(identityFromHeaders(socket.request.headers, socket.id), key);
282
+ });
283
+ const feed = attachRoomFeed(ctx.io, { lobby });
284
+ return {
285
+ shutdown: () => {
286
+ relay.close();
287
+ feed.close();
288
+ },
289
+ };
290
+ },
291
+ };
292
+ const health = () => {
293
+ const fields = {};
294
+ const problems = [];
295
+ for (const s of statics) {
296
+ if (s.health === undefined)
297
+ continue;
298
+ fields[s.health.field] = s.built ? 'built' : 'missing';
299
+ if (!s.built)
300
+ problems.push(s.health.problem);
301
+ }
302
+ fields.rooms = state.lobby?.list().length ?? 0;
303
+ return { fields, problems };
304
+ };
305
+ const server = await createGameServer({
306
+ id,
307
+ config: {
308
+ host: config.host,
309
+ port: config.port,
310
+ log,
311
+ edgeAuth: auth.edgeAuth,
312
+ gate: auth.gate,
313
+ basePrefix: config.basePrefix,
314
+ bundle: { indexHtml: join(config.webDir, 'index.html'), webDir: config.webDir, embedEntries: options.embedEntries ?? [] },
315
+ repoRoot: options.repoRoot,
316
+ health,
317
+ restartEvent: `${id}:restarting`,
318
+ telemetry: () => monitoringSink({
319
+ baseUrl: config.monitoringBaseUrl,
320
+ serviceKey: config.serviceKey,
321
+ site: siteOf(config.basePrefix, id),
322
+ log,
323
+ service: id,
324
+ serviceKeyEnvVar: `${envPrefix}_SERVICE_KEY`,
325
+ }),
326
+ firstSeen: { file: config.callersSeenFile, log },
327
+ erase: { deriveParticipantId: fkOf },
328
+ ...options.kernel,
329
+ },
330
+ state,
331
+ plugins: [lobbyPlugin, roomsPlugin, ...(options.plugins ?? []), pagePlugin, socketsPlugin],
332
+ });
333
+ return server;
334
+ }
335
+ /** The room routes' request bodies, for a game with one room type. */
336
+ function relayWire(gameType, roomIdRe) {
337
+ const object = (fields, required, message) => ({
338
+ safeParse(body) {
339
+ const ok = typeof body === 'object' &&
340
+ body !== null &&
341
+ !Array.isArray(body) &&
342
+ Object.keys(body).every((k) => k in fields) &&
343
+ required.every((k) => k in body) &&
344
+ Object.entries(body).every(([k, v]) => fields[k](v));
345
+ return ok ? { success: true, data: body } : { success: false, error: { issues: [{ code: 'invalid_type', path: [], message }] } };
346
+ },
347
+ });
348
+ const text = (max, min = 0) => (v) => typeof v === 'string' && v.trim().length >= min && v.length <= max;
349
+ const optional = (check) => (v) => v === undefined || check(v);
350
+ return {
351
+ roomIdRe,
352
+ createRoomBody: object({ name: text(60, 1), gameType: (v) => v === gameType, password: optional(text(100)) }, ['name', 'gameType'], 'expected { name, gameType, password? }'),
353
+ joinRoomBody: object({ password: optional(text(100)) }, [], 'expected { password? }'),
354
+ readyBody: object({ ready: (v) => typeof v === 'boolean' }, ['ready'], 'expected { ready }'),
355
+ emptyBody: object({}, [], 'expected an empty body'),
356
+ watchpartyBindBody: object({ room: text(100, 1) }, ['room'], 'expected { room }'),
357
+ patchRoomBody: object({ gameType: text(40, 1) }, ['gameType'], 'expected { gameType }'),
358
+ };
359
+ }
@@ -73,7 +73,7 @@ export { participantHandle } from '@wolffm/rooms-protocol';
73
73
  * rebind it, and only before this module has derived its first id.
74
74
  */
75
75
  let derive = createParticipantIdDeriver(PARTICIPANT_ID_DOMAIN);
76
- let participantIdDomainConfigured = false;
76
+ let participantIdDomainConfigured = null;
77
77
  let participantIdDerived = false;
78
78
  /**
79
79
  * Swap the domain {@link deriveParticipantId}/{@link identityFromHeaders} close over, for a
@@ -95,14 +95,17 @@ let participantIdDerived = false;
95
95
  * drops it as part of its own version bump — no code change on either side beyond that.
96
96
  */
97
97
  export function configureParticipantIdDomain(domain) {
98
- if (participantIdDomainConfigured) {
98
+ // The same domain again is the same derivation: a no-op (a game's boot, then its tests' second boot).
99
+ if (participantIdDomainConfigured === domain)
100
+ return;
101
+ if (participantIdDomainConfigured !== null) {
99
102
  throw new Error('configureParticipantIdDomain: already configured once for this process');
100
103
  }
101
104
  if (participantIdDerived) {
102
105
  throw new Error('configureParticipantIdDomain: a participant id was already derived under the default domain; too late to swap it');
103
106
  }
104
107
  derive = createParticipantIdDeriver(domain);
105
- participantIdDomainConfigured = true;
108
+ participantIdDomainConfigured = domain;
106
109
  }
107
110
  /**
108
111
  * Mint an id for one connection.
@@ -0,0 +1,73 @@
1
+ /**
2
+ * Starting a relay room's match: who may, who hosts it, and the 3-2-1 every screen counts.
3
+ * Generic to every game whose match runs in one browser and reaches the others over the relay
4
+ * (`play/relay-socket.ts`); moved here from hadoku-bomberman, its first.
5
+ *
6
+ * ## Why the server holds this
7
+ *
8
+ * The match runs in ONE browser, its host's: that page runs the sim and sends
9
+ * every snapshot over the relay (docs/NETCODE.md). The relay refuses anything
10
+ * a watcher sends, so a spectating leader could never start a match from
11
+ * their own page — the Start press has to land somewhere every page can see.
12
+ * Here: `POST /api/rooms/:id/start` (`relay-game.ts`) records a PENDING start, every room body
13
+ * carries it (`relay-game.ts`'s room view), every page counts down to it, and the
14
+ * one page it names as host sends the relay `start` at zero.
15
+ *
16
+ * ## Who may start, and who hosts
17
+ *
18
+ * The leader, always — seated or watching. Anyone seated, too (the old rule:
19
+ * any player starts an idle room). The host is the caller when seated,
20
+ * otherwise the first seated person; a room with nobody seated has nobody to
21
+ * run the match, and says so.
22
+ *
23
+ * The host is also who the relay accepts a round's end from
24
+ * (the relay match's `leaderSeat`, `relay-game.ts`): the relay protocol's "host" was the leader's
25
+ * seat, which refused the end of any round the leader did not start.
26
+ *
27
+ * A start is pending only until zero. After that it is the host's match, and
28
+ * a page that loads later (a reload, a remount) must not find it: it would
29
+ * count down from nothing, hide Start, and — on the host's page — begin the
30
+ * same match a second time. Only `hostOf` outlives zero, for the relay.
31
+ *
32
+ * In memory only: a countdown lasts seconds, and a restart mid-countdown
33
+ * costs one press of Start.
34
+ */
35
+ /** The 3-2-1. */
36
+ export declare const COUNTDOWN_MS = 3000;
37
+ /** What a room body carries while a start is pending. `startsInMs` is relative, so no two clocks need agree. */
38
+ export interface StartView {
39
+ matchId: string;
40
+ seed: number;
41
+ hostId: string;
42
+ startsInMs: number;
43
+ }
44
+ export interface StartableRoom {
45
+ id: string;
46
+ leader: string;
47
+ seats: readonly (string | null)[];
48
+ members: readonly {
49
+ id: string;
50
+ }[];
51
+ }
52
+ export type StartRefusal = 'not-allowed' | 'no-player';
53
+ export interface Starts {
54
+ /** The leader's or a seated player's Start. A start already pending is answered as is. */
55
+ request(room: StartableRoom, callerId: string): {
56
+ ok: true;
57
+ start: StartView;
58
+ } | {
59
+ ok: false;
60
+ reason: StartRefusal;
61
+ };
62
+ /** The pending start a room body carries, or null. */
63
+ view(roomId: string): StartView | null;
64
+ /** Who hosts the room's current (or last) match, or null before the first. */
65
+ hostOf(roomId: string): string | null;
66
+ /** The room is gone. */
67
+ forget(roomId: string): void;
68
+ }
69
+ export declare function createStarts(opts?: {
70
+ now?: () => number;
71
+ random?: () => number;
72
+ countdownMs?: number;
73
+ }): Starts;
@@ -0,0 +1,95 @@
1
+ /**
2
+ * Starting a relay room's match: who may, who hosts it, and the 3-2-1 every screen counts.
3
+ * Generic to every game whose match runs in one browser and reaches the others over the relay
4
+ * (`play/relay-socket.ts`); moved here from hadoku-bomberman, its first.
5
+ *
6
+ * ## Why the server holds this
7
+ *
8
+ * The match runs in ONE browser, its host's: that page runs the sim and sends
9
+ * every snapshot over the relay (docs/NETCODE.md). The relay refuses anything
10
+ * a watcher sends, so a spectating leader could never start a match from
11
+ * their own page — the Start press has to land somewhere every page can see.
12
+ * Here: `POST /api/rooms/:id/start` (`relay-game.ts`) records a PENDING start, every room body
13
+ * carries it (`relay-game.ts`'s room view), every page counts down to it, and the
14
+ * one page it names as host sends the relay `start` at zero.
15
+ *
16
+ * ## Who may start, and who hosts
17
+ *
18
+ * The leader, always — seated or watching. Anyone seated, too (the old rule:
19
+ * any player starts an idle room). The host is the caller when seated,
20
+ * otherwise the first seated person; a room with nobody seated has nobody to
21
+ * run the match, and says so.
22
+ *
23
+ * The host is also who the relay accepts a round's end from
24
+ * (the relay match's `leaderSeat`, `relay-game.ts`): the relay protocol's "host" was the leader's
25
+ * seat, which refused the end of any round the leader did not start.
26
+ *
27
+ * A start is pending only until zero. After that it is the host's match, and
28
+ * a page that loads later (a reload, a remount) must not find it: it would
29
+ * count down from nothing, hide Start, and — on the host's page — begin the
30
+ * same match a second time. Only `hostOf` outlives zero, for the relay.
31
+ *
32
+ * In memory only: a countdown lasts seconds, and a restart mid-countdown
33
+ * costs one press of Start.
34
+ */
35
+ /** The 3-2-1. */
36
+ export const COUNTDOWN_MS = 3_000;
37
+ export function createStarts(opts = {}) {
38
+ const now = opts.now ?? Date.now;
39
+ const countdownMs = opts.countdownMs ?? COUNTDOWN_MS;
40
+ const random = opts.random ?? Math.random;
41
+ const pending = new Map();
42
+ const hosts = new Map();
43
+ const live = (roomId) => {
44
+ const p = pending.get(roomId);
45
+ if (p === undefined)
46
+ return null;
47
+ if (now() >= p.startsAt) {
48
+ pending.delete(roomId);
49
+ return null;
50
+ }
51
+ return p;
52
+ };
53
+ const toView = (p) => ({
54
+ matchId: p.matchId,
55
+ seed: p.seed,
56
+ hostId: p.hostId,
57
+ startsInMs: Math.max(0, p.startsAt - now()),
58
+ });
59
+ return {
60
+ request(room, callerId) {
61
+ const isPerson = (holder) => holder !== null && room.members.some((m) => m.id === holder);
62
+ const seated = room.seats.includes(callerId);
63
+ if (!seated && room.leader !== callerId)
64
+ return { ok: false, reason: 'not-allowed' };
65
+ const already = live(room.id);
66
+ if (already !== null)
67
+ return { ok: true, start: toView(already) };
68
+ const hostId = seated ? callerId : room.seats.find(isPerson);
69
+ if (hostId === undefined)
70
+ return { ok: false, reason: 'no-player' };
71
+ const t = now();
72
+ const start = {
73
+ // The stats store's MATCH_ID_PATTERN holds: [A-Za-z0-9_-]{8,64}.
74
+ matchId: `m-${t.toString(36)}-${Math.floor(random() * 1e9).toString(36)}`,
75
+ seed: Math.floor(random() * 0x7fffffff),
76
+ hostId,
77
+ startsAt: t + countdownMs,
78
+ };
79
+ pending.set(room.id, start);
80
+ hosts.set(room.id, hostId);
81
+ return { ok: true, start: toView(start) };
82
+ },
83
+ view(roomId) {
84
+ const p = live(roomId);
85
+ return p === null ? null : toView(p);
86
+ },
87
+ hostOf(roomId) {
88
+ return hosts.get(roomId) ?? null;
89
+ },
90
+ forget(roomId) {
91
+ pending.delete(roomId);
92
+ hosts.delete(roomId);
93
+ },
94
+ };
95
+ }
@@ -0,0 +1,86 @@
1
+ /**
2
+ * A relay game's round results, reported to the game-stats store.
3
+ *
4
+ * The relay is opaque end to end (`play/relay-socket.ts` fans a seat's message out without
5
+ * reading it), so no server-side place sees a round end. The match host's page POSTs each round's
6
+ * result instead: `POST /api/rooms/:id/result { matchId, result }`, where `result` is whatever
7
+ * the game's bundle reports and `matchId` is the ROUND's own id, minted by the host (the store
8
+ * keeps the first report per id, so one id per room would drop every round after the first).
9
+ *
10
+ * The game turns its own payload into the store's report (`toReport`). Everything else is here:
11
+ * who may report (the room's leader, or anyone seated, since whoever pressed Start hosts), the id
12
+ * check, and who sits where.
13
+ *
14
+ * ## Identity comes from the server, never from the result
15
+ *
16
+ * The result names players by the `clientId` the match roster gave them. Each is looked up in
17
+ * the seats as the server holds them (`buildFrozenSeats`), so a host cannot attribute a seat to
18
+ * anyone the server did not seat. A human with a friend key reports `kind: 'user'` with that key,
19
+ * which prefs-api resolves and discards; a human without one is a `guest`. Never a userId: that
20
+ * would be a claim, and the key is a credential. It lives in server memory, goes to prefs-api and
21
+ * nowhere else, never onto the wire nor into a log line.
22
+ */
23
+ import type { Router } from 'express';
24
+ import { type MatchReport } from '@wolffm/prefs-client/games';
25
+ import type { StatsReporter } from './reporter.js';
26
+ /** Who sat in one slot when the round ended: what a game's `toReport` names players by. */
27
+ export type FrozenSeat = {
28
+ playerId: number;
29
+ clientId: string;
30
+ kind: 'user';
31
+ userKey: string;
32
+ name: string;
33
+ } | {
34
+ playerId: number;
35
+ clientId: string;
36
+ kind: 'guest' | 'bot';
37
+ name: string;
38
+ };
39
+ /** What a game's `toReport` is handed beside its own payload. */
40
+ export interface RoundContext {
41
+ matchId: string;
42
+ roomId: string;
43
+ endedAt: number;
44
+ seats: readonly FrozenSeat[];
45
+ }
46
+ export type ReportOutcome = {
47
+ ok: true;
48
+ report: MatchReport;
49
+ } | {
50
+ ok: false;
51
+ reason: string;
52
+ };
53
+ /** A room as this reads it: who holds each seat, its members, and its bots' names. */
54
+ export interface ResultRoom {
55
+ leader: string;
56
+ seats: readonly (string | null)[];
57
+ members: readonly {
58
+ id: string;
59
+ name: string;
60
+ }[];
61
+ aiSeats?: readonly ({
62
+ name: string;
63
+ } | null)[];
64
+ }
65
+ /**
66
+ * Who sits in each occupied seat NOW, in seat order, with a dense `playerId` — the match roster's
67
+ * own numbering. A human's `clientId` is their full participant id (the roster's); a bot's is
68
+ * `botClientId(seat)`, by SEAT number, never by how many bots came before it, so it agrees with
69
+ * the roster whichever seats the bots took. A bot is named as the room names it (`aiSeats`).
70
+ */
71
+ export declare function buildFrozenSeats(room: Pick<ResultRoom, 'seats' | 'members' | 'aiSeats'>, userKeys: ReadonlyMap<string, string>, botClientId?: (seat: number) => string): FrozenSeat[];
72
+ export interface ResultRouteDeps {
73
+ lobby: {
74
+ get(roomId: string): ResultRoom | undefined;
75
+ };
76
+ /** Each `/room` connection's friend key, by participant id. */
77
+ userKeys: ReadonlyMap<string, string>;
78
+ stats: StatsReporter;
79
+ /** The game's own: its bundle's payload, as the store's report, or why not. */
80
+ toReport(raw: unknown, ctx: RoundContext): ReportOutcome;
81
+ botClientId?: (seat: number) => string;
82
+ log: (line: Record<string, unknown>) => void;
83
+ now?: () => number;
84
+ }
85
+ /** Mount `POST /rooms/:id/result` on `api` (mounted at `/api`, below the tier floor). */
86
+ export declare function attachResultRoute(api: Router, deps: ResultRouteDeps): void;
@@ -0,0 +1,82 @@
1
+ /**
2
+ * A relay game's round results, reported to the game-stats store.
3
+ *
4
+ * The relay is opaque end to end (`play/relay-socket.ts` fans a seat's message out without
5
+ * reading it), so no server-side place sees a round end. The match host's page POSTs each round's
6
+ * result instead: `POST /api/rooms/:id/result { matchId, result }`, where `result` is whatever
7
+ * the game's bundle reports and `matchId` is the ROUND's own id, minted by the host (the store
8
+ * keeps the first report per id, so one id per room would drop every round after the first).
9
+ *
10
+ * The game turns its own payload into the store's report (`toReport`). Everything else is here:
11
+ * who may report (the room's leader, or anyone seated, since whoever pressed Start hosts), the id
12
+ * check, and who sits where.
13
+ *
14
+ * ## Identity comes from the server, never from the result
15
+ *
16
+ * The result names players by the `clientId` the match roster gave them. Each is looked up in
17
+ * the seats as the server holds them (`buildFrozenSeats`), so a host cannot attribute a seat to
18
+ * anyone the server did not seat. A human with a friend key reports `kind: 'user'` with that key,
19
+ * which prefs-api resolves and discards; a human without one is a `guest`. Never a userId: that
20
+ * would be a claim, and the key is a credential. It lives in server memory, goes to prefs-api and
21
+ * nowhere else, never onto the wire nor into a log line.
22
+ */
23
+ import { MATCH_ID_PATTERN } from '@wolffm/prefs-client/games';
24
+ import { AI_SEAT, CLOSED_SEAT } from '@wolffm/platform-wire/seats';
25
+ import { participantHandle } from '@wolffm/rooms-protocol';
26
+ import { callerOf } from '../http/request.js';
27
+ /**
28
+ * Who sits in each occupied seat NOW, in seat order, with a dense `playerId` — the match roster's
29
+ * own numbering. A human's `clientId` is their full participant id (the roster's); a bot's is
30
+ * `botClientId(seat)`, by SEAT number, never by how many bots came before it, so it agrees with
31
+ * the roster whichever seats the bots took. A bot is named as the room names it (`aiSeats`).
32
+ */
33
+ export function buildFrozenSeats(room, userKeys, botClientId = (seat) => `ai:${seat}`) {
34
+ const seats = [];
35
+ let bots = 0;
36
+ for (const [seat, holder] of room.seats.entries()) {
37
+ if (holder === null || holder === CLOSED_SEAT)
38
+ continue;
39
+ const playerId = seats.length;
40
+ if (holder === AI_SEAT) {
41
+ bots += 1;
42
+ seats.push({ playerId, clientId: botClientId(seat), kind: 'bot', name: room.aiSeats?.[seat]?.name ?? `Bot ${bots}` });
43
+ continue;
44
+ }
45
+ const name = room.members.find((m) => m.id === holder)?.name ?? participantHandle(holder);
46
+ const userKey = userKeys.get(holder);
47
+ seats.push(userKey === undefined ? { playerId, clientId: holder, kind: 'guest', name } : { playerId, clientId: holder, kind: 'user', userKey, name });
48
+ }
49
+ return seats;
50
+ }
51
+ /** Mount `POST /rooms/:id/result` on `api` (mounted at `/api`, below the tier floor). */
52
+ export function attachResultRoute(api, deps) {
53
+ const now = deps.now ?? Date.now;
54
+ api.post('/rooms/:id/result', (req, res) => {
55
+ const roomId = String(req.params.id);
56
+ const room = deps.lobby.get(roomId);
57
+ if (room === undefined) {
58
+ res.status(404).json({ error: 'no such room' });
59
+ return;
60
+ }
61
+ const caller = callerOf(req);
62
+ if (room.leader !== caller.id && !room.seats.includes(caller.id)) {
63
+ res.status(403).json({ error: 'only a seated player may report a result' });
64
+ return;
65
+ }
66
+ const body = req.body;
67
+ const matchId = body?.matchId;
68
+ if (typeof matchId !== 'string' || !MATCH_ID_PATTERN.test(matchId)) {
69
+ res.status(400).json({ error: "a result needs its round's own matchId" });
70
+ return;
71
+ }
72
+ const seats = buildFrozenSeats(room, deps.userKeys, deps.botClientId);
73
+ const built = deps.toReport(body?.result, { matchId, roomId, endedAt: now(), seats });
74
+ if (!built.ok) {
75
+ deps.log({ evt: 'stats-refused', roomId, reason: built.reason });
76
+ res.status(built.reason === 'bad-result' ? 400 : 422).json({ ok: false, error: built.reason });
77
+ return;
78
+ }
79
+ deps.stats.report(built.report);
80
+ res.json({ ok: true });
81
+ });
82
+ }
@@ -0,0 +1,40 @@
1
+ /**
2
+ * Reporting a finished match to the game-stats store (prefs-api, `/prefs/api/v1/_games/<game>/*`):
3
+ * fire and forget, with a bounded, idempotent retry. Every attempt re-posts the same `matchId`,
4
+ * and the store keeps the first report per id, so a retry after a lost response cannot count a
5
+ * match twice. Moved here from hadoku-bomberman; any game reporting matches uses it.
6
+ */
7
+ import { type MatchReport, type RecordMatchOptions, type RecordMatchResult } from '@wolffm/prefs-client/games';
8
+ export type RecordMatch = (opts: RecordMatchOptions, report: MatchReport) => Promise<RecordMatchResult>;
9
+ export interface StatsReporterOptions {
10
+ /** The store's game id: `/_games/<gameId>/*`. */
11
+ gameId: string;
12
+ /** This server's service-tier key. Empty or absent = reporting is off. */
13
+ serviceKey: string | undefined;
14
+ /** The env var that sets it, named in the one line that says reporting is off. */
15
+ serviceKeyEnvVar?: string;
16
+ log: (line: Record<string, unknown>) => void;
17
+ /** Injected by tests. `recordMatch` from @wolffm/prefs-client/games otherwise. */
18
+ record?: RecordMatch;
19
+ /**
20
+ * Waits before each RETRY. Bounded: a store that is down for longer than
21
+ * this loses the round, which is better than a queue that grows without one.
22
+ */
23
+ retryDelaysMs?: readonly number[];
24
+ }
25
+ export interface StatsReporter {
26
+ readonly enabled: boolean;
27
+ /** Fire and forget. Never throws, never blocks the caller. */
28
+ report(report: MatchReport): void;
29
+ /** Resolves when every report in flight has settled. For tests and shutdown. */
30
+ idle(): Promise<void>;
31
+ }
32
+ export declare const DEFAULT_RETRY_DELAYS_MS: readonly [2000, 10000, 60000];
33
+ /**
34
+ * Report matches to the store, or log once that it will not.
35
+ *
36
+ * Every attempt re-posts the same `matchId`, and the store treats a repeat as
37
+ * a no-op, so a retry after a response that was lost in transit cannot count a
38
+ * round twice.
39
+ */
40
+ export declare function createStatsReporter(opts: StatsReporterOptions): StatsReporter;
@@ -0,0 +1,82 @@
1
+ /**
2
+ * Reporting a finished match to the game-stats store (prefs-api, `/prefs/api/v1/_games/<game>/*`):
3
+ * fire and forget, with a bounded, idempotent retry. Every attempt re-posts the same `matchId`,
4
+ * and the store keeps the first report per id, so a retry after a lost response cannot count a
5
+ * match twice. Moved here from hadoku-bomberman; any game reporting matches uses it.
6
+ */
7
+ import { GameStatsError, recordMatch as recordMatchHttp, } from '@wolffm/prefs-client/games';
8
+ export const DEFAULT_RETRY_DELAYS_MS = [2_000, 10_000, 60_000];
9
+ /**
10
+ * A 4xx other than 408/429 is the store REFUSING this report — a bad key, a
11
+ * key that does not resolve, a malformed payload. Sending it again changes
12
+ * nothing. Everything else (network, 5xx, 408, 429) may be transient.
13
+ */
14
+ function retryable(err) {
15
+ if (err instanceof GameStatsError) {
16
+ return err.status >= 500 || err.status === 408 || err.status === 429;
17
+ }
18
+ return true;
19
+ }
20
+ const sleep = (ms) => new Promise((r) => {
21
+ const t = setTimeout(r, ms);
22
+ t.unref?.();
23
+ });
24
+ /**
25
+ * Report matches to the store, or log once that it will not.
26
+ *
27
+ * Every attempt re-posts the same `matchId`, and the store treats a repeat as
28
+ * a no-op, so a retry after a response that was lost in transit cannot count a
29
+ * round twice.
30
+ */
31
+ export function createStatsReporter(opts) {
32
+ const { log } = opts;
33
+ const record = opts.record ?? recordMatchHttp;
34
+ const delays = opts.retryDelaysMs ?? DEFAULT_RETRY_DELAYS_MS;
35
+ const serviceKey = opts.serviceKey ?? '';
36
+ const inFlight = new Set();
37
+ if (serviceKey === '') {
38
+ log({ evt: 'stats-disabled', reason: `${opts.serviceKeyEnvVar ?? 'the service key'} unset` });
39
+ }
40
+ const send = async (report) => {
41
+ for (let attempt = 0;; attempt += 1) {
42
+ try {
43
+ const res = await record({ gameId: opts.gameId, serviceKey }, report);
44
+ log({
45
+ evt: 'stats-recorded',
46
+ matchId: report.matchId,
47
+ duplicate: res.duplicate,
48
+ attempt: attempt + 1,
49
+ });
50
+ return;
51
+ }
52
+ catch (err) {
53
+ const status = err instanceof GameStatsError ? err.status : null;
54
+ const message = err instanceof Error ? err.message : String(err);
55
+ const again = retryable(err) && attempt < delays.length;
56
+ log({
57
+ evt: again ? 'stats-retry' : 'stats-failed',
58
+ matchId: report.matchId,
59
+ attempt: attempt + 1,
60
+ status,
61
+ error: message,
62
+ });
63
+ if (!again)
64
+ return;
65
+ await sleep(delays[attempt] ?? 0);
66
+ }
67
+ }
68
+ };
69
+ return {
70
+ enabled: serviceKey !== '',
71
+ report(report) {
72
+ if (serviceKey === '')
73
+ return;
74
+ const p = send(report).finally(() => inFlight.delete(p));
75
+ inFlight.add(p);
76
+ },
77
+ async idle() {
78
+ while (inFlight.size > 0)
79
+ await Promise.all(inFlight);
80
+ },
81
+ };
82
+ }
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@hadoku/game-server",
3
- "version": "0.1.40",
4
- "gitHead": "01e4b514259bb37d2b1e397ee20e092a53a10848",
3
+ "version": "0.1.42",
4
+ "gitHead": "ba602183061ee25158e7aa66723ac902b94e3698",
5
5
  "type": "module",
6
6
  "license": "MIT",
7
7
  "description": "The server parts any hosted game shares, above the kernel: the app config and edge auth, the room core (identity, seats, sessions, membership, the room list, the generic room routes), match hosting (the host contract, local and remote JVMs, placement, the start queue, recordings, the in-process and relay runtimes), streams, erase, telemetry and usage. Knows no game; Magic plugs in from apps/server. MIT; imports only node built-ins, express, socket.io, @wolffm/* and the platform packages.",
@@ -16,9 +16,9 @@
16
16
  "play/remote/"
17
17
  ],
18
18
  "dependencies": {
19
- "@wolffm/host-wire": "npm:@hadoku/host-wire@0.1.40",
20
- "@wolffm/platform-wire": "npm:@hadoku/platform-wire@0.1.40",
21
- "@wolffm/service-kernel": "npm:@hadoku/service-kernel@0.1.73",
19
+ "@wolffm/host-wire": "npm:@hadoku/host-wire@0.1.42",
20
+ "@wolffm/platform-wire": "npm:@hadoku/platform-wire@0.1.42",
21
+ "@wolffm/service-kernel": "npm:@hadoku/service-kernel@0.1.75",
22
22
  "@wolffm/prefs-client": "npm:@hadoku/prefs-client@^1.1.27",
23
23
  "@wolffm/rooms-protocol": "npm:@hadoku/rooms-protocol@^0.45.110",
24
24
  "@wolffm/rooms-server": "npm:@hadoku/rooms-server@^0.45.110",