CompileController.js 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797
  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. clsiCacheShard
  183. ) => {
  184. if (error) {
  185. Metrics.inc('compile-error')
  186. return next(error)
  187. }
  188. Metrics.inc('compile-status', 1, { status })
  189. if (pdfDownloadDomain && outputUrlPrefix) {
  190. pdfDownloadDomain += outputUrlPrefix
  191. }
  192. if (limits) {
  193. // For a compile request to be sent to clsi we need limits.
  194. // If we get here without having the limits object populated, it is
  195. // a reasonable assumption to make that nothing was compiled.
  196. // We need to know the limits in order to make use of the events.
  197. AnalyticsManager.recordEventForSession(
  198. req.session,
  199. 'compile-result-backend',
  200. {
  201. projectId,
  202. ownerAnalyticsId: limits.ownerAnalyticsId,
  203. status,
  204. compileTime: timings?.compileE2E,
  205. timeout: limits.timeout === 60 ? 'short' : 'long',
  206. server: clsiServerId?.includes('-c2d-') ? 'faster' : 'normal',
  207. isAutoCompile,
  208. isInitialCompile: stats?.isInitialCompile === 1,
  209. restoredClsiCache: stats?.restoredClsiCache === 1,
  210. stopOnFirstError,
  211. }
  212. )
  213. }
  214. const outputFilesArchive = buildId
  215. ? getOutputFilesArchiveSpecification(projectId, userId, buildId)
  216. : null
  217. res.json({
  218. status,
  219. outputFiles,
  220. outputFilesArchive,
  221. compileGroup: limits?.compileGroup,
  222. clsiServerId,
  223. clsiCacheShard,
  224. validationProblems,
  225. stats,
  226. timings,
  227. outputUrlPrefix,
  228. pdfDownloadDomain,
  229. pdfCachingMinChunkSize,
  230. })
  231. }
  232. )
  233. })
  234. },
  235. stopCompile(req, res, next) {
  236. const projectId = req.params.Project_id
  237. const userId = SessionManager.getLoggedInUserId(req.session)
  238. CompileManager.stopCompile(projectId, userId, function (error) {
  239. if (error) {
  240. return next(error)
  241. }
  242. res.sendStatus(200)
  243. })
  244. },
  245. // Used for submissions through the public API
  246. compileSubmission(req, res, next) {
  247. res.setTimeout(COMPILE_TIMEOUT_MS)
  248. const submissionId = req.params.submission_id
  249. const options = {}
  250. if (req.body?.rootResourcePath != null) {
  251. options.rootResourcePath = req.body.rootResourcePath
  252. }
  253. if (req.body?.compiler) {
  254. options.compiler = req.body.compiler
  255. }
  256. if (req.body?.draft) {
  257. options.draft = req.body.draft
  258. }
  259. if (['validate', 'error', 'silent'].includes(req.body?.check)) {
  260. options.check = req.body.check
  261. }
  262. options.compileGroup =
  263. req.body?.compileGroup || Settings.defaultFeatures.compileGroup
  264. options.compileBackendClass = Settings.apis.clsi.submissionBackendClass
  265. options.timeout =
  266. req.body?.timeout || Settings.defaultFeatures.compileTimeout
  267. ClsiManager.sendExternalRequest(
  268. submissionId,
  269. req.body,
  270. options,
  271. function (error, status, outputFiles, clsiServerId, validationProblems) {
  272. if (error) {
  273. return next(error)
  274. }
  275. res.json({
  276. status,
  277. outputFiles,
  278. clsiServerId,
  279. validationProblems,
  280. })
  281. }
  282. )
  283. },
  284. _getSplitTestOptions,
  285. _getUserIdForCompile(req) {
  286. if (!Settings.disablePerUserCompiles) {
  287. return SessionManager.getLoggedInUserId(req.session)
  288. }
  289. return null
  290. },
  291. _compileAsUser(req, callback) {
  292. callback(null, CompileController._getUserIdForCompile(req))
  293. },
  294. _downloadAsUser(req, callback) {
  295. callback(null, CompileController._getUserIdForCompile(req))
  296. },
  297. downloadPdf(req, res, next) {
  298. Metrics.inc('pdf-downloads')
  299. const projectId = req.params.Project_id
  300. const rateLimit = function (callback) {
  301. pdfDownloadRateLimiter
  302. .consume(req.ip, 1, { method: 'ip' })
  303. .then(() => {
  304. callback(null, true)
  305. })
  306. .catch(err => {
  307. if (err instanceof Error) {
  308. callback(err)
  309. } else {
  310. callback(null, false)
  311. }
  312. })
  313. }
  314. ProjectGetter.getProject(projectId, { name: 1 }, function (err, project) {
  315. if (err) {
  316. return next(err)
  317. }
  318. res.contentType('application/pdf')
  319. const filename = `${CompileController._getSafeProjectName(project)}.pdf`
  320. if (req.query.popupDownload) {
  321. res.setContentDisposition('attachment', { filename })
  322. } else {
  323. res.setContentDisposition('inline', { filename })
  324. }
  325. rateLimit(function (err, canContinue) {
  326. if (err) {
  327. logger.err({ err }, 'error checking rate limit for pdf download')
  328. res.sendStatus(500)
  329. } else if (!canContinue) {
  330. logger.debug(
  331. { projectId, ip: req.ip },
  332. 'rate limit hit downloading pdf'
  333. )
  334. res.sendStatus(500)
  335. } else {
  336. CompileController._downloadAsUser(req, function (error, userId) {
  337. if (error) {
  338. return next(error)
  339. }
  340. const url = CompileController._getFileUrl(
  341. projectId,
  342. userId,
  343. req.params.build_id,
  344. 'output.pdf'
  345. )
  346. CompileController.proxyToClsi(
  347. projectId,
  348. 'output-file',
  349. url,
  350. {},
  351. req,
  352. res,
  353. next
  354. )
  355. })
  356. }
  357. })
  358. })
  359. },
  360. _getSafeProjectName(project) {
  361. return project.name.replace(/[^\p{L}\p{Nd}]/gu, '_')
  362. },
  363. deleteAuxFiles(req, res, next) {
  364. const projectId = req.params.Project_id
  365. const { clsiserverid } = req.query
  366. CompileController._compileAsUser(req, function (error, userId) {
  367. if (error) {
  368. return next(error)
  369. }
  370. CompileManager.deleteAuxFiles(
  371. projectId,
  372. userId,
  373. clsiserverid,
  374. function (error) {
  375. if (error) {
  376. return next(error)
  377. }
  378. res.sendStatus(200)
  379. }
  380. )
  381. })
  382. },
  383. // this is only used by templates, so is not called with a userId
  384. compileAndDownloadPdf(req, res, next) {
  385. const projectId = req.params.project_id
  386. // pass userId as null, since templates are an "anonymous" compile
  387. CompileManager.compile(projectId, null, {}, (err, _status, outputFiles) => {
  388. if (err) {
  389. logger.err(
  390. { err, projectId },
  391. 'something went wrong compile and downloading pdf'
  392. )
  393. res.sendStatus(500)
  394. return
  395. }
  396. const pdf = outputFiles.find(f => f.path === 'output.pdf')
  397. if (!pdf) {
  398. logger.warn(
  399. { projectId },
  400. 'something went wrong compile and downloading pdf: no pdf'
  401. )
  402. res.sendStatus(500)
  403. return
  404. }
  405. CompileController.proxyToClsi(
  406. projectId,
  407. 'output-file',
  408. pdf.url,
  409. {},
  410. req,
  411. res,
  412. next
  413. )
  414. })
  415. },
  416. getFileFromClsi(req, res, next) {
  417. const projectId = req.params.Project_id
  418. CompileController._downloadAsUser(req, function (error, userId) {
  419. if (error) {
  420. return next(error)
  421. }
  422. const qs = {}
  423. const url = CompileController._getFileUrl(
  424. projectId,
  425. userId,
  426. req.params.build_id,
  427. req.params.file
  428. )
  429. CompileController.proxyToClsi(
  430. projectId,
  431. 'output-file',
  432. url,
  433. qs,
  434. req,
  435. res,
  436. next
  437. )
  438. })
  439. },
  440. getFileFromClsiWithoutUser(req, res, next) {
  441. const submissionId = req.params.submission_id
  442. const url = CompileController._getFileUrl(
  443. submissionId,
  444. null,
  445. req.params.build_id,
  446. req.params.file
  447. )
  448. const limits = {
  449. compileGroup:
  450. req.body?.compileGroup ||
  451. req.query?.compileGroup ||
  452. Settings.defaultFeatures.compileGroup,
  453. compileBackendClass: Settings.apis.clsi.submissionBackendClass,
  454. }
  455. CompileController.proxyToClsiWithLimits(
  456. submissionId,
  457. 'output-file',
  458. url,
  459. {},
  460. limits,
  461. req,
  462. res,
  463. next
  464. )
  465. },
  466. // compute a GET file url for a given project, user (optional), build (optional) and file
  467. _getFileUrl(projectId, userId, buildId, file) {
  468. let url
  469. if (userId != null && buildId != null) {
  470. url = `/project/${projectId}/user/${userId}/build/${buildId}/output/${file}`
  471. } else if (userId != null) {
  472. url = `/project/${projectId}/user/${userId}/output/${file}`
  473. } else if (buildId != null) {
  474. url = `/project/${projectId}/build/${buildId}/output/${file}`
  475. } else {
  476. url = `/project/${projectId}/output/${file}`
  477. }
  478. return url
  479. },
  480. // compute a POST url for a project, user (optional) and action
  481. _getUrl(projectId, userId, action) {
  482. let path = `/project/${projectId}`
  483. if (userId != null) {
  484. path += `/user/${userId}`
  485. }
  486. return `${path}/${action}`
  487. },
  488. proxySyncPdf(req, res, next) {
  489. const projectId = req.params.Project_id
  490. const { page, h, v, editorId, buildId } = req.query
  491. if (!page?.match(/^\d+$/)) {
  492. return next(new Error('invalid page parameter'))
  493. }
  494. if (!h?.match(/^-?\d+\.\d+$/)) {
  495. return next(new Error('invalid h parameter'))
  496. }
  497. if (!v?.match(/^-?\d+\.\d+$/)) {
  498. return next(new Error('invalid v parameter'))
  499. }
  500. // whether this request is going to a per-user container
  501. CompileController._compileAsUser(req, function (error, userId) {
  502. if (error) {
  503. return next(error)
  504. }
  505. getImageNameForProject(projectId, (error, imageName) => {
  506. if (error) return next(error)
  507. getSplitTestOptionsCb(req, res, (error, splitTestOptions) => {
  508. if (error) return next(error)
  509. const { compileFromClsiCache } = splitTestOptions
  510. const url = CompileController._getUrl(projectId, userId, 'sync/pdf')
  511. CompileController.proxyToClsi(
  512. projectId,
  513. 'sync-to-pdf',
  514. url,
  515. { page, h, v, imageName, editorId, buildId, compileFromClsiCache },
  516. req,
  517. res,
  518. next
  519. )
  520. })
  521. })
  522. })
  523. },
  524. proxySyncCode(req, res, next) {
  525. const projectId = req.params.Project_id
  526. const { file, line, column, editorId, buildId } = req.query
  527. if (file == null) {
  528. return next(new Error('missing file parameter'))
  529. }
  530. // Check that we are dealing with a simple file path (this is not
  531. // strictly needed because synctex uses this parameter as a label
  532. // to look up in the synctex output, and does not open the file
  533. // itself). Since we have valid synctex paths like foo/./bar we
  534. // allow those by replacing /./ with /
  535. const testPath = file.replace('/./', '/')
  536. if (Path.resolve('/', testPath) !== `/${testPath}`) {
  537. return next(new Error('invalid file parameter'))
  538. }
  539. if (!line?.match(/^\d+$/)) {
  540. return next(new Error('invalid line parameter'))
  541. }
  542. if (!column?.match(/^\d+$/)) {
  543. return next(new Error('invalid column parameter'))
  544. }
  545. CompileController._compileAsUser(req, function (error, userId) {
  546. if (error) {
  547. return next(error)
  548. }
  549. getImageNameForProject(projectId, (error, imageName) => {
  550. if (error) return next(error)
  551. getSplitTestOptionsCb(req, res, (error, splitTestOptions) => {
  552. if (error) return next(error)
  553. const { compileFromClsiCache } = splitTestOptions
  554. const url = CompileController._getUrl(projectId, userId, 'sync/code')
  555. CompileController.proxyToClsi(
  556. projectId,
  557. 'sync-to-code',
  558. url,
  559. {
  560. file,
  561. line,
  562. column,
  563. imageName,
  564. editorId,
  565. buildId,
  566. compileFromClsiCache,
  567. },
  568. req,
  569. res,
  570. next
  571. )
  572. })
  573. })
  574. })
  575. },
  576. proxyToClsi(projectId, action, url, qs, req, res, next) {
  577. CompileManager.getProjectCompileLimits(projectId, function (error, limits) {
  578. if (error) {
  579. return next(error)
  580. }
  581. CompileController.proxyToClsiWithLimits(
  582. projectId,
  583. action,
  584. url,
  585. qs,
  586. limits,
  587. req,
  588. res,
  589. next
  590. )
  591. })
  592. },
  593. proxyToClsiWithLimits(projectId, action, url, qs, limits, req, res, next) {
  594. _getPersistenceOptions(
  595. req,
  596. projectId,
  597. limits.compileGroup,
  598. limits.compileBackendClass,
  599. (err, persistenceOptions) => {
  600. if (err) {
  601. OError.tag(err, 'error getting cookie jar for clsi request')
  602. return next(err)
  603. }
  604. url = new URL(`${Settings.apis.clsi.url}${url}`)
  605. url.search = new URLSearchParams({
  606. ...persistenceOptions.qs,
  607. ...qs,
  608. }).toString()
  609. const timer = new Metrics.Timer(
  610. 'proxy_to_clsi',
  611. 1,
  612. { path: action },
  613. [0, 100, 1000, 2000, 5000, 10000, 15000, 20000, 30000, 45000, 60000]
  614. )
  615. Metrics.inc('proxy_to_clsi', 1, { path: action, status: 'start' })
  616. fetchStreamWithResponse(url.href, {
  617. method: req.method,
  618. signal: AbortSignal.timeout(60 * 1000),
  619. headers: persistenceOptions.headers,
  620. })
  621. .then(({ stream, response }) => {
  622. if (req.destroyed) {
  623. // The client has disconnected already, avoid trying to write into the broken connection.
  624. Metrics.inc('proxy_to_clsi', 1, {
  625. path: action,
  626. status: 'req-aborted',
  627. })
  628. return
  629. }
  630. Metrics.inc('proxy_to_clsi', 1, {
  631. path: action,
  632. status: response.status,
  633. })
  634. for (const key of ['Content-Length', 'Content-Type']) {
  635. if (response.headers.has(key)) {
  636. res.setHeader(key, response.headers.get(key))
  637. }
  638. }
  639. res.writeHead(response.status)
  640. return pipeline(stream, res)
  641. })
  642. .then(() => {
  643. timer.labels.status = 'success'
  644. timer.done()
  645. })
  646. .catch(err => {
  647. const reqAborted = Boolean(req.destroyed)
  648. const status = reqAborted ? 'req-aborted-late' : 'error'
  649. timer.labels.status = status
  650. const duration = timer.done()
  651. Metrics.inc('proxy_to_clsi', 1, { path: action, status })
  652. const streamingStarted = Boolean(res.headersSent)
  653. if (!streamingStarted) {
  654. if (err instanceof RequestFailedError) {
  655. res.sendStatus(err.response.status)
  656. } else {
  657. res.sendStatus(500)
  658. }
  659. }
  660. if (
  661. streamingStarted &&
  662. reqAborted &&
  663. err.code === 'ERR_STREAM_PREMATURE_CLOSE'
  664. ) {
  665. // Ignore noisy spurious error
  666. return
  667. }
  668. if (
  669. err instanceof RequestFailedError &&
  670. ['sync-to-code', 'sync-to-pdf', 'output-file'].includes(action)
  671. ) {
  672. // Ignore noisy error
  673. // https://github.com/overleaf/internal/issues/15201
  674. return
  675. }
  676. logger.warn(
  677. {
  678. err,
  679. projectId,
  680. url,
  681. action,
  682. reqAborted,
  683. streamingStarted,
  684. duration,
  685. },
  686. 'CLSI proxy error'
  687. )
  688. })
  689. }
  690. )
  691. },
  692. wordCount(req, res, next) {
  693. const projectId = req.params.Project_id
  694. const file = req.query.file || false
  695. const { clsiserverid } = req.query
  696. CompileController._compileAsUser(req, function (error, userId) {
  697. if (error) {
  698. return next(error)
  699. }
  700. CompileManager.wordCount(
  701. projectId,
  702. userId,
  703. file,
  704. clsiserverid,
  705. function (error, body) {
  706. if (error) {
  707. return next(error)
  708. }
  709. res.json(body)
  710. }
  711. )
  712. })
  713. },
  714. }
  715. function _getPersistenceOptions(
  716. req,
  717. projectId,
  718. compileGroup,
  719. compileBackendClass,
  720. callback
  721. ) {
  722. const { clsiserverid } = req.query
  723. const userId = SessionManager.getLoggedInUserId(req)
  724. if (clsiserverid && typeof clsiserverid === 'string') {
  725. callback(null, {
  726. qs: { clsiserverid, compileGroup, compileBackendClass },
  727. headers: {},
  728. })
  729. } else {
  730. ClsiCookieManager.getServerId(
  731. projectId,
  732. userId,
  733. compileGroup,
  734. compileBackendClass,
  735. (err, clsiServerId) => {
  736. if (err) return callback(err)
  737. callback(null, {
  738. qs: { compileGroup, compileBackendClass },
  739. headers: clsiServerId
  740. ? {
  741. Cookie: new Cookie({
  742. key: Settings.clsiCookie.key,
  743. value: clsiServerId,
  744. }).cookieString(),
  745. }
  746. : {},
  747. })
  748. }
  749. )
  750. }
  751. }