You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

agent.js 15KB

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