OutputCacheManager.js 17 KB

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