Skip to content

Commit 8579fb7

Browse files
committed
fix(net): close aborted happy eyeballs connection attempts
Api requests now bound each connection attempt with the remaining time budget, so attempts that are not yet attached to the request cannot outlive it. Destroying a tls socket during a stalled handshake does not close the underlying tcp connection, so aborted attempts leaked their connections. Attempts now own the tcp transport and reset it when aborted.
1 parent 81e683b commit 8579fb7

3 files changed

Lines changed: 83 additions & 18 deletions

File tree

‎packages/playwright-core/src/server/fetch.ts‎

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -343,7 +343,12 @@ export abstract class APIRequestContext extends SdkObject {
343343
= (url.protocol === 'https:' ? https : http).request;
344344
// If we have a proxy agent already, do not override it.
345345
const agent = options.agent || (url.protocol === 'https:' ? httpsHappyEyeballsAgent : httpHappyEyeballsAgent);
346-
const requestOptions = { ...options, agent };
346+
const requestOptions: SendRequestOptions = { ...options, agent };
347+
// Happy eyeballs sockets are not attached to the request until the tls handshake,
348+
// so request.destroy() cannot reach them. Bound each connection attempt with the
349+
// remaining time budget so that stalled attempts do not outlive the request.
350+
if (progress.deadline)
351+
requestOptions.timeout = Math.max(1, progress.deadline - monotonicTime());
347352

348353
const startAt = monotonicTime();
349354
const startAtWallTime = Date.now();

‎packages/utils/happyEyeballs.ts‎

Lines changed: 38 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -115,7 +115,7 @@ export async function createConnectionAsync(
115115
const hostname = clientRequestArgsToHostName(options);
116116
const addresses = await lookup(hostname);
117117
const dnsLookupAt = monotonicTime();
118-
const sockets = new Set<net.Socket>();
118+
const sockets = new Map<net.Socket, net.Socket>();
119119
let firstError;
120120
let errorCount = 0;
121121
const handleError = (socket: net.Socket, err: Error) => {
@@ -126,52 +126,73 @@ export async function createConnectionAsync(
126126
if (errorCount === addresses.length)
127127
oncreate?.(firstError);
128128
};
129+
const abortAttempt = (socket: net.Socket, transport: net.Socket) => {
130+
// Destroying a tls socket during the handshake does not close the underlying
131+
// tcp connection, and neither does destroying the transport once it has been
132+
// wrapped. Resetting the transport before touching the tls socket does.
133+
transport.resetAndDestroy();
134+
socket.destroy();
135+
};
129136

130137
const connected = new ManualPromise();
131138
for (const { address } of addresses) {
139+
// Own the tcp transport instead of letting tls.connect() create it,
140+
// so that a stalled attempt can be closed via abortAttempt().
141+
const transport = net.createConnection({
142+
...options,
143+
port: options.port as number,
144+
host: address });
132145
const socket = useTLS ?
133146
tls.connect({
134147
...(options as tls.ConnectionOptions),
135-
port: options.port as number,
136-
host: address,
148+
socket: transport,
137149
servername: hostname }) :
138-
net.createConnection({
139-
...options,
140-
port: options.port as number,
141-
host: address });
150+
transport;
142151

143152
(socket as any)[kDNSLookupAt] = dnsLookupAt;
144-
// tls.connect() ignores the timeout option, so set it on the socket directly.
153+
// tls.connect() ignores the timeout option, so set it on the transport directly.
154+
// It bounds this connection attempt; the winner's timer is reset upon commitment.
145155
if (options.timeout !== undefined)
146-
socket.setTimeout(options.timeout);
156+
transport.setTimeout(options.timeout);
147157

148-
socket.on('connect', () => {
158+
transport.on('connect', () => {
149159
(socket as any)[kTCPConnectionAt] = monotonicTime();
150160
});
151161
// For tls, wait for the handshake instead of committing upon tcp connection.
152162
// Otherwise, a route where tcp connects but tls stalls would starve
153-
// working alternatives. A tls socket may fire 'error' or 'timeout' after
163+
// working alternatives. A socket may fire 'error' or 'timeout' after
154164
// 'connect', which counts as a failed attempt for this address.
155165
socket.on(useTLS ? 'secureConnect' : 'connect', () => {
156166
if (!sockets.delete(socket))
157167
return;
158168
if (useTLS)
159169
(socket as any)[kTLSHandshakeAt] = monotonicTime();
170+
transport.setTimeout(0);
160171
connected.resolve();
161172
oncreate?.(null, socket);
162173
// TODO: Cache the result?
163174
// Close other outstanding sockets.
164-
for (const s of sockets)
165-
s.destroy();
175+
for (const [s, t] of sockets)
176+
abortAttempt(s, t);
166177
sockets.clear();
167178
});
168-
socket.on('timeout', () => {
179+
transport.on('timeout', () => {
169180
// Timeout is not an error, so we have to manually close the socket.
170-
socket.destroy();
181+
abortAttempt(socket, transport);
171182
handleError(socket, new Error('Connection timeout'));
172183
});
173-
socket.on('error', e => handleError(socket, e));
174-
sockets.add(socket);
184+
socket.on('error', e => {
185+
if (socket !== transport)
186+
transport.resetAndDestroy();
187+
handleError(socket, e);
188+
});
189+
if (socket !== transport) {
190+
transport.on('error', e => {
191+
socket.destroy();
192+
handleError(socket, e);
193+
});
194+
}
195+
sockets.set(socket, transport);
175196
await Promise.race([
176197
connected,
177198
new Promise(f => setTimeout(f, connectionAttemptDelayMs))

‎tests/library/browsercontext-fetch-happy-eyeballs.spec.ts‎

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -79,6 +79,7 @@ it('should fall back to another address when tls handshake stalls', async ({ con
7979
const stalledSockets = new Set<net.Socket>();
8080
const stallServer = net.createServer(socket => {
8181
stalledSockets.add(socket);
82+
socket.on('error', () => {});
8283
socket.on('close', () => stalledSockets.delete(socket));
8384
});
8485
await new Promise<void>((resolve, reject) => {
@@ -96,6 +97,7 @@ it('should fall back to another address when tls handshake stalls', async ({ con
9697
} as any);
9798
expect(response.status()).toBe(200);
9899
expect(await response.text()).toBe('Hello');
100+
await expect.poll(() => stalledSockets.size).toBe(0);
99101
} finally {
100102
for (const socket of stalledSockets)
101103
socket.destroy();
@@ -104,6 +106,43 @@ it('should fall back to another address when tls handshake stalls', async ({ con
104106
}
105107
});
106108

109+
it('should close stalled sockets when the request times out', async ({ context }) => {
110+
it.skip(!!process.env.INSIDE_DOCKER, 'docker does not support IPv6 by default');
111+
const stalledSockets = new Set<net.Socket>();
112+
let socketsSeen = 0;
113+
const trackSocket = (socket: net.Socket) => {
114+
++socketsSeen;
115+
stalledSockets.add(socket);
116+
socket.on('error', () => {});
117+
socket.on('close', () => stalledSockets.delete(socket));
118+
};
119+
const stallServer6 = net.createServer(trackSocket);
120+
const port = await new Promise<number>(resolve => stallServer6.listen(0, '::1', () => resolve((stallServer6.address() as net.AddressInfo).port)));
121+
const stallServer4 = net.createServer(trackSocket);
122+
await new Promise<void>((resolve, reject) => {
123+
stallServer4.on('error', reject);
124+
stallServer4.listen(port, '127.0.0.1', resolve);
125+
});
126+
try {
127+
const error = await context.request.get(`https://localhost:${port}/`, {
128+
ignoreHTTPSErrors: true,
129+
timeout: 1000,
130+
__testHookLookup: (): LookupAddress[] => [
131+
{ address: '::1', family: 6 },
132+
{ address: '127.0.0.1', family: 4 },
133+
],
134+
} as any).catch(e => e);
135+
expect(error.message).toContain('Timeout 1000ms exceeded');
136+
expect(socketsSeen).toBe(2);
137+
await expect.poll(() => stalledSockets.size).toBe(0);
138+
} finally {
139+
for (const socket of stalledSockets)
140+
socket.destroy();
141+
await new Promise(resolve => stallServer4.close(resolve));
142+
await new Promise(resolve => stallServer6.close(resolve));
143+
}
144+
});
145+
107146
it('should work with ip6 and port as the host', async ({ request, server }) => {
108147
it.skip(!!process.env.INSIDE_DOCKER, 'docker does not support IPv6 by default');
109148
const response = await request.get(`http://[::1]:${server.PORT}/simple.json`);

0 commit comments

Comments
 (0)