auto.js 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206
  1. 'use strict';
  2. // See https://github.com/facebook/jest/issues/2549
  3. // eslint-disable-next-line node/prefer-global/url
  4. const {URL, urlToHttpOptions} = require('url');
  5. const http = require('http');
  6. const https = require('https');
  7. const resolveALPN = require('resolve-alpn');
  8. const QuickLRU = require('quick-lru');
  9. const {Agent, globalAgent} = require('./agent.js');
  10. const Http2ClientRequest = require('./client-request.js');
  11. const calculateServerName = require('./utils/calculate-server-name.js');
  12. const delayAsyncDestroy = require('./utils/delay-async-destroy.js');
  13. const cache = new QuickLRU({maxSize: 100});
  14. const queue = new Map();
  15. const installSocket = (agent, socket, options) => {
  16. socket._httpMessage = {shouldKeepAlive: true};
  17. const onFree = () => {
  18. agent.emit('free', socket, options);
  19. };
  20. socket.on('free', onFree);
  21. const onClose = () => {
  22. agent.removeSocket(socket, options);
  23. };
  24. socket.on('close', onClose);
  25. const onTimeout = () => {
  26. const {freeSockets} = agent;
  27. for (const sockets of Object.values(freeSockets)) {
  28. if (sockets.includes(socket)) {
  29. socket.destroy();
  30. return;
  31. }
  32. }
  33. };
  34. socket.on('timeout', onTimeout);
  35. const onRemove = () => {
  36. agent.removeSocket(socket, options);
  37. socket.off('close', onClose);
  38. socket.off('free', onFree);
  39. socket.off('timeout', onTimeout);
  40. socket.off('agentRemove', onRemove);
  41. };
  42. socket.on('agentRemove', onRemove);
  43. agent.emit('free', socket, options);
  44. };
  45. const createResolveProtocol = (cache, queue = new Map(), connect = undefined) => {
  46. return async options => {
  47. const name = `${options.host}:${options.port}:${options.ALPNProtocols.sort()}`;
  48. if (!cache.has(name)) {
  49. if (queue.has(name)) {
  50. const result = await queue.get(name);
  51. return {alpnProtocol: result.alpnProtocol};
  52. }
  53. const {path} = options;
  54. options.path = options.socketPath;
  55. const resultPromise = resolveALPN(options, connect);
  56. queue.set(name, resultPromise);
  57. try {
  58. const result = await resultPromise;
  59. cache.set(name, result.alpnProtocol);
  60. queue.delete(name);
  61. options.path = path;
  62. return result;
  63. } catch (error) {
  64. queue.delete(name);
  65. options.path = path;
  66. throw error;
  67. }
  68. }
  69. return {alpnProtocol: cache.get(name)};
  70. };
  71. };
  72. const defaultResolveProtocol = createResolveProtocol(cache, queue);
  73. module.exports = async (input, options, callback) => {
  74. if (typeof input === 'string') {
  75. input = urlToHttpOptions(new URL(input));
  76. } else if (input instanceof URL) {
  77. input = urlToHttpOptions(input);
  78. } else {
  79. input = {...input};
  80. }
  81. if (typeof options === 'function' || options === undefined) {
  82. // (options, callback)
  83. callback = options;
  84. options = input;
  85. } else {
  86. // (input, options, callback)
  87. options = Object.assign(input, options);
  88. }
  89. options.ALPNProtocols = options.ALPNProtocols || ['h2', 'http/1.1'];
  90. if (!Array.isArray(options.ALPNProtocols) || options.ALPNProtocols.length === 0) {
  91. throw new Error('The `ALPNProtocols` option must be an Array with at least one entry');
  92. }
  93. options.protocol = options.protocol || 'https:';
  94. const isHttps = options.protocol === 'https:';
  95. options.host = options.hostname || options.host || 'localhost';
  96. options.session = options.tlsSession;
  97. options.servername = options.servername || calculateServerName((options.headers && options.headers.host) || options.host);
  98. options.port = options.port || (isHttps ? 443 : 80);
  99. options._defaultAgent = isHttps ? https.globalAgent : http.globalAgent;
  100. const resolveProtocol = options.resolveProtocol || defaultResolveProtocol;
  101. // Note: We don't support `h2session` here
  102. let {agent} = options;
  103. if (agent !== undefined && agent !== false && agent.constructor.name !== 'Object') {
  104. throw new Error('The `options.agent` can be only an object `http`, `https` or `http2` properties');
  105. }
  106. if (isHttps) {
  107. options.resolveSocket = true;
  108. let {socket, alpnProtocol, timeout} = await resolveProtocol(options);
  109. if (timeout) {
  110. if (socket) {
  111. socket.destroy();
  112. }
  113. const error = new Error(`Timed out resolving ALPN: ${options.timeout} ms`);
  114. error.code = 'ETIMEDOUT';
  115. error.ms = options.timeout;
  116. throw error;
  117. }
  118. // We can't accept custom `createConnection` because the API is different for HTTP/2
  119. if (socket && options.createConnection) {
  120. socket.destroy();
  121. socket = undefined;
  122. }
  123. delete options.resolveSocket;
  124. const isHttp2 = alpnProtocol === 'h2';
  125. if (agent) {
  126. agent = isHttp2 ? agent.http2 : agent.https;
  127. options.agent = agent;
  128. }
  129. if (agent === undefined) {
  130. agent = isHttp2 ? globalAgent : https.globalAgent;
  131. }
  132. if (socket) {
  133. if (agent === false) {
  134. socket.destroy();
  135. } else {
  136. const defaultCreateConnection = (isHttp2 ? Agent : https.Agent).prototype.createConnection;
  137. if (agent.createConnection === defaultCreateConnection) {
  138. if (isHttp2) {
  139. options._reuseSocket = socket;
  140. } else {
  141. installSocket(agent, socket, options);
  142. }
  143. } else {
  144. socket.destroy();
  145. }
  146. }
  147. }
  148. if (isHttp2) {
  149. return delayAsyncDestroy(new Http2ClientRequest(options, callback));
  150. }
  151. } else if (agent) {
  152. options.agent = agent.http;
  153. }
  154. return delayAsyncDestroy(http.request(options, callback));
  155. };
  156. module.exports.protocolCache = cache;
  157. module.exports.resolveProtocol = defaultResolveProtocol;
  158. module.exports.createResolveProtocol = createResolveProtocol;