CompileController.js 18 KB

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