CompileController.js 23 KB

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