index.js 1.3 KB

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