CompileManager.js 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897
  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. // apply a series of file modifications/creations for draft mode and tikz
  114. if (request.draft) {
  115. await DraftModeManager.promises.injectDraftMode(
  116. Path.join(compileDir, request.rootResourcePath)
  117. )
  118. }
  119. const needsMainFile = await TikzManager.promises.checkMainFile(
  120. compileDir,
  121. request.rootResourcePath,
  122. resourceList
  123. )
  124. if (needsMainFile) {
  125. await TikzManager.promises.injectOutputFile(
  126. compileDir,
  127. request.rootResourcePath
  128. )
  129. }
  130. }
  131. } catch (error) {
  132. if (error instanceof Errors.FilesOutOfSyncError) {
  133. OError.tag(error, 'files out of sync, please retry', {
  134. projectId: request.project_id,
  135. userId: request.user_id,
  136. })
  137. } else {
  138. OError.tag(error, 'error writing resources to disk', {
  139. projectId: request.project_id,
  140. userId: request.user_id,
  141. })
  142. }
  143. throw error
  144. }
  145. timings.sync = Date.now() - syncStart
  146. logger.debug(
  147. {
  148. projectId: request.project_id,
  149. userId: request.user_id,
  150. timeTaken: timings.sync,
  151. },
  152. 'written files to disk'
  153. )
  154. // set up environment variables for chktex
  155. const env = {
  156. OVERLEAF_PROJECT_ID: request.project_id,
  157. }
  158. if (Settings.texliveOpenoutAny && Settings.texliveOpenoutAny !== '') {
  159. // override default texlive openout_any environment variable
  160. env.openout_any = Settings.texliveOpenoutAny
  161. }
  162. if (Settings.texliveMaxPrintLine && Settings.texliveMaxPrintLine !== '') {
  163. // override default texlive max_print_line environment variable
  164. env.max_print_line = Settings.texliveMaxPrintLine
  165. }
  166. // only run chktex on LaTeX files (not knitr .Rtex files or any others)
  167. const isLaTeXFile = request.rootResourcePath?.match(/\.tex$/i)
  168. if (request.check != null && isLaTeXFile) {
  169. env.CHKTEX_OPTIONS = '-nall -e9 -e10 -w15 -w16'
  170. env.CHKTEX_ULIMIT_OPTIONS = '-t 5 -v 64000'
  171. if (request.check === 'error') {
  172. env.CHKTEX_EXIT_ON_ERROR = 1
  173. }
  174. if (request.check === 'validate') {
  175. env.CHKTEX_VALIDATE = 1
  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. null
  574. )
  575. return {
  576. stdout,
  577. downloadedFromCache,
  578. }
  579. } catch (error) {
  580. throw OError.tag(error, 'error running synctex', {
  581. command,
  582. projectId,
  583. userId,
  584. })
  585. }
  586. }
  587. )
  588. }
  589. async function wordcount(projectId, userId, filename, image) {
  590. logger.debug({ projectId, userId, filename, image }, 'running wordcount')
  591. const filePath = `$COMPILE_DIR/${filename}`
  592. const command = ['texcount', '-nocol', '-inc', filePath]
  593. const compileDir = getCompileDir(projectId, userId)
  594. const timeout = 60 * 1000
  595. const compileName = getCompileName(projectId, userId)
  596. const compileGroup = 'wordcount'
  597. if (image && !_isImageNameAllowed(image)) {
  598. throw new Errors.InvalidParameter('invalid image')
  599. }
  600. try {
  601. await fsPromises.mkdir(compileDir, { recursive: true })
  602. } catch (err) {
  603. throw OError.tag(err, 'error ensuring dir for wordcount', {
  604. projectId,
  605. userId,
  606. filename,
  607. })
  608. }
  609. try {
  610. const { stdout } = await CommandRunner.promises.run(
  611. compileName,
  612. command,
  613. compileDir,
  614. image,
  615. timeout,
  616. {},
  617. compileGroup,
  618. null
  619. )
  620. const results = _parseWordcountFromOutput(stdout)
  621. logger.debug(
  622. { projectId, userId, wordcount: results },
  623. 'word count results'
  624. )
  625. return results
  626. } catch (err) {
  627. throw OError.tag(err, 'error reading word count output', {
  628. command,
  629. compileDir,
  630. projectId,
  631. userId,
  632. })
  633. }
  634. }
  635. function _parseWordcountFromOutput(output) {
  636. const results = {
  637. encode: '',
  638. textWords: 0,
  639. headWords: 0,
  640. outside: 0,
  641. headers: 0,
  642. elements: 0,
  643. mathInline: 0,
  644. mathDisplay: 0,
  645. errors: 0,
  646. messages: '',
  647. }
  648. for (const line of output.split('\n')) {
  649. const [data, info] = line.split(':')
  650. if (data.indexOf('Encoding') > -1) {
  651. results.encode = info.trim()
  652. }
  653. if (data.indexOf('in text') > -1) {
  654. results.textWords = parseInt(info, 10)
  655. }
  656. if (data.indexOf('in head') > -1) {
  657. results.headWords = parseInt(info, 10)
  658. }
  659. if (data.indexOf('outside') > -1) {
  660. results.outside = parseInt(info, 10)
  661. }
  662. if (data.indexOf('of head') > -1) {
  663. results.headers = parseInt(info, 10)
  664. }
  665. if (data.indexOf('Number of floats/tables/figures') > -1) {
  666. results.elements = parseInt(info, 10)
  667. }
  668. if (data.indexOf('Number of math inlines') > -1) {
  669. results.mathInline = parseInt(info, 10)
  670. }
  671. if (data.indexOf('Number of math displayed') > -1) {
  672. results.mathDisplay = parseInt(info, 10)
  673. }
  674. if (data === '(errors') {
  675. // errors reported as (errors:123)
  676. results.errors = parseInt(info, 10)
  677. }
  678. if (line.indexOf('!!! ') > -1) {
  679. // errors logged as !!! message !!!
  680. results.messages += line + '\n'
  681. }
  682. }
  683. return results
  684. }
  685. function _isImageNameAllowed(imageName) {
  686. const ALLOWED_IMAGES =
  687. Settings.clsi && Settings.clsi.docker && Settings.clsi.docker.allowedImages
  688. return !ALLOWED_IMAGES || ALLOWED_IMAGES.includes(imageName)
  689. }
  690. function _emitMetrics(request, status, stats, timings) {
  691. if (request.metricsOpts.path === 'clsi-perf') {
  692. ClsiMetrics.e2eCompileDurationClsiPerfSeconds.set(
  693. { variant: request.metricsOpts.method },
  694. timings.compileE2E / 1000
  695. )
  696. }
  697. if (shouldSkipMetrics(request)) {
  698. return
  699. }
  700. // find the image tag to log it as a metric, e.g. 2015.1
  701. let tag = 'default'
  702. if (request.imageName != null) {
  703. const match = request.imageName.match(/:(.*)/)
  704. if (match != null) {
  705. tag = match[1]
  706. }
  707. }
  708. const runs = stats.latexmk?.['latexmk-rule-times']
  709. let passes = 0
  710. if (runs != null) {
  711. let cumulativeRuleTimeMs = 0
  712. for (const run of runs) {
  713. if (LATEX_PASSES_RULES.has(run.rule)) {
  714. passes += 1
  715. }
  716. const rule = KNOWN_LATEXMK_RULES.has(run.rule) ? run.rule : 'other'
  717. ClsiMetrics.latexmkRuleDurationSeconds.observe(
  718. {
  719. group: request.compileGroup,
  720. rule,
  721. },
  722. run.time_ms / 1000
  723. )
  724. cumulativeRuleTimeMs += run.time_ms
  725. }
  726. const totalTimeMs = stats.latexmk?.['latexmk-time']?.total
  727. if (totalTimeMs != null) {
  728. ClsiMetrics.latexmkRuleDurationSeconds.observe(
  729. { group: request.compileGroup, rule: 'overhead' },
  730. (totalTimeMs - cumulativeRuleTimeMs) / 1000
  731. )
  732. }
  733. }
  734. const imgTimings = stats.latexmk?.['latexmk-img-times']
  735. if (imgTimings != null) {
  736. for (const timing of imgTimings) {
  737. ClsiMetrics.imageProcessingDurationSeconds.observe(
  738. {
  739. group: request.compileGroup,
  740. type: timing.type,
  741. },
  742. timing.time_ms / 1000
  743. )
  744. }
  745. }
  746. ClsiMetrics.compilesTotal.inc({
  747. status,
  748. engine: request.compiler,
  749. image: tag,
  750. compile: request.metricsOpts.compile,
  751. group: request.compileGroup,
  752. draft: request.draft ? 'true' : 'false',
  753. stop_on_first_error: request.stopOnFirstError ? 'true' : 'false',
  754. passes,
  755. type: request.syncType,
  756. })
  757. if (timings.sync != null) {
  758. ClsiMetrics.syncResourcesDurationSeconds.observe(
  759. {
  760. type: request.syncType,
  761. compile: request.metricsOpts.compile,
  762. group: request.compileGroup,
  763. },
  764. timings.sync / 1000
  765. )
  766. }
  767. if (timings.compile != null) {
  768. ClsiMetrics.compileDurationSeconds.observe(
  769. {
  770. status,
  771. engine: request.compiler,
  772. compile: request.metricsOpts.compile,
  773. group: request.compileGroup,
  774. passes: passes === 0 ? 'none' : passes === 1 ? 'single' : 'multiple',
  775. },
  776. timings.compile / 1000
  777. )
  778. }
  779. if (timings.output != null) {
  780. ClsiMetrics.processOutputFilesDurationSeconds.observe(
  781. {
  782. compile: request.metricsOpts.compile,
  783. group: request.compileGroup,
  784. },
  785. timings.output / 1000
  786. )
  787. }
  788. if (timings.compileE2E != null) {
  789. ClsiMetrics.e2eCompileDurationSeconds.observe(
  790. {
  791. compileFromHistory: !!request.rawChangeOperations,
  792. compile: request.metricsOpts.compile,
  793. group: request.compileGroup,
  794. },
  795. timings.compileE2E / 1000
  796. )
  797. }
  798. }
  799. export default {
  800. doCompileWithLock: callbackify(doCompileWithLock),
  801. stopCompile: callbackify(stopCompile),
  802. clearProject: callbackify(clearProject),
  803. clearExpiredProjects: callbackify(clearExpiredProjects),
  804. syncFromCode: callbackifyMultiResult(syncFromCode, [
  805. 'codePositions',
  806. 'downloadedFromCache',
  807. ]),
  808. syncFromPdf: callbackifyMultiResult(syncFromPdf, [
  809. 'pdfPositions',
  810. 'downloadedFromCache',
  811. ]),
  812. wordcount: callbackify(wordcount),
  813. promises: {
  814. doCompileWithLock,
  815. stopCompile,
  816. clearProject,
  817. clearExpiredProjects,
  818. syncFromCode,
  819. syncFromPdf,
  820. wordcount,
  821. },
  822. }