@hadoku/game-server 0.1.267 → 0.1.269
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/play/game-adapter.d.ts +8 -77
- package/dist/play/game-adapter.js +5 -0
- package/dist/play/match-registry.d.ts +120 -0
- package/dist/play/match-registry.js +158 -0
- package/dist/play/match-socket.d.ts +279 -0
- package/dist/play/match-socket.js +462 -0
- package/dist/play/per-match.d.ts +15 -0
- package/dist/play/per-match.js +21 -0
- package/package.json +6 -6
|
@@ -1,82 +1,13 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* What a game supplies
|
|
3
|
-
*
|
|
4
|
-
* `
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
*
|
|
8
|
-
*
|
|
9
|
-
*
|
|
10
|
-
* - `Spec` — how a match is configured (Forge's `MatchSpec`).
|
|
11
|
-
* - `Line` — what the engine's bridge sends up, one line at a time (Forge's `BridgeLine`).
|
|
12
|
-
* - `Cmd` — what the host sends down to the engine (Forge's `BridgeCommand`).
|
|
13
|
-
* - `Frame` — what a seat or a watcher is shown (Forge's `ServerFrame`).
|
|
14
|
-
* - `Checkpoint` — an opaque mid-game save a match can be restored from (Forge's
|
|
15
|
-
* `TurnSnapshot`). Nothing calls this generically yet, so it defaults to `unknown`.
|
|
2
|
+
* What a game supplies under the match shell: its session ({@link GameSession}), the half of a match
|
|
3
|
+
* that talks to its engine, and how it reads one engine line ({@link ClassifiedLine}). `play/match.ts`'s
|
|
4
|
+
* `Match` runs a `ForgeSession`; `fixtures/toy-game/match.ts`'s `ToyMatch` runs the toy's.
|
|
5
|
+
*/
|
|
6
|
+
/**
|
|
7
|
+
* What one engine line means to the shell: the engine is `ready`, a line for one seat's game, the game
|
|
8
|
+
* is `over` (`winners`/`losers` name seats; `drawn` when the rules named no winner), a `checkpoint` a
|
|
9
|
+
* restore starts from, a `fatal` line the match fails on, or `info` the shell need not act on.
|
|
16
10
|
*/
|
|
17
|
-
export interface GameAdapter<Spec, Line, Cmd, Frame, Checkpoint = unknown> {
|
|
18
|
-
/**
|
|
19
|
-
* The seats a spec wants, in order. `class Match`'s constructor reads exactly this off
|
|
20
|
-
* `spec.seats`: `ai`, and the `name`/`displayName` pair
|
|
21
|
-
* `SeatSpecWithIdentity` widens Forge's `SeatSpec` with.
|
|
22
|
-
*/
|
|
23
|
-
seats(spec: Spec): {
|
|
24
|
-
ai: boolean;
|
|
25
|
-
name: string;
|
|
26
|
-
}[];
|
|
27
|
-
/**
|
|
28
|
-
* What one line from the engine's bridge means, generically. `Match.onLine`
|
|
29
|
-
* is this switch for Forge today — its cases collapse onto this union
|
|
30
|
-
* one for one:
|
|
31
|
-
* - `'ready'` ← Forge's `'ready'`: the bridge has a game; record each seat's deck.
|
|
32
|
-
* - `'seat'` ← Forge's `'frame'`: a line addressed to one seat's game, forwarded
|
|
33
|
-
* to {@link GameSession.onLine}.
|
|
34
|
-
* - `'over'` ← Forge's `'gameover'`: the game ended. `winners`/`losers` name SEATS, not
|
|
35
|
-
* the engine's own ids (Forge's `winner`/`losers` read back through each seat's player id,
|
|
36
|
-
* `play/match/outcome.ts`'s `winnerSeatFromLosers`); `drawn` is true when the rules named no
|
|
37
|
-
* winner at all. A seat in neither array was simply not placed.
|
|
38
|
-
* - `'checkpoint'` ← Forge's `'snapshot'`: a mid-game save, kept as `latestSnapshot`
|
|
39
|
-
* for a later restart (`MatchRegistry.restore`).
|
|
40
|
-
* - `'fatal'` ← Forge's `'fatal'`: the bridge or the JVM died; `Match.fail`
|
|
41
|
-
* follows.
|
|
42
|
-
* - `'info'` ← everything else Forge logs but a shell need not act on itself
|
|
43
|
-
* (`'resent'`, `'input'`, `'probe'`, `'log'`, `'dropped'`, `'scan-overtaken'`,
|
|
44
|
-
* `'impersonated'`, `'rejected'`, `'stale'`, `'pace'`, `'pace-read'`, `'unsupported'`).
|
|
45
|
-
*/
|
|
46
|
-
classify(line: Line): ClassifiedLine<Checkpoint>;
|
|
47
|
-
/**
|
|
48
|
-
* Builds this match's engine session: the half of `class Match` that actually talks to the
|
|
49
|
-
* engine, handed the three ways a shell may be told something (`out`). Forge has no single
|
|
50
|
-
* method shaped like this today — it is the generalisation of three separate sinks:
|
|
51
|
-
* `Match.command` (the `Cmd` sink: `out.command`), `Match.send`/`Match.emit`
|
|
52
|
-
* (the per-seat `Frame` sink: `out.toSeat`), and
|
|
53
|
-
* `Match.tellWatchers`/`Match.sendWatcher` (the watcher `Frame` sink:
|
|
54
|
-
* `out.toWatchers`). Forge's real session, `ForgeSession`, is built by `Match` itself and reaches
|
|
55
|
-
* those sinks directly; nothing builds one through here yet.
|
|
56
|
-
*/
|
|
57
|
-
session(out: {
|
|
58
|
-
toSeat(seat: number, f: Frame): void;
|
|
59
|
-
toWatchers(f: Frame): void;
|
|
60
|
-
command(c: Cmd): void;
|
|
61
|
-
}): GameSession<Line, Cmd>;
|
|
62
|
-
/**
|
|
63
|
-
* A spec that resumes from a checkpoint rather than starting fresh — Forge's own
|
|
64
|
-
* `restoredSpec` (`play/match/registry.ts`): drop
|
|
65
|
-
* the chooser, open on the checkpoint's state, skip the opening hand.
|
|
66
|
-
*/
|
|
67
|
-
restoreSpec(spec: Spec, cp: Checkpoint): Spec;
|
|
68
|
-
/**
|
|
69
|
-
* The command that ends this seat's game as a loss — Forge's
|
|
70
|
-
* `{ t: 'act', seat, frame: { kind: 'act', method: 'concede' } }`, repeated until the engine answers it.
|
|
71
|
-
*/
|
|
72
|
-
concede(seat: number): Cmd;
|
|
73
|
-
/**
|
|
74
|
-
* A frame that tells a seat something in words, with no game state behind it — Forge's
|
|
75
|
-
* `endNotice` (`showErrorDialog`, `MATCH_ENDED_TITLE`).
|
|
76
|
-
*/
|
|
77
|
-
notice(text: string): Frame;
|
|
78
|
-
}
|
|
79
|
-
/** What {@link GameAdapter.classify} reads one engine line as. */
|
|
80
11
|
export type ClassifiedLine<Checkpoint> = {
|
|
81
12
|
t: 'ready';
|
|
82
13
|
} | {
|
|
@@ -1 +1,6 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* What a game supplies under the match shell: its session ({@link GameSession}), the half of a match
|
|
3
|
+
* that talks to its engine, and how it reads one engine line ({@link ClassifiedLine}). `play/match.ts`'s
|
|
4
|
+
* `Match` runs a `ForgeSession`; `fixtures/toy-game/match.ts`'s `ToyMatch` runs the toy's.
|
|
5
|
+
*/
|
|
1
6
|
export {};
|
|
@@ -0,0 +1,120 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The server's hosted matches by id, and a small record of each it has let go of: it makes a match
|
|
3
|
+
* (the game's `make`) and starts it, takes back one an earlier server left running (`adopt`), starts
|
|
4
|
+
* one again on a new engine when its host is lost (`restore`), and leaves every live one running for
|
|
5
|
+
* the next server (`handOver`). A match reaches out only while the registry holds it for its id: a
|
|
6
|
+
* restored match's old engine can still talk on its way out, and none of it may reach a seat.
|
|
7
|
+
* What only the game knows rides on the `on*` hooks (Magic's: `play/match.ts`'s `createMatchRegistry`).
|
|
8
|
+
*/
|
|
9
|
+
import type { ParticipantId } from '@wolffm/rooms-protocol';
|
|
10
|
+
import type { HostEvents, MatchHost, MatchRecord, MatchSpec, TurnSnapshot } from './match-host.js';
|
|
11
|
+
import type { HostedMatch } from './match/hosted.js';
|
|
12
|
+
import type { ShellSeat } from './match/shell.js';
|
|
13
|
+
type Msg = {
|
|
14
|
+
t: string;
|
|
15
|
+
};
|
|
16
|
+
type Hosted = HostedMatch<Msg, Msg>;
|
|
17
|
+
/** What a match that is not new is built with: who holds each seat, when it started, where its game and clock stand. */
|
|
18
|
+
export type HostedRestore = {
|
|
19
|
+
epoch: string | null;
|
|
20
|
+
owners: (string | null)[];
|
|
21
|
+
startedAt: number;
|
|
22
|
+
snapshot?: TurnSnapshot | null;
|
|
23
|
+
checkpoint?: unknown;
|
|
24
|
+
clockMs?: [number, number];
|
|
25
|
+
clockPaused?: boolean;
|
|
26
|
+
clockSeated?: boolean;
|
|
27
|
+
};
|
|
28
|
+
/** A game resumed from a parked match: who holds each seat, the turn-start snapshot it opens on, each seat's clock. */
|
|
29
|
+
export type HostedResume = {
|
|
30
|
+
owners: readonly (string | null)[];
|
|
31
|
+
snapshot: TurnSnapshot;
|
|
32
|
+
clockMs?: [number, number];
|
|
33
|
+
};
|
|
34
|
+
/** What {@link HostedRegistry.restore} did: back to its checkpoint (`turn`, when that is a turn-start snapshot), or a fresh game from its spec. */
|
|
35
|
+
export type HostedRestored<M> = {
|
|
36
|
+
match: M;
|
|
37
|
+
from: 'snapshot' | 'spec';
|
|
38
|
+
turn: number | null;
|
|
39
|
+
};
|
|
40
|
+
export type EndedSeat = Pick<ShellSeat, 'seat' | 'ai' | 'owner' | 'playerId'>;
|
|
41
|
+
/** What is kept of every ended match: its id, how it ended, who held each seat, and nothing of its play. A game's own record adds what its readers still ask. */
|
|
42
|
+
export declare class EndedBase<S extends EndedSeat = EndedSeat> {
|
|
43
|
+
readonly id: string;
|
|
44
|
+
readonly status: 'stopped' | 'failed';
|
|
45
|
+
readonly failure: string | null;
|
|
46
|
+
readonly seats: readonly S[];
|
|
47
|
+
constructor(match: Hosted, seats: readonly S[]);
|
|
48
|
+
seatOf(participantId: ParticipantId): number | null;
|
|
49
|
+
/** Nothing is under way. */
|
|
50
|
+
live(): null;
|
|
51
|
+
/** It is over: there is nothing left to enter. */
|
|
52
|
+
entered(): boolean[];
|
|
53
|
+
}
|
|
54
|
+
/** A game's hooks as its match calls them: the registry names the match. */
|
|
55
|
+
export type BoundHooks<H, K extends keyof H> = {
|
|
56
|
+
[P in K]-?: NonNullable<H[P]> extends (m: never, ...args: infer A) => unknown ? (...args: A) => void : never;
|
|
57
|
+
};
|
|
58
|
+
export interface HostedRegistryDeps<M extends Hosted, Spec extends MatchSpec, Ended, From extends HostedResume, H, K extends keyof H> {
|
|
59
|
+
/** Builds the game's match with its bound hooks and the registry's own two (a restart of the turn, and its ending). Nothing starts here. */
|
|
60
|
+
make(id: string, spec: Spec, hooks: BoundHooks<H, K> & {
|
|
61
|
+
restartTurn(): void;
|
|
62
|
+
ended(): void;
|
|
63
|
+
}, restore?: HostedRestore): M;
|
|
64
|
+
/** Where the game's hooks named in `hookNames` are read, each when it is called. */
|
|
65
|
+
hooks: H;
|
|
66
|
+
hookNames: readonly K[];
|
|
67
|
+
newId(): string;
|
|
68
|
+
/** What is kept of a match once the registry lets go of it, the newest `endedKept`. */
|
|
69
|
+
ended(match: M): Ended;
|
|
70
|
+
endedKept: number;
|
|
71
|
+
/** How long a failed match stays held, and restorable, before it is let go of. */
|
|
72
|
+
overGraceMs: number;
|
|
73
|
+
/** The ceiling ({@link HostedRegistry.full}). Default `MAX_CONCURRENT_MATCHES`. */
|
|
74
|
+
maxMatches?: number;
|
|
75
|
+
/** The places in the ceiling something other than a match holds now. */
|
|
76
|
+
extraPlaces?(): number;
|
|
77
|
+
/** The re-attach half of the host. Absent on a host whose engines die with the server. */
|
|
78
|
+
attach?(record: MatchRecord, events: HostEvents<Msg, Msg>): MatchHost<Msg>;
|
|
79
|
+
log(entry: Record<string, unknown>): void;
|
|
80
|
+
freed?(match: M): void;
|
|
81
|
+
now?: () => number;
|
|
82
|
+
/** A new match is in the registry and has not started. */
|
|
83
|
+
onCreated?(match: M, from: From | undefined): void;
|
|
84
|
+
/** A match taken back is in the registry: told before its engine's replay and again after it. */
|
|
85
|
+
onAdopted?(match: M, record: MatchRecord): void;
|
|
86
|
+
/** `next` replaces `old` under its id, before `old` is stopped and before `next` starts. */
|
|
87
|
+
onRestored?(old: M, next: M, from: 'snapshot' | 'spec'): void;
|
|
88
|
+
}
|
|
89
|
+
export interface HostedRegistry<M, Spec, Ended, From> {
|
|
90
|
+
/** A new match, under a new id. `from`: a parked game resumed on its turn-start snapshot, its seats held by `from.owners`, its clock where it was left. */
|
|
91
|
+
create(spec: Spec, from?: From): M;
|
|
92
|
+
/** A match the registry holds: from its create until it ends ({@link find} has the rest). */
|
|
93
|
+
get(id: string): M | undefined;
|
|
94
|
+
/**
|
|
95
|
+
* The match while the registry holds it, then its ended record. It is let go of when it is stopped
|
|
96
|
+
* (by a stop, or past its finished game's grace), or `overGraceMs` after it failed: the window a
|
|
97
|
+
* failed match is still restorable in and its seats can still read why it ended.
|
|
98
|
+
*/
|
|
99
|
+
find(id: string): M | Ended | undefined;
|
|
100
|
+
/** Matches that hold an engine: starting, running, or over but not yet stopped. */
|
|
101
|
+
active(): M[];
|
|
102
|
+
stopAll(): void;
|
|
103
|
+
/** The ceiling when it is reached, else null: matches starting or running and `extraPlaces` hold a place; a finished match holds none. */
|
|
104
|
+
full(): number | null;
|
|
105
|
+
/** Take back a match an earlier server left running: its host replays its stream before this returns, epoch and owners kept. Null: the host cannot re-attach. */
|
|
106
|
+
adopt(record: MatchRecord): M | null;
|
|
107
|
+
/**
|
|
108
|
+
* Start this match again on a new engine when its own is lost: from its latest checkpoint, or with
|
|
109
|
+
* none as a fresh game from its spec. It keeps its id, owners and start time and gets a new epoch, so
|
|
110
|
+
* every client resyncs; the old match is stopped and says nothing more. Null: no such match.
|
|
111
|
+
*/
|
|
112
|
+
restore(id: string): HostedRestored<M> | null;
|
|
113
|
+
/** The server is going down: every match that holds an engine is left running for the next one; `ending` could not be, and is owed an explanation and a stop. */
|
|
114
|
+
handOver(): {
|
|
115
|
+
handed: M[];
|
|
116
|
+
ending: M[];
|
|
117
|
+
};
|
|
118
|
+
}
|
|
119
|
+
export declare function createHostedRegistry<M extends Hosted, Spec extends MatchSpec, Ended, From extends HostedResume = HostedResume, H = Record<string, never>, K extends keyof H = never>(deps: HostedRegistryDeps<M, Spec, Ended, From, H, K>): HostedRegistry<M, Spec, Ended, From>;
|
|
120
|
+
export {};
|
|
@@ -0,0 +1,158 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The server's hosted matches by id, and a small record of each it has let go of: it makes a match
|
|
3
|
+
* (the game's `make`) and starts it, takes back one an earlier server left running (`adopt`), starts
|
|
4
|
+
* one again on a new engine when its host is lost (`restore`), and leaves every live one running for
|
|
5
|
+
* the next server (`handOver`). A match reaches out only while the registry holds it for its id: a
|
|
6
|
+
* restored match's old engine can still talk on its way out, and none of it may reach a seat.
|
|
7
|
+
* What only the game knows rides on the `on*` hooks (Magic's: `play/match.ts`'s `createMatchRegistry`).
|
|
8
|
+
*/
|
|
9
|
+
import { randomBytes } from 'node:crypto';
|
|
10
|
+
import { MAX_CONCURRENT_MATCHES } from './host.js';
|
|
11
|
+
/** What is kept of every ended match: its id, how it ended, who held each seat, and nothing of its play. A game's own record adds what its readers still ask. */
|
|
12
|
+
export class EndedBase {
|
|
13
|
+
id;
|
|
14
|
+
status;
|
|
15
|
+
failure;
|
|
16
|
+
seats;
|
|
17
|
+
constructor(match, seats) {
|
|
18
|
+
this.id = match.id;
|
|
19
|
+
this.status = match.status === 'failed' ? 'failed' : 'stopped';
|
|
20
|
+
this.failure = match.failure;
|
|
21
|
+
this.seats = seats;
|
|
22
|
+
}
|
|
23
|
+
seatOf(participantId) {
|
|
24
|
+
return this.seats.find((s) => s.owner === participantId)?.seat ?? null;
|
|
25
|
+
}
|
|
26
|
+
/** Nothing is under way. */
|
|
27
|
+
live() {
|
|
28
|
+
return null;
|
|
29
|
+
}
|
|
30
|
+
/** It is over: there is nothing left to enter. */
|
|
31
|
+
entered() {
|
|
32
|
+
return this.seats.map(() => true);
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
export function createHostedRegistry(deps) {
|
|
36
|
+
const matches = new Map();
|
|
37
|
+
/** Oldest first, so the first key is the one to evict. */
|
|
38
|
+
const ended = new Map();
|
|
39
|
+
const now = deps.now ?? Date.now;
|
|
40
|
+
const free = (m) => {
|
|
41
|
+
if (matches.get(m.id) !== m)
|
|
42
|
+
return;
|
|
43
|
+
matches.delete(m.id);
|
|
44
|
+
ended.delete(m.id);
|
|
45
|
+
ended.set(m.id, deps.ended(m));
|
|
46
|
+
for (const id of ended.keys()) {
|
|
47
|
+
if (ended.size <= deps.endedKept)
|
|
48
|
+
break;
|
|
49
|
+
ended.delete(id);
|
|
50
|
+
}
|
|
51
|
+
deps.log({ evt: 'match-freed', matchId: m.id, status: m.status });
|
|
52
|
+
deps.freed?.(m);
|
|
53
|
+
};
|
|
54
|
+
const active = () => [...matches.values()].filter((m) => m.status === 'starting' || m.status === 'running' || m.status === 'over');
|
|
55
|
+
const build = (id, spec, restore) => {
|
|
56
|
+
let match;
|
|
57
|
+
const when = (f) => (...args) => {
|
|
58
|
+
const m = match;
|
|
59
|
+
if (m !== undefined && matches.get(id) === m)
|
|
60
|
+
f(m, ...args);
|
|
61
|
+
};
|
|
62
|
+
const call = (name) => when((m, ...args) => deps.hooks[name]?.call(deps.hooks, m, ...args));
|
|
63
|
+
const bound = Object.fromEntries(deps.hookNames.map((name) => [name, call(name)]));
|
|
64
|
+
const restartTurn = when(() => void registry.restore(id));
|
|
65
|
+
// A failed match stays restorable, and its seats can still read why, for the grace a finished one keeps its board.
|
|
66
|
+
const letGo = when((m) => {
|
|
67
|
+
if (m.status === 'failed')
|
|
68
|
+
setTimeout(() => free(m), deps.overGraceMs).unref();
|
|
69
|
+
else
|
|
70
|
+
free(m);
|
|
71
|
+
});
|
|
72
|
+
match = deps.make(id, spec, { ...bound, restartTurn, ended: letGo }, restore);
|
|
73
|
+
return match;
|
|
74
|
+
};
|
|
75
|
+
const registry = {
|
|
76
|
+
create(spec, from) {
|
|
77
|
+
const id = deps.newId();
|
|
78
|
+
// `spec` goes through unchanged: with `from` given, `restore.checkpoint` is `HostedMatch`'s cue to run it through its `restoreSpec`.
|
|
79
|
+
const match = build(id, spec, from === undefined
|
|
80
|
+
? undefined
|
|
81
|
+
: { epoch: null, owners: [...from.owners], startedAt: now(), snapshot: from.snapshot, checkpoint: from.snapshot, ...(from.clockMs === undefined ? {} : { clockMs: from.clockMs }) });
|
|
82
|
+
matches.set(id, match);
|
|
83
|
+
ended.delete(id);
|
|
84
|
+
deps.onCreated?.(match, from);
|
|
85
|
+
match.start();
|
|
86
|
+
return match;
|
|
87
|
+
},
|
|
88
|
+
get: (id) => matches.get(id),
|
|
89
|
+
find: (id) => matches.get(id) ?? ended.get(id),
|
|
90
|
+
active,
|
|
91
|
+
stopAll() {
|
|
92
|
+
for (const m of matches.values())
|
|
93
|
+
m.stop();
|
|
94
|
+
},
|
|
95
|
+
full() {
|
|
96
|
+
const max = deps.maxMatches ?? MAX_CONCURRENT_MATCHES;
|
|
97
|
+
const playing = active().filter((m) => m.status === 'starting' || m.status === 'running').length + (deps.extraPlaces?.() ?? 0);
|
|
98
|
+
return playing >= max ? max : null;
|
|
99
|
+
},
|
|
100
|
+
adopt(record) {
|
|
101
|
+
const attach = deps.attach;
|
|
102
|
+
if (attach === undefined)
|
|
103
|
+
return null;
|
|
104
|
+
const match = build(record.matchId, record.spec, {
|
|
105
|
+
epoch: record.epoch,
|
|
106
|
+
owners: record.owners,
|
|
107
|
+
startedAt: Date.parse(record.startedAt),
|
|
108
|
+
snapshot: record.snapshot ?? null,
|
|
109
|
+
...(record.clockMs === undefined ? {} : { clockMs: record.clockMs }),
|
|
110
|
+
...(record.clockPaused === true ? { clockPaused: true } : {}),
|
|
111
|
+
...(record.clockSeated === true ? { clockSeated: true } : {}),
|
|
112
|
+
});
|
|
113
|
+
matches.set(record.matchId, match);
|
|
114
|
+
ended.delete(record.matchId);
|
|
115
|
+
deps.onAdopted?.(match, record);
|
|
116
|
+
match.resume((events) => attach(record, events));
|
|
117
|
+
deps.onAdopted?.(match, record);
|
|
118
|
+
return match;
|
|
119
|
+
},
|
|
120
|
+
restore(id) {
|
|
121
|
+
const old = matches.get(id);
|
|
122
|
+
if (old === undefined)
|
|
123
|
+
return null;
|
|
124
|
+
const snapshot = old.latestSnapshot;
|
|
125
|
+
// A turn-start snapshot when the game writes one, else its own checkpoint.
|
|
126
|
+
const checkpoint = snapshot ?? old.latestCheckpoint;
|
|
127
|
+
const from = checkpoint === null ? 'spec' : 'snapshot';
|
|
128
|
+
// Never the old epoch's spelling, `${id}:${startedAt}`, even within its millisecond.
|
|
129
|
+
const epoch = `${id}:${now()}:${randomBytes(4).toString('hex')}`;
|
|
130
|
+
const clockMs = old.clockLeft();
|
|
131
|
+
const match = build(id, old.spec, {
|
|
132
|
+
epoch,
|
|
133
|
+
owners: old.owners(),
|
|
134
|
+
startedAt: old.startedAt,
|
|
135
|
+
snapshot,
|
|
136
|
+
...(checkpoint === null ? {} : { checkpoint }),
|
|
137
|
+
...(clockMs === null ? {} : { clockMs, ...(old.clockPaused ? { clockPaused: true } : {}), ...(old.clockSeated ? { clockSeated: true } : {}) }),
|
|
138
|
+
});
|
|
139
|
+
matches.set(id, match);
|
|
140
|
+
deps.onRestored?.(old, match, from);
|
|
141
|
+
old.stop();
|
|
142
|
+
for (const s of old.seats)
|
|
143
|
+
if (s.here)
|
|
144
|
+
match.seatConnected(s.seat);
|
|
145
|
+
deps.log({ evt: 'match-restored', matchId: id, from, ...(snapshot === null ? {} : { turn: snapshot.turn }), fromEpoch: old.epoch, epoch: match.epoch, oldStatus: old.status });
|
|
146
|
+
match.start();
|
|
147
|
+
return { match, from, turn: snapshot?.turn ?? null };
|
|
148
|
+
},
|
|
149
|
+
handOver() {
|
|
150
|
+
const handed = [];
|
|
151
|
+
const ending = [];
|
|
152
|
+
for (const m of active())
|
|
153
|
+
(m.handOver() ? handed : ending).push(m);
|
|
154
|
+
return { handed, ending };
|
|
155
|
+
},
|
|
156
|
+
};
|
|
157
|
+
return registry;
|
|
158
|
+
}
|
|
@@ -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,10 +1,10 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@hadoku/game-server",
|
|
3
|
-
"version": "0.1.
|
|
4
|
-
"gitHead": "
|
|
3
|
+
"version": "0.1.269",
|
|
4
|
+
"gitHead": "2365a991158c0730cd170e1f17b9e09063d022d8",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"license": "MIT",
|
|
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.",
|
|
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.",
|
|
8
8
|
"exports": {
|
|
9
9
|
"./*": {
|
|
10
10
|
"types": "./dist/*.d.ts",
|
|
@@ -16,9 +16,9 @@
|
|
|
16
16
|
"play/remote/"
|
|
17
17
|
],
|
|
18
18
|
"dependencies": {
|
|
19
|
-
"@wolffm/host-wire": "npm:@hadoku/host-wire@0.1.
|
|
20
|
-
"@wolffm/platform-wire": "npm:@hadoku/platform-wire@0.1.
|
|
21
|
-
"@wolffm/service-kernel": "npm:@hadoku/service-kernel@0.1.
|
|
19
|
+
"@wolffm/host-wire": "npm:@hadoku/host-wire@0.1.269",
|
|
20
|
+
"@wolffm/platform-wire": "npm:@hadoku/platform-wire@0.1.269",
|
|
21
|
+
"@wolffm/service-kernel": "npm:@hadoku/service-kernel@0.1.302",
|
|
22
22
|
"@wolffm/prefs-client": "npm:@hadoku/prefs-client@^1.2.4",
|
|
23
23
|
"@wolffm/rooms-protocol": "npm:@hadoku/rooms-protocol@^0.45.158",
|
|
24
24
|
"@wolffm/rooms-server": "npm:@hadoku/rooms-server@^0.45.158",
|