UrlFetcher.js 3.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128
  1. import fs from 'node:fs'
  2. import logger from '@overleaf/logger'
  3. import Settings from '@overleaf/settings'
  4. import {
  5. CustomHttpAgent,
  6. CustomHttpsAgent,
  7. fetchStream,
  8. RequestFailedError,
  9. } from '@overleaf/fetch-utils'
  10. import { URL } from 'node:url'
  11. import { pipeline } from 'node:stream/promises'
  12. import Metrics from '@overleaf/metrics'
  13. const MAX_CONNECT_TIME = 1000
  14. const httpAgent = new CustomHttpAgent({ connectTimeout: MAX_CONNECT_TIME })
  15. const httpsAgent = new CustomHttpsAgent({ connectTimeout: MAX_CONNECT_TIME })
  16. async function pipeUrlToFileWithRetry(url, fallbackURL, filePath) {
  17. let remainingAttempts = 3
  18. let lastErr
  19. while (remainingAttempts-- > 0) {
  20. const timer = new Metrics.Timer('url_fetcher', {
  21. path: lastErr ? ' retry' : 'fetch',
  22. })
  23. try {
  24. await pipeUrlToFile(url, fallbackURL, filePath)
  25. timer.done({ status: 'success' })
  26. return
  27. } catch (err) {
  28. timer.done({ status: 'error' })
  29. logger.warn(
  30. { err, url, filePath, remainingAttempts },
  31. 'error downloading url'
  32. )
  33. lastErr = err
  34. }
  35. }
  36. throw lastErr
  37. }
  38. async function pipeUrlToFile(url, fallbackURL, filePath) {
  39. const u = new URL(url)
  40. if (
  41. Settings.filestoreDomainOveride &&
  42. u.host !== Settings.apis.clsiPerf.host
  43. ) {
  44. url = `${Settings.filestoreDomainOveride}${u.pathname}${u.search}`
  45. }
  46. if (fallbackURL) {
  47. const u2 = new URL(fallbackURL)
  48. if (
  49. Settings.filestoreDomainOveride &&
  50. u2.host !== Settings.apis.clsiPerf.host
  51. ) {
  52. fallbackURL = `${Settings.filestoreDomainOveride}${u2.pathname}${u2.search}`
  53. }
  54. }
  55. let stream
  56. try {
  57. stream = await fetchStream(url, {
  58. signal: AbortSignal.timeout(60 * 1000),
  59. // provide a function to get the agent for each request
  60. // as there may be multiple requests with different protocols
  61. // due to redirects.
  62. agent: _url => (_url.protocol === 'https:' ? httpsAgent : httpAgent),
  63. })
  64. } catch (err) {
  65. if (
  66. fallbackURL &&
  67. err instanceof RequestFailedError &&
  68. err.response.status === 404
  69. ) {
  70. stream = await fetchStream(fallbackURL, {
  71. signal: AbortSignal.timeout(60 * 1000),
  72. // provide a function to get the agent for each request
  73. // as there may be multiple requests with different protocols
  74. // due to redirects.
  75. agent: _url => (_url.protocol === 'https:' ? httpsAgent : httpAgent),
  76. })
  77. url = fallbackURL
  78. } else {
  79. throw err
  80. }
  81. }
  82. const source = inferSource(url)
  83. if (source !== 'clsi-perf') {
  84. Metrics.inc('url_source', 1, { path: source })
  85. }
  86. const atomicWrite = filePath + '~'
  87. try {
  88. const output = fs.createWriteStream(atomicWrite)
  89. await pipeline(stream, output)
  90. await fs.promises.rename(atomicWrite, filePath)
  91. if (source !== 'clsi-perf') {
  92. Metrics.count('UrlFetcher.downloaded_bytes', output.bytesWritten, {
  93. path: source,
  94. })
  95. }
  96. } catch (err) {
  97. try {
  98. await fs.promises.unlink(atomicWrite)
  99. } catch (e) {}
  100. throw err
  101. }
  102. }
  103. const BUCKET_REGEX = /\/bucket\/([^/]+)\/key\//
  104. function inferSource(url) {
  105. if (url.includes(Settings.apis.clsiPerf.host)) {
  106. return 'clsi-perf'
  107. } else if (url.includes('/project/') && url.includes('/file/')) {
  108. return 'user-files'
  109. } else if (url.includes('/key/')) {
  110. const match = url.match(BUCKET_REGEX)
  111. if (match) return match[1]
  112. }
  113. return 'unknown'
  114. }
  115. export default {
  116. promises: {
  117. pipeUrlToFileWithRetry,
  118. },
  119. }