agent.js 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397
  1. 'use strict';
  2. const OriginalAgent = require('http').Agent;
  3. const ms = require('humanize-ms');
  4. const debug = require('debug')('agentkeepalive');
  5. const deprecate = require('depd')('agentkeepalive');
  6. const {
  7. INIT_SOCKET,
  8. CURRENT_ID,
  9. CREATE_ID,
  10. SOCKET_CREATED_TIME,
  11. SOCKET_NAME,
  12. SOCKET_REQUEST_COUNT,
  13. SOCKET_REQUEST_FINISHED_COUNT,
  14. } = require('./constants');
  15. // OriginalAgent come from
  16. // - https://github.com/nodejs/node/blob/v8.12.0/lib/_http_agent.js
  17. // - https://github.com/nodejs/node/blob/v10.12.0/lib/_http_agent.js
  18. // node <= 10
  19. let defaultTimeoutListenerCount = 1;
  20. const majorVersion = parseInt(process.version.split('.', 1)[0].substring(1));
  21. if (majorVersion >= 11 && majorVersion <= 12) {
  22. defaultTimeoutListenerCount = 2;
  23. } else if (majorVersion >= 13) {
  24. defaultTimeoutListenerCount = 3;
  25. }
  26. class Agent extends OriginalAgent {
  27. constructor(options) {
  28. options = options || {};
  29. options.keepAlive = options.keepAlive !== false;
  30. // default is keep-alive and 15s free socket timeout
  31. if (options.freeSocketTimeout === undefined) {
  32. options.freeSocketTimeout = 15000;
  33. }
  34. // Legacy API: keepAliveTimeout should be rename to `freeSocketTimeout`
  35. if (options.keepAliveTimeout) {
  36. deprecate('options.keepAliveTimeout is deprecated, please use options.freeSocketTimeout instead');
  37. options.freeSocketTimeout = options.keepAliveTimeout;
  38. delete options.keepAliveTimeout;
  39. }
  40. // Legacy API: freeSocketKeepAliveTimeout should be rename to `freeSocketTimeout`
  41. if (options.freeSocketKeepAliveTimeout) {
  42. deprecate('options.freeSocketKeepAliveTimeout is deprecated, please use options.freeSocketTimeout instead');
  43. options.freeSocketTimeout = options.freeSocketKeepAliveTimeout;
  44. delete options.freeSocketKeepAliveTimeout;
  45. }
  46. // Sets the socket to timeout after timeout milliseconds of inactivity on the socket.
  47. // By default is double free socket timeout.
  48. if (options.timeout === undefined) {
  49. // make sure socket default inactivity timeout >= 30s
  50. options.timeout = Math.max(options.freeSocketTimeout * 2, 30000);
  51. }
  52. // support humanize format
  53. options.timeout = ms(options.timeout);
  54. options.freeSocketTimeout = ms(options.freeSocketTimeout);
  55. options.socketActiveTTL = options.socketActiveTTL ? ms(options.socketActiveTTL) : 0;
  56. super(options);
  57. this[CURRENT_ID] = 0;
  58. // create socket success counter
  59. this.createSocketCount = 0;
  60. this.createSocketCountLastCheck = 0;
  61. this.createSocketErrorCount = 0;
  62. this.createSocketErrorCountLastCheck = 0;
  63. this.closeSocketCount = 0;
  64. this.closeSocketCountLastCheck = 0;
  65. // socket error event count
  66. this.errorSocketCount = 0;
  67. this.errorSocketCountLastCheck = 0;
  68. // request finished counter
  69. this.requestCount = 0;
  70. this.requestCountLastCheck = 0;
  71. // including free socket timeout counter
  72. this.timeoutSocketCount = 0;
  73. this.timeoutSocketCountLastCheck = 0;
  74. this.on('free', socket => {
  75. // https://github.com/nodejs/node/pull/32000
  76. // Node.js native agent will check socket timeout eqs agent.options.timeout.
  77. // Use the ttl or freeSocketTimeout to overwrite.
  78. const timeout = this.calcSocketTimeout(socket);
  79. if (timeout > 0 && socket.timeout !== timeout) {
  80. socket.setTimeout(timeout);
  81. }
  82. });
  83. }
  84. get freeSocketKeepAliveTimeout() {
  85. deprecate('agent.freeSocketKeepAliveTimeout is deprecated, please use agent.options.freeSocketTimeout instead');
  86. return this.options.freeSocketTimeout;
  87. }
  88. get timeout() {
  89. deprecate('agent.timeout is deprecated, please use agent.options.timeout instead');
  90. return this.options.timeout;
  91. }
  92. get socketActiveTTL() {
  93. deprecate('agent.socketActiveTTL is deprecated, please use agent.options.socketActiveTTL instead');
  94. return this.options.socketActiveTTL;
  95. }
  96. calcSocketTimeout(socket) {
  97. /**
  98. * return <= 0: should free socket
  99. * return > 0: should update socket timeout
  100. * return undefined: not find custom timeout
  101. */
  102. let freeSocketTimeout = this.options.freeSocketTimeout;
  103. const socketActiveTTL = this.options.socketActiveTTL;
  104. if (socketActiveTTL) {
  105. // check socketActiveTTL
  106. const aliveTime = Date.now() - socket[SOCKET_CREATED_TIME];
  107. const diff = socketActiveTTL - aliveTime;
  108. if (diff <= 0) {
  109. return diff;
  110. }
  111. if (freeSocketTimeout && diff < freeSocketTimeout) {
  112. freeSocketTimeout = diff;
  113. }
  114. }
  115. // set freeSocketTimeout
  116. if (freeSocketTimeout) {
  117. // set free keepalive timer
  118. // try to use socket custom freeSocketTimeout first, support headers['keep-alive']
  119. // https://github.com/node-modules/urllib/blob/b76053020923f4d99a1c93cf2e16e0c5ba10bacf/lib/urllib.js#L498
  120. const customFreeSocketTimeout = socket.freeSocketTimeout || socket.freeSocketKeepAliveTimeout;
  121. return customFreeSocketTimeout || freeSocketTimeout;
  122. }
  123. }
  124. keepSocketAlive(socket) {
  125. const result = super.keepSocketAlive(socket);
  126. // should not keepAlive, do nothing
  127. if (!result) return result;
  128. const customTimeout = this.calcSocketTimeout(socket);
  129. if (typeof customTimeout === 'undefined') {
  130. return true;
  131. }
  132. if (customTimeout <= 0) {
  133. debug('%s(requests: %s, finished: %s) free but need to destroy by TTL, request count %s, diff is %s',
  134. socket[SOCKET_NAME], socket[SOCKET_REQUEST_COUNT], socket[SOCKET_REQUEST_FINISHED_COUNT], customTimeout);
  135. return false;
  136. }
  137. if (socket.timeout !== customTimeout) {
  138. socket.setTimeout(customTimeout);
  139. }
  140. return true;
  141. }
  142. // only call on addRequest
  143. reuseSocket(...args) {
  144. // reuseSocket(socket, req)
  145. super.reuseSocket(...args);
  146. const socket = args[0];
  147. const req = args[1];
  148. req.reusedSocket = true;
  149. const agentTimeout = this.options.timeout;
  150. if (getSocketTimeout(socket) !== agentTimeout) {
  151. // reset timeout before use
  152. socket.setTimeout(agentTimeout);
  153. debug('%s reset timeout to %sms', socket[SOCKET_NAME], agentTimeout);
  154. }
  155. socket[SOCKET_REQUEST_COUNT]++;
  156. debug('%s(requests: %s, finished: %s) reuse on addRequest, timeout %sms',
  157. socket[SOCKET_NAME], socket[SOCKET_REQUEST_COUNT], socket[SOCKET_REQUEST_FINISHED_COUNT],
  158. getSocketTimeout(socket));
  159. }
  160. [CREATE_ID]() {
  161. const id = this[CURRENT_ID]++;
  162. if (this[CURRENT_ID] === Number.MAX_SAFE_INTEGER) this[CURRENT_ID] = 0;
  163. return id;
  164. }
  165. [INIT_SOCKET](socket, options) {
  166. // bugfix here.
  167. // https on node 8, 10 won't set agent.options.timeout by default
  168. // TODO: need to fix on node itself
  169. if (options.timeout) {
  170. const timeout = getSocketTimeout(socket);
  171. if (!timeout) {
  172. socket.setTimeout(options.timeout);
  173. }
  174. }
  175. if (this.options.keepAlive) {
  176. // Disable Nagle's algorithm: http://blog.caustik.com/2012/04/08/scaling-node-js-to-100k-concurrent-connections/
  177. // https://fengmk2.com/benchmark/nagle-algorithm-delayed-ack-mock.html
  178. socket.setNoDelay(true);
  179. }
  180. this.createSocketCount++;
  181. if (this.options.socketActiveTTL) {
  182. socket[SOCKET_CREATED_TIME] = Date.now();
  183. }
  184. // don't show the hole '-----BEGIN CERTIFICATE----' key string
  185. socket[SOCKET_NAME] = `sock[${this[CREATE_ID]()}#${options._agentKey}]`.split('-----BEGIN', 1)[0];
  186. socket[SOCKET_REQUEST_COUNT] = 1;
  187. socket[SOCKET_REQUEST_FINISHED_COUNT] = 0;
  188. installListeners(this, socket, options);
  189. }
  190. createConnection(options, oncreate) {
  191. let called = false;
  192. const onNewCreate = (err, socket) => {
  193. if (called) return;
  194. called = true;
  195. if (err) {
  196. this.createSocketErrorCount++;
  197. return oncreate(err);
  198. }
  199. this[INIT_SOCKET](socket, options);
  200. oncreate(err, socket);
  201. };
  202. const newSocket = super.createConnection(options, onNewCreate);
  203. if (newSocket) onNewCreate(null, newSocket);
  204. }
  205. get statusChanged() {
  206. const changed = this.createSocketCount !== this.createSocketCountLastCheck ||
  207. this.createSocketErrorCount !== this.createSocketErrorCountLastCheck ||
  208. this.closeSocketCount !== this.closeSocketCountLastCheck ||
  209. this.errorSocketCount !== this.errorSocketCountLastCheck ||
  210. this.timeoutSocketCount !== this.timeoutSocketCountLastCheck ||
  211. this.requestCount !== this.requestCountLastCheck;
  212. if (changed) {
  213. this.createSocketCountLastCheck = this.createSocketCount;
  214. this.createSocketErrorCountLastCheck = this.createSocketErrorCount;
  215. this.closeSocketCountLastCheck = this.closeSocketCount;
  216. this.errorSocketCountLastCheck = this.errorSocketCount;
  217. this.timeoutSocketCountLastCheck = this.timeoutSocketCount;
  218. this.requestCountLastCheck = this.requestCount;
  219. }
  220. return changed;
  221. }
  222. getCurrentStatus() {
  223. return {
  224. createSocketCount: this.createSocketCount,
  225. createSocketErrorCount: this.createSocketErrorCount,
  226. closeSocketCount: this.closeSocketCount,
  227. errorSocketCount: this.errorSocketCount,
  228. timeoutSocketCount: this.timeoutSocketCount,
  229. requestCount: this.requestCount,
  230. freeSockets: inspect(this.freeSockets),
  231. sockets: inspect(this.sockets),
  232. requests: inspect(this.requests),
  233. };
  234. }
  235. }
  236. // node 8 don't has timeout attribute on socket
  237. // https://github.com/nodejs/node/pull/21204/files#diff-e6ef024c3775d787c38487a6309e491dR408
  238. function getSocketTimeout(socket) {
  239. return socket.timeout || socket._idleTimeout;
  240. }
  241. function installListeners(agent, socket, options) {
  242. debug('%s create, timeout %sms', socket[SOCKET_NAME], getSocketTimeout(socket));
  243. // listener socket events: close, timeout, error, free
  244. function onFree() {
  245. // create and socket.emit('free') logic
  246. // https://github.com/nodejs/node/blob/master/lib/_http_agent.js#L311
  247. // no req on the socket, it should be the new socket
  248. if (!socket._httpMessage && socket[SOCKET_REQUEST_COUNT] === 1) return;
  249. socket[SOCKET_REQUEST_FINISHED_COUNT]++;
  250. agent.requestCount++;
  251. debug('%s(requests: %s, finished: %s) free',
  252. socket[SOCKET_NAME], socket[SOCKET_REQUEST_COUNT], socket[SOCKET_REQUEST_FINISHED_COUNT]);
  253. // should reuse on pedding requests?
  254. const name = agent.getName(options);
  255. if (socket.writable && agent.requests[name] && agent.requests[name].length) {
  256. // will be reuse on agent free listener
  257. socket[SOCKET_REQUEST_COUNT]++;
  258. debug('%s(requests: %s, finished: %s) will be reuse on agent free event',
  259. socket[SOCKET_NAME], socket[SOCKET_REQUEST_COUNT], socket[SOCKET_REQUEST_FINISHED_COUNT]);
  260. }
  261. }
  262. socket.on('free', onFree);
  263. function onClose(isError) {
  264. debug('%s(requests: %s, finished: %s) close, isError: %s',
  265. socket[SOCKET_NAME], socket[SOCKET_REQUEST_COUNT], socket[SOCKET_REQUEST_FINISHED_COUNT], isError);
  266. agent.closeSocketCount++;
  267. }
  268. socket.on('close', onClose);
  269. // start socket timeout handler
  270. function onTimeout() {
  271. // onTimeout and emitRequestTimeout(_http_client.js)
  272. // https://github.com/nodejs/node/blob/v12.x/lib/_http_client.js#L711
  273. const listenerCount = socket.listeners('timeout').length;
  274. // node <= 10, default listenerCount is 1, onTimeout
  275. // 11 < node <= 12, default listenerCount is 2, onTimeout and emitRequestTimeout
  276. // node >= 13, default listenerCount is 3, onTimeout,
  277. // onTimeout(https://github.com/nodejs/node/pull/32000/files#diff-5f7fb0850412c6be189faeddea6c5359R333)
  278. // and emitRequestTimeout
  279. const timeout = getSocketTimeout(socket);
  280. const req = socket._httpMessage;
  281. const reqTimeoutListenerCount = req && req.listeners('timeout').length || 0;
  282. debug('%s(requests: %s, finished: %s) timeout after %sms, listeners %s, defaultTimeoutListenerCount %s, hasHttpRequest %s, HttpRequest timeoutListenerCount %s',
  283. socket[SOCKET_NAME], socket[SOCKET_REQUEST_COUNT], socket[SOCKET_REQUEST_FINISHED_COUNT],
  284. timeout, listenerCount, defaultTimeoutListenerCount, !!req, reqTimeoutListenerCount);
  285. if (debug.enabled) {
  286. debug('timeout listeners: %s', socket.listeners('timeout').map(f => f.name).join(', '));
  287. }
  288. agent.timeoutSocketCount++;
  289. const name = agent.getName(options);
  290. if (agent.freeSockets[name] && agent.freeSockets[name].indexOf(socket) !== -1) {
  291. // free socket timeout, destroy quietly
  292. socket.destroy();
  293. // Remove it from freeSockets list immediately to prevent new requests
  294. // from being sent through this socket.
  295. agent.removeSocket(socket, options);
  296. debug('%s is free, destroy quietly', socket[SOCKET_NAME]);
  297. } else {
  298. // if there is no any request socket timeout handler,
  299. // agent need to handle socket timeout itself.
  300. //
  301. // custom request socket timeout handle logic must follow these rules:
  302. // 1. Destroy socket first
  303. // 2. Must emit socket 'agentRemove' event tell agent remove socket
  304. // from freeSockets list immediately.
  305. // Otherise you may be get 'socket hang up' error when reuse
  306. // free socket and timeout happen in the same time.
  307. if (reqTimeoutListenerCount === 0) {
  308. const error = new Error('Socket timeout');
  309. error.code = 'ERR_SOCKET_TIMEOUT';
  310. error.timeout = timeout;
  311. // must manually call socket.end() or socket.destroy() to end the connection.
  312. // https://nodejs.org/dist/latest-v10.x/docs/api/net.html#net_socket_settimeout_timeout_callback
  313. socket.destroy(error);
  314. agent.removeSocket(socket, options);
  315. debug('%s destroy with timeout error', socket[SOCKET_NAME]);
  316. }
  317. }
  318. }
  319. socket.on('timeout', onTimeout);
  320. function onError(err) {
  321. const listenerCount = socket.listeners('error').length;
  322. debug('%s(requests: %s, finished: %s) error: %s, listenerCount: %s',
  323. socket[SOCKET_NAME], socket[SOCKET_REQUEST_COUNT], socket[SOCKET_REQUEST_FINISHED_COUNT],
  324. err, listenerCount);
  325. agent.errorSocketCount++;
  326. if (listenerCount === 1) {
  327. // if socket don't contain error event handler, don't catch it, emit it again
  328. debug('%s emit uncaught error event', socket[SOCKET_NAME]);
  329. socket.removeListener('error', onError);
  330. socket.emit('error', err);
  331. }
  332. }
  333. socket.on('error', onError);
  334. function onRemove() {
  335. debug('%s(requests: %s, finished: %s) agentRemove',
  336. socket[SOCKET_NAME],
  337. socket[SOCKET_REQUEST_COUNT], socket[SOCKET_REQUEST_FINISHED_COUNT]);
  338. // We need this function for cases like HTTP 'upgrade'
  339. // (defined by WebSockets) where we need to remove a socket from the
  340. // pool because it'll be locked up indefinitely
  341. socket.removeListener('close', onClose);
  342. socket.removeListener('error', onError);
  343. socket.removeListener('free', onFree);
  344. socket.removeListener('timeout', onTimeout);
  345. socket.removeListener('agentRemove', onRemove);
  346. }
  347. socket.on('agentRemove', onRemove);
  348. }
  349. module.exports = Agent;
  350. function inspect(obj) {
  351. const res = {};
  352. for (const key in obj) {
  353. res[key] = obj[key].length;
  354. }
  355. return res;
  356. }