Skip to content

Commit 56db855

Browse files
committed
test(test-utils): Keep the refused port of the fake ingest reserved
`startFakeIngests` closed a listener to get a port that refuses connections. The OS can give that port to the next listener, for example the app under test, and the tunnel then forwards to the app itself. The port is now the local port of an open connection, which has no listener and which the OS gives to no one.
1 parent 260270c commit 56db855

1 file changed

Lines changed: 12 additions & 6 deletions

File tree

‎dev-packages/test-utils/src/tunnel-hardening.ts‎

Lines changed: 12 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22
// app keeps serving after each one. The tunnel must never break the app, whatever the client, the envelope or the
33
// ingest does. Only Node built-ins, so Bun and Deno tests can import this file directly.
44
import { Buffer } from 'node:buffer';
5+
import { once } from 'node:events';
56
import * as http from 'node:http';
67
import * as net from 'node:net';
78
import * as zlib from 'node:zlib';
@@ -45,23 +46,28 @@ export interface FakeIngests {
4546
* Starts the fake ingests on free ports.
4647
*/
4748
export async function startFakeIngests(): Promise<FakeIngests> {
48-
const servers: http.Server[] = [];
49+
const servers: net.Server[] = [];
4950
const sockets = new Set<net.Socket>();
5051
const ports: Record<string, number> = {};
5152

5253
for (const [name, handler] of Object.entries(INGEST_HANDLERS)) {
53-
const server = http.createServer(handler ?? (() => undefined));
54+
const server: net.Server = handler ? http.createServer(handler) : net.createServer();
5455
server.on('connection', socket => {
5556
sockets.add(socket);
5657
socket.on('close', () => sockets.delete(socket));
5758
});
5859
await new Promise<void>(resolve => server.listen(0, '127.0.0.1', resolve));
59-
ports[name] = (server.address() as net.AddressInfo).port;
60+
servers.push(server);
61+
const { port } = server.address() as net.AddressInfo;
6062
if (handler) {
61-
servers.push(server);
63+
ports[name] = port;
6264
} else {
63-
// Keep the port, refuse connections.
64-
await new Promise<void>(resolve => server.close(() => resolve()));
65+
// The OS can give a closed port to the next listener, for example the app under test. The local port of an
66+
// open connection has no listener either, and the OS gives it to no one until the connection closes.
67+
const socket = net.connect(port, '127.0.0.1');
68+
await once(socket, 'connect');
69+
sockets.add(socket);
70+
ports[name] = socket.localPort!;
6571
}
6672
}
6773

0 commit comments

Comments
 (0)