@hadoku/game-server 0.1.266 → 0.1.268
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.
|
@@ -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
|
+
}
|
|
@@ -33,9 +33,14 @@
|
|
|
33
33
|
* rejoins by sending `relay:join` again on the socket it already has (`relay-channel.ts` does on
|
|
34
34
|
* every `relay:ended`): no new event and no reconnect. Until it does, that socket speaks for
|
|
35
35
|
* nothing — its sends and its disconnect belong to the match it joined, which is over.
|
|
36
|
+
*
|
|
37
|
+
* ## One tab drives a seat
|
|
38
|
+
*
|
|
39
|
+
* The newest socket of a seat drives it (`./seat-control.ts`). The one it replaced is sent `relay:role`
|
|
40
|
+
* `elsewhere` and closed, so its page can offer Play here; the same tab's dead socket is closed silently.
|
|
36
41
|
*/
|
|
37
42
|
import type { Server as SocketIOServer } from 'socket.io';
|
|
38
|
-
import type
|
|
43
|
+
import { type ParticipantId } from '@wolffm/rooms-protocol';
|
|
39
44
|
import { type RateLimitConfig } from '@wolffm/rooms-server';
|
|
40
45
|
import { type Gate } from '@wolffm/service-kernel/http';
|
|
41
46
|
import { type RelayOutcome, type RelaySession, type RelaySink } from './runtimes/relay.js';
|
|
@@ -46,6 +51,8 @@ export declare const RELAY_EVENTS: {
|
|
|
46
51
|
* numbers), or `{ winners: null }` when every seat left. To every live socket of the match,
|
|
47
52
|
* the sender of `over` and every watcher included, so the room can show the result. */
|
|
48
53
|
readonly ended: "relay:ended";
|
|
54
|
+
/** `{ matchId, role: 'elsewhere' }`: a newer tab of this player took the seat, and this socket is closed. */
|
|
55
|
+
readonly role: "relay:role";
|
|
49
56
|
};
|
|
50
57
|
/** Messages per sender: four times bomberman's own host, which sends its state at 30 Hz, so no
|
|
51
58
|
* game this relay was built for comes near it, and a bundle that floods its room does. */
|
|
@@ -86,7 +93,7 @@ export interface RelayRoster {
|
|
|
86
93
|
} | undefined;
|
|
87
94
|
/** This match's own session, wired to `sink`; `onEnded` is this file's own cleanup, called once. */
|
|
88
95
|
attach(sink: RelaySink, onEnded: (outcome: RelayOutcome | null) => void): RelaySession;
|
|
89
|
-
/** A seat's
|
|
96
|
+
/** A seat's socket joined, or the socket driving it went. Absent: nothing is told. */
|
|
90
97
|
seatConnected?(seat: number): void;
|
|
91
98
|
seatDisconnected?(seat: number): void;
|
|
92
99
|
}
|
|
@@ -33,13 +33,20 @@
|
|
|
33
33
|
* rejoins by sending `relay:join` again on the socket it already has (`relay-channel.ts` does on
|
|
34
34
|
* every `relay:ended`): no new event and no reconnect. Until it does, that socket speaks for
|
|
35
35
|
* nothing — its sends and its disconnect belong to the match it joined, which is over.
|
|
36
|
+
*
|
|
37
|
+
* ## One tab drives a seat
|
|
38
|
+
*
|
|
39
|
+
* The newest socket of a seat drives it (`./seat-control.ts`). The one it replaced is sent `relay:role`
|
|
40
|
+
* `elsewhere` and closed, so its page can offer Play here; the same tab's dead socket is closed silently.
|
|
36
41
|
*/
|
|
42
|
+
import { isTabId } from '@wolffm/rooms-protocol';
|
|
37
43
|
import { MultiRateLimiter } from '@wolffm/rooms-server';
|
|
38
44
|
import { createEdgeAuth, rankOf, tierOf } from '@wolffm/service-kernel/auth';
|
|
39
45
|
import { createGate } from '@wolffm/service-kernel/http';
|
|
40
46
|
import { identityFromHeaders } from '../room/identity.js';
|
|
41
47
|
import { handshakeEdgeTier } from '../room/socket-auth.js';
|
|
42
48
|
import { costlyActLimit } from '../http/request.js';
|
|
49
|
+
import { createSeatControl } from './seat-control.js';
|
|
43
50
|
export const RELAY_EVENTS = {
|
|
44
51
|
join: 'relay:join',
|
|
45
52
|
message: 'relay:message',
|
|
@@ -47,6 +54,8 @@ export const RELAY_EVENTS = {
|
|
|
47
54
|
* numbers), or `{ winners: null }` when every seat left. To every live socket of the match,
|
|
48
55
|
* the sender of `over` and every watcher included, so the room can show the result. */
|
|
49
56
|
ended: 'relay:ended',
|
|
57
|
+
/** `{ matchId, role: 'elsewhere' }`: a newer tab of this player took the seat, and this socket is closed. */
|
|
58
|
+
role: 'relay:role',
|
|
50
59
|
};
|
|
51
60
|
/** Messages per sender: four times bomberman's own host, which sends its state at 30 Hz, so no
|
|
52
61
|
* game this relay was built for comes near it, and a bundle that floods its room does. */
|
|
@@ -105,6 +114,11 @@ export function attachRelay(io, deps) {
|
|
|
105
114
|
(deps.gate ?? defaultRelayGate(deps)).gateSocketIo(io, { minTier: deps.minTier, surface: 'play-socket' });
|
|
106
115
|
const log = deps.log ?? (() => { });
|
|
107
116
|
const live = new Map();
|
|
117
|
+
const seats = createSeatControl();
|
|
118
|
+
const driverOf = (matchId, seat) => {
|
|
119
|
+
const id = seats.driver(matchId, seat);
|
|
120
|
+
return id === null ? undefined : io.sockets.sockets.get(id);
|
|
121
|
+
};
|
|
108
122
|
const joinLimit = costlyActLimit(deps.joinRateLimit === undefined ? RELAY_JOIN_RATE_LIMIT : deps.joinRateLimit, {
|
|
109
123
|
act: 'relay-join',
|
|
110
124
|
onRefused: () => log({ evt: 'relay-join-refused', reason: 'rate-limited' }),
|
|
@@ -117,12 +131,10 @@ export function attachRelay(io, deps) {
|
|
|
117
131
|
const found = live.get(matchId);
|
|
118
132
|
if (found !== undefined)
|
|
119
133
|
return found;
|
|
120
|
-
const seatSockets = new Map();
|
|
121
134
|
const watcherSockets = new Set();
|
|
122
135
|
const session = roster.attach({
|
|
123
136
|
toSeat: (seat, msg) => {
|
|
124
|
-
|
|
125
|
-
s.emit(RELAY_EVENTS.message, msg);
|
|
137
|
+
driverOf(matchId, seat)?.emit(RELAY_EVENTS.message, msg);
|
|
126
138
|
},
|
|
127
139
|
toWatchers: (msg) => {
|
|
128
140
|
for (const s of watcherSockets)
|
|
@@ -131,16 +143,16 @@ export function attachRelay(io, deps) {
|
|
|
131
143
|
}, (outcome) => {
|
|
132
144
|
const ending = live.get(matchId);
|
|
133
145
|
const word = { winners: outcome?.winners ?? null };
|
|
134
|
-
for (
|
|
135
|
-
|
|
136
|
-
s.emit(RELAY_EVENTS.ended, word);
|
|
146
|
+
for (let seat = 0; seat < roster.seatCount; seat += 1)
|
|
147
|
+
driverOf(matchId, seat)?.emit(RELAY_EVENTS.ended, word);
|
|
137
148
|
for (const s of ending?.watcherSockets ?? [])
|
|
138
149
|
s.emit(RELAY_EVENTS.ended, word);
|
|
139
150
|
live.delete(matchId);
|
|
151
|
+
seats.forget(matchId);
|
|
140
152
|
log({ evt: 'relay-ended', matchId, winners: word.winners });
|
|
141
153
|
deps.onEnded?.(matchId, outcome);
|
|
142
154
|
});
|
|
143
|
-
const entry = { session, roster,
|
|
155
|
+
const entry = { session, roster, watcherSockets };
|
|
144
156
|
live.set(matchId, entry);
|
|
145
157
|
return entry;
|
|
146
158
|
}
|
|
@@ -149,6 +161,8 @@ export function attachRelay(io, deps) {
|
|
|
149
161
|
// The match this socket joined, by its live entry rather than its id: a room's next match
|
|
150
162
|
// lives under the same id, and a socket that has not rejoined it speaks for nothing there.
|
|
151
163
|
let joined = null;
|
|
164
|
+
/** This socket's sends were refused for having lost its seat: said once, not once per send. */
|
|
165
|
+
let refusedElsewhere = false;
|
|
152
166
|
socket.on(RELAY_EVENTS.join, (payload, ack) => {
|
|
153
167
|
const reply = ack ?? (() => { });
|
|
154
168
|
const matchId = readMatchId(payload);
|
|
@@ -175,12 +189,14 @@ export function attachRelay(io, deps) {
|
|
|
175
189
|
match.watcherSockets.add(socket);
|
|
176
190
|
}
|
|
177
191
|
else {
|
|
178
|
-
const
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
192
|
+
const tab = payload.tabId;
|
|
193
|
+
const { replaced, sameTab } = seats.take(matchId, role, socket.id, isTabId(tab) ? `${participantId}\n${tab}` : null);
|
|
194
|
+
const old = replaced === null ? undefined : io.sockets.sockets.get(replaced);
|
|
195
|
+
if (old !== undefined && !sameTab)
|
|
196
|
+
old.emit(RELAY_EVENTS.role, { matchId, role: 'elsewhere' });
|
|
197
|
+
old?.disconnect(true);
|
|
198
|
+
// Told on every seat join, the same as `MatchShell.seatConnected` itself is: harmless to
|
|
199
|
+
// tell twice, and cheaper than tracking whether the seat had a driver a moment ago.
|
|
184
200
|
match.roster.seatConnected?.(role);
|
|
185
201
|
}
|
|
186
202
|
joined = { matchId, match, seat: role };
|
|
@@ -201,6 +217,12 @@ export function attachRelay(io, deps) {
|
|
|
201
217
|
log({ evt: 'relay-send-refused', matchId: joined.matchId, reason: 'watcher' });
|
|
202
218
|
return;
|
|
203
219
|
}
|
|
220
|
+
if (!seats.holds(joined.matchId, joined.seat, socket.id)) {
|
|
221
|
+
if (!refusedElsewhere)
|
|
222
|
+
log({ evt: 'relay-send-refused', matchId: joined.matchId, reason: 'elsewhere' });
|
|
223
|
+
refusedElsewhere = true;
|
|
224
|
+
return;
|
|
225
|
+
}
|
|
204
226
|
if (messageLimit !== null && !messageLimit.allow(participantId)) {
|
|
205
227
|
if (!throttled.has(participantId))
|
|
206
228
|
log({ evt: 'relay-send-refused', matchId: joined.matchId, reason: 'rate-limited' });
|
|
@@ -219,15 +241,11 @@ export function attachRelay(io, deps) {
|
|
|
219
241
|
if (joined.seat === null) {
|
|
220
242
|
match.watcherSockets.delete(socket);
|
|
221
243
|
}
|
|
222
|
-
else {
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
//
|
|
226
|
-
|
|
227
|
-
// good is the roster's own rejoin-grace timer's call — told only once the
|
|
228
|
-
// seat's last live socket is actually gone, never on an earlier one among several tabs.
|
|
229
|
-
if (set === undefined || set.size === 0)
|
|
230
|
-
match.roster.seatDisconnected?.(joined.seat);
|
|
244
|
+
else if (seats.release(joined.matchId, joined.seat, socket.id)) {
|
|
245
|
+
// A plain disconnect is not a leave: rejoining is `relay:join` again on a new socket.
|
|
246
|
+
// Whether this is a leave for good is the roster's own rejoin-grace timer's call, told
|
|
247
|
+
// only when the seat's driver goes, never when a socket a newer tab replaced does.
|
|
248
|
+
match.roster.seatDisconnected?.(joined.seat);
|
|
231
249
|
}
|
|
232
250
|
log({ evt: 'relay-disconnected', matchId: joined.matchId, seat: joined.seat });
|
|
233
251
|
});
|
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.268",
|
|
4
|
+
"gitHead": "7e4245c9b315269a20097fc89d20c3982b307e4a",
|
|
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.268",
|
|
20
|
+
"@wolffm/platform-wire": "npm:@hadoku/platform-wire@0.1.268",
|
|
21
|
+
"@wolffm/service-kernel": "npm:@hadoku/service-kernel@0.1.301",
|
|
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",
|