OutputCacheManager.js 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688
  1. import { callbackify, promisify } from 'node:util'
  2. import async from 'async'
  3. import fs from 'node:fs'
  4. import Path from 'node:path'
  5. import logger from '@overleaf/logger'
  6. import _ from 'lodash'
  7. import Settings from '@overleaf/settings'
  8. import crypto from 'node:crypto'
  9. import Metrics from '@overleaf/metrics'
  10. import OutputFileOptimiser from './OutputFileOptimiser.js'
  11. import ContentCacheManager from './ContentCacheManager.js'
  12. import {
  13. QueueLimitReachedError,
  14. TimedOutError,
  15. NoXrefTableError,
  16. } from './Errors.js'
  17. let OutputCacheManager
  18. const OLDEST_BUILD_DIR = new Map()
  19. const PENDING_PROJECT_ACTIONS = new Map()
  20. function init() {
  21. doInit().catch(err => {
  22. logger.fatal({ err }, 'low level error setting up cleanup of output dir')
  23. // consider shutting down?
  24. })
  25. }
  26. async function doInit() {
  27. await fillCache()
  28. const oldestTimestamp = await runBulkCleanup()
  29. scheduleBulkCleanup(oldestTimestamp)
  30. }
  31. function scheduleBulkCleanup(oldestTimestamp) {
  32. const delay =
  33. Math.max(OutputCacheManager.CACHE_AGE + oldestTimestamp - Date.now(), 0) +
  34. 60 * 1000
  35. setTimeout(async function () {
  36. const oldestTimestamp = await runBulkCleanup()
  37. scheduleBulkCleanup(oldestTimestamp)
  38. }, delay)
  39. }
  40. async function fillCache() {
  41. const handle = await fs.promises.opendir(Settings.path.outputDir)
  42. try {
  43. for await (const { name: projectIdAndUserId } of handle) {
  44. OLDEST_BUILD_DIR.set(
  45. Path.join(Settings.path.outputDir, projectIdAndUserId),
  46. // Queue them for cleanup in the next hour.
  47. Date.now() - Math.random() * OutputCacheManager.CACHE_AGE
  48. )
  49. }
  50. } finally {
  51. try {
  52. await handle.close()
  53. } catch (e) {}
  54. }
  55. }
  56. async function runBulkCleanup() {
  57. const cleanupThreshold = Date.now() - OutputCacheManager.CACHE_AGE
  58. let oldestTimestamp = Date.now()
  59. for (const [dir, timeStamp] of OLDEST_BUILD_DIR.entries()) {
  60. if (timeStamp < cleanupThreshold) {
  61. await cleanupDirectory(dir, { limit: OutputCacheManager.CACHE_LIMIT })
  62. } else if (timeStamp < oldestTimestamp) {
  63. oldestTimestamp = timeStamp
  64. }
  65. }
  66. return oldestTimestamp
  67. }
  68. async function cleanupDirectory(dir, options) {
  69. return await queueDirOperation(dir, async () => {
  70. try {
  71. await OutputCacheManager.promises.expireOutputFiles(dir, options)
  72. } catch (err) {
  73. logger.err({ dir, err }, 'cleanup of output directory failed')
  74. }
  75. })
  76. }
  77. /**
  78. * @template T
  79. *
  80. * @param {string} dir
  81. * @param {() => Promise<T>} fn
  82. * @return {Promise<T>}
  83. */
  84. async function queueDirOperation(dir, fn) {
  85. const pending = PENDING_PROJECT_ACTIONS.get(dir) || Promise.resolve()
  86. const p = pending.then(fn, fn).finally(() => {
  87. if (PENDING_PROJECT_ACTIONS.get(dir) === p) {
  88. PENDING_PROJECT_ACTIONS.delete(dir)
  89. }
  90. })
  91. PENDING_PROJECT_ACTIONS.set(dir, p)
  92. return p
  93. }
  94. export default OutputCacheManager = {
  95. CONTENT_SUBDIR: 'content',
  96. CACHE_SUBDIR: 'generated-files',
  97. ARCHIVE_SUBDIR: 'archived-logs',
  98. // build id is HEXDATE-HEXRANDOM from Date.now() and RandomBytes
  99. BUILD_REGEX: /^[0-9a-f]+-[0-9a-f]+$/,
  100. CONTENT_REGEX: /^[0-9a-f]+-[0-9a-f]+$/,
  101. CACHE_LIMIT: 2, // maximum number of cache directories
  102. CACHE_AGE: 90 * 60 * 1000, // up to 90 minutes old
  103. init,
  104. queueDirOperation: callbackify(queueDirOperation),
  105. path(buildId, file) {
  106. // used by static server, given build id return '.cache/clsi/buildId'
  107. if (buildId.match(OutputCacheManager.BUILD_REGEX)) {
  108. return Path.join(OutputCacheManager.CACHE_SUBDIR, buildId, file)
  109. } else {
  110. // for invalid build id, return top level
  111. return file
  112. }
  113. },
  114. generateBuildId(callback) {
  115. // generate a secure build id from Date.now() and 8 random bytes in hex
  116. crypto.randomBytes(8, function (err, buf) {
  117. if (err) {
  118. return callback(err)
  119. }
  120. const random = buf.toString('hex')
  121. const date = Date.now().toString(16)
  122. callback(err, `${date}-${random}`)
  123. })
  124. },
  125. saveOutputFiles(
  126. { request, stats, timings },
  127. outputFiles,
  128. compileDir,
  129. outputDir,
  130. callback
  131. ) {
  132. const getBuildId = cb => {
  133. if (request.buildId) return cb(null, request.buildId)
  134. OutputCacheManager.generateBuildId(cb)
  135. }
  136. getBuildId(function (err, buildId) {
  137. if (err) {
  138. return callback(err)
  139. }
  140. if (!OLDEST_BUILD_DIR.has(outputDir)) {
  141. // Register for cleanup
  142. OLDEST_BUILD_DIR.set(outputDir, Date.now())
  143. }
  144. OutputCacheManager.queueDirOperation(
  145. outputDir,
  146. () =>
  147. OutputCacheManager.promises.saveOutputFilesInBuildDir(
  148. outputFiles,
  149. compileDir,
  150. outputDir,
  151. buildId
  152. ),
  153. function (err, result) {
  154. if (err) {
  155. return callback(err)
  156. }
  157. OutputCacheManager.collectOutputPdfSize(
  158. result,
  159. outputDir,
  160. stats,
  161. (err, outputFiles) => {
  162. if (err) return callback(err, { outputFiles, buildId })
  163. const enablePdfCaching = request.enablePdfCaching
  164. const enablePdfCachingDark =
  165. Settings.enablePdfCachingDark && !request.enablePdfCaching
  166. if (
  167. !Settings.enablePdfCaching ||
  168. (!enablePdfCaching && !enablePdfCachingDark)
  169. ) {
  170. return callback(null, { outputFiles, buildId })
  171. }
  172. OutputCacheManager.saveStreamsInContentDir(
  173. { request, stats, timings, enablePdfCachingDark },
  174. outputFiles,
  175. compileDir,
  176. outputDir,
  177. (err, status) => {
  178. Metrics.inc('pdf-caching-status', 1, {
  179. status,
  180. ...request.metricsOpts,
  181. })
  182. if (err) {
  183. logger.warn(
  184. { err, outputDir, stats, timings },
  185. 'pdf caching failed'
  186. )
  187. return callback(null, { outputFiles, buildId })
  188. }
  189. callback(err, { outputFiles, buildId })
  190. }
  191. )
  192. }
  193. )
  194. }
  195. )
  196. })
  197. },
  198. saveOutputFilesInBuildDir(
  199. outputFiles,
  200. compileDir,
  201. outputDir,
  202. buildId,
  203. callback
  204. ) {
  205. // make a compileDir/CACHE_SUBDIR/build_id directory and
  206. // copy all the output files into it
  207. // Put the files into a new cache subdirectory
  208. const cacheDir = Path.join(
  209. outputDir,
  210. OutputCacheManager.CACHE_SUBDIR,
  211. buildId
  212. )
  213. // Is it a per-user compile? check if compile directory is PROJECTID-USERID
  214. const perUser = Path.basename(compileDir).match(
  215. /^[0-9a-f]{24}-[0-9a-f]{24}$/
  216. )
  217. // Archive logs in background
  218. if (Settings.clsi?.archive_logs || Settings.clsi?.strace) {
  219. OutputCacheManager.archiveLogs(
  220. outputFiles,
  221. compileDir,
  222. outputDir,
  223. buildId,
  224. function (err) {
  225. if (err) {
  226. return logger.warn({ err }, 'erroring archiving log files')
  227. }
  228. }
  229. )
  230. }
  231. // make the new cache directory
  232. fs.mkdir(cacheDir, { recursive: true }, function (err) {
  233. if (err) {
  234. logger.error(
  235. { err, directory: cacheDir },
  236. 'error creating cache directory'
  237. )
  238. callback(err)
  239. } else {
  240. // copy all the output files into the new cache directory
  241. const results = []
  242. const dirCache = new Set()
  243. dirCache.add(cacheDir)
  244. async.mapSeries(
  245. outputFiles,
  246. function (file, cb) {
  247. // don't send dot files as output, express doesn't serve them
  248. if (OutputCacheManager._fileIsHidden(file.path)) {
  249. logger.debug(
  250. { compileDir, path: file.path },
  251. 'ignoring dotfile in output'
  252. )
  253. return cb()
  254. }
  255. // copy other files into cache directory if valid
  256. const src = Path.join(compileDir, file.path)
  257. const dst = Path.join(cacheDir, file.path)
  258. OutputCacheManager._checkIfShouldCopy(
  259. src,
  260. function (err, shouldCopy) {
  261. if (err) {
  262. return cb(err)
  263. }
  264. if (!shouldCopy) {
  265. return cb()
  266. }
  267. OutputCacheManager._copyFile(src, dst, dirCache, err => {
  268. if (err) {
  269. return cb(err)
  270. }
  271. file.build = buildId
  272. results.push(file)
  273. cb()
  274. })
  275. }
  276. )
  277. },
  278. function (err) {
  279. if (err) {
  280. callback(err)
  281. // clean up the directory we just created
  282. fs.rm(cacheDir, { force: true, recursive: true }, function (err) {
  283. if (err) {
  284. return logger.error(
  285. { err, dir: cacheDir },
  286. 'error removing cache dir after failure'
  287. )
  288. }
  289. })
  290. } else {
  291. // pass back the list of new files in the cache
  292. callback(null, results)
  293. // let file expiry run in the background, expire all previous files if per-user
  294. cleanupDirectory(outputDir, {
  295. keep: buildId,
  296. limit: perUser ? 1 : null,
  297. }).catch(() => {})
  298. }
  299. }
  300. )
  301. }
  302. })
  303. },
  304. collectOutputPdfSize(outputFiles, outputDir, stats, callback) {
  305. const outputFile = outputFiles.find(x => x.path === 'output.pdf')
  306. if (!outputFile) return callback(null, outputFiles)
  307. const outputFilePath = Path.join(
  308. outputDir,
  309. OutputCacheManager.path(outputFile.build, outputFile.path)
  310. )
  311. fs.stat(outputFilePath, (err, stat) => {
  312. if (err) return callback(err, outputFiles)
  313. outputFile.size = stat.size
  314. stats['pdf-size'] = outputFile.size
  315. callback(null, outputFiles)
  316. })
  317. },
  318. saveStreamsInContentDir(
  319. { request, stats, timings, enablePdfCachingDark },
  320. outputFiles,
  321. compileDir,
  322. outputDir,
  323. callback
  324. ) {
  325. const cacheRoot = Path.join(outputDir, OutputCacheManager.CONTENT_SUBDIR)
  326. // check if content dir exists
  327. OutputCacheManager.ensureContentDir(cacheRoot, function (err, contentDir) {
  328. if (err) return callback(err, 'content-dir-unavailable')
  329. const outputFile = outputFiles.find(x => x.path === 'output.pdf')
  330. if (outputFile) {
  331. // possibly we should copy the file from the build dir here
  332. const outputFilePath = Path.join(
  333. outputDir,
  334. OutputCacheManager.path(outputFile.build, outputFile.path)
  335. )
  336. const pdfSize = outputFile.size
  337. const timer = new Metrics.Timer(
  338. 'compute-pdf-ranges',
  339. 1,
  340. request.metricsOpts
  341. )
  342. ContentCacheManager.update(
  343. {
  344. contentDir,
  345. filePath: outputFilePath,
  346. pdfSize,
  347. pdfCachingMinChunkSize: request.pdfCachingMinChunkSize,
  348. compileTime: timings.compile,
  349. },
  350. function (err, result) {
  351. if (err && err instanceof NoXrefTableError) {
  352. return callback(null, err.message)
  353. }
  354. if (err && err instanceof QueueLimitReachedError) {
  355. logger.warn({ err, outputDir }, 'pdf caching queue limit reached')
  356. stats['pdf-caching-queue-limit-reached'] = 1
  357. return callback(null, 'queue-limit')
  358. }
  359. if (err && err instanceof TimedOutError) {
  360. logger.warn(
  361. { err, outputDir, stats, timings },
  362. 'pdf caching timed out'
  363. )
  364. stats['pdf-caching-timed-out'] = 1
  365. return callback(null, 'timed-out')
  366. }
  367. if (err) return callback(err, 'failed')
  368. const {
  369. contentRanges,
  370. newContentRanges,
  371. reclaimedSpace,
  372. overheadDeleteStaleHashes,
  373. timedOutErr,
  374. startXRefTable,
  375. } = result
  376. let status = 'success'
  377. if (timedOutErr) {
  378. // Soft failure: let the frontend use partial set of ranges.
  379. logger.warn(
  380. {
  381. err: timedOutErr,
  382. overheadDeleteStaleHashes,
  383. outputDir,
  384. stats,
  385. timings,
  386. },
  387. 'pdf caching timed out - soft failure'
  388. )
  389. stats['pdf-caching-timed-out'] = 1
  390. status = 'timed-out-soft-failure'
  391. }
  392. if (enablePdfCachingDark) {
  393. // In dark mode we are doing the computation only and do not emit
  394. // any ranges to the frontend.
  395. } else {
  396. outputFile.contentId = Path.basename(contentDir)
  397. outputFile.ranges = contentRanges
  398. outputFile.startXRefTable = startXRefTable
  399. }
  400. timings['compute-pdf-caching'] = timer.done()
  401. stats['pdf-caching-n-ranges'] = contentRanges.length
  402. stats['pdf-caching-total-ranges-size'] = contentRanges.reduce(
  403. (sum, next) => sum + (next.end - next.start),
  404. 0
  405. )
  406. stats['pdf-caching-n-new-ranges'] = newContentRanges.length
  407. stats['pdf-caching-new-ranges-size'] = newContentRanges.reduce(
  408. (sum, next) => sum + (next.end - next.start),
  409. 0
  410. )
  411. stats['pdf-caching-reclaimed-space'] = reclaimedSpace
  412. timings['pdf-caching-overhead-delete-stale-hashes'] =
  413. overheadDeleteStaleHashes
  414. callback(null, status)
  415. }
  416. )
  417. } else {
  418. callback(null, 'missing-pdf')
  419. }
  420. })
  421. },
  422. ensureContentDir(contentRoot, callback) {
  423. fs.mkdir(contentRoot, { recursive: true }, function (err) {
  424. if (err) {
  425. return callback(err)
  426. }
  427. fs.readdir(contentRoot, function (err, results) {
  428. if (err) return callback(err)
  429. const dirs = results.sort()
  430. const contentId = dirs.find(dir =>
  431. OutputCacheManager.BUILD_REGEX.test(dir)
  432. )
  433. if (contentId) {
  434. callback(null, Path.join(contentRoot, contentId))
  435. } else {
  436. // make a content directory
  437. OutputCacheManager.generateBuildId(function (err, contentId) {
  438. if (err) {
  439. return callback(err)
  440. }
  441. const contentDir = Path.join(contentRoot, contentId)
  442. fs.mkdir(contentDir, { recursive: true }, function (err) {
  443. if (err) {
  444. return callback(err)
  445. }
  446. callback(null, contentDir)
  447. })
  448. })
  449. }
  450. })
  451. })
  452. },
  453. archiveLogs(outputFiles, compileDir, outputDir, buildId, callback) {
  454. const archiveDir = Path.join(
  455. outputDir,
  456. OutputCacheManager.ARCHIVE_SUBDIR,
  457. buildId
  458. )
  459. logger.debug({ dir: archiveDir }, 'archiving log files for project')
  460. fs.mkdir(archiveDir, { recursive: true }, function (err) {
  461. if (err) {
  462. return callback(err)
  463. }
  464. const dirCache = new Set()
  465. dirCache.add(archiveDir)
  466. async.mapSeries(
  467. outputFiles,
  468. function (file, cb) {
  469. const src = Path.join(compileDir, file.path)
  470. const dst = Path.join(archiveDir, file.path)
  471. OutputCacheManager._checkIfShouldArchive(
  472. src,
  473. function (err, shouldArchive) {
  474. if (err) {
  475. return cb(err)
  476. }
  477. if (!shouldArchive) {
  478. return cb()
  479. }
  480. OutputCacheManager._copyFile(src, dst, dirCache, cb)
  481. }
  482. )
  483. },
  484. callback
  485. )
  486. })
  487. },
  488. expireOutputFiles(outputDir, options, callback) {
  489. // look in compileDir for build dirs and delete if > N or age of mod time > T
  490. const cleanupAll = cb => {
  491. fs.rm(outputDir, { force: true, recursive: true }, err => {
  492. if (err) {
  493. return cb(err)
  494. }
  495. // Drop reference after successful cleanup of the output dir.
  496. OLDEST_BUILD_DIR.delete(outputDir)
  497. cb(null)
  498. })
  499. }
  500. const cacheRoot = Path.join(outputDir, OutputCacheManager.CACHE_SUBDIR)
  501. fs.readdir(cacheRoot, function (err, results) {
  502. if (err) {
  503. if (err.code === 'ENOENT') {
  504. // cache directory is empty
  505. return cleanupAll(callback)
  506. }
  507. logger.error({ err, projectId: cacheRoot }, 'error clearing cache')
  508. return callback(err)
  509. }
  510. const dirs = results.sort().reverse()
  511. const currentTime = Date.now()
  512. let oldestDirTimeToKeep = 0
  513. const isExpired = function (dir, index) {
  514. if (options?.keep === dir) {
  515. // This is the directory we just created for the compile request.
  516. oldestDirTimeToKeep = currentTime
  517. return false
  518. }
  519. // remove any directories over the requested (non-null) limit
  520. if (options?.limit != null && index > options.limit) {
  521. return true
  522. }
  523. // remove any directories over the hard limit
  524. if (index > OutputCacheManager.CACHE_LIMIT) {
  525. return true
  526. }
  527. // we can get the build time from the first part of the directory name DDDD-RRRR
  528. // DDDD is date and RRRR is random bytes
  529. const dirTime = parseInt(dir.split('-')[0], 16)
  530. const age = currentTime - dirTime
  531. const expired = age > OutputCacheManager.CACHE_AGE
  532. if (expired) {
  533. return true
  534. }
  535. oldestDirTimeToKeep = dirTime
  536. return false
  537. }
  538. const toRemove = _.filter(dirs, isExpired)
  539. if (toRemove.length === dirs.length) {
  540. // No builds left after cleanup.
  541. return cleanupAll(callback)
  542. }
  543. const removeDir = (dir, cb) =>
  544. fs.rm(
  545. Path.join(cacheRoot, dir),
  546. { force: true, recursive: true },
  547. function (err, result) {
  548. logger.debug({ cache: cacheRoot, dir }, 'removed expired cache dir')
  549. if (err) {
  550. logger.error({ err, dir }, 'cache remove error')
  551. }
  552. cb(err, result)
  553. }
  554. )
  555. async.eachSeries(
  556. toRemove,
  557. (dir, cb) => removeDir(dir, cb),
  558. err => {
  559. if (err) {
  560. // On error: keep the timestamp in the past.
  561. // The next iteration of the cleanup loop will retry the deletion.
  562. return callback(err)
  563. }
  564. // On success: push the timestamp into the future.
  565. OLDEST_BUILD_DIR.set(outputDir, oldestDirTimeToKeep)
  566. callback(null)
  567. }
  568. )
  569. })
  570. },
  571. _fileIsHidden(path) {
  572. return path?.match(/^\.|\/\./) != null
  573. },
  574. _ensureParentExists(dst, dirCache, callback) {
  575. let parent = Path.dirname(dst)
  576. if (dirCache.has(parent)) {
  577. callback()
  578. } else {
  579. fs.mkdir(parent, { recursive: true }, err => {
  580. if (err) return callback(err)
  581. while (!dirCache.has(parent)) {
  582. dirCache.add(parent)
  583. parent = Path.dirname(parent)
  584. }
  585. callback()
  586. })
  587. }
  588. },
  589. _copyFile(src, dst, dirCache, callback) {
  590. OutputCacheManager._ensureParentExists(dst, dirCache, err => {
  591. if (err) {
  592. logger.warn(
  593. { err, dst },
  594. 'creating parent directory in output cache failed'
  595. )
  596. return callback(err, false)
  597. }
  598. // copy output file into the cache
  599. fs.copyFile(src, dst, function (err) {
  600. if (err?.code === 'ENOENT') {
  601. logger.warn(
  602. { err, file: src },
  603. 'file has disappeared when copying to build cache'
  604. )
  605. callback(err, false)
  606. } else if (err) {
  607. logger.error({ err, src, dst }, 'copy error for file in cache')
  608. callback(err)
  609. } else {
  610. if (Settings.clsi?.optimiseInDocker) {
  611. // don't run any optimisations on the pdf when they are done
  612. // in the docker container
  613. callback()
  614. } else {
  615. // call the optimiser for the file too
  616. OutputFileOptimiser.optimiseFile(src, dst, callback)
  617. }
  618. }
  619. })
  620. })
  621. },
  622. _checkIfShouldCopy(src, callback) {
  623. callback(null, !Path.basename(src).match(/^strace/))
  624. },
  625. _checkIfShouldArchive(src, callback) {
  626. if (Path.basename(src).match(/^strace/)) {
  627. return callback(null, true)
  628. }
  629. const basename = Path.basename(src)
  630. if (
  631. Settings.clsi?.archive_logs &&
  632. ['output.log', 'output.blg'].includes(basename)
  633. ) {
  634. return callback(null, true)
  635. }
  636. callback(null, false)
  637. },
  638. }
  639. OutputCacheManager.promises = {
  640. expireOutputFiles: promisify(OutputCacheManager.expireOutputFiles),
  641. saveOutputFiles: promisify(OutputCacheManager.saveOutputFiles),
  642. saveOutputFilesInBuildDir: promisify(
  643. OutputCacheManager.saveOutputFilesInBuildDir
  644. ),
  645. queueDirOperation,
  646. generateBuildId: promisify(OutputCacheManager.generateBuildId),
  647. }