ClsiManager.mjs 26 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016
  1. import { callbackify } from 'node:util'
  2. import { callbackifyMultiResult } from '@overleaf/promise-utils'
  3. import {
  4. fetchString,
  5. fetchStringWithResponse,
  6. fetchStream,
  7. RequestFailedError,
  8. } from '@overleaf/fetch-utils'
  9. import Settings from '@overleaf/settings'
  10. import ProjectGetter from '../Project/ProjectGetter.js'
  11. import ProjectEntityHandler from '../Project/ProjectEntityHandler.js'
  12. import logger from '@overleaf/logger'
  13. import OError from '@overleaf/o-error'
  14. import { Cookie } from 'tough-cookie'
  15. import ClsiCookieManagerFactory from './ClsiCookieManager.js'
  16. import ClsiStateManager from './ClsiStateManager.js'
  17. import _ from 'lodash'
  18. import ClsiFormatChecker from './ClsiFormatChecker.js'
  19. import DocumentUpdaterHandler from '../DocumentUpdater/DocumentUpdaterHandler.js'
  20. import Metrics from '@overleaf/metrics'
  21. import Errors from '../Errors/Errors.js'
  22. import ClsiCacheHandler from './ClsiCacheHandler.js'
  23. import HistoryManager from '../History/HistoryManager.js'
  24. import SplitTestHandler from '../SplitTests/SplitTestHandler.js'
  25. import AnalyticsManager from '../Analytics/AnalyticsManager.js'
  26. const ClsiCookieManager = ClsiCookieManagerFactory(
  27. Settings.apis.clsi?.backendGroupName
  28. )
  29. const NewBackendCloudClsiCookieManager = ClsiCookieManagerFactory(
  30. Settings.apis.clsi_new?.backendGroupName
  31. )
  32. const VALID_COMPILERS = ['pdflatex', 'latex', 'xelatex', 'lualatex']
  33. const OUTPUT_FILE_TIMEOUT_MS = 60000
  34. const CLSI_COOKIES_ENABLED = (Settings.clsiCookie?.key ?? '') !== ''
  35. // The timeout in services/clsi/app.js is 10 minutes, so we'll be on the safe side with 12 minutes
  36. const COMPILE_REQUEST_TIMEOUT_MS = 12 * 60 * 1000
  37. async function clearClsiServerId(projectId, userId) {
  38. const jobs = [ClsiCookieManager.promises.clearServerId(projectId, userId)]
  39. if (Settings.apis.clsi_new?.url) {
  40. // Mirror resetting the clsiserverid in both backends.
  41. jobs.push(
  42. NewBackendCloudClsiCookieManager.promises.clearServerId(projectId, userId)
  43. )
  44. }
  45. await Promise.all(jobs)
  46. }
  47. function collectMetricsOnBlgFiles(outputFiles) {
  48. let topLevel = 0
  49. let nested = 0
  50. for (const outputFile of outputFiles) {
  51. if (outputFile.type === 'blg') {
  52. if (outputFile.path.includes('/')) {
  53. nested++
  54. } else {
  55. topLevel++
  56. }
  57. }
  58. }
  59. Metrics.count('blg_output_file', topLevel, 1, { path: 'top-level' })
  60. Metrics.count('blg_output_file', nested, 1, { path: 'nested' })
  61. }
  62. async function sendRequest(projectId, userId, options) {
  63. if (options == null) {
  64. options = {}
  65. }
  66. let result = await sendRequestOnce(projectId, userId, options)
  67. if (result.status === 'conflict') {
  68. // Try again, with a full compile
  69. result = await sendRequestOnce(projectId, userId, {
  70. ...options,
  71. syncType: 'full',
  72. })
  73. } else if (result.status === 'unavailable') {
  74. result = await sendRequestOnce(projectId, userId, {
  75. ...options,
  76. syncType: 'full',
  77. forceNewClsiServer: true,
  78. })
  79. }
  80. return result
  81. }
  82. async function sendRequestOnce(projectId, userId, options) {
  83. let req
  84. try {
  85. req = await _buildRequest(projectId, options)
  86. } catch (err) {
  87. if (err.message === 'no main file specified') {
  88. return {
  89. status: 'validation-problems',
  90. validationProblems: { mainFile: err.message },
  91. }
  92. } else {
  93. throw OError.tag(err, 'Could not build request to CLSI', {
  94. projectId,
  95. options,
  96. })
  97. }
  98. }
  99. return await _sendBuiltRequest(projectId, userId, req, options)
  100. }
  101. // for public API requests where there is no project id
  102. async function sendExternalRequest(submissionId, clsiRequest, options) {
  103. if (options == null) {
  104. options = {}
  105. }
  106. return await _sendBuiltRequest(submissionId, null, clsiRequest, options)
  107. }
  108. async function stopCompile(projectId, userId, options) {
  109. if (options == null) {
  110. options = {}
  111. }
  112. const { compileBackendClass, compileGroup } = options
  113. const url = _getCompilerUrl(
  114. compileBackendClass,
  115. compileGroup,
  116. projectId,
  117. userId,
  118. 'compile/stop'
  119. )
  120. const opts = { method: 'POST' }
  121. await _makeRequest(
  122. projectId,
  123. userId,
  124. compileGroup,
  125. compileBackendClass,
  126. url,
  127. opts
  128. )
  129. }
  130. async function deleteAuxFiles(projectId, userId, options, clsiserverid) {
  131. if (options == null) {
  132. options = {}
  133. }
  134. const { compileBackendClass, compileGroup } = options
  135. const url = _getCompilerUrl(
  136. compileBackendClass,
  137. compileGroup,
  138. projectId,
  139. userId
  140. )
  141. const opts = {
  142. method: 'DELETE',
  143. }
  144. try {
  145. await _makeRequestWithClsiServerId(
  146. projectId,
  147. userId,
  148. compileGroup,
  149. compileBackendClass,
  150. url,
  151. opts,
  152. clsiserverid
  153. )
  154. } finally {
  155. // always clear the clsi-cache
  156. try {
  157. await ClsiCacheHandler.clearCache(projectId, userId)
  158. } catch (err) {
  159. logger.warn({ err, projectId, userId }, 'purge clsi-cache failed')
  160. }
  161. // always clear the project state from the docupdater, even if there
  162. // was a problem with the request to the clsi
  163. try {
  164. await DocumentUpdaterHandler.promises.clearProjectState(projectId)
  165. } finally {
  166. // always clear the clsi server id, even if prior actions failed
  167. await clearClsiServerId(projectId, userId)
  168. }
  169. }
  170. }
  171. async function _sendBuiltRequest(projectId, userId, req, options) {
  172. if (options.forceNewClsiServer) {
  173. await clearClsiServerId(projectId, userId)
  174. }
  175. const validationProblems =
  176. await ClsiFormatChecker.promises.checkRecoursesForProblems(
  177. req.compile?.resources
  178. )
  179. if (validationProblems != null) {
  180. logger.debug(
  181. { projectId, validationProblems },
  182. 'problems with users latex before compile was attempted'
  183. )
  184. return {
  185. status: 'validation-problems',
  186. validationProblems,
  187. }
  188. }
  189. const { response, clsiServerId } = await _postToClsi(
  190. projectId,
  191. userId,
  192. req,
  193. options.compileBackendClass,
  194. options.compileGroup
  195. )
  196. const outputFiles = _parseOutputFiles(
  197. projectId,
  198. response && response.compile && response.compile.outputFiles
  199. )
  200. collectMetricsOnBlgFiles(outputFiles)
  201. const compile = response?.compile || {}
  202. return {
  203. status: compile.status,
  204. outputFiles,
  205. clsiServerId,
  206. buildId: compile.buildId,
  207. stats: compile.stats,
  208. timings: compile.timings,
  209. outputUrlPrefix: compile.outputUrlPrefix,
  210. clsiCacheShard: compile.clsiCacheShard,
  211. }
  212. }
  213. async function _makeRequestWithClsiServerId(
  214. projectId,
  215. userId,
  216. compileGroup,
  217. compileBackendClass,
  218. url,
  219. opts,
  220. clsiserverid
  221. ) {
  222. if (clsiserverid) {
  223. // ignore cookies and newBackend, go straight to the clsi node
  224. const urlWithId = new URL(url)
  225. urlWithId.searchParams.set('clsiserverid', clsiserverid)
  226. let body
  227. try {
  228. body = await fetchString(urlWithId, opts)
  229. } catch (err) {
  230. throw OError.tag(err, 'error making request to CLSI', {
  231. userId,
  232. projectId,
  233. })
  234. }
  235. let json
  236. try {
  237. json = JSON.parse(body)
  238. } catch (err) {
  239. // some responses are empty. Ignore JSON parsing errors.
  240. }
  241. _makeNewBackendRequest(
  242. projectId,
  243. userId,
  244. compileGroup,
  245. compileBackendClass,
  246. url,
  247. opts
  248. ).catch(err => {
  249. logger.warn({ err }, 'Error making request to new CLSI backend')
  250. })
  251. return { body: json }
  252. } else {
  253. return await _makeRequest(
  254. projectId,
  255. userId,
  256. compileGroup,
  257. compileBackendClass,
  258. url,
  259. opts
  260. )
  261. }
  262. }
  263. async function _makeRequest(
  264. projectId,
  265. userId,
  266. compileGroup,
  267. compileBackendClass,
  268. url,
  269. opts
  270. ) {
  271. const currentBackendStartTime = new Date()
  272. const clsiServerId = await ClsiCookieManager.promises.getServerId(
  273. projectId,
  274. userId,
  275. compileGroup,
  276. compileBackendClass
  277. )
  278. opts.headers = {
  279. Accept: 'application/json',
  280. 'Content-Type': 'application/json',
  281. }
  282. if (CLSI_COOKIES_ENABLED) {
  283. const cookie = new Cookie({
  284. key: Settings.clsiCookie.key,
  285. value: clsiServerId,
  286. })
  287. opts.headers.Cookie = cookie.cookieString()
  288. }
  289. const timer = new Metrics.Timer('compile.currentBackend')
  290. let response, body
  291. try {
  292. ;({ body, response } = await fetchStringWithResponse(url, opts))
  293. } catch (err) {
  294. throw OError.tag(err, 'error making request to CLSI', {
  295. projectId,
  296. userId,
  297. })
  298. }
  299. Metrics.inc(`compile.currentBackend.response.${response.status}`)
  300. let json
  301. try {
  302. json = JSON.parse(body)
  303. } catch (err) {
  304. // some responses are empty. Ignore JSON parsing errors
  305. }
  306. timer.done()
  307. let newClsiServerId
  308. if (CLSI_COOKIES_ENABLED) {
  309. newClsiServerId = _getClsiServerIdFromResponse(response)
  310. await ClsiCookieManager.promises.setServerId(
  311. projectId,
  312. userId,
  313. compileGroup,
  314. compileBackendClass,
  315. newClsiServerId,
  316. clsiServerId
  317. )
  318. }
  319. const currentCompileTime = new Date() - currentBackendStartTime
  320. // Start new backend request in the background
  321. const newBackendStartTime = new Date()
  322. _makeNewBackendRequest(
  323. projectId,
  324. userId,
  325. compileGroup,
  326. compileBackendClass,
  327. url,
  328. opts
  329. )
  330. .then(result => {
  331. if (result == null || !url.pathname.endsWith('/compile')) {
  332. return
  333. }
  334. const current = json.compile
  335. const {
  336. body: { compile: next },
  337. newCompileBackendClass,
  338. } = result
  339. const newBackendCompileTime = new Date() - newBackendStartTime
  340. const statusCodeSame = next.status === current.status
  341. const timeDifference = newBackendCompileTime - currentCompileTime
  342. logger.debug(
  343. {
  344. statusCodeSame,
  345. timeDifference,
  346. currentCompileTime,
  347. newBackendCompileTime,
  348. projectId,
  349. },
  350. 'both clsi requests returned'
  351. )
  352. if (
  353. current.status === 'success' &&
  354. current.status === next.status &&
  355. current.stats.isInitialCompile === next.stats.isInitialCompile &&
  356. current.stats.restoredClsiCache === next.stats.restoredClsiCache
  357. ) {
  358. const fraction = next.timings.compileE2E / current.timings.compileE2E
  359. Metrics.histogram(
  360. 'compile_backend_difference_v1',
  361. fraction * 100,
  362. [
  363. // Increment the version in the metrics name when changing the buckets.
  364. 0,
  365. 10, 20, 30, 40, 45, 50, 55, 60, 65, 70, 75, 80, 85, 90, 95, 100,
  366. 105, 110, 115, 120,
  367. ],
  368. { path: compileBackendClass, method: newCompileBackendClass }
  369. )
  370. AnalyticsManager.recordEventForUserInBackground(
  371. userId,
  372. 'double-compile-result',
  373. {
  374. projectId,
  375. compileBackendClass,
  376. newCompileBackendClass,
  377. status: current.status,
  378. compileTime: current.timings.compileE2E,
  379. newCompileTime: next.timings.compileE2E,
  380. clsiServerId: newClsiServerId || clsiServerId,
  381. newClsiServerId: result.newClsiServerId,
  382. // Successful compiles are guaranteed to have an output.pdf file.
  383. pdfSize: current.outputFiles.find(f => f.path === 'output.pdf')
  384. .size,
  385. newPdfSize: next.outputFiles.find(f => f.path === 'output.pdf')
  386. .size,
  387. }
  388. )
  389. }
  390. })
  391. .catch(err => {
  392. logger.warn({ err }, 'Error making request to new CLSI backend')
  393. })
  394. return {
  395. body: json,
  396. clsiServerId: newClsiServerId || clsiServerId,
  397. }
  398. }
  399. async function _makeNewBackendRequest(
  400. projectId,
  401. userId,
  402. compileGroup,
  403. currentCompileBackendClass,
  404. url,
  405. opts
  406. ) {
  407. if (Settings.apis.clsi_new?.url == null) {
  408. return null
  409. }
  410. url = new URL(
  411. url.toString().replace(Settings.apis.clsi.url, Settings.apis.clsi_new.url)
  412. )
  413. // Sample x% of projects to move up one bracket.
  414. if (
  415. SplitTestHandler.getPercentile(projectId, 'double-compile', 'release') >=
  416. Settings.apis.clsi_new.sample
  417. )
  418. return null
  419. let newCompileBackendClass
  420. switch (currentCompileBackendClass) {
  421. case 'n2d':
  422. newCompileBackendClass = 'n4'
  423. break
  424. case 'c2d':
  425. newCompileBackendClass = 'n4'
  426. break
  427. default:
  428. throw new Error('unknown ?compileBackendClass')
  429. }
  430. url.searchParams.set('compileBackendClass', newCompileBackendClass)
  431. const clsiServerId =
  432. await NewBackendCloudClsiCookieManager.promises.getServerId(
  433. projectId,
  434. userId,
  435. compileGroup,
  436. newCompileBackendClass
  437. )
  438. opts = {
  439. ...opts,
  440. headers: {
  441. Accept: 'application/json',
  442. 'Content-Type': 'application/json',
  443. },
  444. }
  445. if (CLSI_COOKIES_ENABLED) {
  446. const cookie = new Cookie({
  447. key: Settings.clsiCookie.key,
  448. value: clsiServerId,
  449. })
  450. opts.headers.Cookie = cookie.cookieString()
  451. }
  452. const timer = new Metrics.Timer('compile.newBackend')
  453. let response, body
  454. try {
  455. ;({ body, response } = await fetchStringWithResponse(url, opts))
  456. } catch (err) {
  457. throw OError.tag(err, 'error making request to new CLSI', {
  458. userId,
  459. projectId,
  460. })
  461. }
  462. let json
  463. try {
  464. json = JSON.parse(body)
  465. } catch (err) {
  466. // Some responses are empty. Ignore JSON parsing errors
  467. }
  468. timer.done()
  469. let newClsiServerId
  470. if (CLSI_COOKIES_ENABLED) {
  471. newClsiServerId = _getClsiServerIdFromResponse(response)
  472. await NewBackendCloudClsiCookieManager.promises.setServerId(
  473. projectId,
  474. userId,
  475. compileGroup,
  476. newCompileBackendClass,
  477. newClsiServerId,
  478. clsiServerId
  479. )
  480. }
  481. return {
  482. response,
  483. body: json,
  484. newCompileBackendClass,
  485. newClsiServerId: clsiServerId || newClsiServerId,
  486. }
  487. }
  488. function _getCompilerUrl(
  489. compileBackendClass,
  490. compileGroup,
  491. projectId,
  492. userId,
  493. action
  494. ) {
  495. const u = new URL(`/project/${projectId}`, Settings.apis.clsi.url)
  496. if (userId != null) {
  497. u.pathname += `/user/${userId}`
  498. }
  499. if (action != null) {
  500. u.pathname += `/${action}`
  501. }
  502. u.searchParams.set('compileBackendClass', compileBackendClass)
  503. u.searchParams.set('compileGroup', compileGroup)
  504. return u
  505. }
  506. async function _postToClsi(
  507. projectId,
  508. userId,
  509. req,
  510. compileBackendClass,
  511. compileGroup
  512. ) {
  513. const url = _getCompilerUrl(
  514. compileBackendClass,
  515. compileGroup,
  516. projectId,
  517. userId,
  518. 'compile'
  519. )
  520. const opts = {
  521. json: req,
  522. method: 'POST',
  523. signal: AbortSignal.timeout(COMPILE_REQUEST_TIMEOUT_MS),
  524. }
  525. try {
  526. const { body, clsiServerId } = await _makeRequest(
  527. projectId,
  528. userId,
  529. compileGroup,
  530. compileBackendClass,
  531. url,
  532. opts
  533. )
  534. return { response: body, clsiServerId }
  535. } catch (err) {
  536. if (err instanceof RequestFailedError) {
  537. if (err.response.status === 413) {
  538. return { response: { compile: { status: 'project-too-large' } } }
  539. } else if (err.response.status === 409) {
  540. return { response: { compile: { status: 'conflict' } } }
  541. } else if (err.response.status === 423) {
  542. return { response: { compile: { status: 'compile-in-progress' } } }
  543. } else if (err.response.status === 503) {
  544. return { response: { compile: { status: 'unavailable' } } }
  545. } else {
  546. throw new OError(
  547. `CLSI returned non-success code: ${err.response.status}`,
  548. {
  549. projectId,
  550. userId,
  551. compileOptions: req.compile.options,
  552. rootResourcePath: req.compile.rootResourcePath,
  553. clsiResponse: err.body,
  554. statusCode: err.response.status,
  555. }
  556. )
  557. }
  558. } else {
  559. throw new OError(
  560. 'failed to make request to CLSI',
  561. {
  562. projectId,
  563. userId,
  564. compileOptions: req.compile.options,
  565. rootResourcePath: req.compile.rootResourcePath,
  566. },
  567. err
  568. )
  569. }
  570. }
  571. }
  572. function _parseOutputFiles(projectId, rawOutputFiles = []) {
  573. const outputFiles = []
  574. for (const file of rawOutputFiles) {
  575. const f = {
  576. path: file.path, // the clsi is now sending this to web
  577. url: new URL(file.url).pathname, // the location of the file on the clsi, excluding the host part
  578. type: file.type,
  579. build: file.build,
  580. }
  581. if (file.path === 'output.pdf') {
  582. f.contentId = file.contentId
  583. f.ranges = file.ranges || []
  584. f.size = file.size
  585. f.startXRefTable = file.startXRefTable
  586. f.createdAt = new Date()
  587. }
  588. outputFiles.push(f)
  589. }
  590. return outputFiles
  591. }
  592. async function _buildRequest(projectId, options) {
  593. const project = await ProjectGetter.promises.getProject(projectId, {
  594. compiler: 1,
  595. rootDoc_id: 1,
  596. imageName: 1,
  597. rootFolder: 1,
  598. 'overleaf.history.id': 1,
  599. })
  600. if (project == null) {
  601. throw new Errors.NotFoundError(`project does not exist: ${projectId}`)
  602. }
  603. if (!VALID_COMPILERS.includes(project.compiler)) {
  604. project.compiler = 'pdflatex'
  605. }
  606. if (options.incrementalCompilesEnabled || options.syncType != null) {
  607. // new way, either incremental or full
  608. const timer = new Metrics.Timer('editor.compile-getdocs-redis')
  609. let projectStateHash, docUpdaterDocs
  610. try {
  611. ;({ projectStateHash, docs: docUpdaterDocs } =
  612. await getContentFromDocUpdaterIfMatch(projectId, project, options))
  613. } catch (err) {
  614. logger.error({ err, projectId }, 'error checking project state')
  615. // note: we don't bail out when there's an error getting
  616. // incremental files from the docupdater, we just fall back
  617. // to a normal compile below
  618. }
  619. timer.done()
  620. // see if we can send an incremental update to the CLSI
  621. if (docUpdaterDocs != null && options.syncType !== 'full') {
  622. Metrics.inc('compile-from-redis')
  623. return _buildRequestFromDocupdater(
  624. projectId,
  625. options,
  626. project,
  627. projectStateHash,
  628. docUpdaterDocs
  629. )
  630. } else {
  631. Metrics.inc('compile-from-mongo')
  632. return await _buildRequestFromMongo(
  633. projectId,
  634. options,
  635. project,
  636. projectStateHash
  637. )
  638. }
  639. } else {
  640. // old way, always from mongo
  641. const timer = new Metrics.Timer('editor.compile-getdocs-mongo')
  642. const { docs, files } = await _getContentFromMongo(projectId)
  643. timer.done()
  644. return _finaliseRequest(projectId, options, project, docs, files)
  645. }
  646. }
  647. async function getContentFromDocUpdaterIfMatch(projectId, project, options) {
  648. const projectStateHash = ClsiStateManager.computeHash(project, options)
  649. const docs = await DocumentUpdaterHandler.promises.getProjectDocsIfMatch(
  650. projectId,
  651. projectStateHash
  652. )
  653. return { projectStateHash, docs }
  654. }
  655. async function getOutputFileStream(
  656. projectId,
  657. userId,
  658. options,
  659. clsiServerId,
  660. buildId,
  661. outputFilePath
  662. ) {
  663. const { compileBackendClass, compileGroup } = options
  664. const url = new URL(
  665. `${Settings.apis.clsi.url}/project/${projectId}/user/${userId}/build/${buildId}/output/${outputFilePath}`
  666. )
  667. url.searchParams.set('compileBackendClass', compileBackendClass)
  668. url.searchParams.set('compileGroup', compileGroup)
  669. url.searchParams.set('clsiserverid', clsiServerId)
  670. try {
  671. const stream = await fetchStream(url, {
  672. signal: AbortSignal.timeout(OUTPUT_FILE_TIMEOUT_MS),
  673. })
  674. return stream
  675. } catch (err) {
  676. throw new Errors.OutputFileFetchFailedError(
  677. 'failed to fetch output file from CLSI',
  678. {
  679. projectId,
  680. userId,
  681. url,
  682. status: err.response?.status,
  683. }
  684. )
  685. }
  686. }
  687. function _buildRequestFromDocupdater(
  688. projectId,
  689. options,
  690. project,
  691. projectStateHash,
  692. docUpdaterDocs
  693. ) {
  694. const docPath = ProjectEntityHandler.getAllDocPathsFromProject(project)
  695. const docs = {}
  696. for (const doc of docUpdaterDocs || []) {
  697. const path = docPath[doc._id]
  698. docs[path] = doc
  699. }
  700. // send new docs but not files as those are already on the clsi
  701. options = _.clone(options)
  702. options.syncType = 'incremental'
  703. options.syncState = projectStateHash
  704. // create stub doc entries for any possible root docs, if not
  705. // present in the docupdater. This allows finaliseRequest to
  706. // identify the root doc.
  707. const possibleRootDocIds = [options.rootDoc_id, project.rootDoc_id]
  708. for (const rootDocId of possibleRootDocIds) {
  709. if (rootDocId != null && rootDocId in docPath) {
  710. const path = docPath[rootDocId]
  711. if (docs[path] == null) {
  712. docs[path] = { _id: rootDocId, path }
  713. }
  714. }
  715. }
  716. return _finaliseRequest(projectId, options, project, docs, [])
  717. }
  718. async function _buildRequestFromMongo(
  719. projectId,
  720. options,
  721. project,
  722. projectStateHash
  723. ) {
  724. const { docs, files } = await _getContentFromMongo(projectId)
  725. options = {
  726. ...options,
  727. syncType: 'full',
  728. syncState: projectStateHash,
  729. }
  730. return _finaliseRequest(projectId, options, project, docs, files)
  731. }
  732. async function _getContentFromMongo(projectId) {
  733. await DocumentUpdaterHandler.promises.flushProjectToMongo(projectId)
  734. const docs = await ProjectEntityHandler.promises.getAllDocs(projectId)
  735. const files = await ProjectEntityHandler.promises.getAllFiles(projectId)
  736. return { docs, files }
  737. }
  738. function _finaliseRequest(projectId, options, project, docs, files) {
  739. const resources = []
  740. let flags
  741. let rootResourcePath = null
  742. let rootResourcePathOverride = null
  743. let hasMainFile = false
  744. let numberOfDocsInProject = 0
  745. for (let path in docs) {
  746. const doc = docs[path]
  747. path = path.replace(/^\//, '') // Remove leading /
  748. numberOfDocsInProject++
  749. if (doc.lines != null) {
  750. // add doc to resources unless it is just a stub entry
  751. resources.push({
  752. path,
  753. content: doc.lines.join('\n'),
  754. })
  755. }
  756. if (
  757. project.rootDoc_id != null &&
  758. doc._id.toString() === project.rootDoc_id.toString()
  759. ) {
  760. rootResourcePath = path
  761. }
  762. if (
  763. options.rootDoc_id != null &&
  764. doc._id.toString() === options.rootDoc_id.toString()
  765. ) {
  766. rootResourcePathOverride = path
  767. }
  768. if (path === 'main.tex') {
  769. hasMainFile = true
  770. }
  771. }
  772. if (rootResourcePathOverride != null) {
  773. rootResourcePath = rootResourcePathOverride
  774. }
  775. if (rootResourcePath == null) {
  776. if (hasMainFile) {
  777. rootResourcePath = 'main.tex'
  778. } else if (numberOfDocsInProject === 1) {
  779. // only one file, must be the main document
  780. for (const path in docs) {
  781. // Remove leading /
  782. rootResourcePath = path.replace(/^\//, '')
  783. }
  784. } else {
  785. throw new OError('no main file specified', { projectId })
  786. }
  787. }
  788. const historyId = project.overleaf.history.id
  789. if (!historyId) {
  790. throw new OError('project does not have a history id', { projectId })
  791. }
  792. for (let path in files) {
  793. const file = files[path]
  794. path = path.replace(/^\//, '') // Remove leading /
  795. resources.push({
  796. path,
  797. url: HistoryManager.getFilestoreBlobURL(historyId, file.hash),
  798. modified: file.created?.getTime(),
  799. })
  800. }
  801. if (options.fileLineErrors) {
  802. flags = ['-file-line-error']
  803. }
  804. return {
  805. compile: {
  806. options: {
  807. buildId: options.buildId,
  808. editorId: options.editorId,
  809. compiler: project.compiler,
  810. timeout: options.timeout,
  811. imageName: project.imageName,
  812. draft: Boolean(options.draft),
  813. stopOnFirstError: Boolean(options.stopOnFirstError),
  814. check: options.check,
  815. syncType: options.syncType,
  816. syncState: options.syncState,
  817. compileGroup: options.compileGroup,
  818. // Overleaf alpha/staff users get compileGroup=alpha (via getProjectCompileLimits in CompileManager), enroll them into the premium rollout of clsi-cache.
  819. compileFromClsiCache:
  820. ['alpha', 'priority'].includes(options.compileGroup) &&
  821. options.compileFromClsiCache,
  822. populateClsiCache:
  823. ['alpha', 'priority'].includes(options.compileGroup) &&
  824. options.populateClsiCache,
  825. enablePdfCaching:
  826. (Settings.enablePdfCaching && options.enablePdfCaching) || false,
  827. pdfCachingMinChunkSize: options.pdfCachingMinChunkSize,
  828. flags,
  829. metricsMethod: options.compileGroup,
  830. metricsPath: options.metricsPath,
  831. },
  832. rootResourcePath,
  833. resources,
  834. },
  835. }
  836. }
  837. async function wordCount(projectId, userId, file, limits, clsiserverid) {
  838. const { compileBackendClass, compileGroup } = limits
  839. const req = await _buildRequest(projectId, limits)
  840. const filename = file || req.compile.rootResourcePath
  841. const url = _getCompilerUrl(
  842. compileBackendClass,
  843. compileGroup,
  844. projectId,
  845. userId,
  846. 'wordcount'
  847. )
  848. url.searchParams.set('file', filename)
  849. url.searchParams.set('image', req.compile.options.imageName)
  850. const opts = {
  851. method: 'GET',
  852. }
  853. const { body } = await _makeRequestWithClsiServerId(
  854. projectId,
  855. userId,
  856. compileGroup,
  857. compileBackendClass,
  858. url,
  859. opts,
  860. clsiserverid
  861. )
  862. return body
  863. }
  864. async function syncTeX(
  865. projectId,
  866. userId,
  867. {
  868. direction,
  869. compileFromClsiCache,
  870. limits,
  871. imageName,
  872. validatedOptions,
  873. clsiServerId,
  874. }
  875. ) {
  876. const { compileBackendClass, compileGroup } = limits
  877. const url = _getCompilerUrl(
  878. compileBackendClass,
  879. compileGroup,
  880. projectId,
  881. userId,
  882. `sync/${direction}`
  883. )
  884. url.searchParams.set(
  885. 'compileFromClsiCache',
  886. compileFromClsiCache && ['alpha', 'priority'].includes(compileGroup)
  887. )
  888. url.searchParams.set('imageName', imageName)
  889. for (const [key, value] of Object.entries(validatedOptions)) {
  890. url.searchParams.set(key, value)
  891. }
  892. const opts = {
  893. method: 'GET',
  894. }
  895. try {
  896. const { body } = await _makeRequestWithClsiServerId(
  897. projectId,
  898. userId,
  899. compileGroup,
  900. compileBackendClass,
  901. url,
  902. opts,
  903. clsiServerId
  904. )
  905. return body
  906. } catch (err) {
  907. if (err instanceof RequestFailedError && err.response.status === 404) {
  908. throw new Errors.NotFoundError()
  909. }
  910. throw err
  911. }
  912. }
  913. function _getClsiServerIdFromResponse(response) {
  914. const setCookieHeaders = response.headers.raw()['set-cookie'] ?? []
  915. for (const header of setCookieHeaders) {
  916. const cookie = Cookie.parse(header)
  917. if (cookie.key === Settings.clsiCookie.key) {
  918. return cookie.value
  919. }
  920. }
  921. return null
  922. }
  923. export default {
  924. sendRequest: callbackifyMultiResult(sendRequest, [
  925. 'status',
  926. 'outputFiles',
  927. 'clsiServerId',
  928. 'validationProblems',
  929. 'stats',
  930. 'timings',
  931. 'outputUrlPrefix',
  932. 'buildId',
  933. 'clsiCacheShard',
  934. ]),
  935. sendExternalRequest: callbackifyMultiResult(sendExternalRequest, [
  936. 'status',
  937. 'outputFiles',
  938. 'clsiServerId',
  939. 'validationProblems',
  940. 'stats',
  941. 'timings',
  942. 'outputUrlPrefix',
  943. ]),
  944. stopCompile: callbackify(stopCompile),
  945. deleteAuxFiles: callbackify(deleteAuxFiles),
  946. getOutputFileStream: callbackify(getOutputFileStream),
  947. wordCount: callbackify(wordCount),
  948. syncTeX: callbackify(syncTeX),
  949. promises: {
  950. sendRequest,
  951. sendExternalRequest,
  952. stopCompile,
  953. deleteAuxFiles,
  954. getOutputFileStream,
  955. wordCount,
  956. syncTeX,
  957. },
  958. }