diff --git a/lib/https.js b/lib/https.js index 38623d258a2..4fc8c72f193 100644 --- a/lib/https.js +++ b/lib/https.js @@ -456,22 +456,28 @@ function createConnection(...args) { if (options[kPerRequestCheckServerIdentity]) socket[kPerRequestCheckServerIdentity] = true; - if (reuseSession) { - // Cache new session for reuse - socket.on('session', (session) => { - this._cacheSession(options._agentKey, session); - }); - - // Evict session on error - socket.once('close', (err) => { - if (err) - this._evictSession(options._agentKey); - }); - } + if (reuseSession) + cacheSessions(this, socket, options._agentKey); return socket; } +// Not inlined in createConnection(): these listeners live as long as the +// socket, and closures created there share a context that holds `cb`, which +// leads to the request that created the socket. +function cacheSessions(agent, socket, key) { + // Cache new session for reuse + socket.on('session', (session) => { + agent._cacheSession(key, session); + }); + + // Evict session on error + socket.once('close', (err) => { + if (err) + agent._evictSession(key); + }); +} + /** * Creates a new `HttpAgent` instance. * @param {{ diff --git a/test/parallel/test-https-agent-keepalive-request-collectable.js b/test/parallel/test-https-agent-keepalive-request-collectable.js new file mode 100644 index 00000000000..fad011748f6 --- /dev/null +++ b/test/parallel/test-https-agent-keepalive-request-collectable.js @@ -0,0 +1,39 @@ +// Flags: --expose-gc +'use strict'; +const common = require('../common'); +if (!common.hasCrypto) + common.skip('missing crypto'); + +// A keep-alive socket in the agent's free pool must not keep the request +// that created it reachable. + +const assert = require('assert'); +const https = require('https'); +const fixtures = require('../common/fixtures'); +const { gcUntil } = require('../common/gc'); + +const server = https.createServer({ + key: fixtures.readKey('agent1-key.pem'), + cert: fixtures.readKey('agent1-cert.pem'), +}, (req, res) => res.end('ok')); + +server.listen(0, common.mustCall(() => { + const agent = new https.Agent({ keepAlive: true }); + let ref; + + agent.once('free', common.mustCall(() => { + setImmediate(common.mustCall(async () => { + assert.strictEqual(Object.keys(agent.freeSockets).length, 1); + await gcUntil('the first request is collected', + () => ref.deref() === undefined); + agent.destroy(); + server.close(); + })); + })); + + ref = new WeakRef(https.get({ + port: server.address().port, + agent, + rejectUnauthorized: false, + }, common.mustCall((res) => res.resume()))); +}));