OutputCacheManager.js 18 KB

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