CompileManager.js 24 KB

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