Skip to content

Commit

Permalink
fix: Specifying timeout made the connection fail immediately
Browse files Browse the repository at this point in the history
  • Loading branch information
prantlf committed Dec 12, 2021
1 parent e6f8481 commit cad761e
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 20 deletions.
10 changes: 6 additions & 4 deletions lib/nettime.js
Expand Up @@ -179,9 +179,11 @@ function makeSingleRequest (options) {
}
request.end()

// Workaround for Node.js 10+.
// Workaround for Node.js 10+, which does not abort the connection attempt
// any more, if it takes longer than the specified timeout. The local abort
// handler will convert the abortion to a timeout in this case.
if (timeout) {
timeoutHandler = setTimeout(() => request.abort())
timeoutHandler = setTimeout(() => request.abort(), timeout)
}

function getParameters () {
Expand All @@ -203,8 +205,8 @@ function makeSingleRequest (options) {
} = new URL(url)
const auth = username
? password
? username + '.' + password
: username
? username + '.' + password
: username
: undefined
const path = pathname ? pathname + search : undefined
const method = options.method || (data ? 'POST' : 'GET')
Expand Down
50 changes: 34 additions & 16 deletions tests/nettime.js
Expand Up @@ -118,20 +118,22 @@ function makeRequest (protocol, host, port, path, options) {
}
}
const rejectUnauthorized = false
return nettime(https || options ? {
url,
credentials,
data,
failOnOutputFileError,
headers,
httpVersion,
includeHeaders,
method,
outputFile,
rejectUnauthorized,
returnResponse,
timeout
} : url)
return nettime(https || options
? {
url,
credentials,
data,
failOnOutputFileError,
headers,
httpVersion,
includeHeaders,
method,
outputFile,
rejectUnauthorized,
returnResponse,
timeout
}
: url)
.then(checkRequest.bind(null, {
httpVersion,
returnResponse,
Expand Down Expand Up @@ -163,7 +165,7 @@ function checkRequest (options, result) {
checkTiming(firstByte)
checkTiming(timings.contentTransfer)
checkTiming(timings.socketClose)
test.ok(getTestDuration(tcpConnection, firstByte) >= 1 * 1e6)
test.ok(getTestDuration(tcpConnection, firstByte) >= 1e6)
return result
}

Expand Down Expand Up @@ -289,9 +291,25 @@ test.test('test with a missing web page', test => {
.then(test.end)
})

test.test('test timed out connection to an unreachable host', test => {
test.test('test failed connection to a not responding host', test => {
const start = new Date().getTime()
return makeRequest('http', '192.0.2.1', 80, '/', {
timeout: 10
})
.then(test.fail)
.catch(error => {
const end = new Date().getTime()
test.ok(start + 9 < end)
test.ok(error instanceof Error)
test.equal(error.code, 'ETIMEDOUT')
})
.catch(test.threw)
.then(test.end)
})

test.test('test response timeout', test => {
return makeRequest('http', ipAddress, insecurePort, '', {
timeout: 1
})
.then(test.fail)
.catch(error => {
Expand Down

0 comments on commit cad761e

Please sign in to comment.