index.js 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306
  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 { fetchOpts } = parseOpts(opts)
  87. fetchOpts.redirect = 'manual'
  88. const response = await performRequest(url, fetchOpts)
  89. if (response.status < 300 || response.status >= 400) {
  90. const body = await maybeGetResponseBody(response)
  91. throw new RequestFailedError(url, opts, response, body)
  92. }
  93. const location = response.headers.get('Location')
  94. if (!location) {
  95. const body = await maybeGetResponseBody(response)
  96. throw new RequestFailedError(url, opts, response, body).withCause(
  97. new OError('missing Location response header on 3xx response', {
  98. headers: Object.fromEntries(response.headers.entries()),
  99. })
  100. )
  101. }
  102. await discardResponseBody(response)
  103. return location
  104. }
  105. /**
  106. * Make a request and return a string.
  107. *
  108. * @param {string | URL} url - request URL
  109. * @param {any} [opts] - fetch options
  110. * @return {Promise<string>}
  111. * @throws {RequestFailedError} if the response has a failure status code
  112. */
  113. async function fetchString(url, opts = {}) {
  114. const { body } = await fetchStringWithResponse(url, opts)
  115. return body
  116. }
  117. async function fetchStringWithResponse(url, opts = {}) {
  118. const { fetchOpts } = parseOpts(opts)
  119. const response = await performRequest(url, fetchOpts)
  120. if (!response.ok) {
  121. const body = await maybeGetResponseBody(response)
  122. throw new RequestFailedError(url, opts, response, body)
  123. }
  124. const body = await response.text()
  125. return { body, response }
  126. }
  127. class RequestFailedError extends OError {
  128. constructor(url, opts, response, body) {
  129. super('request failed', {
  130. url,
  131. method: opts.method ?? 'GET',
  132. status: response.status,
  133. })
  134. this.response = response
  135. if (body != null) {
  136. this.body = body
  137. }
  138. }
  139. }
  140. function parseOpts(opts) {
  141. const fetchOpts = _.omit(opts, ['json', 'signal', 'basicAuth'])
  142. if (opts.json) {
  143. setupJsonBody(fetchOpts, opts.json)
  144. }
  145. if (opts.basicAuth) {
  146. setupBasicAuth(fetchOpts, opts.basicAuth)
  147. }
  148. const abortController = new AbortController()
  149. fetchOpts.signal = abortController.signal
  150. if (opts.signal) {
  151. abortOnSignal(abortController, opts.signal)
  152. }
  153. if (opts.body instanceof Readable) {
  154. abortOnDestroyedRequest(abortController, fetchOpts.body)
  155. }
  156. return { fetchOpts, abortController }
  157. }
  158. function setupJsonBody(fetchOpts, json) {
  159. fetchOpts.body = JSON.stringify(json)
  160. fetchOpts.headers = fetchOpts.headers ?? {}
  161. fetchOpts.headers['Content-Type'] = 'application/json'
  162. }
  163. function setupBasicAuth(fetchOpts, basicAuth) {
  164. fetchOpts.headers = fetchOpts.headers ?? {}
  165. fetchOpts.headers.Authorization =
  166. 'Basic ' +
  167. Buffer.from(`${basicAuth.user}:${basicAuth.password}`).toString('base64')
  168. }
  169. function abortOnSignal(abortController, signal) {
  170. const listener = () => {
  171. abortController.abort(signal.reason)
  172. }
  173. if (signal.aborted) {
  174. abortController.abort(signal.reason)
  175. }
  176. signal.addEventListener('abort', listener)
  177. }
  178. function abortOnDestroyedRequest(abortController, stream) {
  179. stream.on('close', () => {
  180. if (!stream.readableEnded) {
  181. abortController.abort()
  182. }
  183. })
  184. }
  185. function abortOnDestroyedResponse(abortController, response) {
  186. response.body.on('close', () => {
  187. if (!response.bodyUsed) {
  188. abortController.abort()
  189. }
  190. })
  191. }
  192. async function performRequest(url, fetchOpts) {
  193. let response
  194. try {
  195. response = await fetch(url, fetchOpts)
  196. } catch (err) {
  197. if (fetchOpts.body instanceof Readable) {
  198. fetchOpts.body.destroy()
  199. }
  200. throw OError.tag(err, err.message, {
  201. url,
  202. method: fetchOpts.method ?? 'GET',
  203. })
  204. }
  205. if (fetchOpts.body instanceof Readable) {
  206. response.body.on('close', () => {
  207. if (!fetchOpts.body.readableEnded) {
  208. fetchOpts.body.destroy()
  209. }
  210. })
  211. }
  212. return response
  213. }
  214. async function discardResponseBody(response) {
  215. // eslint-disable-next-line no-unused-vars
  216. for await (const chunk of response.body) {
  217. // discard the body
  218. }
  219. }
  220. /**
  221. * @param {Response} response
  222. */
  223. async function maybeGetResponseBody(response) {
  224. try {
  225. return await response.text()
  226. } catch (err) {
  227. return null
  228. }
  229. }
  230. // Define custom http and https agents with support for connect timeouts
  231. class ConnectTimeoutError extends OError {
  232. constructor(options) {
  233. super('connect timeout', options)
  234. }
  235. }
  236. function withTimeout(createConnection, options, callback) {
  237. if (options.connectTimeout) {
  238. // Wrap createConnection in a timeout
  239. const timer = setTimeout(() => {
  240. socket.destroy(new ConnectTimeoutError(options))
  241. }, options.connectTimeout)
  242. const socket = createConnection(options, (err, stream) => {
  243. clearTimeout(timer)
  244. callback(err, stream)
  245. })
  246. return socket
  247. } else {
  248. // Fallback to default createConnection
  249. return createConnection(options, callback)
  250. }
  251. }
  252. class CustomHttpAgent extends http.Agent {
  253. createConnection(options, callback) {
  254. return withTimeout(super.createConnection.bind(this), options, callback)
  255. }
  256. }
  257. class CustomHttpsAgent extends https.Agent {
  258. createConnection(options, callback) {
  259. return withTimeout(super.createConnection.bind(this), options, callback)
  260. }
  261. }
  262. module.exports = {
  263. fetchJson,
  264. fetchJsonWithResponse,
  265. fetchStream,
  266. fetchStreamWithResponse,
  267. fetchNothing,
  268. fetchRedirect,
  269. fetchString,
  270. fetchStringWithResponse,
  271. RequestFailedError,
  272. ConnectTimeoutError,
  273. CustomHttpAgent,
  274. CustomHttpsAgent,
  275. }