OutputCacheManager.js 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563
  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 { 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 TimedOutError) {
  278. logger.warn(
  279. { err, outputDir, stats, timings },
  280. 'pdf caching timed out'
  281. )
  282. stats['pdf-caching-timed-out'] = 1
  283. return callback(null, outputFiles)
  284. }
  285. if (err) return callback(err, outputFiles)
  286. const [contentRanges, newContentRanges, reclaimedSpace] = result
  287. if (Settings.enablePdfCachingDark) {
  288. // In dark mode we are doing the computation only and do not emit
  289. // any ranges to the frontend.
  290. } else {
  291. outputFile.contentId = Path.basename(contentDir)
  292. outputFile.ranges = contentRanges
  293. }
  294. timings['compute-pdf-caching'] = timer.done()
  295. stats['pdf-caching-n-ranges'] = contentRanges.length
  296. stats['pdf-caching-total-ranges-size'] = contentRanges.reduce(
  297. (sum, next) => sum + (next.end - next.start),
  298. 0
  299. )
  300. stats['pdf-caching-n-new-ranges'] = newContentRanges.length
  301. stats['pdf-caching-new-ranges-size'] = newContentRanges.reduce(
  302. (sum, next) => sum + (next.end - next.start),
  303. 0
  304. )
  305. stats['pdf-caching-reclaimed-space'] = reclaimedSpace
  306. callback(null, outputFiles)
  307. }
  308. )
  309. } else {
  310. callback(null, outputFiles)
  311. }
  312. })
  313. },
  314. ensureContentDir(contentRoot, callback) {
  315. fse.ensureDir(contentRoot, function (err) {
  316. if (err != null) {
  317. return callback(err)
  318. }
  319. fs.readdir(contentRoot, function (err, results) {
  320. const dirs = results.sort()
  321. const contentId = dirs.find(dir =>
  322. OutputCacheManager.BUILD_REGEX.test(dir)
  323. )
  324. if (contentId) {
  325. callback(null, Path.join(contentRoot, contentId))
  326. } else {
  327. // make a content directory
  328. OutputCacheManager.generateBuildId(function (err, contentId) {
  329. if (err) {
  330. return callback(err)
  331. }
  332. const contentDir = Path.join(contentRoot, contentId)
  333. fse.ensureDir(contentDir, function (err) {
  334. if (err) {
  335. return callback(err)
  336. }
  337. return callback(null, contentDir)
  338. })
  339. })
  340. }
  341. })
  342. })
  343. },
  344. archiveLogs(outputFiles, compileDir, outputDir, buildId, callback) {
  345. if (callback == null) {
  346. callback = function (error) {}
  347. }
  348. const archiveDir = Path.join(
  349. outputDir,
  350. OutputCacheManager.ARCHIVE_SUBDIR,
  351. buildId
  352. )
  353. logger.log({ dir: archiveDir }, 'archiving log files for project')
  354. return fse.ensureDir(archiveDir, function (err) {
  355. if (err != null) {
  356. return callback(err)
  357. }
  358. return async.mapSeries(
  359. outputFiles,
  360. function (file, cb) {
  361. const [src, dst] = Array.from([
  362. Path.join(compileDir, file.path),
  363. Path.join(archiveDir, file.path),
  364. ])
  365. return OutputCacheManager._checkFileIsSafe(
  366. src,
  367. function (err, isSafe) {
  368. if (err != null) {
  369. return cb(err)
  370. }
  371. if (!isSafe) {
  372. return cb()
  373. }
  374. return OutputCacheManager._checkIfShouldArchive(
  375. src,
  376. function (err, shouldArchive) {
  377. if (err != null) {
  378. return cb(err)
  379. }
  380. if (!shouldArchive) {
  381. return cb()
  382. }
  383. return OutputCacheManager._copyFile(src, dst, cb)
  384. }
  385. )
  386. }
  387. )
  388. },
  389. callback
  390. )
  391. })
  392. },
  393. expireOutputFiles(cacheRoot, options, callback) {
  394. // look in compileDir for build dirs and delete if > N or age of mod time > T
  395. if (callback == null) {
  396. callback = function (error) {}
  397. }
  398. return fs.readdir(cacheRoot, function (err, results) {
  399. if (err != null) {
  400. if (err.code === 'ENOENT') {
  401. return callback(null)
  402. } // cache directory is empty
  403. logger.error({ err, project_id: cacheRoot }, 'error clearing cache')
  404. return callback(err)
  405. }
  406. const dirs = results.sort().reverse()
  407. const currentTime = Date.now()
  408. const isExpired = function (dir, index) {
  409. if ((options != null ? options.keep : undefined) === dir) {
  410. return false
  411. }
  412. // remove any directories over the requested (non-null) limit
  413. if (
  414. (options != null ? options.limit : undefined) != null &&
  415. index > options.limit
  416. ) {
  417. return true
  418. }
  419. // remove any directories over the hard limit
  420. if (index > OutputCacheManager.CACHE_LIMIT) {
  421. return true
  422. }
  423. // we can get the build time from the first part of the directory name DDDD-RRRR
  424. // DDDD is date and RRRR is random bytes
  425. const dirTime = parseInt(
  426. __guard__(dir.split('-'), x => x[0]),
  427. 16
  428. )
  429. const age = currentTime - dirTime
  430. return age > OutputCacheManager.CACHE_AGE
  431. }
  432. const toRemove = _.filter(dirs, isExpired)
  433. const removeDir = (dir, cb) =>
  434. fse.remove(Path.join(cacheRoot, dir), function (err, result) {
  435. logger.log({ cache: cacheRoot, dir }, 'removed expired cache dir')
  436. if (err != null) {
  437. logger.error({ err, dir }, 'cache remove error')
  438. }
  439. return cb(err, result)
  440. })
  441. return async.eachSeries(
  442. toRemove,
  443. (dir, cb) => removeDir(dir, cb),
  444. callback
  445. )
  446. })
  447. },
  448. _fileIsHidden(path) {
  449. return (path != null ? path.match(/^\.|\/\./) : undefined) != null
  450. },
  451. _checkFileIsSafe(src, callback) {
  452. // check if we have a valid file to copy into the cache
  453. if (callback == null) {
  454. callback = function (error, isSafe) {}
  455. }
  456. return fs.stat(src, function (err, stats) {
  457. if ((err != null ? err.code : undefined) === 'ENOENT') {
  458. logger.warn(
  459. { err, file: src },
  460. 'file has disappeared before copying to build cache'
  461. )
  462. return callback(err, false)
  463. } else if (err != null) {
  464. // some other problem reading the file
  465. logger.error({ err, file: src }, 'stat error for file in cache')
  466. return callback(err, false)
  467. } else if (!stats.isFile()) {
  468. // other filetype - reject it
  469. logger.warn(
  470. { src, stat: stats },
  471. 'nonfile output - refusing to copy to cache'
  472. )
  473. return callback(null, false)
  474. } else {
  475. // it's a plain file, ok to copy
  476. return callback(null, true)
  477. }
  478. })
  479. },
  480. _copyFile(src, dst, callback) {
  481. // copy output file into the cache
  482. return fse.copy(src, dst, function (err) {
  483. if ((err != null ? err.code : undefined) === 'ENOENT') {
  484. logger.warn(
  485. { err, file: src },
  486. 'file has disappeared when copying to build cache'
  487. )
  488. return callback(err, false)
  489. } else if (err != null) {
  490. logger.error({ err, src, dst }, 'copy error for file in cache')
  491. return callback(err)
  492. } else {
  493. if (
  494. Settings.clsi != null ? Settings.clsi.optimiseInDocker : undefined
  495. ) {
  496. // don't run any optimisations on the pdf when they are done
  497. // in the docker container
  498. return callback()
  499. } else {
  500. // call the optimiser for the file too
  501. return OutputFileOptimiser.optimiseFile(src, dst, callback)
  502. }
  503. }
  504. })
  505. },
  506. _checkIfShouldCopy(src, callback) {
  507. if (callback == null) {
  508. callback = function (err, shouldCopy) {}
  509. }
  510. return callback(null, !Path.basename(src).match(/^strace/))
  511. },
  512. _checkIfShouldArchive(src, callback) {
  513. let needle
  514. if (callback == null) {
  515. callback = function (err, shouldCopy) {}
  516. }
  517. if (Path.basename(src).match(/^strace/)) {
  518. return callback(null, true)
  519. }
  520. if (
  521. (Settings.clsi != null ? Settings.clsi.archive_logs : undefined) &&
  522. ((needle = Path.basename(src)),
  523. ['output.log', 'output.blg'].includes(needle))
  524. ) {
  525. return callback(null, true)
  526. }
  527. return callback(null, false)
  528. },
  529. }
  530. function __guard__(value, transform) {
  531. return typeof value !== 'undefined' && value !== null
  532. ? transform(value)
  533. : undefined
  534. }