OutputCacheManager.js 18 KB

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