OutputCacheManager.js 21 KB

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