CompileManager.js 24 KB

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