index.js 8.6 KB

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