CLSICacheHandler.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433
  1. // @ts-check
  2. const crypto = require('node:crypto')
  3. const fs = require('node:fs')
  4. const Path = require('node:path')
  5. const { pipeline } = require('node:stream/promises')
  6. const { createGzip, createGunzip } = require('node:zlib')
  7. const { crc32 } = require('node:zlib')
  8. const tarFs = require('tar-fs')
  9. const _ = require('lodash')
  10. const {
  11. fetchNothing,
  12. fetchStream,
  13. RequestFailedError,
  14. } = require('@overleaf/fetch-utils')
  15. const logger = require('@overleaf/logger')
  16. const Metrics = require('@overleaf/metrics')
  17. const Settings = require('@overleaf/settings')
  18. const { MeteredStream } = require('@overleaf/stream-utils')
  19. const { CACHE_SUBDIR } = require('./OutputCacheManager')
  20. const { isExtraneousFile } = require('./ResourceWriter')
  21. const TIMEOUT = 5_000
  22. /**
  23. * @type {Map<string, number>}
  24. */
  25. const lastFailures = new Map()
  26. const TIMING_BUCKETS = [
  27. 0, 10, 100, 1000, 2000, 5000, 10000, 15000, 20000, 30000,
  28. ]
  29. const MAX_ENTRIES_IN_OUTPUT_TAR = 100
  30. const MAX_BLG_FILES = 50
  31. const OBJECT_ID_REGEX = /^[0-9a-f]{24}$/
  32. const MIGRATE_FROM = new Date('2026-01-14').getTime()
  33. const MIGRATE_UNTIL = new Date('2026-01-21').getTime()
  34. /**
  35. * @param {string} projectId
  36. * @return {{shard: string, url: string}}
  37. */
  38. function getShard(projectId) {
  39. // Layout of mongodb object id bytes:
  40. // [timestamp 4bytes][random per machine 5bytes][counter 3bytes]
  41. // [32bit 4bytes]
  42. const last4Bytes = Buffer.from(projectId, 'hex').subarray(8, 12)
  43. const counter = last4Bytes.readUInt32BE()
  44. const nShards = Settings.apis.clsiCache.shards.length
  45. // Use the "counter" part of the id for a stable assignment with an even
  46. // distribution. This is where the current data resides.
  47. const preferredShard = counter % nShards
  48. // Gradually migrate over to the crc base shard assignment.
  49. const remaining = MIGRATE_UNTIL - Date.now()
  50. if ((counter % 100) / 100 < remaining / (MIGRATE_UNTIL - MIGRATE_FROM)) {
  51. const shard = Settings.apis.clsiCache.shards[preferredShard]
  52. if (!isCircuitBreakerTripped(shard.url)) return shard
  53. }
  54. // Then use a crc for generating a stable sequence of shards with even
  55. // distribution to try next.
  56. const shards = Settings.apis.clsiCache.shards.slice(0)
  57. let i = 0
  58. while (shards.length > 0) {
  59. const idx = crc32(`${projectId}-${i++}`) % shards.length
  60. const candidate = shards[idx]
  61. if (!isCircuitBreakerTripped(candidate.url)) return candidate
  62. shards.splice(idx, 1)
  63. }
  64. // All shards are down. Return the original preference.
  65. return Settings.apis.clsiCache.shards[preferredShard]
  66. }
  67. /**
  68. * @param {string} url
  69. * @return {boolean}
  70. */
  71. function isCircuitBreakerTripped(url) {
  72. const lastFailure = lastFailures.get(url) ?? 0
  73. if (lastFailure) {
  74. // Circuit breaker that avoids retries for 5-20s.
  75. const retryDelay = TIMEOUT * (1 + 3 * Math.random())
  76. if (performance.now() - lastFailure < retryDelay) {
  77. return true
  78. }
  79. }
  80. return false
  81. }
  82. /**
  83. * @param {string} url
  84. */
  85. function tripCircuitBreaker(url) {
  86. lastFailures.set(url, performance.now()) // The shard is unhealthy. Refresh timestamp of last failure.
  87. }
  88. /**
  89. * @param {string} url
  90. */
  91. function closeCircuitBreaker(url) {
  92. lastFailures.delete(url) // The shard is back up.
  93. }
  94. /**
  95. * @param {Object} opts
  96. * @param {string} opts.projectId
  97. * @param {string} opts.userId
  98. * @param {string} opts.buildId
  99. * @param {string} opts.editorId
  100. * @param {[{path: string}]} opts.outputFiles
  101. * @param {string} opts.compileGroup
  102. * @param {Record<string, number>} opts.stats
  103. * @param {Record<string, number>} opts.timings
  104. * @param {Record<string, any>} opts.options
  105. * @return {string | undefined}
  106. */
  107. function notifyCLSICacheAboutBuild({
  108. projectId,
  109. userId,
  110. buildId,
  111. editorId,
  112. outputFiles,
  113. compileGroup,
  114. stats,
  115. timings,
  116. options,
  117. }) {
  118. if (!Settings.apis.clsiCache.enabled) return undefined
  119. if (!OBJECT_ID_REGEX.test(projectId)) return undefined
  120. const { url, shard } = getShard(projectId)
  121. if (isCircuitBreakerTripped(url)) return undefined
  122. /**
  123. * @param {{path: string}[]} files
  124. */
  125. const enqueue = files => {
  126. const body = Buffer.from(
  127. JSON.stringify({
  128. projectId,
  129. userId,
  130. buildId,
  131. editorId,
  132. files,
  133. downloadHost: Settings.apis.clsi.downloadHost,
  134. clsiServerId: Settings.apis.clsi.clsiServerId,
  135. compileGroup,
  136. stats,
  137. timings,
  138. options,
  139. })
  140. )
  141. const bodySize = body.byteLength
  142. if (bodySize > 10_000_000) {
  143. const outputPDF = files.find(f => f.path === 'output.pdf')
  144. logger.warn(
  145. {
  146. projectId,
  147. userId,
  148. bodySize,
  149. nFiles: files.length,
  150. outputPDFSize:
  151. outputPDF && Buffer.from(JSON.stringify(outputPDF)).byteLength,
  152. nPDFCachingRanges:
  153. outputPDF &&
  154. 'ranges' in outputPDF &&
  155. Array.isArray(outputPDF.ranges) &&
  156. outputPDF.ranges.length,
  157. },
  158. 'large clsi-cache request'
  159. )
  160. }
  161. Metrics.count('clsi_cache_enqueue_files', files.length)
  162. fetchNothing(`${url}/enqueue`, {
  163. method: 'POST',
  164. body,
  165. headers: { 'Content-Type': 'application/json' },
  166. signal: AbortSignal.timeout(TIMEOUT),
  167. })
  168. .then(() => {
  169. closeCircuitBreaker(url)
  170. })
  171. .catch(err => {
  172. tripCircuitBreaker(url)
  173. logger.warn(
  174. { err, projectId, userId, buildId },
  175. 'enqueue for clsi cache failed'
  176. )
  177. })
  178. }
  179. // PDF preview
  180. enqueue(
  181. outputFiles
  182. .filter(
  183. f =>
  184. f.path === 'output.pdf' ||
  185. f.path === 'output.log' ||
  186. f.path === 'output.synctex.gz'
  187. )
  188. .concat(
  189. outputFiles.filter(f => f.path.endsWith('.blg')).slice(0, MAX_BLG_FILES)
  190. )
  191. .map(f => {
  192. const lean = { path: f.path }
  193. if (f.path === 'output.pdf') {
  194. Object.assign(lean, _.pick(f, 'path', 'size', 'contentId', 'ranges'))
  195. }
  196. return lean
  197. })
  198. )
  199. // Compile Cache
  200. buildTarball({ projectId, userId, buildId, outputFiles })
  201. .then(() => {
  202. enqueue([{ path: 'output.tar.gz' }])
  203. })
  204. .catch(err => {
  205. logger.warn(
  206. { err, projectId, userId, buildId },
  207. 'build output.tar.gz for clsi cache failed'
  208. )
  209. })
  210. return shard
  211. }
  212. /**
  213. * @param {Object} opts
  214. * @param {string} opts.projectId
  215. * @param {string} opts.userId
  216. * @param {string} opts.buildId
  217. * @param {[{path: string}]} opts.outputFiles
  218. * @return {Promise<void>}
  219. */
  220. async function buildTarball({ projectId, userId, buildId, outputFiles }) {
  221. const timer = new Metrics.Timer('clsi_cache_build', 1, {}, TIMING_BUCKETS)
  222. const outputDir = Path.join(
  223. Settings.path.outputDir,
  224. userId ? `${projectId}-${userId}` : projectId,
  225. CACHE_SUBDIR,
  226. buildId
  227. )
  228. const files = outputFiles.filter(f => !isExtraneousFile(f.path))
  229. if (files.length > MAX_ENTRIES_IN_OUTPUT_TAR) {
  230. Metrics.inc('clsi_cache_build_too_many_entries')
  231. throw new Error('too many output files for output.tar.gz')
  232. }
  233. Metrics.count('clsi_cache_build_files', files.length)
  234. const path = Path.join(outputDir, 'output.tar.gz')
  235. try {
  236. await pipeline(
  237. tarFs.pack(outputDir, { entries: files.map(f => f.path) }),
  238. createGzip(),
  239. fs.createWriteStream(path)
  240. )
  241. } catch (err) {
  242. try {
  243. await fs.promises.unlink(path)
  244. } catch (e) {}
  245. throw err
  246. } finally {
  247. timer.done()
  248. }
  249. }
  250. /**
  251. * @param {string} projectId
  252. * @param {string} userId
  253. * @param {string} editorId
  254. * @param {string} buildId
  255. * @param {string} outputDir
  256. * @return {Promise<boolean>}
  257. */
  258. async function downloadOutputDotSynctexFromCompileCache(
  259. projectId,
  260. userId,
  261. editorId,
  262. buildId,
  263. outputDir
  264. ) {
  265. if (!Settings.apis.clsiCache.enabled) return false
  266. if (!OBJECT_ID_REGEX.test(projectId)) return false
  267. const { url } = getShard(projectId)
  268. if (isCircuitBreakerTripped(url)) return false
  269. const timer = new Metrics.Timer(
  270. 'clsi_cache_download',
  271. 1,
  272. { method: 'synctex' },
  273. TIMING_BUCKETS
  274. )
  275. let stream
  276. try {
  277. stream = await fetchStream(
  278. `${url}/project/${projectId}/${
  279. userId ? `user/${userId}/` : ''
  280. }build/${editorId}-${buildId}/search/output/output.synctex.gz`,
  281. {
  282. method: 'GET',
  283. signal: AbortSignal.timeout(TIMEOUT),
  284. }
  285. )
  286. } catch (err) {
  287. if (err instanceof RequestFailedError && err.response.status === 404) {
  288. closeCircuitBreaker(url)
  289. timer.done({ status: 'not-found' })
  290. return false
  291. }
  292. tripCircuitBreaker(url)
  293. timer.done({ status: 'error' })
  294. throw err
  295. }
  296. await fs.promises.mkdir(outputDir, { recursive: true })
  297. const dst = Path.join(outputDir, 'output.synctex.gz')
  298. const tmp = dst + crypto.randomUUID()
  299. try {
  300. await pipeline(
  301. stream,
  302. new MeteredStream(Metrics, 'clsi_cache_egress', {
  303. path: 'output.synctex.gz',
  304. }),
  305. fs.createWriteStream(tmp)
  306. )
  307. await fs.promises.rename(tmp, dst)
  308. } catch (err) {
  309. tripCircuitBreaker(url)
  310. try {
  311. await fs.promises.unlink(tmp)
  312. } catch {}
  313. throw err
  314. }
  315. closeCircuitBreaker(url)
  316. timer.done({ status: 'success' })
  317. return true
  318. }
  319. /**
  320. * @param {string} projectId
  321. * @param {string} userId
  322. * @param {string} compileDir
  323. * @return {Promise<boolean>}
  324. */
  325. async function downloadLatestCompileCache(projectId, userId, compileDir) {
  326. if (!Settings.apis.clsiCache.enabled) return false
  327. if (!OBJECT_ID_REGEX.test(projectId)) return false
  328. const { url } = getShard(projectId)
  329. if (isCircuitBreakerTripped(url)) return false
  330. const timer = new Metrics.Timer(
  331. 'clsi_cache_download',
  332. 1,
  333. { method: 'tar' },
  334. TIMING_BUCKETS
  335. )
  336. let stream
  337. try {
  338. stream = await fetchStream(
  339. `${url}/project/${projectId}/${
  340. userId ? `user/${userId}/` : ''
  341. }latest/output/output.tar.gz`,
  342. {
  343. method: 'GET',
  344. signal: AbortSignal.timeout(TIMEOUT),
  345. }
  346. )
  347. } catch (err) {
  348. if (err instanceof RequestFailedError && err.response.status === 404) {
  349. closeCircuitBreaker(url)
  350. timer.done({ status: 'not-found' })
  351. return false
  352. }
  353. tripCircuitBreaker(url)
  354. timer.done({ status: 'error' })
  355. throw err
  356. }
  357. let n = 0
  358. let abort = false
  359. try {
  360. await pipeline(
  361. stream,
  362. new MeteredStream(Metrics, 'clsi_cache_egress', {
  363. path: 'output.tar.gz',
  364. }),
  365. createGunzip(),
  366. tarFs.extract(compileDir, {
  367. // use ignore hook for counting entries (files+folders) and validation.
  368. // Include folders as they incur mkdir calls.
  369. ignore(_, header) {
  370. if (abort) return true // log once
  371. n++
  372. if (n > MAX_ENTRIES_IN_OUTPUT_TAR) {
  373. abort = true
  374. logger.warn(
  375. {
  376. projectId,
  377. userId,
  378. compileDir,
  379. },
  380. 'too many entries in tar-ball from clsi-cache'
  381. )
  382. } else if (header.type !== 'file' && header.type !== 'directory') {
  383. abort = true
  384. logger.warn(
  385. {
  386. projectId,
  387. userId,
  388. compileDir,
  389. entryType: header.type,
  390. },
  391. 'unexpected entry in tar-ball from clsi-cache'
  392. )
  393. }
  394. return abort
  395. },
  396. })
  397. )
  398. } catch (err) {
  399. tripCircuitBreaker(url)
  400. throw err
  401. }
  402. closeCircuitBreaker(url)
  403. Metrics.count('clsi_cache_download_entries', n)
  404. timer.done({ status: 'success' })
  405. return !abort
  406. }
  407. module.exports = {
  408. notifyCLSICacheAboutBuild,
  409. downloadLatestCompileCache,
  410. downloadOutputDotSynctexFromCompileCache,
  411. }