summaryrefslogtreecommitdiff
path: root/web/test/connection.test.ts
blob: 3426881d77d6f520833eb28d0aba6f625753967a (plain)
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
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import { GameConnection } from '$lib/protocol/connection';
import { FakeSocket, SocketSequence } from './fake-socket';

function welcome(overrides: Record<string, unknown> = {}) {
	return {
		t: 'welcome',
		v: 1,
		session: 's1',
		role: 'spectator',
		index: 0,
		description: null,
		event: null,
		state: { currentList: [] },
		seats: {},
		...overrides
	};
}

describe('GameConnection', () => {
	let sockets: SocketSequence;
	let conn: GameConnection;

	beforeEach(() => {
		vi.useFakeTimers();
		sockets = new SocketSequence();
		conn = new GameConnection({
			transport: sockets.factory,
			url: 'ws://test/ws',
			reconnectBaseMs: 100,
			reconnectMaxMs: 400,
			pingIntervalMs: 1_000
		});
	});

	afterEach(() => {
		vi.useRealTimers();
	});

	it('handshakes with hello and records the session from welcome', () => {
		const statuses: string[] = [];
		conn.onStatus = (s) => statuses.push(s);
		conn.connect();
		sockets.current.open();
		expect(sockets.current.lastJson()).toEqual({ t: 'hello', v: 1 });
		expect(conn.status).toBe('open');

		let welcomed: unknown = null;
		conn.onMessage = (m) => (welcomed = m);
		sockets.current.serverSend(welcome({ session: 'abc' }));
		expect(conn.session).toBe('abc');
		expect(welcomed).toMatchObject({ t: 'welcome' });
		expect(statuses).toContain('open');
	});

	// Regression: the open gate must compare against the real
	// `WebSocket.OPEN` readyState (1). A wrong constant (e.g. 0 = CONNECTING)
	// silently dropped every outbound frame — hello, ping, and every command
	// — because the readyState check never matched, while the unit tests
	// passed only because the fake mirrored the same wrong constant.
	it('sends frames only when readyState is the real WebSocket.OPEN (1)', () => {
		conn.connect();
		const socket = sockets.current;
		// Before open the socket is CONNECTING (0): nothing may be sent.
		expect(socket.sent).toHaveLength(0);
		expect(socket.readyState).toBe(0);
		socket.open(); // → OPEN (1)
		expect(socket.readyState).toBe(1);
		expect(socket.lastJson()).toEqual({ t: 'hello', v: 1 });
	});

	it('forwards update, seats, and error to their handlers', () => {
		const messages: string[] = [];
		let errorMessage: string | null = null;
		conn.onMessage = (m) => messages.push(m.t);
		conn.onError = (e) => (errorMessage = e.message);

		conn.connect();
		sockets.current.open();
		sockets.current.serverSend(welcome());

		sockets.current.serverSend({
			t: 'update',
			index: 1,
			description: 'd',
			event: { type: 'none' },
			state: {}
		});
		sockets.current.serverSend({ t: 'seats', seats: { a: null } });
		sockets.current.serverSend({ t: 'error', code: 'rejected', message: 'nope' });
		sockets.current.serverSend({ t: 'pong' });

		expect(messages).toEqual([
			'welcome',
			'update',
			'seats',
			'error',
			'pong'
		]);
		expect(errorMessage).toBe('nope');
	});

	it('sends outbound commands, claims, undo and redo', () => {
		conn.connect();
		sockets.current.open();
		sockets.current.serverSend(welcome());

		conn.sendCmd('draw');
		expect(sockets.current.lastJson()).toEqual({
			t: 'cmd',
			name: 'draw',
			args: {}
		});

		conn.sendCmd('addCharacter', { id: 'Berserker', edition: 'x' });
		expect(sockets.current.lastJson()).toEqual({
			t: 'cmd',
			name: 'addCharacter',
			args: { id: 'Berserker', edition: 'x' }
		});

		conn.claim('Berserker');
		expect(sockets.current.lastJson()).toEqual({
			t: 'claim',
			characterId: 'Berserker'
		});

		conn.undo();
		expect(sockets.current.lastJson()).toEqual({ t: 'undo' });
		conn.redo();
		expect(sockets.current.lastJson()).toEqual({ t: 'redo' });
	});

	it('pings on the keepalive interval while open', () => {
		conn.connect();
		sockets.current.open();
		sockets.current.serverSend(welcome());
		// clear the hello frame so we can see pings
		const before = sockets.current.sent.length;
		vi.advanceTimersByTime(1_000);
		expect(sockets.current.sent.slice(before)).toEqual([
			JSON.stringify({ t: 'ping' })
		]);
		vi.advanceTimersByTime(2_000);
		expect(sockets.current.sent.slice(before)).toHaveLength(3);
	});

	it('reconnects, resyncs via a fresh hello, and backs off across churn', () => {
		conn.connect();
		const first = sockets.current;
		first.open();
		first.serverSend(welcome({ session: 'abc' }));
		expect(conn.session).toBe('abc');

		// Server drops the connection → first retry after the base delay.
		first.serverClose();
		expect(conn.status).toBe('reconnecting');
		vi.advanceTimersByTime(99);
		expect(sockets.sockets.length).toBe(1);
		vi.advanceTimersByTime(1);
		expect(sockets.sockets.length).toBe(2);

		// The reconnect re-sends hello (the resync).
		const second = sockets.current;
		second.open();
		expect(second.lastJson()).toEqual({ t: 'hello', v: 1 });
		expect(conn.status).toBe('open');

		// A failed second attempt (closes without a welcome) doubles the backoff.
		second.serverClose();
		vi.advanceTimersByTime(199);
		expect(sockets.sockets.length).toBe(2);
		vi.advanceTimersByTime(1);
		expect(sockets.sockets.length).toBe(3);
		expect(conn.status).toBe('reconnecting');

		// A real welcome resets the backoff to the base.
		const third = sockets.current;
		third.open();
		third.serverSend(welcome({ session: 'abc' }));
		third.serverClose();
		vi.advanceTimersByTime(99);
		expect(sockets.sockets.length).toBe(3);
		vi.advanceTimersByTime(1);
		expect(sockets.sockets.length).toBe(4);
	});

	it('resync() re-requests a full welcome', () => {
		conn.connect();
		sockets.current.open();
		sockets.current.serverSend(welcome());
		conn.resync();
		expect(sockets.current.lastJson()).toEqual({ t: 'hello', v: 1 });
	});

	it('does not reconnect after an intentional disconnect', () => {
		conn.connect();
		sockets.current.open();
		sockets.current.serverSend(welcome());
		conn.disconnect();
		expect(conn.status).toBe('closed');
		vi.advanceTimersByTime(10_000);
		expect(sockets.sockets.length).toBe(1);
	});

	it('ignores non-JSON frames', () => {
		conn.connect();
		sockets.current.open();
		sockets.current.serverSend('not json');
		expect(conn.session).toBeNull();
	});
});