-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.test.ts
More file actions
445 lines (348 loc) · 14.3 KB
/
server.test.ts
File metadata and controls
445 lines (348 loc) · 14.3 KB
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
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
import { describe, test, expect, beforeAll, afterAll, afterEach } from "bun:test";
import { server, rooms, drain, _resetDrainForTest } from "./server";
const URL = `ws://localhost:${server.port}`;
function connect(): Promise<WebSocket> {
return new Promise((resolve, reject) => {
const ws = new WebSocket(URL);
ws.onopen = () => resolve(ws);
ws.onerror = (e) => reject(e);
});
}
function sendMsg(ws: WebSocket, msg: object) {
ws.send(JSON.stringify(msg));
}
function waitFor(ws: WebSocket, predicate?: (msg: any) => boolean): Promise<any> {
return new Promise((resolve) => {
const prev = ws.onmessage;
ws.onmessage = (event) => {
const data = JSON.parse(event.data);
if (!predicate || predicate(data)) {
ws.onmessage = prev;
resolve(data);
}
};
});
}
function waitForType(ws: WebSocket, type: string): Promise<any> {
return waitFor(ws, (msg) => msg.type === type);
}
// Collect all sockets for cleanup
let sockets: WebSocket[] = [];
function track(ws: WebSocket): WebSocket {
sockets.push(ws);
return ws;
}
afterEach(() => {
for (const ws of sockets) {
if (ws.readyState === WebSocket.OPEN) ws.close();
}
sockets = [];
rooms.clear();
});
afterAll(() => {
server.stop();
});
describe("room creation", () => {
test("creates a room and returns 4-char code", async () => {
const ws = track(await connect());
sendMsg(ws, { type: "create", clientId: "aaa", maxClients: 4 });
const msg = await waitForType(ws, "created");
expect(msg.type).toBe("created");
expect(msg.room).toHaveLength(4);
});
test("rejects create without clientId", async () => {
const ws = track(await connect());
sendMsg(ws, { type: "create", maxClients: 4 });
const msg = await waitForType(ws, "error");
expect(msg.message).toContain("clientId");
});
test("rejects create with invalid maxClients", async () => {
const ws = track(await connect());
sendMsg(ws, { type: "create", clientId: "aaa", maxClients: 0 });
const msg = await waitForType(ws, "error");
expect(msg.message).toContain("maxClients");
});
test("rejects second create from same connection", async () => {
const ws = track(await connect());
sendMsg(ws, { type: "create", clientId: "aaa", maxClients: 4 });
await waitForType(ws, "created");
sendMsg(ws, { type: "create", clientId: "aaa", maxClients: 4 });
const msg = await waitForType(ws, "error");
expect(msg.message).toContain("Already in a room");
});
test("creates a room with preferred room code", async () => {
const ws = track(await connect());
sendMsg(ws, { type: "create", clientId: "aaa", maxClients: 4, room: "ABCD" });
const msg = await waitForType(ws, "created");
expect(msg.room).toBe("ABCD");
});
test("ignores invalid preferred room code", async () => {
const ws = track(await connect());
sendMsg(ws, { type: "create", clientId: "aaa", maxClients: 4, room: "ab" });
const msg = await waitForType(ws, "created");
expect(msg.room).toHaveLength(4);
expect(msg.room).not.toBe("ab");
});
test("generates new code when preferred room is taken", async () => {
const ws1 = track(await connect());
sendMsg(ws1, { type: "create", clientId: "aaa", maxClients: 4, room: "XYZW" });
const msg1 = await waitForType(ws1, "created");
expect(msg1.room).toBe("XYZW");
const ws2 = track(await connect());
sendMsg(ws2, { type: "create", clientId: "bbb", maxClients: 4, room: "XYZW" });
const msg2 = await waitForType(ws2, "created");
expect(msg2.room).not.toBe("XYZW");
});
});
describe("joining", () => {
test("joins an existing room", async () => {
const ws1 = track(await connect());
sendMsg(ws1, { type: "create", clientId: "host", maxClients: 4 });
const { room } = await waitForType(ws1, "created");
const ws2 = track(await connect());
const peerJoinedPromise = waitForType(ws1, "peer_joined");
sendMsg(ws2, { type: "join", clientId: "guest", room });
const joinMsg = await waitForType(ws2, "joined");
const peerMsg = await peerJoinedPromise;
expect(joinMsg.room).toBe(room);
expect(joinMsg.clients).toContain("host");
expect(joinMsg.clients).toContain("guest");
expect(peerMsg.clientId).toBe("guest");
});
test("rejects join to non-existent room", async () => {
const ws = track(await connect());
sendMsg(ws, { type: "join", clientId: "aaa", room: "ZZZZ" });
const msg = await waitForType(ws, "error");
expect(msg.message).toContain("not found");
});
test("rejects join when room is full", async () => {
const ws1 = track(await connect());
sendMsg(ws1, { type: "create", clientId: "host", maxClients: 1 });
const { room } = await waitForType(ws1, "created");
const ws2 = track(await connect());
sendMsg(ws2, { type: "join", clientId: "guest", room });
const msg = await waitForType(ws2, "error");
expect(msg.message).toContain("full");
});
});
describe("messaging", () => {
test("broadcasts message to all other clients", async () => {
const ws1 = track(await connect());
sendMsg(ws1, { type: "create", clientId: "a", maxClients: 3 });
const { room } = await waitForType(ws1, "created");
const ws2 = track(await connect());
sendMsg(ws2, { type: "join", clientId: "b", room });
await waitForType(ws2, "joined");
const ws3 = track(await connect());
sendMsg(ws3, { type: "join", clientId: "c", room });
await waitForType(ws3, "joined");
const p1 = waitForType(ws1, "message");
const p3 = waitForType(ws3, "message");
sendMsg(ws2, { type: "send", data: { hello: "world" } });
const [msg1, msg3] = await Promise.all([p1, p3]);
expect(msg1.from).toBe("b");
expect(msg1.data).toEqual({ hello: "world" });
expect(msg3.from).toBe("b");
});
test("sends targeted message to specific client", async () => {
const ws1 = track(await connect());
sendMsg(ws1, { type: "create", clientId: "a", maxClients: 3 });
const { room } = await waitForType(ws1, "created");
const ws2 = track(await connect());
sendMsg(ws2, { type: "join", clientId: "b", room });
await waitForType(ws2, "joined");
const ws3 = track(await connect());
sendMsg(ws3, { type: "join", clientId: "c", room });
await waitForType(ws3, "joined");
const p1 = waitForType(ws1, "message");
sendMsg(ws2, { type: "send", to: "a", data: "secret" });
const msg = await p1;
expect(msg.from).toBe("b");
expect(msg.data).toBe("secret");
});
test("rejects send when not in a room", async () => {
const ws = track(await connect());
sendMsg(ws, { type: "send", data: "hello" });
const msg = await waitForType(ws, "error");
expect(msg.message).toContain("Not in a room");
});
test("rejects send to unknown target", async () => {
const ws1 = track(await connect());
sendMsg(ws1, { type: "create", clientId: "a", maxClients: 2 });
await waitForType(ws1, "created");
sendMsg(ws1, { type: "send", to: "nobody", data: "hello" });
const msg = await waitForType(ws1, "error");
expect(msg.message).toContain("not found");
});
});
describe("disconnect", () => {
test("broadcasts peer_left on disconnect", async () => {
const ws1 = track(await connect());
sendMsg(ws1, { type: "create", clientId: "host", maxClients: 2 });
const { room } = await waitForType(ws1, "created");
const ws2 = track(await connect());
sendMsg(ws2, { type: "join", clientId: "guest", room });
await waitForType(ws2, "joined");
const peerLeftPromise = waitForType(ws1, "peer_left");
ws2.close();
const msg = await peerLeftPromise;
expect(msg.clientId).toBe("guest");
});
test("room is cleaned up when last client leaves", async () => {
const ws1 = track(await connect());
sendMsg(ws1, { type: "create", clientId: "host", maxClients: 2 });
const { room } = await waitForType(ws1, "created");
expect(rooms.has(room)).toBe(true);
ws1.close();
// Give server a moment to process the close
await new Promise((r) => setTimeout(r, 50));
expect(rooms.has(room)).toBe(false);
});
});
describe("reconnect", () => {
test("reconnecting with same UUID replaces connection", async () => {
const ws1 = track(await connect());
sendMsg(ws1, { type: "create", clientId: "host", maxClients: 2 });
const { room } = await waitForType(ws1, "created");
const ws2 = track(await connect());
sendMsg(ws2, { type: "join", clientId: "guest", room });
await waitForType(ws2, "joined");
// Guest reconnects with new websocket
const ws3 = track(await connect());
sendMsg(ws3, { type: "join", clientId: "guest", room });
const joinMsg = await waitForType(ws3, "joined");
expect(joinMsg.clients).toContain("host");
expect(joinMsg.clients).toContain("guest");
// New connection should receive messages
const msgPromise = waitForType(ws3, "message");
sendMsg(ws1, { type: "send", data: "ping" });
const msg = await msgPromise;
expect(msg.from).toBe("host");
expect(msg.data).toBe("ping");
});
test("replaced connection is closed with code 4000", async () => {
const ws1 = track(await connect());
sendMsg(ws1, { type: "create", clientId: "host", maxClients: 2 });
const { room } = await waitForType(ws1, "created");
const ws2 = track(await connect());
sendMsg(ws2, { type: "join", clientId: "guest", room });
await waitForType(ws2, "joined");
const closePromise = new Promise<CloseEvent>((resolve) => {
ws2.onclose = resolve;
});
const ws3 = track(await connect());
sendMsg(ws3, { type: "join", clientId: "guest", room });
await waitForType(ws3, "joined");
const closeEvent = await closePromise;
expect(closeEvent.code).toBe(4000);
expect(closeEvent.reason).toBe("replaced");
});
test("replaced connection does not trigger peer_left for host", async () => {
const ws1 = track(await connect());
sendMsg(ws1, { type: "create", clientId: "host", maxClients: 2 });
const { room } = await waitForType(ws1, "created");
const ws2 = track(await connect());
sendMsg(ws2, { type: "join", clientId: "guest", room });
await waitForType(ws2, "joined");
let peerLeft = false;
ws1.addEventListener("message", (e) => {
if (JSON.parse(e.data).type === "peer_left") peerLeft = true;
});
const ws3 = track(await connect());
sendMsg(ws3, { type: "join", clientId: "guest", room });
await waitForType(ws3, "joined");
// Let the server finish closing ws2 and processing its close handler
await new Promise((r) => setTimeout(r, 50));
expect(peerLeft).toBe(false);
expect(rooms.get(room)?.clients.size).toBe(2);
});
});
describe("graceful drain", () => {
afterEach(() => _resetDrainForTest());
test("resolves immediately with zero rooms", async () => {
const remaining = await drain({ exitOnComplete: false, deadlineMs: 5000 });
expect(remaining).toBe(0);
});
test("rejects create during drain", async () => {
const drainPromise = drain({ exitOnComplete: false, deadlineMs: 5000 });
const ws = track(await connect());
sendMsg(ws, { type: "create", clientId: "aaa", maxClients: 4 });
const msg = await waitForType(ws, "error");
expect(msg.message).toContain("draining");
await drainPromise;
});
test("waits for active rooms, then resolves when they empty", async () => {
const ws1 = track(await connect());
sendMsg(ws1, { type: "create", clientId: "host", maxClients: 2 });
await waitForType(ws1, "created");
expect(rooms.size).toBe(1);
const drainPromise = drain({ exitOnComplete: false, deadlineMs: 5000 });
// Drain should still be waiting — give it a tick to loop
await new Promise((r) => setTimeout(r, 100));
expect(rooms.size).toBe(1);
// Client leaves
ws1.close();
const remaining = await drainPromise;
expect(remaining).toBe(0);
});
test("existing rooms still accept joins during drain", async () => {
const ws1 = track(await connect());
sendMsg(ws1, { type: "create", clientId: "host", maxClients: 3 });
const { room } = await waitForType(ws1, "created");
// Start draining in the background
const drainPromise = drain({ exitOnComplete: false, deadlineMs: 5000 });
await new Promise((r) => setTimeout(r, 50));
// A controller reconnecting mid-game should still get in
const ws2 = track(await connect());
sendMsg(ws2, { type: "join", clientId: "guest", room });
const msg = await waitForType(ws2, "joined");
expect(msg.room).toBe(room);
ws1.close();
ws2.close();
await drainPromise;
});
test("times out and returns non-zero when rooms outlast deadline", async () => {
const ws1 = track(await connect());
sendMsg(ws1, { type: "create", clientId: "host", maxClients: 2 });
await waitForType(ws1, "created");
expect(rooms.size).toBe(1);
const remaining = await drain({ exitOnComplete: false, deadlineMs: 200 });
expect(remaining).toBe(1);
});
});
describe("room info endpoint", () => {
const HTTP_URL = `http://localhost:${server.port}`;
test("returns 404 for unknown room", async () => {
const res = await fetch(`${HTTP_URL}/room/NOPE`);
expect(res.status).toBe(404);
const body = await res.json();
expect(body.error).toContain("not found");
});
test("returns room info for existing room", async () => {
const ws = track(await connect());
sendMsg(ws, { type: "create", clientId: "aaa", maxClients: 8, room: "INFO" });
await waitForType(ws, "created");
const res = await fetch(`${HTTP_URL}/room/INFO`);
expect(res.status).toBe(200);
const body = await res.json();
expect(body).toEqual({ clients: 1, maxClients: 8, origin: "unknown" });
});
test("sets permissive CORS header", async () => {
const res = await fetch(`${HTTP_URL}/room/NOPE`);
expect(res.headers.get("access-control-allow-origin")).toBe("*");
});
});
describe("protocol errors", () => {
test("rejects invalid JSON", async () => {
const ws = track(await connect());
ws.send("not json");
const msg = await waitForType(ws, "error");
expect(msg.message).toContain("Invalid JSON");
});
test("rejects unknown message type", async () => {
const ws = track(await connect());
sendMsg(ws, { type: "unknown" });
const msg = await waitForType(ws, "error");
expect(msg.message).toContain("Unknown");
});
});