CompileManager.js 22 KB

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