index.js 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354
  1. const _ = require('lodash')
  2. const { Readable } = require('node:stream')
  3. const OError = require('@overleaf/o-error')
  4. const fetch = require('node-fetch')
  5. const http = require('node:http')
  6. const https = require('node:https')
  7. let logger
  8. function setLogger(loggerInstance) {
  9. logger = loggerInstance
  10. }
  11. /**
  12. * @import { Response } from 'node-fetch'
  13. */
  14. /**
  15. * Make a request and return the parsed JSON response.
  16. *
  17. * @param {string | URL} url - request URL
  18. * @param {any} [opts] - fetch options
  19. * @return {Promise<any>} the parsed JSON response
  20. * @throws {RequestFailedError} if the response has a failure status code
  21. */
  22. async function fetchJson(url, opts = {}) {
  23. const { json } = await fetchJsonWithResponse(url, opts)
  24. return json
  25. }
  26. async function fetchJsonWithResponse(url, opts = {}) {
  27. const { fetchOpts, detachSignal } = parseOpts(opts, url)
  28. fetchOpts.headers = fetchOpts.headers ?? {}
  29. fetchOpts.headers.Accept = fetchOpts.headers.Accept ?? 'application/json'
  30. const response = await performRequest(url, fetchOpts, detachSignal)
  31. if (!response.ok) {
  32. const body = await maybeGetResponseBody(response)
  33. throw new RequestFailedError(url, opts, response, body)
  34. }
  35. const json = await response.json()
  36. return { json, response }
  37. }
  38. /**
  39. * Make a request and return a stream.
  40. *
  41. * If the response body is destroyed, the request is aborted.
  42. *
  43. * @param {string | URL} url - request URL
  44. * @param {any} [opts] - fetch options
  45. * @return {Promise<Readable>}
  46. * @throws {RequestFailedError} if the response has a failure status code
  47. */
  48. async function fetchStream(url, opts = {}) {
  49. const { stream } = await fetchStreamWithResponse(url, opts)
  50. return stream
  51. }
  52. async function fetchStreamWithResponse(url, opts = {}) {
  53. const { fetchOpts, abortController, detachSignal } = parseOpts(opts, url)
  54. const response = await performRequest(url, fetchOpts, detachSignal)
  55. if (!response.ok) {
  56. const body = await maybeGetResponseBody(response)
  57. throw new RequestFailedError(url, opts, response, body)
  58. }
  59. abortOnDestroyedResponse(abortController, response)
  60. const stream = response.body
  61. return { stream, response }
  62. }
  63. /**
  64. * Make a request and discard the response.
  65. *
  66. * @param {string | URL} url - request URL
  67. * @param {any} [opts] - fetch options
  68. * @return {Promise<Response>}
  69. * @throws {RequestFailedError} if the response has a failure status code
  70. */
  71. async function fetchNothing(url, opts = {}) {
  72. const { fetchOpts, detachSignal } = parseOpts(opts, url)
  73. const response = await performRequest(url, fetchOpts, detachSignal)
  74. if (!response.ok) {
  75. const body = await maybeGetResponseBody(response)
  76. throw new RequestFailedError(url, opts, response, body)
  77. }
  78. await discardResponseBody(response)
  79. return response
  80. }
  81. /**
  82. * Make a request and extract the redirect from the response.
  83. *
  84. * @param {string | URL} url - request URL
  85. * @param {any} [opts] - fetch options
  86. * @return {Promise<string>}
  87. * @throws {RequestFailedError} if the response has a non redirect status code or missing Location header
  88. */
  89. async function fetchRedirect(url, opts = {}) {
  90. const { location } = await fetchRedirectWithResponse(url, opts)
  91. return location
  92. }
  93. /**
  94. * Make a request and extract the redirect from the response.
  95. *
  96. * @param {string | URL} url - request URL
  97. * @param {object} opts - fetch options
  98. * @return {Promise<{location: string, response: Response}>}
  99. * @throws {RequestFailedError} if the response has a non redirect status code or missing Location header
  100. */
  101. async function fetchRedirectWithResponse(url, opts = {}) {
  102. const { fetchOpts, detachSignal } = parseOpts(opts, url)
  103. fetchOpts.redirect = 'manual'
  104. const response = await performRequest(url, fetchOpts, detachSignal)
  105. if (response.status < 300 || response.status >= 400) {
  106. const body = await maybeGetResponseBody(response)
  107. throw new RequestFailedError(url, opts, response, body)
  108. }
  109. const location = response.headers.get('Location')
  110. if (!location) {
  111. const body = await maybeGetResponseBody(response)
  112. throw new RequestFailedError(url, opts, response, body).withCause(
  113. new OError('missing Location response header on 3xx response', {
  114. headers: Object.fromEntries(response.headers.entries()),
  115. })
  116. )
  117. }
  118. await discardResponseBody(response)
  119. return { location, response }
  120. }
  121. /**
  122. * Make a request and return a string.
  123. *
  124. * @param {string | URL} url - request URL
  125. * @param {any} [opts] - fetch options
  126. * @return {Promise<string>}
  127. * @throws {RequestFailedError} if the response has a failure status code
  128. */
  129. async function fetchString(url, opts = {}) {
  130. const { body } = await fetchStringWithResponse(url, opts)
  131. return body
  132. }
  133. async function fetchStringWithResponse(url, opts = {}) {
  134. const { fetchOpts, detachSignal } = parseOpts(opts, url)
  135. const response = await performRequest(url, fetchOpts, detachSignal)
  136. if (!response.ok) {
  137. const body = await maybeGetResponseBody(response)
  138. throw new RequestFailedError(url, opts, response, body)
  139. }
  140. const body = await response.text()
  141. return { body, response }
  142. }
  143. class RequestFailedError extends OError {
  144. constructor(url, opts, response, body) {
  145. super('request failed', {
  146. url,
  147. method: opts.method ?? 'GET',
  148. status: response.status,
  149. })
  150. this.response = response
  151. if (body != null) {
  152. this.body = body
  153. }
  154. }
  155. }
  156. function parseOpts(opts, url) {
  157. const fetchOpts = _.omit(opts, ['json', 'signal', 'basicAuth'])
  158. if (opts.json) {
  159. setupJsonBody(fetchOpts, opts.json)
  160. }
  161. if (opts.basicAuth) {
  162. setupBasicAuth(fetchOpts, opts.basicAuth)
  163. }
  164. const abortController = new AbortController()
  165. fetchOpts.signal = abortController.signal
  166. let detachSignal
  167. if (opts.signal) {
  168. detachSignal = abortOnSignal(abortController, opts.signal)
  169. } else {
  170. let overTimeoutStart
  171. const stack = new Error().stack
  172. const timeout = setTimeout(() => {
  173. overTimeoutStart = process.hrtime.bigint()
  174. }, 120000)
  175. detachSignal = () => {
  176. clearTimeout(timeout)
  177. if (overTimeoutStart && logger) {
  178. logger.warn(
  179. {
  180. url,
  181. method: opts.method ?? 'GET',
  182. overTimeoutMs:
  183. Number(process.hrtime.bigint() - overTimeoutStart) / 1e6,
  184. stack,
  185. },
  186. 'Fetch request did not complete within 120 seconds'
  187. )
  188. }
  189. }
  190. }
  191. if (opts.body instanceof Readable) {
  192. abortOnDestroyedRequest(abortController, fetchOpts.body)
  193. }
  194. return { fetchOpts, abortController, detachSignal }
  195. }
  196. function setupJsonBody(fetchOpts, json) {
  197. fetchOpts.body = JSON.stringify(json)
  198. fetchOpts.headers = fetchOpts.headers ?? {}
  199. fetchOpts.headers['Content-Type'] = 'application/json'
  200. }
  201. function setupBasicAuth(fetchOpts, basicAuth) {
  202. fetchOpts.headers = fetchOpts.headers ?? {}
  203. fetchOpts.headers.Authorization =
  204. 'Basic ' +
  205. Buffer.from(`${basicAuth.user}:${basicAuth.password}`).toString('base64')
  206. }
  207. function abortOnSignal(abortController, signal) {
  208. const listener = () => {
  209. abortController.abort(signal.reason)
  210. }
  211. if (signal.aborted) {
  212. abortController.abort(signal.reason)
  213. }
  214. signal.addEventListener('abort', listener)
  215. return () => {
  216. signal.removeEventListener('abort', listener)
  217. }
  218. }
  219. function abortOnDestroyedRequest(abortController, stream) {
  220. stream.on('close', () => {
  221. if (!stream.readableEnded) {
  222. abortController.abort()
  223. }
  224. })
  225. }
  226. function abortOnDestroyedResponse(abortController, response) {
  227. response.body.on('close', () => {
  228. if (!response.bodyUsed) {
  229. abortController.abort()
  230. }
  231. })
  232. }
  233. async function performRequest(url, fetchOpts, detachSignal) {
  234. let response
  235. try {
  236. response = await fetch(url, fetchOpts)
  237. } catch (err) {
  238. detachSignal()
  239. if (fetchOpts.body instanceof Readable) {
  240. fetchOpts.body.destroy()
  241. }
  242. throw OError.tag(err, err.message, {
  243. url,
  244. method: fetchOpts.method ?? 'GET',
  245. })
  246. }
  247. response.body.on('close', detachSignal)
  248. if (fetchOpts.body instanceof Readable) {
  249. response.body.on('close', () => {
  250. if (!fetchOpts.body.readableEnded) {
  251. fetchOpts.body.destroy()
  252. }
  253. })
  254. }
  255. return response
  256. }
  257. async function discardResponseBody(response) {
  258. // eslint-disable-next-line no-unused-vars
  259. for await (const chunk of response.body) {
  260. // discard the body
  261. }
  262. }
  263. /**
  264. * @param {Response} response
  265. */
  266. async function maybeGetResponseBody(response) {
  267. try {
  268. return await response.text()
  269. } catch (err) {
  270. return null
  271. }
  272. }
  273. // Define custom http and https agents with support for connect timeouts
  274. class ConnectTimeoutError extends OError {
  275. constructor(options) {
  276. super('connect timeout', options)
  277. }
  278. }
  279. function withTimeout(createConnection, options, callback) {
  280. if (options.connectTimeout) {
  281. // Wrap createConnection in a timeout
  282. const timer = setTimeout(() => {
  283. socket.destroy(new ConnectTimeoutError(options))
  284. }, options.connectTimeout)
  285. const socket = createConnection(options, (err, stream) => {
  286. clearTimeout(timer)
  287. callback(err, stream)
  288. })
  289. return socket
  290. } else {
  291. // Fallback to default createConnection
  292. return createConnection(options, callback)
  293. }
  294. }
  295. class CustomHttpAgent extends http.Agent {
  296. createConnection(options, callback) {
  297. return withTimeout(super.createConnection.bind(this), options, callback)
  298. }
  299. }
  300. class CustomHttpsAgent extends https.Agent {
  301. createConnection(options, callback) {
  302. return withTimeout(super.createConnection.bind(this), options, callback)
  303. }
  304. }
  305. module.exports = {
  306. fetchJson,
  307. fetchJsonWithResponse,
  308. fetchStream,
  309. fetchStreamWithResponse,
  310. fetchNothing,
  311. fetchRedirect,
  312. fetchRedirectWithResponse,
  313. fetchString,
  314. fetchStringWithResponse,
  315. RequestFailedError,
  316. ConnectTimeoutError,
  317. CustomHttpAgent,
  318. CustomHttpsAgent,
  319. setLogger,
  320. }