Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: don't leak socket if client is destroyed while connecting #2058

Merged
merged 2 commits into from
Apr 14, 2023
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
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,
ronag marked this conversation as resolved.
Show resolved Hide resolved
}

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