|
| 1 | +/** |
| 2 | + * Copyright (c) Meta Platforms, Inc. and affiliates. |
| 3 | + * |
| 4 | + * This source code is licensed under the MIT license found in the |
| 5 | + * LICENSE file in the root directory of this source tree. |
| 6 | + * |
| 7 | + * @flow strict-local |
| 8 | + * @format |
| 9 | + */ |
| 10 | + |
| 11 | +import http from 'node:http'; |
| 12 | +import WebSocket from 'ws'; |
| 13 | + |
| 14 | +export type TestServer = Readonly<{ |
| 15 | + baseUrl: URL, |
| 16 | + mount: (path: string, wss: ws$WebSocketServer) => void, |
| 17 | + server: http$Server, |
| 18 | + connect: ( |
| 19 | + path: string, |
| 20 | + options?: Readonly<{origin?: string}>, |
| 21 | + ) => Promise<TestClient>, |
| 22 | + close: () => Promise<void>, |
| 23 | +}>; |
| 24 | + |
| 25 | +export type TestClient = Readonly<{ |
| 26 | + send: (message: unknown) => void, |
| 27 | + sendRaw: (data: string | Buffer) => void, |
| 28 | + next: () => Promise<unknown>, |
| 29 | + /** |
| 30 | + * Resolves with the messages received before the server answers a `getid` |
| 31 | + * request, which it handles after everything this client was sent earlier. |
| 32 | + */ |
| 33 | + drain: () => Promise<Array<unknown>>, |
| 34 | + getId: () => Promise<string>, |
| 35 | + close: () => void, |
| 36 | +}>; |
| 37 | + |
| 38 | +/** |
| 39 | + * Retry an assertion until it passes, for an effect the server applies after |
| 40 | + * the client has already sent its message. |
| 41 | + */ |
| 42 | +export async function waitUntil(assertion: () => void): Promise<void> { |
| 43 | + const deadline = Date.now() + 2000; |
| 44 | + for (;;) { |
| 45 | + try { |
| 46 | + assertion(); |
| 47 | + return; |
| 48 | + } catch (e) { |
| 49 | + if (Date.now() > deadline) { |
| 50 | + throw e; |
| 51 | + } |
| 52 | + await new Promise(resolve => setTimeout(resolve, 10)); |
| 53 | + } |
| 54 | + } |
| 55 | +} |
| 56 | + |
| 57 | +export async function startTestServer(): Promise<TestServer> { |
| 58 | + const endpoints = new Map<string, ws$WebSocketServer>(); |
| 59 | + const sockets = new Set<WebSocket>(); |
| 60 | + const server = http.createServer(); |
| 61 | + server.on('upgrade', (req, socket, head) => { |
| 62 | + const wss = endpoints.get(new URL(req.url, 'http://localhost').pathname); |
| 63 | + if (wss == null) { |
| 64 | + socket.destroy(); |
| 65 | + return; |
| 66 | + } |
| 67 | + wss.handleUpgrade(req, socket, head, ws => wss.emit('connection', ws, req)); |
| 68 | + }); |
| 69 | + await new Promise(resolve => server.listen(0, 'localhost', resolve)); |
| 70 | + const address = server.address(); |
| 71 | + if (address == null || typeof address === 'string') { |
| 72 | + throw new Error('Expected the server to listen on a TCP port'); |
| 73 | + } |
| 74 | + const baseUrl = new URL(`http://localhost:${address.port}`); |
| 75 | + |
| 76 | + return { |
| 77 | + baseUrl, |
| 78 | + mount: (path, wss) => { |
| 79 | + endpoints.set(path, wss); |
| 80 | + }, |
| 81 | + server, |
| 82 | + connect: async (path, options) => { |
| 83 | + const socket = new WebSocket(`ws://localhost:${address.port}${path}`, { |
| 84 | + headers: options?.origin == null ? {} : {Origin: options.origin}, |
| 85 | + }); |
| 86 | + sockets.add(socket); |
| 87 | + const received: Array<unknown> = []; |
| 88 | + const waiting: Array<(message: unknown) => void> = []; |
| 89 | + socket.on('message', data => { |
| 90 | + const message = JSON.parse(String(data)); |
| 91 | + const resolve = waiting.shift(); |
| 92 | + if (resolve != null) { |
| 93 | + resolve(message); |
| 94 | + } else { |
| 95 | + received.push(message); |
| 96 | + } |
| 97 | + }); |
| 98 | + await new Promise((resolve, reject) => { |
| 99 | + socket.once('open', resolve); |
| 100 | + socket.once('error', reject); |
| 101 | + socket.once('unexpected-response', (req, res) => |
| 102 | + reject(new Error(`HTTP ${res.statusCode}`)), |
| 103 | + ); |
| 104 | + }); |
| 105 | + |
| 106 | + const next = (): Promise<unknown> => |
| 107 | + received.length > 0 |
| 108 | + ? Promise.resolve(received.shift()) |
| 109 | + : new Promise(resolve => waiting.push(resolve)); |
| 110 | + |
| 111 | + return { |
| 112 | + send: message => socket.send(JSON.stringify(message)), |
| 113 | + sendRaw: data => socket.send(data), |
| 114 | + next, |
| 115 | + drain: async () => { |
| 116 | + socket.send( |
| 117 | + JSON.stringify({ |
| 118 | + version: 2, |
| 119 | + method: 'getid', |
| 120 | + target: 'server', |
| 121 | + id: 'drain', |
| 122 | + }), |
| 123 | + ); |
| 124 | + const before = []; |
| 125 | + let message = await next(); |
| 126 | + while (!isReplyTo(message, 'drain')) { |
| 127 | + before.push(message); |
| 128 | + message = await next(); |
| 129 | + } |
| 130 | + return before; |
| 131 | + }, |
| 132 | + getId: async () => { |
| 133 | + socket.send( |
| 134 | + JSON.stringify({ |
| 135 | + version: 2, |
| 136 | + method: 'getid', |
| 137 | + target: 'server', |
| 138 | + id: 'getid', |
| 139 | + }), |
| 140 | + ); |
| 141 | + const message = await next(); |
| 142 | + if ( |
| 143 | + message == null || |
| 144 | + typeof message !== 'object' || |
| 145 | + message.id !== 'getid' || |
| 146 | + typeof message.result !== 'string' |
| 147 | + ) { |
| 148 | + throw new Error('Expected a getid reply'); |
| 149 | + } |
| 150 | + return message.result; |
| 151 | + }, |
| 152 | + close: () => socket.close(), |
| 153 | + }; |
| 154 | + }, |
| 155 | + close: async () => { |
| 156 | + sockets.forEach(socket => socket.terminate()); |
| 157 | + server.closeAllConnections(); |
| 158 | + await new Promise(resolve => server.close(() => resolve())); |
| 159 | + }, |
| 160 | + }; |
| 161 | +} |
| 162 | + |
| 163 | +function isReplyTo(message: unknown, id: string): boolean { |
| 164 | + return message != null && typeof message === 'object' && message.id === id; |
| 165 | +} |
0 commit comments