CompileController.js 23 KB

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