1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
|
/**
* The X-Haven WebSocket client (PLAN.md section 3.5).
*
* Responsibilities:
* - the `hello` handshake (the session id rides in the cookie, set by the
* `/session` endpoint / the upgrade request)
* - a keepalive `ping` so the server's dead-connection sweep never closes a
* live tab
* - automatic reconnect with exponential backoff; every (re)connect re-sends
* `hello`, which the server answers with a full `welcome` — that is the
* resync
* - typed dispatch of `welcome` / `update` / `seats` / `error` / `pong`
* - outbound command / claim / undo / redo helpers
*
* The [WebSocket]-compatible transport is injectable so the reconnect and
* resync behaviour can be exercised in unit tests with a fake socket.
*/
import type {
ErrorMessage,
ServerMessage
} from './types';
import { claimMessage, helloMessage, pingMessage } from './types';
export type ConnectionStatus =
| 'connecting'
| 'open'
| 'reconnecting'
| 'closed';
/** A `WebSocket`-compatible surface (enough for the tests' fake). */
export interface Transport {
onopen: ((ev?: unknown) => void) | null;
onclose: ((ev?: unknown) => void) | null;
onerror: ((ev?: unknown) => void) | null;
onmessage: ((ev: { data: unknown }) => void) | null;
send(data: string): void;
close(): void;
readyState: number; // 0 OPEN
}
export interface ConnectionOptions {
/** Absolute `ws://` / `wss://` URL. Defaults to the page origin `/ws`. */
url?: string;
/** Inject a transport factory (tests). Defaults to `new WebSocket(url)`. */
transport?: (url: string) => Transport;
/** Reconnect base delay in ms (doubles each attempt, capped). */
reconnectBaseMs?: number;
reconnectMaxMs?: number;
/** Keepalive ping interval in ms. */
pingIntervalMs?: number;
}
const OPEN = 0;
export class GameConnection {
status: ConnectionStatus = 'connecting';
/** The session id from the last `welcome` (null before the handshake). */
session: string | null = null;
onStatus: ((status: ConnectionStatus) => void) | null = null;
/** Every server message, in order (including `pong`). */
onMessage: ((message: ServerMessage) => void) | null = null;
/** Convenience hook for `error` messages only. */
onError: ((error: ErrorMessage) => void) | null = null;
private ws: Transport | null = null;
private readonly options: Required<
Pick<
ConnectionOptions,
'reconnectBaseMs' | 'reconnectMaxMs' | 'pingIntervalMs'
>
> &
ConnectionOptions;
private readonly url: string;
private intentionalClose = false;
private reconnectDelay = 0;
private reconnectTimer: ReturnType<typeof setTimeout> | null = null;
private pingTimer: ReturnType<typeof setInterval> | null = null;
private disposed = false;
constructor(options: ConnectionOptions = {}) {
this.options = {
reconnectBaseMs: 500,
reconnectMaxMs: 15_000,
pingIntervalMs: 25_000,
...options
};
const explicit = options.url;
if (explicit) {
this.url = explicit;
} else {
const proto = window.location.protocol === 'https:' ? 'wss' : 'ws';
this.url = `${proto}://${window.location.host}/ws`;
}
}
private makeTransport(): Transport {
if (this.options.transport) return this.options.transport(this.url);
return new WebSocket(this.url) as unknown as Transport;
}
connect(): void {
this.intentionalClose = false;
this.openSocket();
}
/** Stop connecting and never reconnect (page teardown). */
disconnect(): void {
this.disposed = true;
this.intentionalClose = true;
this.clearTimers();
this.ws?.close();
this.ws = null;
}
private setStatus(status: ConnectionStatus) {
this.status = status;
this.onStatus?.(status);
}
private openSocket() {
if (this.disposed) return;
this.setStatus(this.ws === null && this.session === null ? 'connecting' : 'reconnecting');
const ws = this.makeTransport();
this.ws = ws;
ws.onopen = () => {
this.setStatus('open');
this.sendRaw(helloMessage());
this.startPing();
};
ws.onmessage = (ev) => {
const text = typeof ev.data === 'string' ? ev.data : '';
let message: ServerMessage;
try {
message = JSON.parse(text) as ServerMessage;
} catch {
return; // ignore non-JSON frames
}
if (message.t === 'welcome') {
this.session = message.session;
// A real resync landed: the connection is healthy, so the
// backoff starts fresh from the base on the next drop.
this.reconnectDelay = 0;
}
this.onMessage?.(message);
if (message.t === 'error') this.onError?.(message);
};
ws.onclose = () => {
this.stopPing();
if (this.disposed || this.intentionalClose) {
this.setStatus('closed');
return;
}
this.scheduleReconnect();
};
// onerror is always followed by onclose in the browser; nothing to do.
ws.onerror = () => {};
}
private scheduleReconnect() {
this.setStatus('reconnecting');
const delay = this.reconnectDelay || this.options.reconnectBaseMs;
this.reconnectDelay = Math.min(
delay * 2,
this.options.reconnectMaxMs
);
this.reconnectTimer = setTimeout(() => this.openSocket(), delay);
}
private clearTimers() {
if (this.reconnectTimer) {
clearTimeout(this.reconnectTimer);
this.reconnectTimer = null;
}
this.stopPing();
}
private startPing() {
this.stopPing();
this.pingTimer = setInterval(() => {
if (this.ws && this.ws.readyState === OPEN) this.sendRaw(pingMessage());
}, this.options.pingIntervalMs);
}
private stopPing() {
if (this.pingTimer) {
clearInterval(this.pingTimer);
this.pingTimer = null;
}
}
private sendRaw(message: object) {
if (this.ws && this.ws.readyState === OPEN) {
this.ws.send(JSON.stringify(message));
}
}
/** Execute a registered command (players only on the server side). */
sendCmd(name: string, args: Record<string, unknown> = {}): void {
this.sendRaw({ t: 'cmd', name, args });
}
/** Claim (or re-assert) a character seat. */
claim(characterId: string): void {
this.sendRaw(claimMessage(characterId));
}
undo(): void {
this.sendRaw({ t: 'undo' });
}
redo(): void {
this.sendRaw({ t: 'redo' });
}
/** Re-request a full resync (the server re-answers with a `welcome`). */
resync(): void {
this.sendRaw(helloMessage());
}
}
|