CompileController.js 21 KB

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