CompileManager.js 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895
  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.rawChangeOperations) {
  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. const lock = LockManager.getExistingLock(getCompileDir(projectId, userId))
  346. let lockReleased
  347. if (lock) {
  348. lockReleased = lock.waitForRelease()
  349. } else {
  350. if (!LatexRunner.isRunning(compileName)) return
  351. logger.warn({ projectId, userId }, 'found running compile without lock')
  352. lockReleased = Promise.resolve()
  353. }
  354. await LatexRunner.promises.killLatex(compileName)
  355. await lockReleased
  356. }
  357. async function clearProject(projectId, userId) {
  358. const compileDir = getCompileDir(projectId, userId)
  359. await fsPromises.rm(compileDir, { force: true, recursive: true })
  360. }
  361. async function clearProjectWithListing(projectId, userId, allEntries) {
  362. const compileDir = getCompileDir(projectId, userId)
  363. const exists = await _checkDirectory(compileDir)
  364. if (!exists) {
  365. // skip removal if no directory present
  366. return
  367. }
  368. for (const pathInProject of allEntries) {
  369. const path = Path.join(compileDir, pathInProject)
  370. if (path.endsWith('/')) {
  371. await fsPromises.rmdir(path)
  372. } else {
  373. await fsPromises.unlink(path)
  374. }
  375. }
  376. await fsPromises.rmdir(compileDir)
  377. }
  378. async function _findAllDirs() {
  379. const root = Settings.path.compilesDir
  380. const files = await fsPromises.readdir(root)
  381. const allDirs = files.map(file => Path.join(root, file))
  382. return allDirs
  383. }
  384. async function clearExpiredProjects(maxCacheAgeMs) {
  385. const now = Date.now()
  386. const dirs = await _findAllDirs()
  387. for (const dir of dirs) {
  388. let stats
  389. try {
  390. stats = await fsPromises.stat(dir)
  391. } catch (err) {
  392. // ignore errors checking directory
  393. continue
  394. }
  395. const age = now - stats.mtime
  396. const hasExpired = age > maxCacheAgeMs
  397. if (hasExpired) {
  398. await fsPromises.rm(dir, { force: true, recursive: true })
  399. }
  400. }
  401. }
  402. async function _checkDirectory(compileDir) {
  403. let stats
  404. try {
  405. stats = await fsPromises.lstat(compileDir)
  406. } catch (err) {
  407. if (err.code === 'ENOENT') {
  408. // directory does not exist
  409. return false
  410. }
  411. OError.tag(err, 'error on stat of project directory for removal', {
  412. dir: compileDir,
  413. })
  414. throw err
  415. }
  416. if (!stats.isDirectory()) {
  417. throw new OError('project directory is not directory', {
  418. dir: compileDir,
  419. stats,
  420. })
  421. }
  422. return true
  423. }
  424. async function syncFromCode(projectId, userId, filename, line, column, opts) {
  425. // If LaTeX was run in a virtual environment, the file path that synctex expects
  426. // might not match the file path on the host. The .synctex.gz file however, will be accessed
  427. // wherever it is on the host.
  428. const compileName = getCompileName(projectId, userId)
  429. const baseDir = Settings.path.synctexBaseDir(compileName)
  430. const inputFilePath = Path.join(baseDir, filename)
  431. const outputFilePath = Path.join(baseDir, 'output.pdf')
  432. const command = [
  433. 'synctex',
  434. 'view',
  435. '-i',
  436. `${line}:${column}:${inputFilePath}`,
  437. '-o',
  438. outputFilePath,
  439. ]
  440. const { stdout, downloadedFromCache } = await _runSynctex(
  441. projectId,
  442. userId,
  443. command,
  444. opts
  445. )
  446. logger.debug(
  447. { projectId, userId, filename, line, column, command, stdout },
  448. 'synctex code output'
  449. )
  450. return {
  451. codePositions: SynctexOutputParser.parseViewOutput(stdout),
  452. downloadedFromCache,
  453. }
  454. }
  455. async function syncFromPdf(projectId, userId, page, h, v, opts) {
  456. const compileName = getCompileName(projectId, userId)
  457. const baseDir = Settings.path.synctexBaseDir(compileName)
  458. const outputFilePath = `${baseDir}/output.pdf`
  459. const command = [
  460. 'synctex',
  461. 'edit',
  462. '-o',
  463. `${page}:${h}:${v}:${outputFilePath}`,
  464. ]
  465. const { stdout, downloadedFromCache } = await _runSynctex(
  466. projectId,
  467. userId,
  468. command,
  469. opts
  470. )
  471. logger.debug({ projectId, userId, page, h, v, stdout }, 'synctex pdf output')
  472. return {
  473. pdfPositions: SynctexOutputParser.parseEditOutput(stdout, baseDir),
  474. downloadedFromCache,
  475. }
  476. }
  477. async function _checkFileExists(dir, filename) {
  478. try {
  479. await fsPromises.stat(dir)
  480. } catch (error) {
  481. if (error.code === 'ENOENT') {
  482. throw new Errors.NotFoundError('no output directory')
  483. }
  484. throw error
  485. }
  486. const file = Path.join(dir, filename)
  487. let stats
  488. try {
  489. stats = await fsPromises.stat(file)
  490. } catch (error) {
  491. if (error.code === 'ENOENT') {
  492. throw new Errors.NotFoundError('no output file')
  493. }
  494. }
  495. if (!stats.isFile()) {
  496. throw new Error('not a file')
  497. }
  498. }
  499. async function _runSynctex(projectId, userId, command, opts) {
  500. const { imageName, editorId, buildId, compileFromClsiCache } = opts
  501. if (imageName && !_isImageNameAllowed(imageName)) {
  502. throw new Errors.InvalidParameter('invalid image')
  503. }
  504. if (editorId && !/^[a-f0-9-]+$/.test(editorId)) {
  505. throw new Errors.InvalidParameter('invalid editorId')
  506. }
  507. if (buildId && !OutputCacheManager.BUILD_REGEX.test(buildId)) {
  508. throw new Errors.InvalidParameter('invalid buildId')
  509. }
  510. const outputDir = getOutputDir(projectId, userId)
  511. const runInOutputDir = buildId && CommandRunner.canRunSyncTeXInOutputDir()
  512. const directory = runInOutputDir
  513. ? Path.join(outputDir, OutputCacheManager.CACHE_SUBDIR, buildId)
  514. : getCompileDir(projectId, userId)
  515. const timeout = 60 * 1000 // increased to allow for large projects
  516. const compileName = getCompileName(projectId, userId)
  517. const compileGroup = runInOutputDir ? 'synctex-output' : 'synctex'
  518. const defaultImageName =
  519. Settings.clsi && Settings.clsi.docker && Settings.clsi.docker.image
  520. // eslint-disable-next-line @typescript-eslint/return-await
  521. return await OutputCacheManager.promises.queueDirOperation(
  522. outputDir,
  523. /**
  524. * @return {Promise<{stdout: string, downloadedFromCache: boolean}>}
  525. */
  526. async () => {
  527. let downloadedFromCache = false
  528. try {
  529. await _checkFileExists(directory, 'output.synctex.gz')
  530. if (compileFromClsiCache) {
  531. try {
  532. await _checkFileExists(directory, 'output.log')
  533. } catch (err) {
  534. if (err instanceof Errors.NotFoundError) downloadedFromCache = true
  535. }
  536. }
  537. } catch (err) {
  538. if (
  539. err instanceof Errors.NotFoundError &&
  540. compileFromClsiCache &&
  541. editorId &&
  542. buildId
  543. ) {
  544. try {
  545. downloadedFromCache =
  546. await downloadOutputDotSynctexFromCompileCache(
  547. projectId,
  548. userId,
  549. editorId,
  550. buildId,
  551. directory
  552. )
  553. } catch (err) {
  554. logger.warn(
  555. { err, projectId, userId, editorId, buildId },
  556. 'failed to download output.synctex.gz from clsi-cache'
  557. )
  558. }
  559. await _checkFileExists(directory, 'output.synctex.gz')
  560. } else {
  561. throw err
  562. }
  563. }
  564. try {
  565. const { stdout } = await CommandRunner.promises.run(
  566. compileName,
  567. command,
  568. directory,
  569. imageName || defaultImageName,
  570. timeout,
  571. {},
  572. compileGroup
  573. )
  574. return {
  575. stdout,
  576. downloadedFromCache,
  577. }
  578. } catch (error) {
  579. throw OError.tag(error, 'error running synctex', {
  580. command,
  581. projectId,
  582. userId,
  583. })
  584. }
  585. }
  586. )
  587. }
  588. async function wordcount(projectId, userId, filename, image) {
  589. logger.debug({ projectId, userId, filename, image }, 'running wordcount')
  590. const filePath = `$COMPILE_DIR/${filename}`
  591. const command = ['texcount', '-nocol', '-inc', filePath]
  592. const compileDir = getCompileDir(projectId, userId)
  593. const timeout = 60 * 1000
  594. const compileName = getCompileName(projectId, userId)
  595. const compileGroup = 'wordcount'
  596. if (image && !_isImageNameAllowed(image)) {
  597. throw new Errors.InvalidParameter('invalid image')
  598. }
  599. try {
  600. await fsPromises.mkdir(compileDir, { recursive: true })
  601. } catch (err) {
  602. throw OError.tag(err, 'error ensuring dir for wordcount', {
  603. projectId,
  604. userId,
  605. filename,
  606. })
  607. }
  608. try {
  609. const { stdout } = await CommandRunner.promises.run(
  610. compileName,
  611. command,
  612. compileDir,
  613. image,
  614. timeout,
  615. {},
  616. compileGroup
  617. )
  618. const results = _parseWordcountFromOutput(stdout)
  619. logger.debug(
  620. { projectId, userId, wordcount: results },
  621. 'word count results'
  622. )
  623. return results
  624. } catch (err) {
  625. throw OError.tag(err, 'error reading word count output', {
  626. command,
  627. compileDir,
  628. projectId,
  629. userId,
  630. })
  631. }
  632. }
  633. function _parseWordcountFromOutput(output) {
  634. const results = {
  635. encode: '',
  636. textWords: 0,
  637. headWords: 0,
  638. outside: 0,
  639. headers: 0,
  640. elements: 0,
  641. mathInline: 0,
  642. mathDisplay: 0,
  643. errors: 0,
  644. messages: '',
  645. }
  646. for (const line of output.split('\n')) {
  647. const [data, info] = line.split(':')
  648. if (data.indexOf('Encoding') > -1) {
  649. results.encode = info.trim()
  650. }
  651. if (data.indexOf('in text') > -1) {
  652. results.textWords = parseInt(info, 10)
  653. }
  654. if (data.indexOf('in head') > -1) {
  655. results.headWords = parseInt(info, 10)
  656. }
  657. if (data.indexOf('outside') > -1) {
  658. results.outside = parseInt(info, 10)
  659. }
  660. if (data.indexOf('of head') > -1) {
  661. results.headers = parseInt(info, 10)
  662. }
  663. if (data.indexOf('Number of floats/tables/figures') > -1) {
  664. results.elements = parseInt(info, 10)
  665. }
  666. if (data.indexOf('Number of math inlines') > -1) {
  667. results.mathInline = parseInt(info, 10)
  668. }
  669. if (data.indexOf('Number of math displayed') > -1) {
  670. results.mathDisplay = parseInt(info, 10)
  671. }
  672. if (data === '(errors') {
  673. // errors reported as (errors:123)
  674. results.errors = parseInt(info, 10)
  675. }
  676. if (line.indexOf('!!! ') > -1) {
  677. // errors logged as !!! message !!!
  678. results.messages += line + '\n'
  679. }
  680. }
  681. return results
  682. }
  683. function _isImageNameAllowed(imageName) {
  684. const ALLOWED_IMAGES =
  685. Settings.clsi && Settings.clsi.docker && Settings.clsi.docker.allowedImages
  686. return !ALLOWED_IMAGES || ALLOWED_IMAGES.includes(imageName)
  687. }
  688. function _emitMetrics(request, status, stats, timings) {
  689. if (request.metricsOpts.path === 'clsi-perf') {
  690. ClsiMetrics.e2eCompileDurationClsiPerfSeconds.set(
  691. { variant: request.metricsOpts.method },
  692. timings.compileE2E / 1000
  693. )
  694. }
  695. if (shouldSkipMetrics(request)) {
  696. return
  697. }
  698. // find the image tag to log it as a metric, e.g. 2015.1
  699. let tag = 'default'
  700. if (request.imageName != null) {
  701. const match = request.imageName.match(/:(.*)/)
  702. if (match != null) {
  703. tag = match[1]
  704. }
  705. }
  706. const runs = stats.latexmk?.['latexmk-rule-times']
  707. let passes = 0
  708. if (runs != null) {
  709. let cumulativeRuleTimeMs = 0
  710. for (const run of runs) {
  711. if (LATEX_PASSES_RULES.has(run.rule)) {
  712. passes += 1
  713. }
  714. const rule = KNOWN_LATEXMK_RULES.has(run.rule) ? run.rule : 'other'
  715. ClsiMetrics.latexmkRuleDurationSeconds.observe(
  716. {
  717. group: request.compileGroup,
  718. rule,
  719. },
  720. run.time_ms / 1000
  721. )
  722. cumulativeRuleTimeMs += run.time_ms
  723. }
  724. const totalTimeMs = stats.latexmk?.['latexmk-time']?.total
  725. if (totalTimeMs != null) {
  726. ClsiMetrics.latexmkRuleDurationSeconds.observe(
  727. { group: request.compileGroup, rule: 'overhead' },
  728. (totalTimeMs - cumulativeRuleTimeMs) / 1000
  729. )
  730. }
  731. }
  732. const imgTimings = stats.latexmk?.['latexmk-img-times']
  733. if (imgTimings != null) {
  734. for (const timing of imgTimings) {
  735. ClsiMetrics.imageProcessingDurationSeconds.observe(
  736. {
  737. group: request.compileGroup,
  738. type: timing.type,
  739. },
  740. timing.time_ms / 1000
  741. )
  742. }
  743. }
  744. ClsiMetrics.compilesTotal.inc({
  745. status,
  746. engine: request.compiler,
  747. image: tag,
  748. compile: request.metricsOpts.compile,
  749. group: request.compileGroup,
  750. draft: request.draft ? 'true' : 'false',
  751. stop_on_first_error: request.stopOnFirstError ? 'true' : 'false',
  752. passes,
  753. type: request.syncType,
  754. })
  755. if (timings.sync != null) {
  756. ClsiMetrics.syncResourcesDurationSeconds.observe(
  757. {
  758. type: request.syncType,
  759. compile: request.metricsOpts.compile,
  760. group: request.compileGroup,
  761. },
  762. timings.sync / 1000
  763. )
  764. }
  765. if (timings.compile != null) {
  766. ClsiMetrics.compileDurationSeconds.observe(
  767. {
  768. status,
  769. engine: request.compiler,
  770. compile: request.metricsOpts.compile,
  771. group: request.compileGroup,
  772. passes: passes === 0 ? 'none' : passes === 1 ? 'single' : 'multiple',
  773. },
  774. timings.compile / 1000
  775. )
  776. }
  777. if (timings.output != null) {
  778. ClsiMetrics.processOutputFilesDurationSeconds.observe(
  779. {
  780. compile: request.metricsOpts.compile,
  781. group: request.compileGroup,
  782. },
  783. timings.output / 1000
  784. )
  785. }
  786. if (timings.compileE2E != null) {
  787. ClsiMetrics.e2eCompileDurationSeconds.observe(
  788. {
  789. compileFromHistory: !!request.rawChangeOperations,
  790. compile: request.metricsOpts.compile,
  791. group: request.compileGroup,
  792. },
  793. timings.compileE2E / 1000
  794. )
  795. }
  796. }
  797. export default {
  798. doCompileWithLock: callbackify(doCompileWithLock),
  799. stopCompile: callbackify(stopCompile),
  800. clearProject: callbackify(clearProject),
  801. clearExpiredProjects: callbackify(clearExpiredProjects),
  802. syncFromCode: callbackifyMultiResult(syncFromCode, [
  803. 'codePositions',
  804. 'downloadedFromCache',
  805. ]),
  806. syncFromPdf: callbackifyMultiResult(syncFromPdf, [
  807. 'pdfPositions',
  808. 'downloadedFromCache',
  809. ]),
  810. wordcount: callbackify(wordcount),
  811. promises: {
  812. doCompileWithLock,
  813. stopCompile,
  814. clearProject,
  815. clearExpiredProjects,
  816. syncFromCode,
  817. syncFromPdf,
  818. wordcount,
  819. },
  820. }