OutputCacheManager.js 21 KB

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