Skip to content

Commit 772c28b

Browse files
committed
http: make timeout event work with agent timeout
The `'timeout'` event is currently not emitted on the `ClientRequest` instance when the socket timeout expires if only the `timeout` option of the agent is set. This happens because, under these circumstances, `listenSocketTimeout()` is not called. This commit fixes the issue by calling it also when only the agent `timeout` option is set.
1 parent 8b2e861 commit 772c28b

File tree

2 files changed

+27
-1
lines changed

2 files changed

+27
-1
lines changed

lib/_http_client.js

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -653,7 +653,10 @@ function tickOnSocket(req, socket) {
653653
socket.on('end', socketOnEnd);
654654
socket.on('close', socketCloseListener);
655655

656-
if (req.timeout !== undefined) {
656+
if (
657+
req.timeout !== undefined ||
658+
(req.agent && req.agent.options && req.agent.options.timeout)
659+
) {
657660
listenSocketTimeout(req);
658661
}
659662
req.emit('socket', socket);
Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
'use strict';
2+
3+
const { expectsError, mustCall } = require('../common');
4+
const { Agent, get } = require('http');
5+
6+
// Test that the `'timeout'` event is emitted on the `ClientRequest` instance
7+
// when the socket timeout set via the `timeout` option of the `Agent` expires.
8+
9+
const request = get({
10+
agent: new Agent({ timeout: 500 }),
11+
// Non-routable IP address to prevent the connection from being established.
12+
host: '192.0.2.1'
13+
});
14+
15+
request.on('error', expectsError({
16+
type: Error,
17+
code: 'ECONNRESET',
18+
message: 'socket hang up'
19+
}));
20+
21+
request.on('timeout', mustCall(() => {
22+
request.abort();
23+
}));

0 commit comments

Comments
 (0)