OutputCacheManager.js 23 KB

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