OutputCacheManager.js 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677
  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: 90 * 60 * 1000, // up to 90 minutes 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)
  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 src = Path.join(compileDir, file.path)
  247. const dst = Path.join(cacheDir, file.path)
  248. OutputCacheManager._checkIfShouldCopy(
  249. src,
  250. function (err, shouldCopy) {
  251. if (err) {
  252. return cb(err)
  253. }
  254. if (!shouldCopy) {
  255. return cb()
  256. }
  257. OutputCacheManager._copyFile(src, dst, dirCache, err => {
  258. if (err) {
  259. return cb(err)
  260. }
  261. file.build = buildId
  262. results.push(file)
  263. cb()
  264. })
  265. }
  266. )
  267. },
  268. function (err) {
  269. if (err) {
  270. callback(err)
  271. // clean up the directory we just created
  272. fs.rm(cacheDir, { force: true, recursive: true }, function (err) {
  273. if (err) {
  274. return logger.error(
  275. { err, dir: cacheDir },
  276. 'error removing cache dir after failure'
  277. )
  278. }
  279. })
  280. } else {
  281. // pass back the list of new files in the cache
  282. callback(null, results)
  283. // let file expiry run in the background, expire all previous files if per-user
  284. cleanupDirectory(outputDir, {
  285. keep: buildId,
  286. limit: perUser ? 1 : null,
  287. }).catch(() => {})
  288. }
  289. }
  290. )
  291. }
  292. })
  293. },
  294. collectOutputPdfSize(outputFiles, outputDir, stats, callback) {
  295. const outputFile = outputFiles.find(x => x.path === 'output.pdf')
  296. if (!outputFile) return callback(null, outputFiles)
  297. const outputFilePath = Path.join(
  298. outputDir,
  299. OutputCacheManager.path(outputFile.build, outputFile.path)
  300. )
  301. fs.stat(outputFilePath, (err, stat) => {
  302. if (err) return callback(err, outputFiles)
  303. outputFile.size = stat.size
  304. stats['pdf-size'] = outputFile.size
  305. callback(null, outputFiles)
  306. })
  307. },
  308. saveStreamsInContentDir(
  309. { request, stats, timings, enablePdfCachingDark },
  310. outputFiles,
  311. compileDir,
  312. outputDir,
  313. callback
  314. ) {
  315. const cacheRoot = Path.join(outputDir, OutputCacheManager.CONTENT_SUBDIR)
  316. // check if content dir exists
  317. OutputCacheManager.ensureContentDir(cacheRoot, function (err, contentDir) {
  318. if (err) return callback(err, 'content-dir-unavailable')
  319. const outputFile = outputFiles.find(x => x.path === 'output.pdf')
  320. if (outputFile) {
  321. // possibly we should copy the file from the build dir here
  322. const outputFilePath = Path.join(
  323. outputDir,
  324. OutputCacheManager.path(outputFile.build, outputFile.path)
  325. )
  326. const pdfSize = outputFile.size
  327. const timer = new Metrics.Timer(
  328. 'compute-pdf-ranges',
  329. 1,
  330. request.metricsOpts
  331. )
  332. ContentCacheManager.update(
  333. {
  334. contentDir,
  335. filePath: outputFilePath,
  336. pdfSize,
  337. pdfCachingMinChunkSize: request.pdfCachingMinChunkSize,
  338. compileTime: timings.compile,
  339. },
  340. function (err, result) {
  341. if (err && err instanceof NoXrefTableError) {
  342. return callback(null, err.message)
  343. }
  344. if (err && err instanceof QueueLimitReachedError) {
  345. logger.warn({ err, outputDir }, 'pdf caching queue limit reached')
  346. stats['pdf-caching-queue-limit-reached'] = 1
  347. return callback(null, 'queue-limit')
  348. }
  349. if (err && err instanceof TimedOutError) {
  350. logger.warn(
  351. { err, outputDir, stats, timings },
  352. 'pdf caching timed out'
  353. )
  354. stats['pdf-caching-timed-out'] = 1
  355. return callback(null, 'timed-out')
  356. }
  357. if (err) return callback(err, 'failed')
  358. const {
  359. contentRanges,
  360. newContentRanges,
  361. reclaimedSpace,
  362. overheadDeleteStaleHashes,
  363. timedOutErr,
  364. startXRefTable,
  365. } = result
  366. let status = 'success'
  367. if (timedOutErr) {
  368. // Soft failure: let the frontend use partial set of ranges.
  369. logger.warn(
  370. {
  371. err: timedOutErr,
  372. overheadDeleteStaleHashes,
  373. outputDir,
  374. stats,
  375. timings,
  376. },
  377. 'pdf caching timed out - soft failure'
  378. )
  379. stats['pdf-caching-timed-out'] = 1
  380. status = 'timed-out-soft-failure'
  381. }
  382. if (enablePdfCachingDark) {
  383. // In dark mode we are doing the computation only and do not emit
  384. // any ranges to the frontend.
  385. } else {
  386. outputFile.contentId = Path.basename(contentDir)
  387. outputFile.ranges = contentRanges
  388. outputFile.startXRefTable = startXRefTable
  389. }
  390. timings['compute-pdf-caching'] = timer.done()
  391. stats['pdf-caching-n-ranges'] = contentRanges.length
  392. stats['pdf-caching-total-ranges-size'] = contentRanges.reduce(
  393. (sum, next) => sum + (next.end - next.start),
  394. 0
  395. )
  396. stats['pdf-caching-n-new-ranges'] = newContentRanges.length
  397. stats['pdf-caching-new-ranges-size'] = newContentRanges.reduce(
  398. (sum, next) => sum + (next.end - next.start),
  399. 0
  400. )
  401. stats['pdf-caching-reclaimed-space'] = reclaimedSpace
  402. timings['pdf-caching-overhead-delete-stale-hashes'] =
  403. overheadDeleteStaleHashes
  404. callback(null, status)
  405. }
  406. )
  407. } else {
  408. callback(null, 'missing-pdf')
  409. }
  410. })
  411. },
  412. ensureContentDir(contentRoot, callback) {
  413. fs.mkdir(contentRoot, { recursive: true }, function (err) {
  414. if (err) {
  415. return callback(err)
  416. }
  417. fs.readdir(contentRoot, function (err, results) {
  418. if (err) return callback(err)
  419. const dirs = results.sort()
  420. const contentId = dirs.find(dir =>
  421. OutputCacheManager.BUILD_REGEX.test(dir)
  422. )
  423. if (contentId) {
  424. callback(null, Path.join(contentRoot, contentId))
  425. } else {
  426. // make a content directory
  427. OutputCacheManager.generateBuildId(function (err, contentId) {
  428. if (err) {
  429. return callback(err)
  430. }
  431. const contentDir = Path.join(contentRoot, contentId)
  432. fs.mkdir(contentDir, { recursive: true }, function (err) {
  433. if (err) {
  434. return callback(err)
  435. }
  436. callback(null, contentDir)
  437. })
  438. })
  439. }
  440. })
  441. })
  442. },
  443. archiveLogs(outputFiles, compileDir, outputDir, buildId, callback) {
  444. const archiveDir = Path.join(
  445. outputDir,
  446. OutputCacheManager.ARCHIVE_SUBDIR,
  447. buildId
  448. )
  449. logger.debug({ dir: archiveDir }, 'archiving log files for project')
  450. fs.mkdir(archiveDir, { recursive: true }, function (err) {
  451. if (err) {
  452. return callback(err)
  453. }
  454. const dirCache = new Set()
  455. dirCache.add(archiveDir)
  456. async.mapSeries(
  457. outputFiles,
  458. function (file, cb) {
  459. const src = Path.join(compileDir, file.path)
  460. const dst = Path.join(archiveDir, file.path)
  461. OutputCacheManager._checkIfShouldArchive(
  462. src,
  463. function (err, shouldArchive) {
  464. if (err) {
  465. return cb(err)
  466. }
  467. if (!shouldArchive) {
  468. return cb()
  469. }
  470. OutputCacheManager._copyFile(src, dst, dirCache, cb)
  471. }
  472. )
  473. },
  474. callback
  475. )
  476. })
  477. },
  478. expireOutputFiles(outputDir, options, callback) {
  479. // look in compileDir for build dirs and delete if > N or age of mod time > T
  480. const cleanupAll = cb => {
  481. fs.rm(outputDir, { force: true, recursive: true }, err => {
  482. if (err) {
  483. return cb(err)
  484. }
  485. // Drop reference after successful cleanup of the output dir.
  486. OLDEST_BUILD_DIR.delete(outputDir)
  487. cb(null)
  488. })
  489. }
  490. const cacheRoot = Path.join(outputDir, OutputCacheManager.CACHE_SUBDIR)
  491. fs.readdir(cacheRoot, function (err, results) {
  492. if (err) {
  493. if (err.code === 'ENOENT') {
  494. // cache directory is empty
  495. return cleanupAll(callback)
  496. }
  497. logger.error({ err, projectId: cacheRoot }, 'error clearing cache')
  498. return callback(err)
  499. }
  500. const dirs = results.sort().reverse()
  501. const currentTime = Date.now()
  502. let oldestDirTimeToKeep = 0
  503. const isExpired = function (dir, index) {
  504. if (options?.keep === dir) {
  505. // This is the directory we just created for the compile request.
  506. oldestDirTimeToKeep = currentTime
  507. return false
  508. }
  509. // remove any directories over the requested (non-null) limit
  510. if (options?.limit != null && index > options.limit) {
  511. return true
  512. }
  513. // remove any directories over the hard limit
  514. if (index > OutputCacheManager.CACHE_LIMIT) {
  515. return true
  516. }
  517. // we can get the build time from the first part of the directory name DDDD-RRRR
  518. // DDDD is date and RRRR is random bytes
  519. const dirTime = parseInt(dir.split('-')[0], 16)
  520. const age = currentTime - dirTime
  521. const expired = age > OutputCacheManager.CACHE_AGE
  522. if (expired) {
  523. return true
  524. }
  525. oldestDirTimeToKeep = dirTime
  526. return false
  527. }
  528. const toRemove = _.filter(dirs, isExpired)
  529. if (toRemove.length === dirs.length) {
  530. // No builds left after cleanup.
  531. return cleanupAll(callback)
  532. }
  533. const removeDir = (dir, cb) =>
  534. fs.rm(
  535. Path.join(cacheRoot, dir),
  536. { force: true, recursive: true },
  537. function (err, result) {
  538. logger.debug({ cache: cacheRoot, dir }, 'removed expired cache dir')
  539. if (err) {
  540. logger.error({ err, dir }, 'cache remove error')
  541. }
  542. cb(err, result)
  543. }
  544. )
  545. async.eachSeries(
  546. toRemove,
  547. (dir, cb) => removeDir(dir, cb),
  548. err => {
  549. if (err) {
  550. // On error: keep the timestamp in the past.
  551. // The next iteration of the cleanup loop will retry the deletion.
  552. return callback(err)
  553. }
  554. // On success: push the timestamp into the future.
  555. OLDEST_BUILD_DIR.set(outputDir, oldestDirTimeToKeep)
  556. callback(null)
  557. }
  558. )
  559. })
  560. },
  561. _fileIsHidden(path) {
  562. return path?.match(/^\.|\/\./) != null
  563. },
  564. _ensureParentExists(dst, dirCache, callback) {
  565. let parent = Path.dirname(dst)
  566. if (dirCache.has(parent)) {
  567. callback()
  568. } else {
  569. fs.mkdir(parent, { recursive: true }, err => {
  570. if (err) return callback(err)
  571. while (!dirCache.has(parent)) {
  572. dirCache.add(parent)
  573. parent = Path.dirname(parent)
  574. }
  575. callback()
  576. })
  577. }
  578. },
  579. _copyFile(src, dst, dirCache, callback) {
  580. OutputCacheManager._ensureParentExists(dst, dirCache, err => {
  581. if (err) {
  582. logger.warn(
  583. { err, dst },
  584. 'creating parent directory in output cache failed'
  585. )
  586. return callback(err, false)
  587. }
  588. // copy output file into the cache
  589. fs.copyFile(src, dst, function (err) {
  590. if (err?.code === 'ENOENT') {
  591. logger.warn(
  592. { err, file: src },
  593. 'file has disappeared when copying to build cache'
  594. )
  595. callback(err, false)
  596. } else if (err) {
  597. logger.error({ err, src, dst }, 'copy error for file in cache')
  598. callback(err)
  599. } else {
  600. if (Settings.clsi?.optimiseInDocker) {
  601. // don't run any optimisations on the pdf when they are done
  602. // in the docker container
  603. callback()
  604. } else {
  605. // call the optimiser for the file too
  606. OutputFileOptimiser.optimiseFile(src, dst, callback)
  607. }
  608. }
  609. })
  610. })
  611. },
  612. _checkIfShouldCopy(src, callback) {
  613. callback(null, !Path.basename(src).match(/^strace/))
  614. },
  615. _checkIfShouldArchive(src, callback) {
  616. if (Path.basename(src).match(/^strace/)) {
  617. return callback(null, true)
  618. }
  619. const basename = Path.basename(src)
  620. if (
  621. Settings.clsi?.archive_logs &&
  622. ['output.log', 'output.blg'].includes(basename)
  623. ) {
  624. return callback(null, true)
  625. }
  626. callback(null, false)
  627. },
  628. }
  629. OutputCacheManager.promises = {
  630. expireOutputFiles: promisify(OutputCacheManager.expireOutputFiles),
  631. saveOutputFiles: promisify(OutputCacheManager.saveOutputFiles),
  632. saveOutputFilesInBuildDir: promisify(
  633. OutputCacheManager.saveOutputFilesInBuildDir
  634. ),
  635. }