OutputCacheManager.js 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559
  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(src, function (
  176. err,
  177. isSafe
  178. ) {
  179. if (err != null) {
  180. return cb(err)
  181. }
  182. if (!isSafe) {
  183. return cb()
  184. }
  185. return OutputCacheManager._checkIfShouldCopy(src, function (
  186. err,
  187. shouldCopy
  188. ) {
  189. if (err != null) {
  190. return cb(err)
  191. }
  192. if (!shouldCopy) {
  193. return cb()
  194. }
  195. return OutputCacheManager._copyFile(src, dst, function (err) {
  196. if (err != null) {
  197. return cb(err)
  198. }
  199. newFile.build = buildId // attach a build id if we cached the file
  200. results.push(newFile)
  201. return cb()
  202. })
  203. })
  204. })
  205. },
  206. function (err) {
  207. if (err != null) {
  208. // pass back the original files if we encountered *any* error
  209. callback(err, outputFiles)
  210. // clean up the directory we just created
  211. return fse.remove(cacheDir, function (err) {
  212. if (err != null) {
  213. return logger.error(
  214. { err, dir: cacheDir },
  215. 'error removing cache dir after failure'
  216. )
  217. }
  218. })
  219. } else {
  220. // pass back the list of new files in the cache
  221. callback(err, results)
  222. // let file expiry run in the background, expire all previous files if per-user
  223. return OutputCacheManager.expireOutputFiles(cacheRoot, {
  224. keep: buildId,
  225. limit: perUser ? 1 : null
  226. })
  227. }
  228. }
  229. )
  230. }
  231. })
  232. },
  233. collectOutputPdfSize(outputFiles, outputDir, stats, callback) {
  234. const outputFile = outputFiles.find((x) => x.path === 'output.pdf')
  235. if (!outputFile) return callback(null, outputFiles)
  236. const outputFilePath = Path.join(
  237. outputDir,
  238. OutputCacheManager.path(outputFile.build, outputFile.path)
  239. )
  240. fs.stat(outputFilePath, (err, stat) => {
  241. if (err) return callback(err, outputFiles)
  242. outputFile.size = stat.size
  243. stats['pdf-size'] = outputFile.size
  244. callback(null, outputFiles)
  245. })
  246. },
  247. saveStreamsInContentDir(
  248. { stats, timings },
  249. outputFiles,
  250. compileDir,
  251. outputDir,
  252. callback
  253. ) {
  254. const cacheRoot = Path.join(outputDir, OutputCacheManager.CONTENT_SUBDIR)
  255. // check if content dir exists
  256. OutputCacheManager.ensureContentDir(cacheRoot, function (err, contentDir) {
  257. if (err) return callback(err, outputFiles)
  258. const outputFile = outputFiles.find((x) => x.path === 'output.pdf')
  259. if (outputFile) {
  260. // possibly we should copy the file from the build dir here
  261. const outputFilePath = Path.join(
  262. outputDir,
  263. OutputCacheManager.path(outputFile.build, outputFile.path)
  264. )
  265. const pdfSize = outputFile.size
  266. const timer = new Metrics.Timer('compute-pdf-ranges')
  267. ContentCacheManager.update(
  268. contentDir,
  269. outputFilePath,
  270. pdfSize,
  271. timings.compile,
  272. function (err, result) {
  273. if (err && err instanceof TimedOutError) {
  274. logger.warn(
  275. { err, outputDir, stats, timings },
  276. 'pdf caching timed out'
  277. )
  278. stats['pdf-caching-timed-out'] = 1
  279. return callback(null, outputFiles)
  280. }
  281. if (err) return callback(err, outputFiles)
  282. const [contentRanges, newContentRanges, reclaimedSpace] = result
  283. if (Settings.enablePdfCachingDark) {
  284. // In dark mode we are doing the computation only and do not emit
  285. // any ranges to the frontend.
  286. } else {
  287. outputFile.contentId = Path.basename(contentDir)
  288. outputFile.ranges = contentRanges
  289. }
  290. timings['compute-pdf-caching'] = timer.done()
  291. stats['pdf-caching-n-ranges'] = contentRanges.length
  292. stats['pdf-caching-total-ranges-size'] = contentRanges.reduce(
  293. (sum, next) => sum + (next.end - next.start),
  294. 0
  295. )
  296. stats['pdf-caching-n-new-ranges'] = newContentRanges.length
  297. stats['pdf-caching-new-ranges-size'] = newContentRanges.reduce(
  298. (sum, next) => sum + (next.end - next.start),
  299. 0
  300. )
  301. stats['pdf-caching-reclaimed-space'] = reclaimedSpace
  302. callback(null, outputFiles)
  303. }
  304. )
  305. } else {
  306. callback(null, outputFiles)
  307. }
  308. })
  309. },
  310. ensureContentDir(contentRoot, callback) {
  311. fse.ensureDir(contentRoot, function (err) {
  312. if (err != null) {
  313. return callback(err)
  314. }
  315. fs.readdir(contentRoot, function (err, results) {
  316. const dirs = results.sort()
  317. const contentId = dirs.find((dir) =>
  318. OutputCacheManager.BUILD_REGEX.test(dir)
  319. )
  320. if (contentId) {
  321. callback(null, Path.join(contentRoot, contentId))
  322. } else {
  323. // make a content directory
  324. OutputCacheManager.generateBuildId(function (err, contentId) {
  325. if (err) {
  326. return callback(err)
  327. }
  328. const contentDir = Path.join(contentRoot, contentId)
  329. fse.ensureDir(contentDir, function (err) {
  330. if (err) {
  331. return callback(err)
  332. }
  333. return callback(null, contentDir)
  334. })
  335. })
  336. }
  337. })
  338. })
  339. },
  340. archiveLogs(outputFiles, compileDir, outputDir, buildId, callback) {
  341. if (callback == null) {
  342. callback = function (error) {}
  343. }
  344. const archiveDir = Path.join(
  345. outputDir,
  346. OutputCacheManager.ARCHIVE_SUBDIR,
  347. buildId
  348. )
  349. logger.log({ dir: archiveDir }, 'archiving log files for project')
  350. return fse.ensureDir(archiveDir, function (err) {
  351. if (err != null) {
  352. return callback(err)
  353. }
  354. return async.mapSeries(
  355. outputFiles,
  356. function (file, cb) {
  357. const [src, dst] = Array.from([
  358. Path.join(compileDir, file.path),
  359. Path.join(archiveDir, file.path)
  360. ])
  361. return OutputCacheManager._checkFileIsSafe(src, function (
  362. err,
  363. isSafe
  364. ) {
  365. if (err != null) {
  366. return cb(err)
  367. }
  368. if (!isSafe) {
  369. return cb()
  370. }
  371. return OutputCacheManager._checkIfShouldArchive(src, function (
  372. err,
  373. shouldArchive
  374. ) {
  375. if (err != null) {
  376. return cb(err)
  377. }
  378. if (!shouldArchive) {
  379. return cb()
  380. }
  381. return OutputCacheManager._copyFile(src, dst, cb)
  382. })
  383. })
  384. },
  385. callback
  386. )
  387. })
  388. },
  389. expireOutputFiles(cacheRoot, options, callback) {
  390. // look in compileDir for build dirs and delete if > N or age of mod time > T
  391. if (callback == null) {
  392. callback = function (error) {}
  393. }
  394. return fs.readdir(cacheRoot, function (err, results) {
  395. if (err != null) {
  396. if (err.code === 'ENOENT') {
  397. return callback(null)
  398. } // cache directory is empty
  399. logger.error({ err, project_id: cacheRoot }, 'error clearing cache')
  400. return callback(err)
  401. }
  402. const dirs = results.sort().reverse()
  403. const currentTime = Date.now()
  404. const isExpired = function (dir, index) {
  405. if ((options != null ? options.keep : undefined) === dir) {
  406. return false
  407. }
  408. // remove any directories over the requested (non-null) limit
  409. if (
  410. (options != null ? options.limit : undefined) != null &&
  411. index > options.limit
  412. ) {
  413. return true
  414. }
  415. // remove any directories over the hard limit
  416. if (index > OutputCacheManager.CACHE_LIMIT) {
  417. return true
  418. }
  419. // we can get the build time from the first part of the directory name DDDD-RRRR
  420. // DDDD is date and RRRR is random bytes
  421. const dirTime = parseInt(
  422. __guard__(dir.split('-'), (x) => x[0]),
  423. 16
  424. )
  425. const age = currentTime - dirTime
  426. return age > OutputCacheManager.CACHE_AGE
  427. }
  428. const toRemove = _.filter(dirs, isExpired)
  429. const removeDir = (dir, cb) =>
  430. fse.remove(Path.join(cacheRoot, dir), function (err, result) {
  431. logger.log({ cache: cacheRoot, dir }, 'removed expired cache dir')
  432. if (err != null) {
  433. logger.error({ err, dir }, 'cache remove error')
  434. }
  435. return cb(err, result)
  436. })
  437. return async.eachSeries(
  438. toRemove,
  439. (dir, cb) => removeDir(dir, cb),
  440. callback
  441. )
  442. })
  443. },
  444. _fileIsHidden(path) {
  445. return (path != null ? path.match(/^\.|\/\./) : undefined) != null
  446. },
  447. _checkFileIsSafe(src, callback) {
  448. // check if we have a valid file to copy into the cache
  449. if (callback == null) {
  450. callback = function (error, isSafe) {}
  451. }
  452. return fs.stat(src, function (err, stats) {
  453. if ((err != null ? err.code : undefined) === 'ENOENT') {
  454. logger.warn(
  455. { err, file: src },
  456. 'file has disappeared before copying to build cache'
  457. )
  458. return callback(err, false)
  459. } else if (err != null) {
  460. // some other problem reading the file
  461. logger.error({ err, file: src }, 'stat error for file in cache')
  462. return callback(err, false)
  463. } else if (!stats.isFile()) {
  464. // other filetype - reject it
  465. logger.warn(
  466. { src, stat: stats },
  467. 'nonfile output - refusing to copy to cache'
  468. )
  469. return callback(null, false)
  470. } else {
  471. // it's a plain file, ok to copy
  472. return callback(null, true)
  473. }
  474. })
  475. },
  476. _copyFile(src, dst, callback) {
  477. // copy output file into the cache
  478. return fse.copy(src, dst, function (err) {
  479. if ((err != null ? err.code : undefined) === 'ENOENT') {
  480. logger.warn(
  481. { err, file: src },
  482. 'file has disappeared when copying to build cache'
  483. )
  484. return callback(err, false)
  485. } else if (err != null) {
  486. logger.error({ err, src, dst }, 'copy error for file in cache')
  487. return callback(err)
  488. } else {
  489. if (
  490. Settings.clsi != null ? Settings.clsi.optimiseInDocker : undefined
  491. ) {
  492. // don't run any optimisations on the pdf when they are done
  493. // in the docker container
  494. return callback()
  495. } else {
  496. // call the optimiser for the file too
  497. return OutputFileOptimiser.optimiseFile(src, dst, callback)
  498. }
  499. }
  500. })
  501. },
  502. _checkIfShouldCopy(src, callback) {
  503. if (callback == null) {
  504. callback = function (err, shouldCopy) {}
  505. }
  506. return callback(null, !Path.basename(src).match(/^strace/))
  507. },
  508. _checkIfShouldArchive(src, callback) {
  509. let needle
  510. if (callback == null) {
  511. callback = function (err, shouldCopy) {}
  512. }
  513. if (Path.basename(src).match(/^strace/)) {
  514. return callback(null, true)
  515. }
  516. if (
  517. (Settings.clsi != null ? Settings.clsi.archive_logs : undefined) &&
  518. ((needle = Path.basename(src)),
  519. ['output.log', 'output.blg'].includes(needle))
  520. ) {
  521. return callback(null, true)
  522. }
  523. return callback(null, false)
  524. }
  525. }
  526. function __guard__(value, transform) {
  527. return typeof value !== 'undefined' && value !== null
  528. ? transform(value)
  529. : undefined
  530. }