diff --git a/lib/https.js b/lib/https.js index 5e5ed04efe8..16f825d4a11 100644 --- a/lib/https.js +++ b/lib/https.js @@ -251,7 +251,10 @@ function establishTunnel(agent, socket, options, tunnelConfig, afterSocket) { socket.removeListener('end', onProxyEnd); socket.removeListener('error', onProxyError); socket.removeListener('readable', read); - socket.setTimeout(0); // Clear the timeout for the tunnel establishment. + // Clear the timeout for the tunnel establishment. Pass the callback so + // its listener is removed too: it would otherwise keep afterSocket, and + // the request behind it, reachable for the life of the socket. + socket.setTimeout(0, onProxyTimeout); } function onProxyError(err) { diff --git a/test/client-proxy/test-https-proxy-timeout-request-collectable.mjs b/test/client-proxy/test-https-proxy-timeout-request-collectable.mjs new file mode 100644 index 00000000000..6871f03fdbf --- /dev/null +++ b/test/client-proxy/test-https-proxy-timeout-request-collectable.mjs @@ -0,0 +1,54 @@ +// Flags: --expose-gc +// A keep-alive socket tunneled through a proxy, for a request with a +// timeout, must not keep the request that created it reachable once it is +// back in the agent's free pool. The timeout makes the tunnel setup add a +// 'timeout' listener on the proxy socket, which must be removed afterwards. + +import * as common from '../common/index.mjs'; +import assert from 'node:assert'; +import { once } from 'events'; +import { createProxyServer } from '../common/proxy-server.js'; +import fixtures from '../common/fixtures.js'; +import { gcUntil } from '../common/gc.js'; + +if (!common.hasCrypto) + common.skip('missing crypto'); + +// https must be dynamically imported so that builds without crypto support +// can skip it. +const { default: https } = await import('node:https'); + +const server = https.createServer({ + cert: fixtures.readKey('agent8-cert.pem'), + key: fixtures.readKey('agent8-key.pem'), +}, common.mustCall((req, res) => res.end('ok'))); +server.listen(0); +await once(server, 'listening'); + +const { proxy } = createProxyServer(); +proxy.listen(0); +await once(proxy, 'listening'); + +const agent = new https.Agent({ + keepAlive: true, + proxyEnv: { + HTTPS_PROXY: `http://localhost:${proxy.address().port}`, + }, + ca: fixtures.readKey('fake-startcom-root-cert.pem'), +}); + +const ref = new WeakRef(https.get({ + hostname: 'localhost', + port: server.address().port, + agent, + timeout: 10_000, +}, common.mustCall((res) => res.resume()))); + +await once(agent, 'free'); +await new Promise(setImmediate); +assert.strictEqual(Object.keys(agent.freeSockets).length, 1); +await gcUntil('the first request is collected', + () => ref.deref() === undefined); +agent.destroy(); +proxy.close(); +server.close();