CompileController.mjs 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778
  1. import { URL } from 'node:url'
  2. import { pipeline } from 'node:stream/promises'
  3. import { Cookie } from 'tough-cookie'
  4. import OError from '@overleaf/o-error'
  5. import Metrics from '@overleaf/metrics'
  6. import ProjectGetter from '../Project/ProjectGetter.mjs'
  7. import CompileManager from './CompileManager.mjs'
  8. import ClsiManager from './ClsiManager.mjs'
  9. import logger from '@overleaf/logger'
  10. import Settings from '@overleaf/settings'
  11. import Errors from '../Errors/Errors.js'
  12. import SessionManager from '../Authentication/SessionManager.js'
  13. import { RateLimiter } from '../../infrastructure/RateLimiter.js'
  14. import Validation from '../../infrastructure/Validation.js'
  15. import ClsiCookieManagerFactory from './ClsiCookieManager.mjs'
  16. import Path from 'node:path'
  17. import AnalyticsManager from '../Analytics/AnalyticsManager.js'
  18. import SplitTestHandler from '../SplitTests/SplitTestHandler.js'
  19. import { expressify } from '@overleaf/promise-utils'
  20. import {
  21. fetchStreamWithResponse,
  22. RequestFailedError,
  23. } from '@overleaf/fetch-utils'
  24. const { z, zz, validateReq } = Validation
  25. const ClsiCookieManager = ClsiCookieManagerFactory(
  26. Settings.apis.clsi?.backendGroupName
  27. )
  28. const COMPILE_TIMEOUT_MS = 10 * 60 * 1000
  29. const pdfDownloadRateLimiter = new RateLimiter('full-pdf-download', {
  30. points: 1000,
  31. duration: 60 * 60,
  32. })
  33. function getOutputFilesArchiveSpecification(projectId, userId, buildId) {
  34. const fileName = 'output.zip'
  35. return {
  36. path: fileName,
  37. url: _CompileController._getFileUrl(projectId, userId, buildId, fileName),
  38. type: 'zip',
  39. }
  40. }
  41. async function getPdfCachingMinChunkSize(req, res) {
  42. const { variant } = await SplitTestHandler.promises.getAssignment(
  43. req,
  44. res,
  45. 'pdf-caching-min-chunk-size'
  46. )
  47. if (variant === 'default') {
  48. return 1_000_000
  49. }
  50. return parseInt(variant, 10)
  51. }
  52. async function _getSplitTestOptions(req, res) {
  53. // Use the query flags from the editor request for overriding the split test.
  54. let query = {}
  55. try {
  56. const u = new URL(req.headers.referer || req.url, Settings.siteUrl)
  57. query = Object.fromEntries(u.searchParams.entries())
  58. } catch (e) {}
  59. const editorReq = { ...req, query }
  60. // Lookup the clsi-cache flag in the backend.
  61. // We may need to turn off the feature on a short notice, without requiring
  62. // all users to reload their editor page to disable the feature.
  63. const { variant: populateClsiCacheVariant } =
  64. await SplitTestHandler.promises.getAssignment(
  65. editorReq,
  66. res,
  67. 'populate-clsi-cache'
  68. )
  69. let populateClsiCache = populateClsiCacheVariant === 'enabled'
  70. let compileFromClsiCache = populateClsiCache // use same split-test
  71. let clsiCachePromptVariant = 'default'
  72. if (!populateClsiCache) {
  73. // Pre-populate the cache for the users in the split-test for prompts.
  74. // Keep the compile from cache disabled for now.
  75. const { variant } = await SplitTestHandler.promises.getAssignment(
  76. editorReq,
  77. res,
  78. 'populate-clsi-cache-for-prompt'
  79. )
  80. ;({ variant: clsiCachePromptVariant } =
  81. await SplitTestHandler.promises.getAssignment(
  82. editorReq,
  83. res,
  84. 'clsi-cache-prompt'
  85. ))
  86. populateClsiCache = variant === 'enabled'
  87. compileFromClsiCache = populateClsiCache
  88. }
  89. const pdfDownloadDomain = Settings.pdfDownloadDomain
  90. if (!req.query.enable_pdf_caching) {
  91. // The frontend does not want to do pdf caching.
  92. return {
  93. compileFromClsiCache,
  94. populateClsiCache,
  95. clsiCachePromptVariant,
  96. pdfDownloadDomain,
  97. enablePdfCaching: false,
  98. }
  99. }
  100. // Double check with the latest split test assignment.
  101. // We may need to turn off the feature on a short notice, without requiring
  102. // all users to reload their editor page to disable the feature.
  103. const { variant } = await SplitTestHandler.promises.getAssignment(
  104. editorReq,
  105. res,
  106. 'pdf-caching-mode'
  107. )
  108. const enablePdfCaching = variant === 'enabled'
  109. if (!enablePdfCaching) {
  110. // Skip the lookup of the chunk size when caching is not enabled.
  111. return {
  112. compileFromClsiCache,
  113. populateClsiCache,
  114. clsiCachePromptVariant,
  115. pdfDownloadDomain,
  116. enablePdfCaching: false,
  117. }
  118. }
  119. const pdfCachingMinChunkSize = await getPdfCachingMinChunkSize(editorReq, res)
  120. return {
  121. compileFromClsiCache,
  122. populateClsiCache,
  123. clsiCachePromptVariant,
  124. pdfDownloadDomain,
  125. enablePdfCaching,
  126. pdfCachingMinChunkSize,
  127. }
  128. }
  129. async function _syncTeX(req, res, direction, validatedOptions) {
  130. const projectId = req.params.Project_id
  131. const { editorId, buildId, clsiserverid: clsiServerId } = req.query
  132. if (!editorId?.match(/^[a-f0-9-]+$/)) throw new Error('invalid ?editorId')
  133. if (!buildId?.match(/^[a-f0-9-]+$/)) throw new Error('invalid ?buildId')
  134. const userId = CompileController._getUserIdForCompile(req)
  135. const { compileFromClsiCache } = await _getSplitTestOptions(req, res)
  136. try {
  137. const body = await CompileManager.promises.syncTeX(projectId, userId, {
  138. direction,
  139. compileFromClsiCache,
  140. validatedOptions: {
  141. ...validatedOptions,
  142. editorId,
  143. buildId,
  144. },
  145. clsiServerId,
  146. })
  147. res.json(body)
  148. } catch (err) {
  149. if (err instanceof Errors.NotFoundError) return res.status(404).end()
  150. throw err
  151. }
  152. }
  153. const deleteAuxFilesSchema = z.object({
  154. params: z.object({
  155. Project_id: zz.objectId(),
  156. }),
  157. query: z.object({
  158. clsiserverid: z.string().optional(),
  159. }),
  160. })
  161. const wordCountSchema = z.object({
  162. params: z.object({
  163. Project_id: zz.objectId(),
  164. }),
  165. query: z.object({
  166. clsiserverid: z.string().optional(),
  167. file: z.string().optional(),
  168. }),
  169. })
  170. const _CompileController = {
  171. async compile(req, res) {
  172. res.setTimeout(COMPILE_TIMEOUT_MS)
  173. const projectId = req.params.Project_id
  174. const isAutoCompile = !!req.query.auto_compile
  175. const fileLineErrors = !!req.query.file_line_errors
  176. const stopOnFirstError = !!req.body.stopOnFirstError
  177. const userId = SessionManager.getLoggedInUserId(req.session)
  178. const options = {
  179. isAutoCompile,
  180. fileLineErrors,
  181. stopOnFirstError,
  182. editorId: req.body.editorId,
  183. }
  184. if (req.body.rootDoc_id) {
  185. options.rootDoc_id = req.body.rootDoc_id
  186. } else if (
  187. req.body.settingsOverride &&
  188. req.body.settingsOverride.rootDoc_id
  189. ) {
  190. // Can be removed after deploy
  191. options.rootDoc_id = req.body.settingsOverride.rootDoc_id
  192. }
  193. if (req.body.compiler) {
  194. options.compiler = req.body.compiler
  195. }
  196. if (req.body.draft) {
  197. options.draft = req.body.draft
  198. }
  199. if (['validate', 'error', 'silent'].includes(req.body.check)) {
  200. options.check = req.body.check
  201. }
  202. if (req.body.incrementalCompilesEnabled) {
  203. options.incrementalCompilesEnabled = true
  204. }
  205. let {
  206. compileFromClsiCache,
  207. populateClsiCache,
  208. clsiCachePromptVariant,
  209. enablePdfCaching,
  210. pdfCachingMinChunkSize,
  211. pdfDownloadDomain,
  212. } = await _getSplitTestOptions(req, res)
  213. options.compileFromClsiCache = compileFromClsiCache
  214. options.populateClsiCache = populateClsiCache
  215. options.enablePdfCaching = enablePdfCaching
  216. if (enablePdfCaching) {
  217. options.pdfCachingMinChunkSize = pdfCachingMinChunkSize
  218. }
  219. const {
  220. status,
  221. outputFiles,
  222. clsiServerId,
  223. limits,
  224. validationProblems,
  225. stats,
  226. timings,
  227. outputUrlPrefix,
  228. buildId,
  229. clsiCacheShard,
  230. } = await CompileManager.promises
  231. .compile(projectId, userId, options)
  232. .catch(error => {
  233. Metrics.inc('compile-error')
  234. throw error
  235. })
  236. Metrics.inc('compile-status', 1, { status })
  237. if (pdfDownloadDomain && outputUrlPrefix) {
  238. pdfDownloadDomain += outputUrlPrefix
  239. }
  240. if (
  241. limits &&
  242. SplitTestHandler.getPercentile(
  243. AnalyticsManager.getIdsFromSession(req.session).analyticsId,
  244. 'compile-result-backend',
  245. 'release'
  246. ) === 1
  247. ) {
  248. // For a compile request to be sent to clsi we need limits.
  249. // If we get here without having the limits object populated, it is
  250. // a reasonable assumption to make that nothing was compiled.
  251. // We need to know the limits in order to make use of the events.
  252. AnalyticsManager.recordEventForSession(
  253. req.session,
  254. 'compile-result-backend',
  255. {
  256. projectId,
  257. ownerAnalyticsId: limits.ownerAnalyticsId,
  258. status,
  259. compileTime: timings?.compileE2E,
  260. timeout: limits.timeout,
  261. server:
  262. clsiServerId?.includes('-c2d-') ||
  263. clsiServerId?.includes('-c3d-') ||
  264. clsiServerId?.includes('-c4d-')
  265. ? 'faster'
  266. : 'normal',
  267. clsiServerId,
  268. isAutoCompile,
  269. isInitialCompile: stats?.isInitialCompile === 1,
  270. restoredClsiCache: stats?.restoredClsiCache === 1,
  271. stopOnFirstError,
  272. isDraftMode: !!options.draft,
  273. }
  274. )
  275. }
  276. const outputFilesArchive = buildId
  277. ? getOutputFilesArchiveSpecification(projectId, userId, buildId)
  278. : null
  279. res.json({
  280. status,
  281. outputFiles,
  282. outputFilesArchive,
  283. compileGroup: limits?.compileGroup,
  284. clsiServerId,
  285. clsiCacheShard,
  286. clsiCachePromptVariant: ['alpha', 'priority'].includes(
  287. limits?.compileGroup
  288. )
  289. ? clsiCachePromptVariant
  290. : 'default',
  291. validationProblems,
  292. stats,
  293. timings,
  294. outputUrlPrefix,
  295. pdfDownloadDomain,
  296. pdfCachingMinChunkSize,
  297. })
  298. },
  299. async stopCompile(req, res) {
  300. const projectId = req.params.Project_id
  301. const userId = SessionManager.getLoggedInUserId(req.session)
  302. await CompileManager.promises.stopCompile(projectId, userId)
  303. res.sendStatus(200)
  304. },
  305. // Used for submissions through the public API
  306. async compileSubmission(req, res) {
  307. res.setTimeout(COMPILE_TIMEOUT_MS)
  308. const submissionId = req.params.submission_id
  309. const options = {}
  310. if (req.body?.rootResourcePath != null) {
  311. options.rootResourcePath = req.body.rootResourcePath
  312. }
  313. if (req.body?.compiler) {
  314. options.compiler = req.body.compiler
  315. }
  316. if (req.body?.draft) {
  317. options.draft = req.body.draft
  318. }
  319. if (['validate', 'error', 'silent'].includes(req.body?.check)) {
  320. options.check = req.body.check
  321. }
  322. options.compileGroup =
  323. req.body?.compileGroup || Settings.defaultFeatures.compileGroup
  324. options.compileBackendClass = Settings.apis.clsi.submissionBackendClass
  325. options.timeout =
  326. req.body?.timeout || Settings.defaultFeatures.compileTimeout
  327. const { status, outputFiles, clsiServerId, validationProblems } =
  328. await ClsiManager.promises.sendExternalRequest(
  329. submissionId,
  330. req.body,
  331. options
  332. )
  333. res.json({
  334. status,
  335. outputFiles,
  336. clsiServerId,
  337. validationProblems,
  338. })
  339. },
  340. _getUserIdForCompile(req) {
  341. if (!Settings.disablePerUserCompiles) {
  342. return SessionManager.getLoggedInUserId(req.session)
  343. }
  344. return null
  345. },
  346. async downloadPdf(req, res) {
  347. Metrics.inc('pdf-downloads')
  348. const projectId = req.params.Project_id
  349. const rateLimit = () =>
  350. pdfDownloadRateLimiter
  351. .consume(req.ip, 1, { method: 'ip' })
  352. .then(() => true)
  353. .catch(err => {
  354. if (err instanceof Error) {
  355. throw err
  356. }
  357. return false
  358. })
  359. const project = await ProjectGetter.promises.getProject(projectId, {
  360. name: 1,
  361. })
  362. res.contentType('application/pdf')
  363. const filename = `${_CompileController._getSafeProjectName(project)}.pdf`
  364. if (req.query.popupDownload) {
  365. res.setContentDisposition('attachment', { filename })
  366. } else {
  367. res.setContentDisposition('inline', { filename })
  368. }
  369. let canContinue
  370. try {
  371. canContinue = await rateLimit()
  372. } catch (err) {
  373. logger.err({ err }, 'error checking rate limit for pdf download')
  374. res.sendStatus(500)
  375. return
  376. }
  377. if (!canContinue) {
  378. logger.debug({ projectId, ip: req.ip }, 'rate limit hit downloading pdf')
  379. res.sendStatus(500) // should it be 429?
  380. } else {
  381. const userId = CompileController._getUserIdForCompile(req)
  382. const url = _CompileController._getFileUrl(
  383. projectId,
  384. userId,
  385. req.params.build_id,
  386. 'output.pdf'
  387. )
  388. await CompileController._proxyToClsi(
  389. projectId,
  390. 'output-file',
  391. url,
  392. {},
  393. req,
  394. res
  395. )
  396. }
  397. },
  398. // Keep in sync with the logic for zip files in ProjectDownloadsController
  399. _getSafeProjectName(project) {
  400. return project.name.replace(/[^\p{L}\p{Nd}]/gu, '_')
  401. },
  402. async deleteAuxFiles(req, res) {
  403. const { params, query } = validateReq(req, deleteAuxFilesSchema)
  404. const projectId = params.Project_id
  405. const { clsiserverid } = query
  406. const userId = await CompileController._getUserIdForCompile(req)
  407. await CompileManager.promises.deleteAuxFiles(
  408. projectId,
  409. userId,
  410. clsiserverid
  411. )
  412. res.sendStatus(200)
  413. },
  414. // this is only used by templates, so is not called with a userId
  415. async compileAndDownloadPdf(req, res) {
  416. const projectId = req.params.project_id
  417. let outputFiles
  418. try {
  419. ;({ outputFiles } = await CompileManager.promises
  420. // pass userId as null, since templates are an "anonymous" compile
  421. .compile(projectId, null, {}))
  422. } catch (err) {
  423. logger.err(
  424. { err, projectId },
  425. 'something went wrong compile and downloading pdf'
  426. )
  427. res.sendStatus(500)
  428. return
  429. }
  430. const pdf = outputFiles.find(f => f.path === 'output.pdf')
  431. if (!pdf) {
  432. logger.warn(
  433. { projectId },
  434. 'something went wrong compile and downloading pdf: no pdf'
  435. )
  436. res.sendStatus(500)
  437. return
  438. }
  439. await CompileController._proxyToClsi(
  440. projectId,
  441. 'output-file',
  442. pdf.url,
  443. {},
  444. req,
  445. res
  446. )
  447. },
  448. async getFileFromClsi(req, res) {
  449. const projectId = req.params.Project_id
  450. const userId = CompileController._getUserIdForCompile(req)
  451. const qs = {}
  452. const url = _CompileController._getFileUrl(
  453. projectId,
  454. userId,
  455. req.params.build_id,
  456. req.params.file
  457. )
  458. await CompileController._proxyToClsi(
  459. projectId,
  460. 'output-file',
  461. url,
  462. qs,
  463. req,
  464. res
  465. )
  466. },
  467. async getFileFromClsiWithoutUser(req, res) {
  468. const submissionId = req.params.submission_id
  469. const url = _CompileController._getFileUrl(
  470. submissionId,
  471. null,
  472. req.params.build_id,
  473. req.params.file
  474. )
  475. const limits = {
  476. compileGroup:
  477. req.body?.compileGroup ||
  478. req.query?.compileGroup ||
  479. Settings.defaultFeatures.compileGroup,
  480. compileBackendClass: Settings.apis.clsi.submissionBackendClass,
  481. }
  482. await CompileController._proxyToClsiWithLimits(
  483. submissionId,
  484. 'output-file',
  485. url,
  486. {},
  487. limits,
  488. req,
  489. res
  490. )
  491. },
  492. // compute a GET file url for a given project, user (optional), build (optional) and file
  493. _getFileUrl(projectId, userId, buildId, file) {
  494. let url
  495. if (userId != null && buildId != null) {
  496. url = `/project/${projectId}/user/${userId}/build/${buildId}/output/${file}`
  497. } else if (userId != null) {
  498. url = `/project/${projectId}/user/${userId}/output/${file}`
  499. } else if (buildId != null) {
  500. url = `/project/${projectId}/build/${buildId}/output/${file}`
  501. } else {
  502. url = `/project/${projectId}/output/${file}`
  503. }
  504. return url
  505. },
  506. async proxySyncPdf(req, res) {
  507. const { page, h, v } = req.query
  508. if (!page?.match(/^\d+$/)) {
  509. throw new Error('invalid page parameter')
  510. }
  511. if (!h?.match(/^-?\d+\.\d+$/)) {
  512. throw new Error('invalid h parameter')
  513. }
  514. if (!v?.match(/^-?\d+\.\d+$/)) {
  515. throw new Error('invalid v parameter')
  516. }
  517. await _syncTeX(req, res, 'pdf', { page, h, v })
  518. },
  519. async proxySyncCode(req, res) {
  520. const { file, line, column } = req.query
  521. if (file == null) {
  522. throw new Error('missing file parameter')
  523. }
  524. // Check that we are dealing with a simple file path (this is not
  525. // strictly needed because synctex uses this parameter as a label
  526. // to look up in the synctex output, and does not open the file
  527. // itself). Since we have valid synctex paths like foo/./bar we
  528. // allow those by replacing /./ with /
  529. const testPath = file.replace('/./', '/')
  530. if (Path.resolve('/', testPath) !== `/${testPath}`) {
  531. throw new Error('invalid file parameter')
  532. }
  533. if (!line?.match(/^\d+$/)) {
  534. throw new Error('invalid line parameter')
  535. }
  536. if (!column?.match(/^\d+$/)) {
  537. throw new Error('invalid column parameter')
  538. }
  539. await _syncTeX(req, res, 'code', { file, line, column })
  540. },
  541. async _proxyToClsi(projectId, action, url, qs, req, res) {
  542. const limits =
  543. await CompileManager.promises.getProjectCompileLimits(projectId)
  544. return CompileController._proxyToClsiWithLimits(
  545. projectId,
  546. action,
  547. url,
  548. qs,
  549. limits,
  550. req,
  551. res
  552. )
  553. },
  554. async _proxyToClsiWithLimits(projectId, action, url, qs, limits, req, res) {
  555. const persistenceOptions = await _getPersistenceOptions(
  556. req,
  557. projectId,
  558. limits.compileGroup,
  559. limits.compileBackendClass
  560. ).catch(err => {
  561. OError.tag(err, 'error getting cookie jar for clsi request')
  562. throw err
  563. })
  564. url = new URL(`${Settings.apis.clsi.url}${url}`)
  565. const searchParams = {
  566. ...persistenceOptions.qs,
  567. ...qs,
  568. }
  569. for (const [key, value] of Object.entries(searchParams)) {
  570. if (value !== undefined) {
  571. // avoid sending "undefined" as a string value
  572. url.searchParams.set(key, value)
  573. }
  574. }
  575. const timer = new Metrics.Timer(
  576. 'proxy_to_clsi',
  577. 1,
  578. { path: action },
  579. [0, 100, 1000, 2000, 5000, 10000, 15000, 20000, 30000, 45000, 60000]
  580. )
  581. Metrics.inc('proxy_to_clsi', 1, { path: action, status: 'start' })
  582. try {
  583. const { stream, response } = await fetchStreamWithResponse(url.href, {
  584. method: req.method,
  585. signal: AbortSignal.timeout(60 * 1000),
  586. headers: persistenceOptions.headers,
  587. })
  588. if (req.destroyed) {
  589. // The client has disconnected already, avoid trying to write into the broken connection.
  590. Metrics.inc('proxy_to_clsi', 1, {
  591. path: action,
  592. status: 'req-aborted',
  593. })
  594. return
  595. }
  596. Metrics.inc('proxy_to_clsi', 1, {
  597. path: action,
  598. status: response.status,
  599. })
  600. for (const key of ['Content-Length', 'Content-Type']) {
  601. if (response.headers.has(key)) {
  602. res.setHeader(key, response.headers.get(key))
  603. }
  604. }
  605. res.writeHead(response.status)
  606. await pipeline(stream, res)
  607. timer.labels.status = 'success'
  608. timer.done()
  609. } catch (err) {
  610. const reqAborted = Boolean(req.destroyed)
  611. const status = reqAborted ? 'req-aborted-late' : 'error'
  612. timer.labels.status = status
  613. const duration = timer.done()
  614. Metrics.inc('proxy_to_clsi', 1, { path: action, status })
  615. const streamingStarted = Boolean(res.headersSent)
  616. if (!streamingStarted) {
  617. if (err instanceof RequestFailedError) {
  618. res.sendStatus(err.response.status)
  619. } else {
  620. res.sendStatus(500)
  621. }
  622. }
  623. if (
  624. streamingStarted &&
  625. reqAborted &&
  626. err.code === 'ERR_STREAM_PREMATURE_CLOSE'
  627. ) {
  628. // Ignore noisy spurious error
  629. return
  630. }
  631. if (
  632. err instanceof RequestFailedError &&
  633. ['sync-to-code', 'sync-to-pdf', 'output-file'].includes(action)
  634. ) {
  635. // Ignore noisy error
  636. // https://github.com/overleaf/internal/issues/15201
  637. return
  638. }
  639. logger.warn(
  640. {
  641. err,
  642. projectId,
  643. url,
  644. action,
  645. reqAborted,
  646. streamingStarted,
  647. duration,
  648. },
  649. 'CLSI proxy error'
  650. )
  651. }
  652. },
  653. async wordCount(req, res) {
  654. const { params, query } = validateReq(req, wordCountSchema)
  655. const projectId = params.Project_id
  656. const file = query.file || false
  657. const { clsiserverid } = query
  658. const userId = CompileController._getUserIdForCompile(req)
  659. const body = await CompileManager.promises.wordCount(
  660. projectId,
  661. userId,
  662. file,
  663. clsiserverid
  664. )
  665. res.json(body)
  666. },
  667. }
  668. async function _getPersistenceOptions(
  669. req,
  670. projectId,
  671. compileGroup,
  672. compileBackendClass
  673. ) {
  674. const { clsiserverid } = req.query
  675. const userId = SessionManager.getLoggedInUserId(req)
  676. if (clsiserverid && typeof clsiserverid === 'string') {
  677. return {
  678. qs: { clsiserverid, compileGroup, compileBackendClass },
  679. headers: {},
  680. }
  681. } else {
  682. const clsiServerId = await ClsiCookieManager.promises.getServerId(
  683. projectId,
  684. userId,
  685. compileGroup,
  686. compileBackendClass
  687. )
  688. return {
  689. qs: { compileGroup, compileBackendClass },
  690. headers: clsiServerId
  691. ? {
  692. Cookie: new Cookie({
  693. key: Settings.clsiCookie.key,
  694. value: clsiServerId,
  695. }).cookieString(),
  696. }
  697. : {},
  698. }
  699. }
  700. }
  701. const CompileController = {
  702. COMPILE_TIMEOUT_MS,
  703. compile: expressify(_CompileController.compile),
  704. stopCompile: expressify(_CompileController.stopCompile),
  705. compileSubmission: expressify(_CompileController.compileSubmission),
  706. downloadPdf: expressify(_CompileController.downloadPdf), //
  707. compileAndDownloadPdf: expressify(_CompileController.compileAndDownloadPdf),
  708. deleteAuxFiles: expressify(_CompileController.deleteAuxFiles),
  709. getFileFromClsi: expressify(_CompileController.getFileFromClsi),
  710. getFileFromClsiWithoutUser: expressify(
  711. _CompileController.getFileFromClsiWithoutUser
  712. ),
  713. proxySyncPdf: expressify(_CompileController.proxySyncPdf),
  714. proxySyncCode: expressify(_CompileController.proxySyncCode),
  715. wordCount: expressify(_CompileController.wordCount),
  716. _getSafeProjectName: _CompileController._getSafeProjectName,
  717. _getSplitTestOptions,
  718. _getUserIdForCompile: _CompileController._getUserIdForCompile,
  719. _proxyToClsi: _CompileController._proxyToClsi,
  720. _proxyToClsiWithLimits: _CompileController._proxyToClsiWithLimits,
  721. }
  722. export default CompileController