index.js 9.0 KB

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