CompileController.js 21 KB

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