OutputCacheManager.js 21 KB

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