Skip to content

Commit

Permalink
fix: don't leak socket if client is destroyed will connecting
Browse files Browse the repository at this point in the history
  • Loading branch information
ronag committed Apr 14, 2023
1 parent 852bf6e commit 3bce739
Show file tree
Hide file tree
Showing 3 changed files with 40 additions and 2 deletions.
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')
})
})
2 changes: 1 addition & 1 deletion types/connector.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ declare namespace buildConnector {
port: string
servername?: string
localAddress?: string | null
httpSocket?: Socket
httpSocket?: Socket,
}

export type Callback = (...args: CallbackArgs) => void
Expand Down

0 comments on commit 3bce739

Please sign in to comment.