@stefan.inc/game-networking 0.0.0 → 0.2.0
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/README.md +27 -3
- package/package.json +1 -1
- package/src/index.ts +4 -0
- package/src/room.ts +229 -0
- package/src/types.ts +31 -0
package/README.md
CHANGED
|
@@ -81,9 +81,34 @@ A transport is a whole deployment and a session is one room in it. Rooms are ind
|
|
|
81
81
|
|
|
82
82
|
### When the host leaves
|
|
83
83
|
|
|
84
|
-
The game lives in the host's browser, so it pauses while the host is away. Peers keep retrying and reconnect when the host is back; a host that reloads restores its own state (from `localStorage`, say) and calls `setState` again.
|
|
84
|
+
With `createHost` and `joinHost` the roles are fixed. The game lives in the host's browser, so it pauses while the host is away. Peers keep retrying and reconnect when the host is back; a host that reloads restores its own state (from `localStorage`, say) and calls `setState` again. That suits a game whose host owns something the others do not, such as a saved campaign.
|
|
85
85
|
|
|
86
|
-
|
|
86
|
+
- Any peer can still carry on by hand: close its session and `createHost` in the same room with the state it holds. The Worker lets one client host a room at a time, so if two try, one gets `host-taken`, and the other peers follow whoever hosts.
|
|
87
|
+
- `takeover: true` hosts a room even while another client holds it, which ends that client's session as `replaced` (it applies when the session starts, not each time its signaling reconnects).
|
|
88
|
+
- A host that went silent without closing (a sleeping laptop) stops holding its room after two and a half minutes.
|
|
89
|
+
|
|
90
|
+
### A room that elects its host
|
|
91
|
+
|
|
92
|
+
`joinRoom` is for a game where nobody in particular is the host. Everyone enters the room the same way, and the room keeps a host for as long as anyone is in it:
|
|
93
|
+
|
|
94
|
+
```ts
|
|
95
|
+
import { joinRoom } from "@stefan.inc/game-networking";
|
|
96
|
+
|
|
97
|
+
const session = joinRoom<GameMsg, Cursor, GameState>(options);
|
|
98
|
+
session.on("role", (role) => setHosting(role === "host"));
|
|
99
|
+
session.on("state", (state) => render(state));
|
|
100
|
+
session.on("message", (msg, from) => {
|
|
101
|
+
// Peers send commands, which reach whoever hosts. The host answers with the next state.
|
|
102
|
+
if (session.role === "host") session.setState(reduce(session.state, msg, from));
|
|
103
|
+
});
|
|
104
|
+
```
|
|
105
|
+
|
|
106
|
+
- The first player into a room hosts it. `create: false` is for joining by a code someone typed: that player waits for a host (and gets `no-host`) instead of starting a room on a wrong code.
|
|
107
|
+
- When the room loses its host, the player who stood next in the host's roster hosts it, from the state it held as a peer, and everyone else follows. A host that closes or reloads its page is replaced in a fraction of a second and comes back as a peer. One whose browser dies takes about five seconds to be missed. One that goes silent holds the room until the Worker gives it up, as above.
|
|
108
|
+
- If the next in line is gone too, the one after takes over three seconds later, and so on down the roster. The Worker lets exactly one claim win, so two players never host one room.
|
|
109
|
+
- `session.role` and the `role` event say whether this browser hosts right now. `setState`, `remove` and `publish` throw on a peer. A game that lists its room calls `publish` again when it becomes the host.
|
|
110
|
+
- Every player must hold the whole state to be able to host, so such a room takes no `view`: the game hides what it must in its own UI. And a room is either elected or fixed: every player in it uses `joinRoom`, or none does.
|
|
111
|
+
- The new host starts from the last state *it* was sent. If it had dropped out a moment before the host did, the room goes back the moves it missed. A player who enters an empty room with nothing, such as a lone host reloading, hosts it from nothing unless the game restores a state of its own.
|
|
87
112
|
|
|
88
113
|
## Behavior
|
|
89
114
|
|
|
@@ -132,7 +157,6 @@ export default {
|
|
|
132
157
|
## What it does not do
|
|
133
158
|
|
|
134
159
|
- Run a game with nobody's browser open. A game that must go on unattended, or keep history across groups, needs a server of its own.
|
|
135
|
-
- Pick a new host by itself. The game decides who carries on.
|
|
136
160
|
- Seats, turns, votes, chat or reconnect tokens. Those are game state and game messages, keyed by the stable `selfId`.
|
|
137
161
|
|
|
138
162
|
## Develop
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@stefan.inc/game-networking",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.2.0",
|
|
4
4
|
"description": "Peer-to-peer networking for small browser games among friends: one player hosts and owns the state, the others connect to it over WebRTC, and a Cloudflare Worker only introduces them.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"board-game",
|
package/src/index.ts
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
export { createMemoryTransport, type MemoryTransport } from "./memory.ts";
|
|
2
2
|
export { applyPatches, diff, frozen, type Patch } from "./patch.ts";
|
|
3
|
+
export { joinRoom } from "./room.ts";
|
|
3
4
|
export { createHost, joinHost } from "./session.ts";
|
|
4
5
|
export { DEFAULT_ROOM, MAX_ROOM_INFO_LENGTH, type RoomListing } from "./signal-protocol.ts";
|
|
5
6
|
export {
|
|
@@ -25,6 +26,9 @@ export {
|
|
|
25
26
|
type PeerId,
|
|
26
27
|
type PeerInfo,
|
|
27
28
|
type PeerOptions,
|
|
29
|
+
type RoomEvents,
|
|
30
|
+
type RoomOptions,
|
|
31
|
+
type RoomSession,
|
|
28
32
|
type Session,
|
|
29
33
|
type SessionEvents,
|
|
30
34
|
type SessionOptions,
|
package/src/room.ts
ADDED
|
@@ -0,0 +1,229 @@
|
|
|
1
|
+
import { createHost, joinHost } from "./session.ts";
|
|
2
|
+
import {
|
|
3
|
+
NetError,
|
|
4
|
+
type ConnectionStatus,
|
|
5
|
+
type HostSession,
|
|
6
|
+
type PeerInfo,
|
|
7
|
+
type RoomEvents,
|
|
8
|
+
type RoomOptions,
|
|
9
|
+
type RoomSession,
|
|
10
|
+
type Session,
|
|
11
|
+
} from "./types.ts";
|
|
12
|
+
|
|
13
|
+
/** How much longer each player further down the roster waits before hosting a room that has no host. */
|
|
14
|
+
const ELECTION_STEP_MS = 3_000;
|
|
15
|
+
|
|
16
|
+
/**
|
|
17
|
+
* A session in a room that elects its host. Everyone joins as a peer. A client that learns the room has no host
|
|
18
|
+
* claims it, sooner the higher it stood in the last roster, and the signaling Worker lets exactly one claim win: the
|
|
19
|
+
* others find the winner hosting and follow it. The new host carries on from the state it held as a peer, so every
|
|
20
|
+
* player holds the whole state and a room like this takes no `view`.
|
|
21
|
+
*/
|
|
22
|
+
export function joinRoom<Msg, Presence, State = unknown>(
|
|
23
|
+
options: RoomOptions<Msg, Presence, State>,
|
|
24
|
+
): RoomSession<Msg, Presence, State> {
|
|
25
|
+
type Events = RoomEvents<Msg, Presence, State>;
|
|
26
|
+
const { create = true, parseState, ...shared } = options;
|
|
27
|
+
const { selfId } = shared;
|
|
28
|
+
|
|
29
|
+
const handlers: { [E in keyof Events]: Set<Events[E]> } = {
|
|
30
|
+
message: new Set(),
|
|
31
|
+
presence: new Set(),
|
|
32
|
+
peers: new Set(),
|
|
33
|
+
state: new Set(),
|
|
34
|
+
status: new Set(),
|
|
35
|
+
error: new Set(),
|
|
36
|
+
role: new Set(),
|
|
37
|
+
};
|
|
38
|
+
const emit = <E extends keyof Events>(event: E, ...args: Parameters<Events[E]>) => {
|
|
39
|
+
for (const handler of handlers[event]) (handler as (...a: typeof args) => void)(...args);
|
|
40
|
+
};
|
|
41
|
+
const report = (error: NetError) => {
|
|
42
|
+
if (handlers.error.size === 0)
|
|
43
|
+
console.warn(`[net] ${error.code}: ${error.message}`, error.cause ?? "");
|
|
44
|
+
emit("error", error);
|
|
45
|
+
};
|
|
46
|
+
|
|
47
|
+
/** `claiming` is a host session that the Worker has not yet said holds the room. To the game it is still a peer. */
|
|
48
|
+
let phase: "peer" | "claiming" | "host" = "peer";
|
|
49
|
+
let inner: Session<Msg, Presence, State>;
|
|
50
|
+
let host: HostSession<Msg, Presence, State> | null = null;
|
|
51
|
+
let unsubscribe: (() => void)[] = [];
|
|
52
|
+
let status: ConnectionStatus = "connecting";
|
|
53
|
+
let peers: PeerInfo[] = [];
|
|
54
|
+
/** The last roster a host sent, which is the order players stand for election in. */
|
|
55
|
+
let roster: PeerInfo[] = [];
|
|
56
|
+
let held: State | undefined;
|
|
57
|
+
let inRoom = false;
|
|
58
|
+
let claimTimer: ReturnType<typeof setTimeout> | undefined;
|
|
59
|
+
|
|
60
|
+
const setStatus = (next: ConnectionStatus) => {
|
|
61
|
+
if (status === next || status === "closed") return;
|
|
62
|
+
status = next;
|
|
63
|
+
emit("status", next);
|
|
64
|
+
};
|
|
65
|
+
const setPeers = (next: PeerInfo[]) => {
|
|
66
|
+
peers = next;
|
|
67
|
+
emit("peers", next);
|
|
68
|
+
};
|
|
69
|
+
const waiting = (): ConnectionStatus => (inRoom ? "reconnecting" : "connecting");
|
|
70
|
+
|
|
71
|
+
const leave = () => {
|
|
72
|
+
clearTimeout(claimTimer);
|
|
73
|
+
claimTimer = undefined;
|
|
74
|
+
for (const off of unsubscribe.splice(0)) off();
|
|
75
|
+
inner.close();
|
|
76
|
+
host = null;
|
|
77
|
+
};
|
|
78
|
+
|
|
79
|
+
const shutdown = () => {
|
|
80
|
+
leave();
|
|
81
|
+
setStatus("closed");
|
|
82
|
+
};
|
|
83
|
+
|
|
84
|
+
/** This client's place among the players the last host had connected, the host itself aside. */
|
|
85
|
+
const rank = () => {
|
|
86
|
+
const hostId = roster[0]?.id;
|
|
87
|
+
const line = roster.filter((peer) => peer.connected && peer.id !== hostId);
|
|
88
|
+
const place = line.findIndex((peer) => peer.id === selfId);
|
|
89
|
+
return place === -1 ? line.length : place;
|
|
90
|
+
};
|
|
91
|
+
|
|
92
|
+
const follow = () => {
|
|
93
|
+
phase = "peer";
|
|
94
|
+
const session = joinHost<Msg, Presence, State>({ ...shared, ...(parseState && { parseState }) });
|
|
95
|
+
inner = session;
|
|
96
|
+
unsubscribe = [
|
|
97
|
+
session.on("message", (msg, from) => emit("message", msg, from)),
|
|
98
|
+
session.on("presence", (presence, from) => emit("presence", presence, from)),
|
|
99
|
+
session.on("peers", (next) => {
|
|
100
|
+
if (next.some((peer) => peer.connected && peer.id !== selfId)) roster = next;
|
|
101
|
+
setPeers(next);
|
|
102
|
+
}),
|
|
103
|
+
session.on("state", (state) => {
|
|
104
|
+
held = state;
|
|
105
|
+
emit("state", state);
|
|
106
|
+
}),
|
|
107
|
+
session.on("status", (next) => {
|
|
108
|
+
if (next === "closed") return;
|
|
109
|
+
if (next === "connected") {
|
|
110
|
+
inRoom = true;
|
|
111
|
+
clearTimeout(claimTimer);
|
|
112
|
+
claimTimer = undefined;
|
|
113
|
+
}
|
|
114
|
+
setStatus(next);
|
|
115
|
+
}),
|
|
116
|
+
session.on("error", (error) => {
|
|
117
|
+
if (error.code === "no-host" && (create || inRoom)) {
|
|
118
|
+
if (claimTimer !== undefined) return;
|
|
119
|
+
const wait = rank() * ELECTION_STEP_MS;
|
|
120
|
+
if (wait === 0) claim();
|
|
121
|
+
else claimTimer = setTimeout(claim, wait);
|
|
122
|
+
return;
|
|
123
|
+
}
|
|
124
|
+
report(error);
|
|
125
|
+
if (error.fatal) shutdown();
|
|
126
|
+
}),
|
|
127
|
+
];
|
|
128
|
+
};
|
|
129
|
+
|
|
130
|
+
const claim = () => {
|
|
131
|
+
claimTimer = undefined;
|
|
132
|
+
if (phase !== "peer" || inner.status === "connected") return;
|
|
133
|
+
leave();
|
|
134
|
+
phase = "claiming";
|
|
135
|
+
const session = createHost<Msg, Presence, State>(shared);
|
|
136
|
+
inner = host = session;
|
|
137
|
+
unsubscribe = [
|
|
138
|
+
session.on("message", (msg, from) => emit("message", msg, from)),
|
|
139
|
+
session.on("presence", (presence, from) => emit("presence", presence, from)),
|
|
140
|
+
session.on("peers", (next) => {
|
|
141
|
+
if (phase === "host") setPeers(next);
|
|
142
|
+
}),
|
|
143
|
+
session.on("status", (next) => {
|
|
144
|
+
if (next === "closed") return;
|
|
145
|
+
if (next === "connected" && phase === "claiming") {
|
|
146
|
+
phase = "host";
|
|
147
|
+
inRoom = true;
|
|
148
|
+
if (held !== undefined) session.setState(held);
|
|
149
|
+
emit("role", "host");
|
|
150
|
+
setPeers(session.peers);
|
|
151
|
+
}
|
|
152
|
+
if (phase === "host") setStatus(next);
|
|
153
|
+
}),
|
|
154
|
+
session.on("error", (error) => {
|
|
155
|
+
// Another client hosts the room: it won the same election, or took the room while this one was away.
|
|
156
|
+
if (error.code === "host-taken") {
|
|
157
|
+
const wasHost = phase === "host";
|
|
158
|
+
leave();
|
|
159
|
+
follow();
|
|
160
|
+
if (wasHost) emit("role", "peer");
|
|
161
|
+
setStatus(waiting());
|
|
162
|
+
return;
|
|
163
|
+
}
|
|
164
|
+
report(error);
|
|
165
|
+
if (error.fatal) shutdown();
|
|
166
|
+
}),
|
|
167
|
+
];
|
|
168
|
+
setStatus(waiting());
|
|
169
|
+
};
|
|
170
|
+
|
|
171
|
+
const hosting = (what: string) => {
|
|
172
|
+
if (phase !== "host" || !host) throw new Error(`Only the room's host can ${what}`);
|
|
173
|
+
return host;
|
|
174
|
+
};
|
|
175
|
+
const assertOpen = () => {
|
|
176
|
+
if (status === "closed") throw new Error("Session is closed");
|
|
177
|
+
};
|
|
178
|
+
|
|
179
|
+
follow();
|
|
180
|
+
peers = inner!.peers;
|
|
181
|
+
|
|
182
|
+
return {
|
|
183
|
+
selfId,
|
|
184
|
+
get room() {
|
|
185
|
+
return inner.room;
|
|
186
|
+
},
|
|
187
|
+
get role() {
|
|
188
|
+
return phase === "host" ? "host" : "peer";
|
|
189
|
+
},
|
|
190
|
+
get status() {
|
|
191
|
+
return status;
|
|
192
|
+
},
|
|
193
|
+
get peers() {
|
|
194
|
+
return peers;
|
|
195
|
+
},
|
|
196
|
+
get state() {
|
|
197
|
+
return held;
|
|
198
|
+
},
|
|
199
|
+
send(msg, to) {
|
|
200
|
+
assertOpen();
|
|
201
|
+
return phase === "claiming" ? false : inner.send(msg, to);
|
|
202
|
+
},
|
|
203
|
+
sendPresence(presence) {
|
|
204
|
+
assertOpen();
|
|
205
|
+
if (phase !== "claiming") inner.sendPresence(presence);
|
|
206
|
+
},
|
|
207
|
+
setState(state) {
|
|
208
|
+
assertOpen();
|
|
209
|
+
hosting("set the state").setState(state);
|
|
210
|
+
held = state;
|
|
211
|
+
},
|
|
212
|
+
remove(peer, reason) {
|
|
213
|
+
assertOpen();
|
|
214
|
+
hosting("remove a player").remove(peer, reason);
|
|
215
|
+
},
|
|
216
|
+
publish(info) {
|
|
217
|
+
assertOpen();
|
|
218
|
+
hosting("publish the room").publish(info);
|
|
219
|
+
},
|
|
220
|
+
on(event: keyof Events, handler: Events[keyof Events]) {
|
|
221
|
+
const set = handlers[event] as Set<typeof handler>;
|
|
222
|
+
set.add(handler);
|
|
223
|
+
return () => void set.delete(handler);
|
|
224
|
+
},
|
|
225
|
+
close() {
|
|
226
|
+
if (status !== "closed") shutdown();
|
|
227
|
+
},
|
|
228
|
+
};
|
|
229
|
+
}
|
package/src/types.ts
CHANGED
|
@@ -134,6 +134,28 @@ export interface HostSession<Msg, Presence, State = unknown> extends Session<Msg
|
|
|
134
134
|
publish(info: unknown): void;
|
|
135
135
|
}
|
|
136
136
|
|
|
137
|
+
export type RoomEvents<Msg, Presence, State> = SessionEvents<Msg, Presence, State> & {
|
|
138
|
+
/** This client started hosting the room, or stopped because another client hosts it now. */
|
|
139
|
+
role: (role: "host" | "peer") => void;
|
|
140
|
+
};
|
|
141
|
+
|
|
142
|
+
/**
|
|
143
|
+
* A session in a room that elects its host: this client hosts it or follows whoever does, and `role` says which. The
|
|
144
|
+
* host's methods throw while it is a peer.
|
|
145
|
+
*/
|
|
146
|
+
export interface RoomSession<Msg, Presence, State = unknown> extends Omit<
|
|
147
|
+
HostSession<Msg, Presence, State>,
|
|
148
|
+
"role" | "on"
|
|
149
|
+
> {
|
|
150
|
+
readonly role: "host" | "peer";
|
|
151
|
+
// Two signatures, not one over `RoomEvents`, so that this is still a `Session` to whatever takes one.
|
|
152
|
+
on<E extends keyof SessionEvents<Msg, Presence, State>>(
|
|
153
|
+
event: E,
|
|
154
|
+
handler: SessionEvents<Msg, Presence, State>[E],
|
|
155
|
+
): () => void;
|
|
156
|
+
on(event: "role", handler: RoomEvents<Msg, Presence, State>["role"]): () => void;
|
|
157
|
+
}
|
|
158
|
+
|
|
137
159
|
export type SessionOptions<Msg, Presence> = {
|
|
138
160
|
/** Stable across reloads; the caller persists it. */
|
|
139
161
|
selfId: PeerId;
|
|
@@ -162,3 +184,12 @@ export type PeerOptions<Msg, Presence, State> = SessionOptions<Msg, Presence> &
|
|
|
162
184
|
/** Boundary validation of a whole state from the host. Throws on bad input. Changes after it are not checked. */
|
|
163
185
|
parseState?: (raw: unknown) => State;
|
|
164
186
|
};
|
|
187
|
+
|
|
188
|
+
export type RoomOptions<Msg, Presence, State> = PeerOptions<Msg, Presence, State> & {
|
|
189
|
+
/**
|
|
190
|
+
* Host the room when nobody does on arrival, which is how a room starts. Default true. With false this client
|
|
191
|
+
* waits for a host as `joinHost` does, and stands for election only once it has been in the room: for joining by
|
|
192
|
+
* a code someone typed, where a wrong code must not start a room.
|
|
193
|
+
*/
|
|
194
|
+
create?: boolean;
|
|
195
|
+
};
|