Files
ukmesh/frontend/test/e2e/socket-replay.spec.ts

58 lines
2.7 KiB
TypeScript

import { expect, test } from '@playwright/test';
import { once } from 'node:events';
import { WebSocketServer } from 'ws';
const packet = (cursor: string, data: string) => JSON.stringify({ type: 'packet', cursor, ts: 1, data });
const invalidFrames = {
'invalid JSON': '{',
'invalid compact snapshot': JSON.stringify({ type: 'initial_state', format: 'columns-v1', ts: 1, cursor: '11', data: {} }),
'an out-of-range packet cursor': packet('9223372036854775808', 'invalid checkpoint'),
};
for (const [malformed, bad] of Object.entries(invalidFrames)) {
test(`the browser resumes after ${malformed} from its last applied packet`, async ({ page }) => {
const server = new WebSocketServer({ host: '127.0.0.1', port: 0, path: '/ws' });
await once(server, 'listening');
const port = (server.address() as { port: number }).port;
const cursors: Array<string | null> = [];
const closeCodes: number[] = [];
const snapshot = (cursor: string) => JSON.stringify({ type: 'initial_state', cursor, ts: 1,
data: { nodes: [], packets: [], messages: [], viable_links: [] } });
server.on('connection', (socket, request) => {
cursors.push(new URL(request.url!, 'http://localhost').searchParams.get('cursor'));
socket.on('close', code => closeCodes.push(code));
if (cursors.length === 1) {
socket.send([snapshot('9'), packet('10', 'first'), bad, packet('12', 'skipped')].join('\n'));
socket.send(packet('13', 'queued'));
} else {
socket.send([snapshot('10'), packet('11', 'second'), packet('12', 'third')].join('\n'));
}
});
try {
// Keep browser transport and close-code validation. Route only this probe
// to the test server so Vite's own socket keeps its original destination.
await page.addInitScript(port => {
const BrowserWebSocket = window.WebSocket;
window.WebSocket = class extends BrowserWebSocket {
constructor(url: string | URL, protocols?: string | string[]) {
const endpoint = new URL(url);
if (endpoint.pathname === '/ws' && endpoint.searchParams.get('network') === 'socket-fixture-A') {
endpoint.host = `127.0.0.1:${port}`;
}
super(endpoint, protocols);
}
};
}, port);
await page.goto('/test/e2e/socket-replay.html');
await expect(page.getByTestId('fixture-socket-messages')).toHaveText(
'A:1:snapshot,A:1:first,A:1:snapshot,A:1:second,A:1:third', { timeout: 12_000 });
expect(cursors).toEqual([null, '10']);
expect(closeCodes).toEqual([4002]);
} finally {
await page.close();
for (const peer of server.clients) peer.terminate();
await new Promise<void>(resolve => server.close(() => resolve()));
}
});
}