CompileManager.js 24 KB

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