CompileController.js 21 KB

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