CompileManager.js 22 KB

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