Skip to content

Commit

Permalink
fix: don't leak socket if client is destroyed while connecting (nodej…
Browse files Browse the repository at this point in the history
…s#2058)

* fix: don't leak socket if client is destroyed will connecting

* Update types/connector.d.ts
  • Loading branch information
ronag authored and metcoder95 committed Jul 21, 2023
1 parent bf414e9 commit d448275
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 1 deletion.
12 changes: 11 additions & 1 deletion lib/client.js
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,8 @@ const {
InformationalError,
BodyTimeoutError,
HTTPParserError,
ResponseExceededMaxSizeError
ResponseExceededMaxSizeError,
ClientDestroyedError
} = require('./core/errors')
const buildConnector = require('./core/connect')
const {
Expand Down Expand Up @@ -1083,6 +1084,11 @@ async function connect (client) {
})
})

if (client.destroyed) {
util.destroy(socket.on('error', () => {}), new ClientDestroyedError())
return
}

if (!llhttpInstance) {
llhttpInstance = await llhttpPromise
llhttpPromise = null
Expand Down Expand Up @@ -1125,6 +1131,10 @@ async function connect (client) {
}
client.emit('connect', client[kUrl], [client])
} catch (err) {
if (client.destroyed) {
return
}

client[kConnecting] = false

if (channels.connectError.hasSubscribers) {
Expand Down
28 changes: 28 additions & 0 deletions test/connect-abort.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
'use strict'

const { test } = require('tap')
const { Client } = require('..')
const { PassThrough } = require('stream')

test(t => {
t.plan(2)

const client = new Client('http://localhost:1234', {
connect: (_, cb) => {
client.destroy()
cb(null, new PassThrough({
destroy (err, cb) {
t.same(err?.name, 'ClientDestroyedError')
cb(null)
}
}))
}
})

client.request({
path: '/',
method: 'GET'
}, (err, data) => {
t.same(err?.name, 'ClientDestroyedError')
})
})

0 comments on commit d448275

Please sign in to comment.