CompileController.mjs 21 KB

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