CompileManager.js 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775
  1. const fsPromises = require('node:fs/promises')
  2. const os = require('node:os')
  3. const Path = require('node:path')
  4. const { callbackify } = require('node:util')
  5. const Settings = require('@overleaf/settings')
  6. const logger = require('@overleaf/logger')
  7. const OError = require('@overleaf/o-error')
  8. const ResourceWriter = require('./ResourceWriter')
  9. const LatexRunner = require('./LatexRunner')
  10. const OutputFileFinder = require('./OutputFileFinder')
  11. const OutputCacheManager = require('./OutputCacheManager')
  12. const Metrics = require('./Metrics')
  13. const DraftModeManager = require('./DraftModeManager')
  14. const TikzManager = require('./TikzManager')
  15. const LockManager = require('./LockManager')
  16. const Errors = require('./Errors')
  17. const CommandRunner = require('./CommandRunner')
  18. const { emitPdfStats } = require('./ContentCacheMetrics')
  19. const SynctexOutputParser = require('./SynctexOutputParser')
  20. const {
  21. downloadLatestCompileCache,
  22. downloadOutputDotSynctexFromCompileCache,
  23. } = require('./CLSICacheHandler')
  24. const StatsManager = require('./StatsManager')
  25. const { callbackifyMultiResult } = require('@overleaf/promise-utils')
  26. const COMPILE_TIME_BUCKETS = [
  27. // NOTE: These buckets are locked in per metric name.
  28. // If you want to change them, you will need to rename metrics.
  29. 0, 1, 2, 3, 4, 6, 8, 11, 15, 22, 31, 43, 61, 86, 121, 170, 240,
  30. ].map(seconds => seconds * 1000)
  31. function getCompileName(projectId, userId) {
  32. if (userId != null) {
  33. return `${projectId}-${userId}`
  34. } else {
  35. return projectId
  36. }
  37. }
  38. function getCompileDir(projectId, userId) {
  39. return Path.join(Settings.path.compilesDir, getCompileName(projectId, userId))
  40. }
  41. function getOutputDir(projectId, userId) {
  42. return Path.join(Settings.path.outputDir, getCompileName(projectId, userId))
  43. }
  44. async function doCompileWithLock(request, stats, timings) {
  45. const compileDir = getCompileDir(request.project_id, request.user_id)
  46. request.isInitialCompile =
  47. (await fsPromises.mkdir(compileDir, { recursive: true })) === compileDir
  48. // prevent simultaneous compiles
  49. const lock = LockManager.acquire(compileDir)
  50. try {
  51. return await doCompile(request, stats, timings)
  52. } finally {
  53. lock.release()
  54. }
  55. }
  56. async function doCompile(request, stats, timings) {
  57. const { project_id: projectId, user_id: userId } = request
  58. const compileDir = getCompileDir(request.project_id, request.user_id)
  59. const timerE2E = new Metrics.Timer(
  60. 'compile-e2e-v2',
  61. 1,
  62. request.metricsOpts,
  63. COMPILE_TIME_BUCKETS
  64. )
  65. if (request.isInitialCompile) {
  66. stats.isInitialCompile = 1
  67. request.metricsOpts.compile = 'initial'
  68. if (request.compileFromClsiCache) {
  69. try {
  70. if (await downloadLatestCompileCache(projectId, userId, compileDir)) {
  71. stats.restoredClsiCache = 1
  72. request.metricsOpts.compile = 'from-clsi-cache'
  73. }
  74. } catch (err) {
  75. logger.warn(
  76. { err, projectId, userId },
  77. 'failed to populate compile dir from cache'
  78. )
  79. }
  80. }
  81. } else {
  82. request.metricsOpts.compile = 'recompile'
  83. }
  84. const writeToDiskTimer = new Metrics.Timer(
  85. 'write-to-disk',
  86. 1,
  87. request.metricsOpts
  88. )
  89. logger.debug(
  90. { projectId: request.project_id, userId: request.user_id },
  91. 'syncing resources to disk'
  92. )
  93. let resourceList
  94. try {
  95. // NOTE: resourceList is insecure, it should only be used to exclude files from the output list
  96. resourceList = await ResourceWriter.promises.syncResourcesToDisk(
  97. request,
  98. compileDir
  99. )
  100. } catch (error) {
  101. if (error instanceof Errors.FilesOutOfSyncError) {
  102. OError.tag(error, 'files out of sync, please retry', {
  103. projectId: request.project_id,
  104. userId: request.user_id,
  105. })
  106. } else {
  107. OError.tag(error, 'error writing resources to disk', {
  108. projectId: request.project_id,
  109. userId: request.user_id,
  110. })
  111. }
  112. throw error
  113. }
  114. logger.debug(
  115. {
  116. projectId: request.project_id,
  117. userId: request.user_id,
  118. timeTaken: Date.now() - writeToDiskTimer.start,
  119. },
  120. 'written files to disk'
  121. )
  122. timings.sync = writeToDiskTimer.done()
  123. // set up environment variables for chktex
  124. const env = {
  125. OVERLEAF_PROJECT_ID: request.project_id,
  126. }
  127. if (Settings.texliveOpenoutAny && Settings.texliveOpenoutAny !== '') {
  128. // override default texlive openout_any environment variable
  129. env.openout_any = Settings.texliveOpenoutAny
  130. }
  131. if (Settings.texliveMaxPrintLine && Settings.texliveMaxPrintLine !== '') {
  132. // override default texlive max_print_line environment variable
  133. env.max_print_line = Settings.texliveMaxPrintLine
  134. }
  135. // only run chktex on LaTeX files (not knitr .Rtex files or any others)
  136. const isLaTeXFile = request.rootResourcePath?.match(/\.tex$/i)
  137. if (request.check != null && isLaTeXFile) {
  138. env.CHKTEX_OPTIONS = '-nall -e9 -e10 -w15 -w16'
  139. env.CHKTEX_ULIMIT_OPTIONS = '-t 5 -v 64000'
  140. if (request.check === 'error') {
  141. env.CHKTEX_EXIT_ON_ERROR = 1
  142. }
  143. if (request.check === 'validate') {
  144. env.CHKTEX_VALIDATE = 1
  145. }
  146. }
  147. // apply a series of file modifications/creations for draft mode and tikz
  148. if (request.draft) {
  149. await DraftModeManager.promises.injectDraftMode(
  150. Path.join(compileDir, request.rootResourcePath)
  151. )
  152. }
  153. const needsMainFile = await TikzManager.promises.checkMainFile(
  154. compileDir,
  155. request.rootResourcePath,
  156. resourceList
  157. )
  158. if (needsMainFile) {
  159. await TikzManager.promises.injectOutputFile(
  160. compileDir,
  161. request.rootResourcePath
  162. )
  163. }
  164. const compileTimer = new Metrics.Timer('run-compile', 1, request.metricsOpts)
  165. // find the image tag to log it as a metric, e.g. 2015.1 (convert . to - for graphite)
  166. let tag = 'default'
  167. if (request.imageName != null) {
  168. const match = request.imageName.match(/:(.*)/)
  169. if (match != null) {
  170. tag = match[1].replace(/\./g, '-')
  171. }
  172. }
  173. // exclude smoke test
  174. if (!request.project_id.match(/^[0-9a-f]{24}$/)) {
  175. tag = 'other'
  176. }
  177. Metrics.inc('compiles', 1, request.metricsOpts)
  178. Metrics.inc(`compiles-with-image.${tag}`, 1, request.metricsOpts)
  179. const compileName = getCompileName(request.project_id, request.user_id)
  180. // Record latexmk -time stats for a subset of users
  181. const recordPerformanceMetrics =
  182. request.user_id != null &&
  183. Settings.performanceLogSamplingPercentage > 0 &&
  184. StatsManager.sampleByHash(
  185. request.user_id,
  186. Settings.performanceLogSamplingPercentage
  187. )
  188. // For selected users, define a `latexmk` property on the stats object
  189. // to collect latexmk -time stats.
  190. if (recordPerformanceMetrics) {
  191. // To prevent any changes to the existing compile responses being sent
  192. // to web, exclude latexmk stats from being exported by marking them
  193. // non-enumerable. This prevents them being serialised by JSON.stringify().
  194. Object.defineProperty(stats, 'latexmk', {
  195. value: {},
  196. enumerable: false,
  197. })
  198. }
  199. try {
  200. await LatexRunner.promises.runLatex(compileName, {
  201. directory: compileDir,
  202. mainFile: request.rootResourcePath,
  203. compiler: request.compiler,
  204. timeout: request.timeout,
  205. image: request.imageName,
  206. flags: request.flags,
  207. environment: env,
  208. compileGroup: request.compileGroup,
  209. stopOnFirstError: request.stopOnFirstError,
  210. stats,
  211. timings,
  212. })
  213. // We use errors to return the validation state. It would be nice to use a
  214. // more appropriate mechanism.
  215. if (request.check === 'validate') {
  216. const validationError = new Error('validation')
  217. validationError.validate = 'pass'
  218. throw validationError
  219. }
  220. } catch (originalError) {
  221. let error = originalError
  222. // request was for validation only
  223. if (request.check === 'validate' && !error.validate) {
  224. error = new Error('validation')
  225. error.validate = originalError.code ? 'fail' : 'pass'
  226. }
  227. // request was for compile, and failed on validation
  228. if (request.check === 'error' && originalError.message === 'exited') {
  229. error = new Error('compilation')
  230. error.validate = 'fail'
  231. }
  232. // record timeout errors as a separate counter, success is recorded later
  233. if (error.timedout) {
  234. Metrics.inc('compiles-timeout', 1, request.metricsOpts)
  235. }
  236. const { outputFiles, allEntries, buildId } = await _saveOutputFiles({
  237. request,
  238. compileDir,
  239. resourceList,
  240. stats,
  241. timings,
  242. })
  243. error.outputFiles = outputFiles // return output files so user can check logs
  244. error.buildId = buildId
  245. // Clear project if this compile was abruptly terminated
  246. if (error.terminated || error.timedout) {
  247. await clearProjectWithListing(
  248. request.project_id,
  249. request.user_id,
  250. allEntries
  251. )
  252. }
  253. throw error
  254. }
  255. // compile completed normally
  256. Metrics.inc('compiles-succeeded', 1, request.metricsOpts)
  257. for (const metricKey in stats) {
  258. const metricValue = stats[metricKey]
  259. if (typeof metricValue === 'number') {
  260. Metrics.count(metricKey, metricValue, 1, request.metricsOpts)
  261. }
  262. }
  263. for (const metricKey in timings) {
  264. const metricValue = timings[metricKey]
  265. if (typeof metricValue === 'number') {
  266. Metrics.timing(metricKey, metricValue, 1, request.metricsOpts)
  267. }
  268. }
  269. const loadavg = typeof os.loadavg === 'function' ? os.loadavg() : undefined
  270. if (loadavg != null) {
  271. Metrics.gauge('load-avg', loadavg[0])
  272. }
  273. const ts = compileTimer.done()
  274. logger.debug(
  275. {
  276. projectId: request.project_id,
  277. userId: request.user_id,
  278. timeTaken: ts,
  279. stats,
  280. timings,
  281. loadavg,
  282. },
  283. 'done compile'
  284. )
  285. if (stats['latex-runs'] > 0) {
  286. Metrics.histogram(
  287. 'avg-compile-per-pass-v2',
  288. ts / stats['latex-runs'],
  289. COMPILE_TIME_BUCKETS,
  290. request.metricsOpts
  291. )
  292. Metrics.timing(
  293. 'avg-compile-per-pass-v2',
  294. ts / stats['latex-runs'],
  295. 1,
  296. request.metricsOpts
  297. )
  298. }
  299. if (stats['latex-runs'] > 0 && timings['cpu-time'] > 0) {
  300. Metrics.timing(
  301. 'run-compile-cpu-time-per-pass',
  302. timings['cpu-time'] / stats['latex-runs'],
  303. 1,
  304. request.metricsOpts
  305. )
  306. }
  307. // Emit compile time.
  308. timings.compile = ts
  309. const { outputFiles, buildId } = await _saveOutputFiles({
  310. request,
  311. compileDir,
  312. resourceList,
  313. stats,
  314. timings,
  315. })
  316. // Emit e2e compile time.
  317. timings.compileE2E = timerE2E.done()
  318. Metrics.timing('compile-e2e-v2', timings.compileE2E, 1, request.metricsOpts)
  319. if (stats['pdf-size']) {
  320. emitPdfStats(stats, timings, request)
  321. }
  322. // Record compile performance for a subset of users
  323. if (recordPerformanceMetrics) {
  324. logger.info(
  325. {
  326. userId: request.user_id,
  327. projectId: request.project_id,
  328. timeTaken: ts,
  329. clsiRequest: request,
  330. stats,
  331. timings,
  332. // explicitly include latexmk stats to bypass the non-enumerable property
  333. latexmk: stats.latexmk,
  334. loadavg1m: loadavg?.[0],
  335. loadavg5m: loadavg?.[1],
  336. loadavg15m: loadavg?.[2],
  337. samplingPercentage: Settings.performanceLogSamplingPercentage,
  338. },
  339. 'sampled performance log'
  340. )
  341. }
  342. return { outputFiles, buildId }
  343. }
  344. async function _saveOutputFiles({
  345. request,
  346. compileDir,
  347. resourceList,
  348. stats,
  349. timings,
  350. }) {
  351. const timer = new Metrics.Timer(
  352. 'process-output-files',
  353. 1,
  354. request.metricsOpts
  355. )
  356. const outputDir = getOutputDir(request.project_id, request.user_id)
  357. const { outputFiles: rawOutputFiles, allEntries } =
  358. await OutputFileFinder.promises.findOutputFiles(resourceList, compileDir)
  359. const { buildId, outputFiles } =
  360. await OutputCacheManager.promises.saveOutputFiles(
  361. { request, stats, timings },
  362. rawOutputFiles,
  363. compileDir,
  364. outputDir
  365. )
  366. timings.output = timer.done()
  367. return { outputFiles, allEntries, buildId }
  368. }
  369. async function stopCompile(projectId, userId) {
  370. const compileName = getCompileName(projectId, userId)
  371. await LatexRunner.promises.killLatex(compileName)
  372. }
  373. async function clearProject(projectId, userId) {
  374. const compileDir = getCompileDir(projectId, userId)
  375. await fsPromises.rm(compileDir, { force: true, recursive: true })
  376. }
  377. async function clearProjectWithListing(projectId, userId, allEntries) {
  378. const compileDir = getCompileDir(projectId, userId)
  379. const exists = await _checkDirectory(compileDir)
  380. if (!exists) {
  381. // skip removal if no directory present
  382. return
  383. }
  384. for (const pathInProject of allEntries) {
  385. const path = Path.join(compileDir, pathInProject)
  386. if (path.endsWith('/')) {
  387. await fsPromises.rmdir(path)
  388. } else {
  389. await fsPromises.unlink(path)
  390. }
  391. }
  392. await fsPromises.rmdir(compileDir)
  393. }
  394. async function _findAllDirs() {
  395. const root = Settings.path.compilesDir
  396. const files = await fsPromises.readdir(root)
  397. const allDirs = files.map(file => Path.join(root, file))
  398. return allDirs
  399. }
  400. async function clearExpiredProjects(maxCacheAgeMs) {
  401. const now = Date.now()
  402. const dirs = await _findAllDirs()
  403. for (const dir of dirs) {
  404. let stats
  405. try {
  406. stats = await fsPromises.stat(dir)
  407. } catch (err) {
  408. // ignore errors checking directory
  409. continue
  410. }
  411. const age = now - stats.mtime
  412. const hasExpired = age > maxCacheAgeMs
  413. if (hasExpired) {
  414. await fsPromises.rm(dir, { force: true, recursive: true })
  415. }
  416. }
  417. }
  418. async function _checkDirectory(compileDir) {
  419. let stats
  420. try {
  421. stats = await fsPromises.lstat(compileDir)
  422. } catch (err) {
  423. if (err.code === 'ENOENT') {
  424. // directory does not exist
  425. return false
  426. }
  427. OError.tag(err, 'error on stat of project directory for removal', {
  428. dir: compileDir,
  429. })
  430. throw err
  431. }
  432. if (!stats.isDirectory()) {
  433. throw new OError('project directory is not directory', {
  434. dir: compileDir,
  435. stats,
  436. })
  437. }
  438. return true
  439. }
  440. async function syncFromCode(projectId, userId, filename, line, column, opts) {
  441. // If LaTeX was run in a virtual environment, the file path that synctex expects
  442. // might not match the file path on the host. The .synctex.gz file however, will be accessed
  443. // wherever it is on the host.
  444. const compileName = getCompileName(projectId, userId)
  445. const baseDir = Settings.path.synctexBaseDir(compileName)
  446. const inputFilePath = Path.join(baseDir, filename)
  447. const outputFilePath = Path.join(baseDir, 'output.pdf')
  448. const command = [
  449. 'synctex',
  450. 'view',
  451. '-i',
  452. `${line}:${column}:${inputFilePath}`,
  453. '-o',
  454. outputFilePath,
  455. ]
  456. const { stdout, downloadedFromCache } = await _runSynctex(
  457. projectId,
  458. userId,
  459. command,
  460. opts
  461. )
  462. logger.debug(
  463. { projectId, userId, filename, line, column, command, stdout },
  464. 'synctex code output'
  465. )
  466. return {
  467. codePositions: SynctexOutputParser.parseViewOutput(stdout),
  468. downloadedFromCache,
  469. }
  470. }
  471. async function syncFromPdf(projectId, userId, page, h, v, opts) {
  472. const compileName = getCompileName(projectId, userId)
  473. const baseDir = Settings.path.synctexBaseDir(compileName)
  474. const outputFilePath = `${baseDir}/output.pdf`
  475. const command = [
  476. 'synctex',
  477. 'edit',
  478. '-o',
  479. `${page}:${h}:${v}:${outputFilePath}`,
  480. ]
  481. const { stdout, downloadedFromCache } = await _runSynctex(
  482. projectId,
  483. userId,
  484. command,
  485. opts
  486. )
  487. logger.debug({ projectId, userId, page, h, v, stdout }, 'synctex pdf output')
  488. return {
  489. pdfPositions: SynctexOutputParser.parseEditOutput(stdout, baseDir),
  490. downloadedFromCache,
  491. }
  492. }
  493. async function _checkFileExists(dir, filename) {
  494. try {
  495. await fsPromises.stat(dir)
  496. } catch (error) {
  497. if (error.code === 'ENOENT') {
  498. throw new Errors.NotFoundError('no output directory')
  499. }
  500. throw error
  501. }
  502. const file = Path.join(dir, filename)
  503. let stats
  504. try {
  505. stats = await fsPromises.stat(file)
  506. } catch (error) {
  507. if (error.code === 'ENOENT') {
  508. throw new Errors.NotFoundError('no output file')
  509. }
  510. }
  511. if (!stats.isFile()) {
  512. throw new Error('not a file')
  513. }
  514. }
  515. async function _runSynctex(projectId, userId, command, opts) {
  516. const { imageName, editorId, buildId, compileFromClsiCache } = opts
  517. if (imageName && !_isImageNameAllowed(imageName)) {
  518. throw new Errors.InvalidParameter('invalid image')
  519. }
  520. if (editorId && !/^[a-f0-9-]+$/.test(editorId)) {
  521. throw new Errors.InvalidParameter('invalid editorId')
  522. }
  523. if (buildId && !OutputCacheManager.BUILD_REGEX.test(buildId)) {
  524. throw new Errors.InvalidParameter('invalid buildId')
  525. }
  526. const outputDir = getOutputDir(projectId, userId)
  527. const runInOutputDir = buildId && CommandRunner.canRunSyncTeXInOutputDir()
  528. const directory = runInOutputDir
  529. ? Path.join(outputDir, OutputCacheManager.CACHE_SUBDIR, buildId)
  530. : getCompileDir(projectId, userId)
  531. const timeout = 60 * 1000 // increased to allow for large projects
  532. const compileName = getCompileName(projectId, userId)
  533. const compileGroup = runInOutputDir ? 'synctex-output' : 'synctex'
  534. const defaultImageName =
  535. Settings.clsi && Settings.clsi.docker && Settings.clsi.docker.image
  536. // eslint-disable-next-line @typescript-eslint/return-await
  537. return await OutputCacheManager.promises.queueDirOperation(
  538. outputDir,
  539. /**
  540. * @return {Promise<{stdout: string, downloadedFromCache: boolean}>}
  541. */
  542. async () => {
  543. let downloadedFromCache = false
  544. try {
  545. await _checkFileExists(directory, 'output.synctex.gz')
  546. } catch (err) {
  547. if (
  548. err instanceof Errors.NotFoundError &&
  549. compileFromClsiCache &&
  550. editorId &&
  551. buildId
  552. ) {
  553. try {
  554. downloadedFromCache =
  555. await downloadOutputDotSynctexFromCompileCache(
  556. projectId,
  557. userId,
  558. editorId,
  559. buildId,
  560. directory
  561. )
  562. } catch (err) {
  563. logger.warn(
  564. { err, projectId, userId, editorId, buildId },
  565. 'failed to download output.synctex.gz from clsi-cache'
  566. )
  567. }
  568. await _checkFileExists(directory, 'output.synctex.gz')
  569. } else {
  570. throw err
  571. }
  572. }
  573. try {
  574. const { stdout } = await CommandRunner.promises.run(
  575. compileName,
  576. command,
  577. directory,
  578. imageName || defaultImageName,
  579. timeout,
  580. {},
  581. compileGroup
  582. )
  583. return {
  584. stdout,
  585. downloadedFromCache,
  586. }
  587. } catch (error) {
  588. throw OError.tag(error, 'error running synctex', {
  589. command,
  590. projectId,
  591. userId,
  592. })
  593. }
  594. }
  595. )
  596. }
  597. async function wordcount(projectId, userId, filename, image) {
  598. logger.debug({ projectId, userId, filename, image }, 'running wordcount')
  599. const filePath = `$COMPILE_DIR/${filename}`
  600. const command = ['texcount', '-nocol', '-inc', filePath]
  601. const compileDir = getCompileDir(projectId, userId)
  602. const timeout = 60 * 1000
  603. const compileName = getCompileName(projectId, userId)
  604. const compileGroup = 'wordcount'
  605. if (image && !_isImageNameAllowed(image)) {
  606. throw new Errors.InvalidParameter('invalid image')
  607. }
  608. try {
  609. await fsPromises.mkdir(compileDir, { recursive: true })
  610. } catch (err) {
  611. throw OError.tag(err, 'error ensuring dir for wordcount', {
  612. projectId,
  613. userId,
  614. filename,
  615. })
  616. }
  617. try {
  618. const { stdout } = await CommandRunner.promises.run(
  619. compileName,
  620. command,
  621. compileDir,
  622. image,
  623. timeout,
  624. {},
  625. compileGroup
  626. )
  627. const results = _parseWordcountFromOutput(stdout)
  628. logger.debug(
  629. { projectId, userId, wordcount: results },
  630. 'word count results'
  631. )
  632. return results
  633. } catch (err) {
  634. throw OError.tag(err, 'error reading word count output', {
  635. command,
  636. compileDir,
  637. projectId,
  638. userId,
  639. })
  640. }
  641. }
  642. function _parseWordcountFromOutput(output) {
  643. const results = {
  644. encode: '',
  645. textWords: 0,
  646. headWords: 0,
  647. outside: 0,
  648. headers: 0,
  649. elements: 0,
  650. mathInline: 0,
  651. mathDisplay: 0,
  652. errors: 0,
  653. messages: '',
  654. }
  655. for (const line of output.split('\n')) {
  656. const [data, info] = line.split(':')
  657. if (data.indexOf('Encoding') > -1) {
  658. results.encode = info.trim()
  659. }
  660. if (data.indexOf('in text') > -1) {
  661. results.textWords = parseInt(info, 10)
  662. }
  663. if (data.indexOf('in head') > -1) {
  664. results.headWords = parseInt(info, 10)
  665. }
  666. if (data.indexOf('outside') > -1) {
  667. results.outside = parseInt(info, 10)
  668. }
  669. if (data.indexOf('of head') > -1) {
  670. results.headers = parseInt(info, 10)
  671. }
  672. if (data.indexOf('Number of floats/tables/figures') > -1) {
  673. results.elements = parseInt(info, 10)
  674. }
  675. if (data.indexOf('Number of math inlines') > -1) {
  676. results.mathInline = parseInt(info, 10)
  677. }
  678. if (data.indexOf('Number of math displayed') > -1) {
  679. results.mathDisplay = parseInt(info, 10)
  680. }
  681. if (data === '(errors') {
  682. // errors reported as (errors:123)
  683. results.errors = parseInt(info, 10)
  684. }
  685. if (line.indexOf('!!! ') > -1) {
  686. // errors logged as !!! message !!!
  687. results.messages += line + '\n'
  688. }
  689. }
  690. return results
  691. }
  692. function _isImageNameAllowed(imageName) {
  693. const ALLOWED_IMAGES =
  694. Settings.clsi && Settings.clsi.docker && Settings.clsi.docker.allowedImages
  695. return !ALLOWED_IMAGES || ALLOWED_IMAGES.includes(imageName)
  696. }
  697. module.exports = {
  698. doCompileWithLock: callbackify(doCompileWithLock),
  699. stopCompile: callbackify(stopCompile),
  700. clearProject: callbackify(clearProject),
  701. clearExpiredProjects: callbackify(clearExpiredProjects),
  702. syncFromCode: callbackifyMultiResult(syncFromCode, [
  703. 'codePositions',
  704. 'downloadedFromCache',
  705. ]),
  706. syncFromPdf: callbackifyMultiResult(syncFromPdf, [
  707. 'pdfPositions',
  708. 'downloadedFromCache',
  709. ]),
  710. wordcount: callbackify(wordcount),
  711. promises: {
  712. doCompileWithLock,
  713. stopCompile,
  714. clearProject,
  715. clearExpiredProjects,
  716. syncFromCode,
  717. syncFromPdf,
  718. wordcount,
  719. },
  720. }