CompileController.js 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635
  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. if (!req.query.enable_pdf_caching) {
  60. // The frontend does not want to do pdf caching.
  61. return {
  62. pdfDownloadDomain,
  63. enablePdfCaching: false,
  64. }
  65. }
  66. // Double check with the latest split test assignment.
  67. // We may need to turn off the feature on a short notice, without requiring
  68. // all users to reload their editor page to disable the feature.
  69. const { variant } = await SplitTestHandler.promises.getAssignment(
  70. editorReq,
  71. res,
  72. 'pdf-caching-mode'
  73. )
  74. const enablePdfCaching = variant === 'enabled'
  75. if (!enablePdfCaching) {
  76. // Skip the lookup of the chunk size when caching is not enabled.
  77. return {
  78. pdfDownloadDomain,
  79. enablePdfCaching: false,
  80. }
  81. }
  82. const pdfCachingMinChunkSize = await getPdfCachingMinChunkSize(editorReq, res)
  83. return {
  84. pdfDownloadDomain,
  85. enablePdfCaching,
  86. pdfCachingMinChunkSize,
  87. }
  88. })
  89. module.exports = CompileController = {
  90. compile(req, res, next) {
  91. res.setTimeout(COMPILE_TIMEOUT_MS)
  92. const projectId = req.params.Project_id
  93. const isAutoCompile = !!req.query.auto_compile
  94. const fileLineErrors = !!req.query.file_line_errors
  95. const stopOnFirstError = !!req.body.stopOnFirstError
  96. const userId = SessionManager.getLoggedInUserId(req.session)
  97. const options = {
  98. isAutoCompile,
  99. fileLineErrors,
  100. stopOnFirstError,
  101. }
  102. if (req.body.rootDoc_id) {
  103. options.rootDoc_id = req.body.rootDoc_id
  104. } else if (
  105. req.body.settingsOverride &&
  106. req.body.settingsOverride.rootDoc_id
  107. ) {
  108. // Can be removed after deploy
  109. options.rootDoc_id = req.body.settingsOverride.rootDoc_id
  110. }
  111. if (req.body.compiler) {
  112. options.compiler = req.body.compiler
  113. }
  114. if (req.body.draft) {
  115. options.draft = req.body.draft
  116. }
  117. if (['validate', 'error', 'silent'].includes(req.body.check)) {
  118. options.check = req.body.check
  119. }
  120. if (req.body.incrementalCompilesEnabled) {
  121. options.incrementalCompilesEnabled = true
  122. }
  123. getSplitTestOptions(req, res, (err, splitTestOptions) => {
  124. if (err) return next(err)
  125. let { enablePdfCaching, pdfCachingMinChunkSize, pdfDownloadDomain } =
  126. splitTestOptions
  127. options.enablePdfCaching = enablePdfCaching
  128. if (enablePdfCaching) {
  129. options.pdfCachingMinChunkSize = pdfCachingMinChunkSize
  130. }
  131. CompileManager.compile(
  132. projectId,
  133. userId,
  134. options,
  135. (
  136. error,
  137. status,
  138. outputFiles,
  139. clsiServerId,
  140. limits,
  141. validationProblems,
  142. stats,
  143. timings,
  144. outputUrlPrefix
  145. ) => {
  146. if (error) {
  147. Metrics.inc('compile-error')
  148. return next(error)
  149. }
  150. Metrics.inc('compile-status', 1, { status })
  151. if (pdfDownloadDomain && outputUrlPrefix) {
  152. pdfDownloadDomain += outputUrlPrefix
  153. }
  154. if (
  155. limits &&
  156. SplitTestHandler.getPercentile(
  157. AnalyticsManager.getIdsFromSession(req.session).analyticsId,
  158. 'compile-result-backend',
  159. 'release'
  160. ) === 1
  161. ) {
  162. // For a compile request to be sent to clsi we need limits.
  163. // If we get here without having the limits object populated, it is
  164. // a reasonable assumption to make that nothing was compiled.
  165. // We need to know the limits in order to make use of the events.
  166. AnalyticsManager.recordEventForSession(
  167. req.session,
  168. 'compile-result-backend',
  169. {
  170. projectId,
  171. ownerAnalyticsId: limits.ownerAnalyticsId,
  172. status,
  173. compileTime: timings?.compileE2E,
  174. timeout: limits.timeout === 60 ? 'short' : 'long',
  175. server: clsiServerId?.includes('-c2d-') ? 'faster' : 'normal',
  176. isAutoCompile,
  177. stopOnFirstError,
  178. }
  179. )
  180. }
  181. res.json({
  182. status,
  183. outputFiles,
  184. compileGroup: limits?.compileGroup,
  185. clsiServerId,
  186. validationProblems,
  187. stats,
  188. timings,
  189. pdfDownloadDomain,
  190. pdfCachingMinChunkSize,
  191. })
  192. }
  193. )
  194. })
  195. },
  196. stopCompile(req, res, next) {
  197. const projectId = req.params.Project_id
  198. const userId = SessionManager.getLoggedInUserId(req.session)
  199. CompileManager.stopCompile(projectId, userId, function (error) {
  200. if (error) {
  201. return next(error)
  202. }
  203. res.sendStatus(200)
  204. })
  205. },
  206. // Used for submissions through the public API
  207. compileSubmission(req, res, next) {
  208. res.setTimeout(COMPILE_TIMEOUT_MS)
  209. const submissionId = req.params.submission_id
  210. const options = {}
  211. if (req.body?.rootResourcePath != null) {
  212. options.rootResourcePath = req.body.rootResourcePath
  213. }
  214. if (req.body?.compiler) {
  215. options.compiler = req.body.compiler
  216. }
  217. if (req.body?.draft) {
  218. options.draft = req.body.draft
  219. }
  220. if (['validate', 'error', 'silent'].includes(req.body?.check)) {
  221. options.check = req.body.check
  222. }
  223. options.compileGroup =
  224. req.body?.compileGroup || Settings.defaultFeatures.compileGroup
  225. options.compileBackendClass = Settings.apis.clsi.defaultBackendClass
  226. options.timeout =
  227. req.body?.timeout || Settings.defaultFeatures.compileTimeout
  228. ClsiManager.sendExternalRequest(
  229. submissionId,
  230. req.body,
  231. options,
  232. function (error, status, outputFiles, clsiServerId, validationProblems) {
  233. if (error) {
  234. return next(error)
  235. }
  236. res.json({
  237. status,
  238. outputFiles,
  239. clsiServerId,
  240. validationProblems,
  241. })
  242. }
  243. )
  244. },
  245. _compileAsUser(req, callback) {
  246. // callback with userId if per-user, undefined otherwise
  247. if (!Settings.disablePerUserCompiles) {
  248. const userId = SessionManager.getLoggedInUserId(req.session)
  249. callback(null, userId)
  250. } else {
  251. callback()
  252. }
  253. }, // do a per-project compile, not per-user
  254. _downloadAsUser(req, callback) {
  255. // callback with userId if per-user, undefined otherwise
  256. if (!Settings.disablePerUserCompiles) {
  257. const userId = SessionManager.getLoggedInUserId(req.session)
  258. callback(null, userId)
  259. } else {
  260. callback()
  261. }
  262. }, // do a per-project compile, not per-user
  263. downloadPdf(req, res, next) {
  264. Metrics.inc('pdf-downloads')
  265. const projectId = req.params.Project_id
  266. const isPdfjsPartialDownload = req.query?.pdfng
  267. const rateLimit = function (callback) {
  268. if (isPdfjsPartialDownload) {
  269. callback(null, true)
  270. } else {
  271. pdfDownloadRateLimiter
  272. .consume(req.ip)
  273. .then(() => {
  274. callback(null, true)
  275. })
  276. .catch(err => {
  277. if (err instanceof Error) {
  278. callback(err)
  279. } else {
  280. callback(null, false)
  281. }
  282. })
  283. }
  284. }
  285. ProjectGetter.getProject(projectId, { name: 1 }, function (err, project) {
  286. if (err) {
  287. return next(err)
  288. }
  289. res.contentType('application/pdf')
  290. const filename = `${CompileController._getSafeProjectName(project)}.pdf`
  291. if (req.query.popupDownload) {
  292. res.setContentDisposition('attachment', { filename })
  293. } else {
  294. res.setContentDisposition('inline', { filename })
  295. }
  296. rateLimit(function (err, canContinue) {
  297. if (err) {
  298. logger.err({ err }, 'error checking rate limit for pdf download')
  299. res.sendStatus(500)
  300. } else if (!canContinue) {
  301. logger.debug(
  302. { projectId, ip: req.ip },
  303. 'rate limit hit downloading pdf'
  304. )
  305. res.sendStatus(500)
  306. } else {
  307. CompileController._downloadAsUser(req, function (error, userId) {
  308. if (error) {
  309. return next(error)
  310. }
  311. const url = CompileController._getFileUrl(
  312. projectId,
  313. userId,
  314. req.params.build_id,
  315. 'output.pdf'
  316. )
  317. CompileController.proxyToClsi(projectId, url, req, res, next)
  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(projectId, url, req, res, next)
  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(projectId, url, req, res, next)
  376. })
  377. },
  378. getFileFromClsiWithoutUser(req, res, next) {
  379. const submissionId = req.params.submission_id
  380. const url = CompileController._getFileUrl(
  381. submissionId,
  382. null,
  383. req.params.build_id,
  384. req.params.file
  385. )
  386. const limits = {
  387. compileGroup:
  388. req.body?.compileGroup ||
  389. req.query?.compileGroup ||
  390. Settings.defaultFeatures.compileGroup,
  391. compileBackendClass: Settings.apis.clsi.defaultBackendClass,
  392. }
  393. CompileController.proxyToClsiWithLimits(
  394. submissionId,
  395. url,
  396. limits,
  397. req,
  398. res,
  399. next
  400. )
  401. },
  402. // compute a GET file url for a given project, user (optional), build (optional) and file
  403. _getFileUrl(projectId, userId, buildId, file) {
  404. let url
  405. if (userId != null && buildId != null) {
  406. url = `/project/${projectId}/user/${userId}/build/${buildId}/output/${file}`
  407. } else if (userId != null) {
  408. url = `/project/${projectId}/user/${userId}/output/${file}`
  409. } else if (buildId != null) {
  410. url = `/project/${projectId}/build/${buildId}/output/${file}`
  411. } else {
  412. url = `/project/${projectId}/output/${file}`
  413. }
  414. return url
  415. },
  416. // compute a POST url for a project, user (optional) and action
  417. _getUrl(projectId, userId, action) {
  418. let path = `/project/${projectId}`
  419. if (userId != null) {
  420. path += `/user/${userId}`
  421. }
  422. return `${path}/${action}`
  423. },
  424. proxySyncPdf(req, res, next) {
  425. const projectId = req.params.Project_id
  426. const { page, h, v } = req.query
  427. if (!page?.match(/^\d+$/)) {
  428. return next(new Error('invalid page parameter'))
  429. }
  430. if (!h?.match(/^-?\d+\.\d+$/)) {
  431. return next(new Error('invalid h parameter'))
  432. }
  433. if (!v?.match(/^-?\d+\.\d+$/)) {
  434. return next(new Error('invalid v parameter'))
  435. }
  436. // whether this request is going to a per-user container
  437. CompileController._compileAsUser(req, function (error, userId) {
  438. if (error) {
  439. return next(error)
  440. }
  441. getImageNameForProject(projectId, (error, imageName) => {
  442. if (error) return next(error)
  443. const url = CompileController._getUrl(projectId, userId, 'sync/pdf')
  444. const destination = { url, qs: { page, h, v, imageName } }
  445. CompileController.proxyToClsi(projectId, destination, req, res, next)
  446. })
  447. })
  448. },
  449. proxySyncCode(req, res, next) {
  450. const projectId = req.params.Project_id
  451. const { file, line, column } = req.query
  452. if (file == null) {
  453. return next(new Error('missing file parameter'))
  454. }
  455. // Check that we are dealing with a simple file path (this is not
  456. // strictly needed because synctex uses this parameter as a label
  457. // to look up in the synctex output, and does not open the file
  458. // itself). Since we have valid synctex paths like foo/./bar we
  459. // allow those by replacing /./ with /
  460. const testPath = file.replace('/./', '/')
  461. if (Path.resolve('/', testPath) !== `/${testPath}`) {
  462. return next(new Error('invalid file parameter'))
  463. }
  464. if (!line?.match(/^\d+$/)) {
  465. return next(new Error('invalid line parameter'))
  466. }
  467. if (!column?.match(/^\d+$/)) {
  468. return next(new Error('invalid column parameter'))
  469. }
  470. CompileController._compileAsUser(req, function (error, userId) {
  471. if (error) {
  472. return next(error)
  473. }
  474. getImageNameForProject(projectId, (error, imageName) => {
  475. if (error) return next(error)
  476. const url = CompileController._getUrl(projectId, userId, 'sync/code')
  477. const destination = { url, qs: { file, line, column, imageName } }
  478. CompileController.proxyToClsi(projectId, destination, req, res, next)
  479. })
  480. })
  481. },
  482. proxyToClsi(projectId, url, req, res, next) {
  483. CompileManager.getProjectCompileLimits(projectId, function (error, limits) {
  484. if (error) {
  485. return next(error)
  486. }
  487. CompileController.proxyToClsiWithLimits(
  488. projectId,
  489. url,
  490. limits,
  491. req,
  492. res,
  493. next
  494. )
  495. })
  496. },
  497. proxyToClsiWithLimits(projectId, url, limits, req, res, next) {
  498. _getPersistenceOptions(
  499. req,
  500. projectId,
  501. limits.compileGroup,
  502. limits.compileBackendClass,
  503. (err, persistenceOptions) => {
  504. let qs
  505. if (err) {
  506. OError.tag(err, 'error getting cookie jar for clsi request')
  507. return next(err)
  508. }
  509. // expand any url parameter passed in as {url:..., qs:...}
  510. if (typeof url === 'object') {
  511. ;({ url, qs } = url)
  512. }
  513. const compilerUrl = Settings.apis.clsi.url
  514. url = `${compilerUrl}${url}`
  515. const oneMinute = 60 * 1000
  516. // the base request
  517. const options = {
  518. url,
  519. method: req.method,
  520. timeout: oneMinute,
  521. ...persistenceOptions,
  522. }
  523. // add any provided query string
  524. if (qs != null) {
  525. options.qs = Object.assign(options.qs || {}, qs)
  526. }
  527. // if we have a build parameter, pass it through to the clsi
  528. if (req.query?.pdfng && req.query?.build != null) {
  529. // only for new pdf viewer
  530. if (options.qs == null) {
  531. options.qs = {}
  532. }
  533. options.qs.build = req.query.build
  534. }
  535. // if we are byte serving pdfs, pass through If-* and Range headers
  536. // do not send any others, there's a proxying loop if Host: is passed!
  537. if (req.query?.pdfng) {
  538. const newHeaders = {}
  539. for (const h in req.headers) {
  540. if (/^(If-|Range)/i.test(h)) {
  541. newHeaders[h] = req.headers[h]
  542. }
  543. }
  544. options.headers = newHeaders
  545. }
  546. const proxy = request(options)
  547. proxy.pipe(res)
  548. proxy.on('error', error =>
  549. logger.warn({ err: error, url }, 'CLSI proxy error')
  550. )
  551. }
  552. )
  553. },
  554. wordCount(req, res, next) {
  555. const projectId = req.params.Project_id
  556. const file = req.query.file || false
  557. const { clsiserverid } = req.query
  558. CompileController._compileAsUser(req, function (error, userId) {
  559. if (error) {
  560. return next(error)
  561. }
  562. CompileManager.wordCount(
  563. projectId,
  564. userId,
  565. file,
  566. clsiserverid,
  567. function (error, body) {
  568. if (error) {
  569. return next(error)
  570. }
  571. res.json(body)
  572. }
  573. )
  574. })
  575. },
  576. }
  577. function _getPersistenceOptions(
  578. req,
  579. projectId,
  580. compileGroup,
  581. compileBackendClass,
  582. callback
  583. ) {
  584. const { clsiserverid } = req.query
  585. const userId = SessionManager.getLoggedInUserId(req)
  586. if (clsiserverid && typeof clsiserverid === 'string') {
  587. callback(null, { qs: { clsiserverid, compileGroup, compileBackendClass } })
  588. } else {
  589. ClsiCookieManager.getCookieJar(
  590. projectId,
  591. userId,
  592. compileGroup,
  593. compileBackendClass,
  594. (err, jar) => {
  595. callback(err, { jar, qs: { compileGroup, compileBackendClass } })
  596. }
  597. )
  598. }
  599. }