CompileManager.js 23 KB

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