| Leo Repp | 58b9f11 | 2021-11-22 11:57:47 +0100 | [diff] [blame^] | 1 | 'use strict'; |
| 2 | |
| 3 | module.exports = function (req, time) { |
| 4 | if (req.timeoutTimer) { |
| 5 | return req; |
| 6 | } |
| 7 | |
| 8 | var delays = isNaN(time) ? time : {socket: time, connect: time}; |
| 9 | var host = req._headers ? (' to ' + req._headers.host) : ''; |
| 10 | |
| 11 | if (delays.connect !== undefined) { |
| 12 | req.timeoutTimer = setTimeout(function timeoutHandler() { |
| 13 | req.abort(); |
| 14 | var e = new Error('Connection timed out on request' + host); |
| 15 | e.code = 'ETIMEDOUT'; |
| 16 | req.emit('error', e); |
| 17 | }, delays.connect); |
| 18 | } |
| 19 | |
| 20 | // Clear the connection timeout timer once a socket is assigned to the |
| 21 | // request and is connected. |
| 22 | req.on('socket', function assign(socket) { |
| 23 | // Socket may come from Agent pool and may be already connected. |
| 24 | if (!(socket.connecting || socket._connecting)) { |
| 25 | connect(); |
| 26 | return; |
| 27 | } |
| 28 | |
| 29 | socket.once('connect', connect); |
| 30 | }); |
| 31 | |
| 32 | function clear() { |
| 33 | if (req.timeoutTimer) { |
| 34 | clearTimeout(req.timeoutTimer); |
| 35 | req.timeoutTimer = null; |
| 36 | } |
| 37 | } |
| 38 | |
| 39 | function connect() { |
| 40 | clear(); |
| 41 | |
| 42 | if (delays.socket !== undefined) { |
| 43 | // Abort the request if there is no activity on the socket for more |
| 44 | // than `delays.socket` milliseconds. |
| 45 | req.setTimeout(delays.socket, function socketTimeoutHandler() { |
| 46 | req.abort(); |
| 47 | var e = new Error('Socket timed out on request' + host); |
| 48 | e.code = 'ESOCKETTIMEDOUT'; |
| 49 | req.emit('error', e); |
| 50 | }); |
| 51 | } |
| 52 | } |
| 53 | |
| 54 | return req.on('error', clear); |
| 55 | }; |