CompileManager.js 25 KB

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