Skip to content

Commit 451993e

Browse files
omsmithtargos
authored andcommitted
http: set default timeout in agent keepSocketAlive
Previous location of setting the timeout would override behaviour of custom HttpAgents' keepSocketAlive. Moving it into the default keepSocketAlive allows it to interoperate with custom agents. Fixes: #33111 PR-URL: #33127 Reviewed-By: Anna Henningsen <anna@addaleax.net> Reviewed-By: Robert Nagy <ronagy@icloud.com> Reviewed-By: Luigi Pinca <luigipinca@gmail.com> Reviewed-By: Juan José Arboleda <soyjuanarbol@gmail.com> Reviewed-By: Andrey Pechkurov <apechkurov@gmail.com>
1 parent e276524 commit 451993e

File tree

2 files changed

+45
-5
lines changed

2 files changed

+45
-5
lines changed

lib/_http_agent.js

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -138,11 +138,6 @@ function Agent(options) {
138138
socket._httpMessage = null;
139139
this.removeSocket(socket, options);
140140

141-
const agentTimeout = this.options.timeout || 0;
142-
if (socket.timeout !== agentTimeout) {
143-
socket.setTimeout(agentTimeout);
144-
}
145-
146141
socket.once('error', freeSocketErrorListener);
147142
freeSockets.push(socket);
148143
});
@@ -402,6 +397,11 @@ Agent.prototype.keepSocketAlive = function keepSocketAlive(socket) {
402397
socket.setKeepAlive(true, this.keepAliveMsecs);
403398
socket.unref();
404399

400+
const agentTimeout = this.options.timeout || 0;
401+
if (socket.timeout !== agentTimeout) {
402+
socket.setTimeout(agentTimeout);
403+
}
404+
405405
return true;
406406
};
407407

test/parallel/test-http-agent-timeout.js

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -92,3 +92,43 @@ const http = require('http');
9292
}));
9393
}));
9494
}
95+
96+
{
97+
// Ensure custom keepSocketAlive timeout is respected
98+
99+
const CUSTOM_TIMEOUT = 60;
100+
const AGENT_TIMEOUT = 50;
101+
102+
class CustomAgent extends http.Agent {
103+
keepSocketAlive(socket) {
104+
if (!super.keepSocketAlive(socket)) {
105+
return false;
106+
}
107+
108+
socket.setTimeout(CUSTOM_TIMEOUT);
109+
return true;
110+
}
111+
}
112+
113+
const agent = new CustomAgent({ keepAlive: true, timeout: AGENT_TIMEOUT });
114+
115+
const server = http.createServer((req, res) => {
116+
res.end();
117+
});
118+
119+
server.listen(0, common.mustCall(() => {
120+
http.get({ port: server.address().port, agent })
121+
.on('response', common.mustCall((res) => {
122+
const socket = res.socket;
123+
assert(socket);
124+
res.resume();
125+
socket.on('free', common.mustCall(() => {
126+
socket.on('timeout', common.mustCall(() => {
127+
assert.strictEqual(socket.timeout, CUSTOM_TIMEOUT);
128+
agent.destroy();
129+
server.close();
130+
}));
131+
}));
132+
}));
133+
}));
134+
}

0 commit comments

Comments
 (0)