index.js 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345
  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. const timeout = setTimeout(() => {
  171. if (logger) {
  172. logger.warn(
  173. { url, method: opts.method ?? 'GET' },
  174. 'Fetch request did not complete within 120 seconds'
  175. )
  176. }
  177. }, 120000)
  178. detachSignal = () => {
  179. clearTimeout(timeout)
  180. }
  181. }
  182. if (opts.body instanceof Readable) {
  183. abortOnDestroyedRequest(abortController, fetchOpts.body)
  184. }
  185. return { fetchOpts, abortController, detachSignal }
  186. }
  187. function setupJsonBody(fetchOpts, json) {
  188. fetchOpts.body = JSON.stringify(json)
  189. fetchOpts.headers = fetchOpts.headers ?? {}
  190. fetchOpts.headers['Content-Type'] = 'application/json'
  191. }
  192. function setupBasicAuth(fetchOpts, basicAuth) {
  193. fetchOpts.headers = fetchOpts.headers ?? {}
  194. fetchOpts.headers.Authorization =
  195. 'Basic ' +
  196. Buffer.from(`${basicAuth.user}:${basicAuth.password}`).toString('base64')
  197. }
  198. function abortOnSignal(abortController, signal) {
  199. const listener = () => {
  200. abortController.abort(signal.reason)
  201. }
  202. if (signal.aborted) {
  203. abortController.abort(signal.reason)
  204. }
  205. signal.addEventListener('abort', listener)
  206. return () => {
  207. signal.removeEventListener('abort', listener)
  208. }
  209. }
  210. function abortOnDestroyedRequest(abortController, stream) {
  211. stream.on('close', () => {
  212. if (!stream.readableEnded) {
  213. abortController.abort()
  214. }
  215. })
  216. }
  217. function abortOnDestroyedResponse(abortController, response) {
  218. response.body.on('close', () => {
  219. if (!response.bodyUsed) {
  220. abortController.abort()
  221. }
  222. })
  223. }
  224. async function performRequest(url, fetchOpts, detachSignal) {
  225. let response
  226. try {
  227. response = await fetch(url, fetchOpts)
  228. } catch (err) {
  229. detachSignal()
  230. if (fetchOpts.body instanceof Readable) {
  231. fetchOpts.body.destroy()
  232. }
  233. throw OError.tag(err, err.message, {
  234. url,
  235. method: fetchOpts.method ?? 'GET',
  236. })
  237. }
  238. response.body.on('close', detachSignal)
  239. if (fetchOpts.body instanceof Readable) {
  240. response.body.on('close', () => {
  241. if (!fetchOpts.body.readableEnded) {
  242. fetchOpts.body.destroy()
  243. }
  244. })
  245. }
  246. return response
  247. }
  248. async function discardResponseBody(response) {
  249. // eslint-disable-next-line no-unused-vars
  250. for await (const chunk of response.body) {
  251. // discard the body
  252. }
  253. }
  254. /**
  255. * @param {Response} response
  256. */
  257. async function maybeGetResponseBody(response) {
  258. try {
  259. return await response.text()
  260. } catch (err) {
  261. return null
  262. }
  263. }
  264. // Define custom http and https agents with support for connect timeouts
  265. class ConnectTimeoutError extends OError {
  266. constructor(options) {
  267. super('connect timeout', options)
  268. }
  269. }
  270. function withTimeout(createConnection, options, callback) {
  271. if (options.connectTimeout) {
  272. // Wrap createConnection in a timeout
  273. const timer = setTimeout(() => {
  274. socket.destroy(new ConnectTimeoutError(options))
  275. }, options.connectTimeout)
  276. const socket = createConnection(options, (err, stream) => {
  277. clearTimeout(timer)
  278. callback(err, stream)
  279. })
  280. return socket
  281. } else {
  282. // Fallback to default createConnection
  283. return createConnection(options, callback)
  284. }
  285. }
  286. class CustomHttpAgent extends http.Agent {
  287. createConnection(options, callback) {
  288. return withTimeout(super.createConnection.bind(this), options, callback)
  289. }
  290. }
  291. class CustomHttpsAgent extends https.Agent {
  292. createConnection(options, callback) {
  293. return withTimeout(super.createConnection.bind(this), options, callback)
  294. }
  295. }
  296. module.exports = {
  297. fetchJson,
  298. fetchJsonWithResponse,
  299. fetchStream,
  300. fetchStreamWithResponse,
  301. fetchNothing,
  302. fetchRedirect,
  303. fetchRedirectWithResponse,
  304. fetchString,
  305. fetchStringWithResponse,
  306. RequestFailedError,
  307. ConnectTimeoutError,
  308. CustomHttpAgent,
  309. CustomHttpsAgent,
  310. setLogger,
  311. }