CompileController.js 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653
  1. let CompileController
  2. const { URL } = require('url')
  3. const OError = require('@overleaf/o-error')
  4. const Metrics = require('@overleaf/metrics')
  5. const ProjectGetter = require('../Project/ProjectGetter')
  6. const CompileManager = require('./CompileManager')
  7. const ClsiManager = require('./ClsiManager')
  8. const logger = require('@overleaf/logger')
  9. const request = require('request')
  10. const Settings = require('@overleaf/settings')
  11. const SessionManager = require('../Authentication/SessionManager')
  12. const { RateLimiter } = require('../../infrastructure/RateLimiter')
  13. const ClsiCookieManager = require('./ClsiCookieManager')(
  14. Settings.apis.clsi?.backendGroupName
  15. )
  16. const Path = require('path')
  17. const AnalyticsManager = require('../Analytics/AnalyticsManager')
  18. const SplitTestHandler = require('../SplitTests/SplitTestHandler')
  19. const { callbackify } = require('../../util/promises')
  20. const COMPILE_TIMEOUT_MS = 10 * 60 * 1000
  21. const pdfDownloadRateLimiter = new RateLimiter('full-pdf-download', {
  22. points: 1000,
  23. duration: 60 * 60,
  24. })
  25. function getImageNameForProject(projectId, callback) {
  26. ProjectGetter.getProject(projectId, { imageName: 1 }, (err, project) => {
  27. if (err) return callback(err)
  28. if (!project) return callback(new Error('project not found'))
  29. callback(null, project.imageName)
  30. })
  31. }
  32. async function getPdfCachingMinChunkSize(req, res) {
  33. const { variant } = await SplitTestHandler.promises.getAssignment(
  34. req,
  35. res,
  36. 'pdf-caching-min-chunk-size'
  37. )
  38. if (variant === 'default') return 1_000_000
  39. return parseInt(variant, 10)
  40. }
  41. const getSplitTestOptions = callbackify(async function (req, res) {
  42. // Use the query flags from the editor request for overriding the split test.
  43. let query = {}
  44. try {
  45. const u = new URL(req.headers.referer || req.url, Settings.siteUrl)
  46. query = Object.fromEntries(u.searchParams.entries())
  47. } catch (e) {}
  48. const editorReq = { ...req, query }
  49. const { variant: domainVariant } =
  50. await SplitTestHandler.promises.getAssignment(
  51. editorReq,
  52. res,
  53. 'pdf-download-domain'
  54. )
  55. const pdfDownloadDomain =
  56. domainVariant === 'user' && Settings.compilesUserContentDomain
  57. ? Settings.compilesUserContentDomain
  58. : Settings.pdfDownloadDomain
  59. const { variant: hybridDomainVariant } =
  60. await SplitTestHandler.promises.getAssignment(
  61. editorReq,
  62. res,
  63. 'pdf-download-domain-hybrid'
  64. )
  65. const enableHybridPdfDownload = hybridDomainVariant === 'enabled'
  66. if (!req.query.enable_pdf_caching) {
  67. // The frontend does not want to do pdf caching.
  68. return {
  69. pdfDownloadDomain,
  70. enableHybridPdfDownload,
  71. enablePdfCaching: false,
  72. }
  73. }
  74. // Double check with the latest split test assignment.
  75. // We may need to turn off the feature on a short notice, without requiring
  76. // all users to reload their editor page to disable the feature.
  77. const { variant } = await SplitTestHandler.promises.getAssignment(
  78. editorReq,
  79. res,
  80. 'pdf-caching-mode'
  81. )
  82. const enablePdfCaching = variant === 'enabled'
  83. if (!enablePdfCaching) {
  84. // Skip the lookup of the chunk size when caching is not enabled.
  85. return {
  86. pdfDownloadDomain,
  87. enableHybridPdfDownload,
  88. enablePdfCaching: false,
  89. }
  90. }
  91. const pdfCachingMinChunkSize = await getPdfCachingMinChunkSize(editorReq, res)
  92. return {
  93. pdfDownloadDomain,
  94. enableHybridPdfDownload,
  95. enablePdfCaching,
  96. pdfCachingMinChunkSize,
  97. }
  98. })
  99. module.exports = CompileController = {
  100. compile(req, res, next) {
  101. res.setTimeout(COMPILE_TIMEOUT_MS)
  102. const projectId = req.params.Project_id
  103. const isAutoCompile = !!req.query.auto_compile
  104. const fileLineErrors = !!req.query.file_line_errors
  105. const stopOnFirstError = !!req.body.stopOnFirstError
  106. const userId = SessionManager.getLoggedInUserId(req.session)
  107. const options = {
  108. isAutoCompile,
  109. fileLineErrors,
  110. stopOnFirstError,
  111. }
  112. if (req.body.rootDoc_id) {
  113. options.rootDoc_id = req.body.rootDoc_id
  114. } else if (
  115. req.body.settingsOverride &&
  116. req.body.settingsOverride.rootDoc_id
  117. ) {
  118. // Can be removed after deploy
  119. options.rootDoc_id = req.body.settingsOverride.rootDoc_id
  120. }
  121. if (req.body.compiler) {
  122. options.compiler = req.body.compiler
  123. }
  124. if (req.body.draft) {
  125. options.draft = req.body.draft
  126. }
  127. if (['validate', 'error', 'silent'].includes(req.body.check)) {
  128. options.check = req.body.check
  129. }
  130. if (req.body.incrementalCompilesEnabled) {
  131. options.incrementalCompilesEnabled = true
  132. }
  133. getSplitTestOptions(req, res, (err, splitTestOptions) => {
  134. if (err) return next(err)
  135. let {
  136. enablePdfCaching,
  137. pdfCachingMinChunkSize,
  138. pdfDownloadDomain,
  139. enableHybridPdfDownload,
  140. } = splitTestOptions
  141. options.enablePdfCaching = enablePdfCaching
  142. if (enablePdfCaching) {
  143. options.pdfCachingMinChunkSize = pdfCachingMinChunkSize
  144. }
  145. CompileManager.compile(
  146. projectId,
  147. userId,
  148. options,
  149. (
  150. error,
  151. status,
  152. outputFiles,
  153. clsiServerId,
  154. limits,
  155. validationProblems,
  156. stats,
  157. timings,
  158. outputUrlPrefix
  159. ) => {
  160. if (error) {
  161. Metrics.inc('compile-error')
  162. return next(error)
  163. }
  164. Metrics.inc('compile-status', 1, { status })
  165. if (pdfDownloadDomain && outputUrlPrefix) {
  166. pdfDownloadDomain += outputUrlPrefix
  167. }
  168. if (
  169. limits &&
  170. SplitTestHandler.getPercentile(
  171. AnalyticsManager.getIdsFromSession(req.session).analyticsId,
  172. 'compile-result-backend',
  173. 'release'
  174. ) === 1
  175. ) {
  176. // For a compile request to be sent to clsi we need limits.
  177. // If we get here without having the limits object populated, it is
  178. // a reasonable assumption to make that nothing was compiled.
  179. // We need to know the limits in order to make use of the events.
  180. AnalyticsManager.recordEventForSession(
  181. req.session,
  182. 'compile-result-backend',
  183. {
  184. projectId,
  185. ownerAnalyticsId: limits.ownerAnalyticsId,
  186. status,
  187. compileTime: timings?.compileE2E,
  188. timeout: limits.timeout === 60 ? 'short' : 'long',
  189. server: clsiServerId?.includes('-c2d-') ? 'faster' : 'normal',
  190. isAutoCompile,
  191. stopOnFirstError,
  192. }
  193. )
  194. }
  195. res.json({
  196. status,
  197. outputFiles,
  198. compileGroup: limits?.compileGroup,
  199. clsiServerId,
  200. validationProblems,
  201. stats,
  202. timings,
  203. pdfDownloadDomain,
  204. pdfCachingMinChunkSize,
  205. enableHybridPdfDownload,
  206. })
  207. }
  208. )
  209. })
  210. },
  211. stopCompile(req, res, next) {
  212. const projectId = req.params.Project_id
  213. const userId = SessionManager.getLoggedInUserId(req.session)
  214. CompileManager.stopCompile(projectId, userId, function (error) {
  215. if (error) {
  216. return next(error)
  217. }
  218. res.sendStatus(200)
  219. })
  220. },
  221. // Used for submissions through the public API
  222. compileSubmission(req, res, next) {
  223. res.setTimeout(COMPILE_TIMEOUT_MS)
  224. const submissionId = req.params.submission_id
  225. const options = {}
  226. if (req.body?.rootResourcePath != null) {
  227. options.rootResourcePath = req.body.rootResourcePath
  228. }
  229. if (req.body?.compiler) {
  230. options.compiler = req.body.compiler
  231. }
  232. if (req.body?.draft) {
  233. options.draft = req.body.draft
  234. }
  235. if (['validate', 'error', 'silent'].includes(req.body?.check)) {
  236. options.check = req.body.check
  237. }
  238. options.compileGroup =
  239. req.body?.compileGroup || Settings.defaultFeatures.compileGroup
  240. options.compileBackendClass = Settings.apis.clsi.defaultBackendClass
  241. options.timeout =
  242. req.body?.timeout || Settings.defaultFeatures.compileTimeout
  243. ClsiManager.sendExternalRequest(
  244. submissionId,
  245. req.body,
  246. options,
  247. function (error, status, outputFiles, clsiServerId, validationProblems) {
  248. if (error) {
  249. return next(error)
  250. }
  251. res.json({
  252. status,
  253. outputFiles,
  254. clsiServerId,
  255. validationProblems,
  256. })
  257. }
  258. )
  259. },
  260. _compileAsUser(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. _downloadAsUser(req, callback) {
  270. // callback with userId if per-user, undefined otherwise
  271. if (!Settings.disablePerUserCompiles) {
  272. const userId = SessionManager.getLoggedInUserId(req.session)
  273. callback(null, userId)
  274. } else {
  275. callback()
  276. }
  277. }, // do a per-project compile, not per-user
  278. downloadPdf(req, res, next) {
  279. Metrics.inc('pdf-downloads')
  280. const projectId = req.params.Project_id
  281. const isPdfjsPartialDownload = req.query?.pdfng
  282. const rateLimit = function (callback) {
  283. if (isPdfjsPartialDownload) {
  284. callback(null, true)
  285. } else {
  286. pdfDownloadRateLimiter
  287. .consume(req.ip)
  288. .then(() => {
  289. callback(null, true)
  290. })
  291. .catch(err => {
  292. if (err instanceof Error) {
  293. callback(err)
  294. } else {
  295. callback(null, false)
  296. }
  297. })
  298. }
  299. }
  300. ProjectGetter.getProject(projectId, { name: 1 }, function (err, project) {
  301. if (err) {
  302. return next(err)
  303. }
  304. res.contentType('application/pdf')
  305. const filename = `${CompileController._getSafeProjectName(project)}.pdf`
  306. if (req.query.popupDownload) {
  307. res.setContentDisposition('attachment', { filename })
  308. } else {
  309. res.setContentDisposition('', { filename })
  310. }
  311. rateLimit(function (err, canContinue) {
  312. if (err) {
  313. logger.err({ err }, 'error checking rate limit for pdf download')
  314. res.sendStatus(500)
  315. } else if (!canContinue) {
  316. logger.debug(
  317. { projectId, ip: req.ip },
  318. 'rate limit hit downloading pdf'
  319. )
  320. res.sendStatus(500)
  321. } else {
  322. CompileController._downloadAsUser(req, function (error, userId) {
  323. if (error) {
  324. return next(error)
  325. }
  326. const url = CompileController._getFileUrl(
  327. projectId,
  328. userId,
  329. req.params.build_id,
  330. 'output.pdf'
  331. )
  332. CompileController.proxyToClsi(projectId, url, req, res, next)
  333. })
  334. }
  335. })
  336. })
  337. },
  338. _getSafeProjectName(project) {
  339. const wordRegExp = /\W/g
  340. const safeProjectName = project.name.replace(wordRegExp, '_')
  341. return safeProjectName
  342. },
  343. deleteAuxFiles(req, res, next) {
  344. const projectId = req.params.Project_id
  345. const { clsiserverid } = req.query
  346. CompileController._compileAsUser(req, function (error, userId) {
  347. if (error) {
  348. return next(error)
  349. }
  350. CompileManager.deleteAuxFiles(
  351. projectId,
  352. userId,
  353. clsiserverid,
  354. function (error) {
  355. if (error) {
  356. return next(error)
  357. }
  358. res.sendStatus(200)
  359. }
  360. )
  361. })
  362. },
  363. // this is only used by templates, so is not called with a userId
  364. compileAndDownloadPdf(req, res, next) {
  365. const projectId = req.params.project_id
  366. // pass userId as null, since templates are an "anonymous" compile
  367. CompileManager.compile(projectId, null, {}, function (err) {
  368. if (err) {
  369. logger.err(
  370. { err, projectId },
  371. 'something went wrong compile and downloading pdf'
  372. )
  373. res.sendStatus(500)
  374. return
  375. }
  376. const url = `/project/${projectId}/output/output.pdf`
  377. CompileController.proxyToClsi(projectId, url, req, res, next)
  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(projectId, url, req, res, next)
  393. })
  394. },
  395. getFileFromClsiWithoutUser(req, res, next) {
  396. const submissionId = req.params.submission_id
  397. const url = CompileController._getFileUrl(
  398. submissionId,
  399. null,
  400. req.params.build_id,
  401. req.params.file
  402. )
  403. const limits = {
  404. compileGroup:
  405. req.body?.compileGroup ||
  406. req.query?.compileGroup ||
  407. Settings.defaultFeatures.compileGroup,
  408. compileBackendClass: Settings.apis.clsi.defaultBackendClass,
  409. }
  410. CompileController.proxyToClsiWithLimits(
  411. submissionId,
  412. url,
  413. limits,
  414. req,
  415. res,
  416. next
  417. )
  418. },
  419. // compute a GET file url for a given project, user (optional), build (optional) and file
  420. _getFileUrl(projectId, userId, buildId, file) {
  421. let url
  422. if (userId != null && buildId != null) {
  423. url = `/project/${projectId}/user/${userId}/build/${buildId}/output/${file}`
  424. } else if (userId != null) {
  425. url = `/project/${projectId}/user/${userId}/output/${file}`
  426. } else if (buildId != null) {
  427. url = `/project/${projectId}/build/${buildId}/output/${file}`
  428. } else {
  429. url = `/project/${projectId}/output/${file}`
  430. }
  431. return url
  432. },
  433. // compute a POST url for a project, user (optional) and action
  434. _getUrl(projectId, userId, action) {
  435. let path = `/project/${projectId}`
  436. if (userId != null) {
  437. path += `/user/${userId}`
  438. }
  439. return `${path}/${action}`
  440. },
  441. proxySyncPdf(req, res, next) {
  442. const projectId = req.params.Project_id
  443. const { page, h, v } = req.query
  444. if (!page?.match(/^\d+$/)) {
  445. return next(new Error('invalid page parameter'))
  446. }
  447. if (!h?.match(/^-?\d+\.\d+$/)) {
  448. return next(new Error('invalid h parameter'))
  449. }
  450. if (!v?.match(/^-?\d+\.\d+$/)) {
  451. return next(new Error('invalid v parameter'))
  452. }
  453. // whether this request is going to a per-user container
  454. CompileController._compileAsUser(req, function (error, userId) {
  455. if (error) {
  456. return next(error)
  457. }
  458. getImageNameForProject(projectId, (error, imageName) => {
  459. if (error) return next(error)
  460. const url = CompileController._getUrl(projectId, userId, 'sync/pdf')
  461. const destination = { url, qs: { page, h, v, imageName } }
  462. CompileController.proxyToClsi(projectId, destination, req, res, next)
  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. const destination = { url, qs: { file, line, column, imageName } }
  495. CompileController.proxyToClsi(projectId, destination, req, res, next)
  496. })
  497. })
  498. },
  499. proxyToClsi(projectId, url, req, res, next) {
  500. CompileManager.getProjectCompileLimits(projectId, function (error, limits) {
  501. if (error) {
  502. return next(error)
  503. }
  504. CompileController.proxyToClsiWithLimits(
  505. projectId,
  506. url,
  507. limits,
  508. req,
  509. res,
  510. next
  511. )
  512. })
  513. },
  514. proxyToClsiWithLimits(projectId, url, limits, req, res, next) {
  515. _getPersistenceOptions(
  516. req,
  517. projectId,
  518. limits.compileGroup,
  519. limits.compileBackendClass,
  520. (err, persistenceOptions) => {
  521. let qs
  522. if (err) {
  523. OError.tag(err, 'error getting cookie jar for clsi request')
  524. return next(err)
  525. }
  526. // expand any url parameter passed in as {url:..., qs:...}
  527. if (typeof url === 'object') {
  528. ;({ url, qs } = url)
  529. }
  530. const compilerUrl = Settings.apis.clsi.url
  531. url = `${compilerUrl}${url}`
  532. const oneMinute = 60 * 1000
  533. // the base request
  534. const options = {
  535. url,
  536. method: req.method,
  537. timeout: oneMinute,
  538. ...persistenceOptions,
  539. }
  540. // add any provided query string
  541. if (qs != null) {
  542. options.qs = Object.assign(options.qs || {}, qs)
  543. }
  544. // if we have a build parameter, pass it through to the clsi
  545. if (req.query?.pdfng && req.query?.build != null) {
  546. // only for new pdf viewer
  547. if (options.qs == null) {
  548. options.qs = {}
  549. }
  550. options.qs.build = req.query.build
  551. }
  552. // if we are byte serving pdfs, pass through If-* and Range headers
  553. // do not send any others, there's a proxying loop if Host: is passed!
  554. if (req.query?.pdfng) {
  555. const newHeaders = {}
  556. for (const h in req.headers) {
  557. if (/^(If-|Range)/i.test(h)) {
  558. newHeaders[h] = req.headers[h]
  559. }
  560. }
  561. options.headers = newHeaders
  562. }
  563. const proxy = request(options)
  564. proxy.pipe(res)
  565. proxy.on('error', error =>
  566. logger.warn({ err: error, url }, 'CLSI proxy error')
  567. )
  568. }
  569. )
  570. },
  571. wordCount(req, res, next) {
  572. const projectId = req.params.Project_id
  573. const file = req.query.file || false
  574. const { clsiserverid } = req.query
  575. CompileController._compileAsUser(req, function (error, userId) {
  576. if (error) {
  577. return next(error)
  578. }
  579. CompileManager.wordCount(
  580. projectId,
  581. userId,
  582. file,
  583. clsiserverid,
  584. function (error, body) {
  585. if (error) {
  586. return next(error)
  587. }
  588. res.json(body)
  589. }
  590. )
  591. })
  592. },
  593. }
  594. function _getPersistenceOptions(
  595. req,
  596. projectId,
  597. compileGroup,
  598. compileBackendClass,
  599. callback
  600. ) {
  601. const { clsiserverid } = req.query
  602. const userId = SessionManager.getLoggedInUserId(req)
  603. if (clsiserverid && typeof clsiserverid === 'string') {
  604. callback(null, { qs: { clsiserverid, compileGroup, compileBackendClass } })
  605. } else {
  606. ClsiCookieManager.getCookieJar(
  607. projectId,
  608. userId,
  609. compileGroup,
  610. compileBackendClass,
  611. (err, jar) => {
  612. callback(err, { jar, qs: { compileGroup, compileBackendClass } })
  613. }
  614. )
  615. }
  616. }