ClsiManager.mjs 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320
  1. import { callbackify } from 'node:util'
  2. import { callbackifyMultiResult } from '@overleaf/promise-utils'
  3. import {
  4. fetchStream,
  5. fetchString,
  6. fetchStringWithResponse,
  7. RequestFailedError,
  8. } from '@overleaf/fetch-utils'
  9. import Settings from '@overleaf/settings'
  10. import ProjectGetter from '../Project/ProjectGetter.mjs'
  11. import ProjectEntityHandler from '../Project/ProjectEntityHandler.mjs'
  12. import logger from '@overleaf/logger'
  13. import OError from '@overleaf/o-error'
  14. import { Cookie } from 'tough-cookie'
  15. import ClsiCookieManagerFactory from './ClsiCookieManager.mjs'
  16. import ClsiStateManager from './ClsiStateManager.mjs'
  17. import _ from 'lodash'
  18. import ClsiFormatChecker from './ClsiFormatChecker.mjs'
  19. import DocumentUpdaterHandler from '../DocumentUpdater/DocumentUpdaterHandler.mjs'
  20. import Metrics from '@overleaf/metrics'
  21. import Errors from '../Errors/Errors.js'
  22. import ClsiCacheHandler from './ClsiCacheHandler.mjs'
  23. import HistoryManager from '../History/HistoryManager.mjs'
  24. import SplitTestHandler from '../SplitTests/SplitTestHandler.mjs'
  25. import AnalyticsManager from '../Analytics/AnalyticsManager.mjs'
  26. import RedisWrapper from '../../infrastructure/RedisWrapper.mjs'
  27. import { getOutputFileURL } from './ClsiURLHelpers.mjs'
  28. // use the redis db with eviction policy enabled
  29. const rclient = RedisWrapper.client('clsi_cookie')
  30. const ClsiCookieManager = ClsiCookieManagerFactory(
  31. Settings.apis.clsi?.backendGroupName
  32. )
  33. const NewBackendCloudClsiCookieManager = ClsiCookieManagerFactory(
  34. Settings.apis.clsi_new?.backendGroupName
  35. )
  36. const VALID_COMPILERS = Settings.safeCompilers
  37. const OUTPUT_FILE_TIMEOUT_MS = 60000
  38. const CLSI_COOKIES_ENABLED = (Settings.clsiCookie?.key ?? '') !== ''
  39. // The timeout in services/clsi/app.js is 10 minutes, so we'll be on the safe side with 12 minutes
  40. const COMPILE_REQUEST_TIMEOUT_MS = 12 * 60 * 1000
  41. // Enable clsi-cache for all compiles for 20min when detecting low capacity.
  42. const ENABLE_COMPILE_FROM_CACHE_ON_503_MS = 20 * 60 * 1000
  43. let enableCompileFromCacheUntil = 0
  44. function _baseHistoryVersionKey(projectId, userId) {
  45. return `baseHistoryVersion:${projectId}:${userId}`
  46. }
  47. async function getBaseHistoryVersion(projectId, userId) {
  48. let v
  49. try {
  50. v = await rclient.get(_baseHistoryVersionKey(projectId, userId))
  51. } catch (err) {
  52. logger.warn({ err, projectId, userId }, 'failed to get baseHistoryVersion')
  53. return -1
  54. }
  55. if (!v) return -1
  56. const n = parseInt(v, 10)
  57. if (Number.isNaN(n)) return -1
  58. return n
  59. }
  60. async function setBaseHistoryVersion(projectId, userId, baseHistoryVersion) {
  61. const clsiCacheExpiryInSeconds = 8 * 24 * 60 * 60 // 8 days
  62. try {
  63. await rclient.setex(
  64. _baseHistoryVersionKey(projectId, userId),
  65. clsiCacheExpiryInSeconds,
  66. baseHistoryVersion
  67. )
  68. } catch (err) {
  69. logger.warn({ err, projectId, userId }, 'failed to set baseHistoryVersion')
  70. }
  71. }
  72. async function clearBaseHistoryVersion(projectId, userId) {
  73. await rclient.del(_baseHistoryVersionKey(projectId, userId))
  74. }
  75. function getDoubleCompilePercentile(projectId) {
  76. return SplitTestHandler.getPercentile(projectId, 'double-compile', 'release')
  77. }
  78. function getNewCompileBackendClass(projectId, compileBackendClass) {
  79. let cfg
  80. switch (compileBackendClass) {
  81. case 'c3d':
  82. cfg = Settings.apis.clsi_new.doubleCompileFree
  83. break
  84. case 'c4d':
  85. cfg = Settings.apis.clsi_new.doubleCompilePremium
  86. break
  87. default:
  88. throw new Error('unknown ?compileBackendClass')
  89. }
  90. if (!cfg.backendClass || !cfg.sample) return null
  91. if (getDoubleCompilePercentile(projectId) >= cfg.sample) return null
  92. return cfg.backendClass
  93. }
  94. /**
  95. * @param {string} projectId
  96. * @param {string | null} userId
  97. * @param {string} compileBackendClass
  98. * @return {Promise<void>}
  99. */
  100. async function clearClsiServerId(projectId, userId, compileBackendClass) {
  101. const jobs = [
  102. ClsiCookieManager.promises.clearServerId(
  103. projectId,
  104. userId,
  105. compileBackendClass
  106. ),
  107. ]
  108. if (Settings.apis.clsi_new?.url) {
  109. // Mirror resetting the clsiserverid in both backends.
  110. const newCompileBackendClass = getNewCompileBackendClass(
  111. projectId,
  112. compileBackendClass
  113. )
  114. if (newCompileBackendClass) {
  115. jobs.push(
  116. NewBackendCloudClsiCookieManager.promises.clearServerId(
  117. projectId,
  118. userId,
  119. newCompileBackendClass
  120. )
  121. )
  122. }
  123. }
  124. await Promise.all(jobs)
  125. }
  126. function collectMetricsOnBlgFiles(outputFiles) {
  127. let topLevel = 0
  128. let nested = 0
  129. for (const outputFile of outputFiles) {
  130. if (outputFile.type === 'blg') {
  131. if (outputFile.path.includes('/')) {
  132. nested++
  133. } else {
  134. topLevel++
  135. }
  136. }
  137. }
  138. Metrics.count('blg_output_file', topLevel, 1, { path: 'top-level' })
  139. Metrics.count('blg_output_file', nested, 1, { path: 'nested' })
  140. }
  141. async function sendRequest(projectId, userId, options) {
  142. if (options == null) {
  143. options = {}
  144. }
  145. let result = await sendRequestOnce(projectId, userId, options)
  146. if (result.status === 'missing-updates') {
  147. // try again with updated baseline
  148. result = await sendRequestOnce(projectId, userId, {
  149. ...options,
  150. baseHistoryVersion: result.baseHistoryVersion,
  151. })
  152. } else if (result.status === 'conflict') {
  153. // Try again, with a full compile
  154. result = await sendRequestOnce(projectId, userId, {
  155. ...options,
  156. syncType: 'full',
  157. })
  158. } else if (result.status === 'unavailable') {
  159. result = await sendRequestOnce(projectId, userId, {
  160. ...options,
  161. syncType: 'full',
  162. forceNewClsiServer: true,
  163. })
  164. }
  165. return result
  166. }
  167. async function sendRequestOnce(projectId, userId, options) {
  168. let req
  169. try {
  170. req = await _buildRequest(projectId, userId, options)
  171. } catch (err) {
  172. if (err.message === 'no main file specified') {
  173. return {
  174. status: 'validation-problems',
  175. validationProblems: { mainFile: err.message },
  176. }
  177. } else {
  178. throw OError.tag(err, 'Could not build request to CLSI', {
  179. projectId,
  180. options,
  181. })
  182. }
  183. }
  184. return await _sendBuiltRequest(projectId, userId, req, options)
  185. }
  186. // for public API requests where there is no project id
  187. async function sendExternalRequest(submissionId, clsiRequest, options) {
  188. if (options == null) {
  189. options = {}
  190. }
  191. return await _sendBuiltRequest(submissionId, null, clsiRequest, options)
  192. }
  193. async function stopCompile(projectId, userId, options) {
  194. if (options == null) {
  195. options = {}
  196. }
  197. const { compileBackendClass, compileGroup } = options
  198. const url = _getCompilerUrl(
  199. compileBackendClass,
  200. compileGroup,
  201. projectId,
  202. userId,
  203. 'compile/stop'
  204. )
  205. const opts = { method: 'POST' }
  206. await _makeRequest(
  207. projectId,
  208. userId,
  209. compileGroup,
  210. compileBackendClass,
  211. url,
  212. opts
  213. )
  214. }
  215. /**
  216. * @param {PromiseSettledResult} result
  217. * @private
  218. */
  219. function _throwIfRejected(result) {
  220. if (result.status === 'rejected') {
  221. throw result.reason
  222. }
  223. }
  224. async function deleteAuxFiles(projectId, userId, options, clsiserverid) {
  225. if (options == null) {
  226. options = {}
  227. }
  228. const { compileBackendClass, compileGroup } = options
  229. const url = _getCompilerUrl(
  230. compileBackendClass,
  231. compileGroup,
  232. projectId,
  233. userId
  234. )
  235. const [
  236. clsiResult,
  237. clsiCacheResult,
  238. documentUpdaterResult,
  239. clsiServerIdResult,
  240. baseHistoryVersionResult,
  241. ] = await Promise.allSettled([
  242. _makeRequestWithClsiServerId(
  243. projectId,
  244. userId,
  245. compileGroup,
  246. compileBackendClass,
  247. url,
  248. { method: 'DELETE' },
  249. clsiserverid
  250. ),
  251. ClsiCacheHandler.clearCache(projectId, userId),
  252. DocumentUpdaterHandler.promises.clearProjectState(projectId),
  253. clearClsiServerId(projectId, userId, compileBackendClass),
  254. clearBaseHistoryVersion(projectId, userId),
  255. ])
  256. if (clsiCacheResult.status === 'rejected') {
  257. logger.warn(
  258. { err: clsiCacheResult.reason, projectId, userId },
  259. 'purge clsi-cache failed'
  260. )
  261. }
  262. if (baseHistoryVersionResult.status === 'rejected') {
  263. logger.warn(
  264. { err: baseHistoryVersionResult.reason, projectId, userId },
  265. 'failed to clear baseHistoryVersion'
  266. )
  267. }
  268. _throwIfRejected(clsiResult)
  269. _throwIfRejected(documentUpdaterResult)
  270. _throwIfRejected(clsiServerIdResult)
  271. }
  272. async function _sendBuiltRequest(projectId, userId, req, options) {
  273. if (options.forceNewClsiServer) {
  274. await clearClsiServerId(projectId, userId, options.compileBackendClass)
  275. }
  276. const validationProblems = ClsiFormatChecker.checkRecoursesForProblems(
  277. req.compile?.resources || []
  278. )
  279. if (validationProblems != null) {
  280. logger.debug(
  281. { projectId, validationProblems },
  282. 'problems with users latex before compile was attempted'
  283. )
  284. return {
  285. status: 'validation-problems',
  286. validationProblems,
  287. }
  288. }
  289. const { response, clsiServerId } = await _postToClsi(
  290. projectId,
  291. userId,
  292. req,
  293. options.compileBackendClass,
  294. options.compileGroup
  295. )
  296. const outputFiles = _parseOutputFiles(
  297. projectId,
  298. response && response.compile && response.compile.outputFiles
  299. )
  300. collectMetricsOnBlgFiles(outputFiles)
  301. const compile = response?.compile || {}
  302. if (compile.baseHistoryVersion) {
  303. await setBaseHistoryVersion(projectId, userId, compile.baseHistoryVersion)
  304. }
  305. return {
  306. status: compile.status,
  307. outputFiles,
  308. clsiServerId,
  309. buildId: compile.buildId,
  310. stats: compile.stats,
  311. timings: compile.timings,
  312. outputUrlPrefix: compile.outputUrlPrefix,
  313. clsiCacheShard: compile.clsiCacheShard,
  314. baseHistoryVersion: compile.baseHistoryVersion,
  315. instanceType: compile.instanceType,
  316. }
  317. }
  318. async function _makeRequestWithClsiServerId(
  319. projectId,
  320. userId,
  321. compileGroup,
  322. compileBackendClass,
  323. url,
  324. opts,
  325. clsiserverid
  326. ) {
  327. if (clsiserverid) {
  328. // ignore cookies and newBackend, go straight to the clsi node
  329. const urlWithId = new URL(url)
  330. urlWithId.searchParams.set('clsiserverid', clsiserverid)
  331. let body
  332. try {
  333. body = await fetchString(urlWithId, opts)
  334. } catch (err) {
  335. throw OError.tag(err, 'error making request to CLSI', {
  336. userId,
  337. projectId,
  338. })
  339. }
  340. let json
  341. try {
  342. json = JSON.parse(body)
  343. } catch (err) {
  344. // some responses are empty. Ignore JSON parsing errors.
  345. }
  346. _makeNewBackendRequest(
  347. projectId,
  348. userId,
  349. compileGroup,
  350. compileBackendClass,
  351. url,
  352. opts
  353. ).catch(err => {
  354. logger.warn({ err }, 'Error making request to new CLSI backend')
  355. })
  356. return { body: json }
  357. } else {
  358. return await _makeRequest(
  359. projectId,
  360. userId,
  361. compileGroup,
  362. compileBackendClass,
  363. url,
  364. opts
  365. )
  366. }
  367. }
  368. async function _makeRequest(
  369. projectId,
  370. userId,
  371. compileGroup,
  372. compileBackendClass,
  373. url,
  374. opts
  375. ) {
  376. const currentBackendStartTime = new Date()
  377. const clsiServerId = await ClsiCookieManager.promises.getServerId(
  378. projectId,
  379. userId,
  380. compileGroup,
  381. compileBackendClass
  382. )
  383. opts.headers = {
  384. Accept: 'application/json',
  385. 'Content-Type': 'application/json',
  386. }
  387. if (CLSI_COOKIES_ENABLED) {
  388. const cookie = new Cookie({
  389. key: Settings.clsiCookie.key,
  390. value: clsiServerId,
  391. })
  392. opts.headers.Cookie = cookie.cookieString()
  393. }
  394. const timer = new Metrics.Timer('compile.currentBackend')
  395. let response, body
  396. try {
  397. ;({ body, response } = await fetchStringWithResponse(url, opts))
  398. } catch (err) {
  399. throw OError.tag(err, 'error making request to CLSI', {
  400. projectId,
  401. userId,
  402. })
  403. }
  404. Metrics.inc(`compile.currentBackend.response.${response.status}`)
  405. let json
  406. try {
  407. json = JSON.parse(body)
  408. } catch (err) {
  409. // some responses are empty. Ignore JSON parsing errors
  410. }
  411. timer.done()
  412. let newClsiServerId
  413. if (CLSI_COOKIES_ENABLED) {
  414. newClsiServerId = getClsiServerIdFromResponse(response)
  415. await ClsiCookieManager.promises.setServerId(
  416. projectId,
  417. userId,
  418. compileGroup,
  419. compileBackendClass,
  420. newClsiServerId,
  421. clsiServerId
  422. )
  423. }
  424. const currentCompileTime = new Date() - currentBackendStartTime
  425. // Start new backend request in the background
  426. const newBackendStartTime = new Date()
  427. _makeNewBackendRequest(
  428. projectId,
  429. userId,
  430. compileGroup,
  431. compileBackendClass,
  432. url,
  433. opts
  434. )
  435. .then(result => {
  436. if (result == null || !url.pathname.endsWith('/compile')) {
  437. return
  438. }
  439. const current = json.compile
  440. const {
  441. body: { compile: next },
  442. newCompileBackendClass,
  443. } = result
  444. const newBackendCompileTime = new Date() - newBackendStartTime
  445. const statusCodeSame = next.status === current.status
  446. const timeDifference = newBackendCompileTime - currentCompileTime
  447. logger.debug(
  448. {
  449. statusCodeSame,
  450. timeDifference,
  451. currentCompileTime,
  452. newBackendCompileTime,
  453. projectId,
  454. },
  455. 'both clsi requests returned'
  456. )
  457. if (
  458. current.status === 'success' &&
  459. current.status === next.status &&
  460. current.stats.isInitialCompile === next.stats.isInitialCompile &&
  461. current.stats.restoredClsiCache === next.stats.restoredClsiCache
  462. ) {
  463. const fraction = next.timings.compileE2E / current.timings.compileE2E
  464. Metrics.histogram(
  465. 'compile_backend_difference_v1',
  466. fraction * 100,
  467. [
  468. // Increment the version in the metrics name when changing the buckets.
  469. 0,
  470. 10, 20, 30, 40, 45, 50, 55, 60, 65, 70, 75, 80, 85, 90, 95, 100,
  471. 105, 110, 115, 120,
  472. ],
  473. { path: compileBackendClass, method: newCompileBackendClass }
  474. )
  475. AnalyticsManager.recordEventForUserInBackground(
  476. userId,
  477. 'double-compile-result',
  478. {
  479. projectId,
  480. compileBackendClass,
  481. newCompileBackendClass,
  482. status: current.status,
  483. compileTime: current.timings.compileE2E,
  484. newCompileTime: next.timings.compileE2E,
  485. clsiServerId: newClsiServerId || clsiServerId,
  486. newClsiServerId: result.newClsiServerId,
  487. // Successful compiles are guaranteed to have an output.pdf file.
  488. pdfSize: current.outputFiles.find(f => f.path === 'output.pdf')
  489. .size,
  490. newPdfSize: next.outputFiles.find(f => f.path === 'output.pdf')
  491. .size,
  492. }
  493. )
  494. }
  495. })
  496. .catch(err => {
  497. logger.warn({ err }, 'Error making request to new CLSI backend')
  498. })
  499. return {
  500. body: json,
  501. clsiServerId: newClsiServerId || clsiServerId,
  502. }
  503. }
  504. async function _makeNewBackendRequest(
  505. projectId,
  506. userId,
  507. compileGroup,
  508. currentCompileBackendClass,
  509. url,
  510. opts
  511. ) {
  512. if (Settings.apis.clsi_new?.url == null) {
  513. return null
  514. }
  515. const newCompileBackendClass = getNewCompileBackendClass(
  516. projectId,
  517. currentCompileBackendClass
  518. )
  519. if (!newCompileBackendClass) return null
  520. url = new URL(
  521. url.toString().replace(Settings.apis.clsi.url, Settings.apis.clsi_new.url)
  522. )
  523. url.searchParams.set('compileBackendClass', newCompileBackendClass)
  524. const clsiServerId =
  525. await NewBackendCloudClsiCookieManager.promises.getServerId(
  526. projectId,
  527. userId,
  528. compileGroup,
  529. newCompileBackendClass
  530. )
  531. opts = {
  532. ...opts,
  533. headers: {
  534. Accept: 'application/json',
  535. 'Content-Type': 'application/json',
  536. },
  537. }
  538. if (CLSI_COOKIES_ENABLED) {
  539. const cookie = new Cookie({
  540. key: Settings.clsiCookie.key,
  541. value: clsiServerId,
  542. })
  543. opts.headers.Cookie = cookie.cookieString()
  544. }
  545. const timer = new Metrics.Timer('compile.newBackend')
  546. let response, body
  547. try {
  548. ;({ body, response } = await fetchStringWithResponse(url, opts))
  549. } catch (err) {
  550. throw OError.tag(err, 'error making request to new CLSI', {
  551. userId,
  552. projectId,
  553. })
  554. }
  555. let json
  556. try {
  557. json = JSON.parse(body)
  558. } catch (err) {
  559. // Some responses are empty. Ignore JSON parsing errors
  560. }
  561. timer.done()
  562. let newClsiServerId
  563. if (CLSI_COOKIES_ENABLED) {
  564. newClsiServerId = getClsiServerIdFromResponse(response)
  565. await NewBackendCloudClsiCookieManager.promises.setServerId(
  566. projectId,
  567. userId,
  568. compileGroup,
  569. newCompileBackendClass,
  570. newClsiServerId,
  571. clsiServerId
  572. )
  573. }
  574. return {
  575. response,
  576. body: json,
  577. newCompileBackendClass,
  578. newClsiServerId: newClsiServerId || clsiServerId,
  579. }
  580. }
  581. function _getCompilerUrl(
  582. compileBackendClass,
  583. compileGroup,
  584. projectId,
  585. userId,
  586. action
  587. ) {
  588. const u = new URL(Settings.apis.clsi.url)
  589. u.pathname = `/project/${projectId}`
  590. if (userId != null) {
  591. u.pathname += `/user/${userId}`
  592. }
  593. if (action != null) {
  594. u.pathname += `/${action}`
  595. }
  596. u.searchParams.set('compileBackendClass', compileBackendClass)
  597. u.searchParams.set('compileGroup', compileGroup)
  598. return u
  599. }
  600. async function _postToClsi(
  601. projectId,
  602. userId,
  603. req,
  604. compileBackendClass,
  605. compileGroup
  606. ) {
  607. const url = _getCompilerUrl(
  608. compileBackendClass,
  609. compileGroup,
  610. projectId,
  611. userId,
  612. 'compile'
  613. )
  614. const opts = {
  615. json: req,
  616. method: 'POST',
  617. signal: AbortSignal.timeout(COMPILE_REQUEST_TIMEOUT_MS),
  618. }
  619. try {
  620. const { body, clsiServerId } = await _makeRequest(
  621. projectId,
  622. userId,
  623. compileGroup,
  624. compileBackendClass,
  625. url,
  626. opts
  627. )
  628. return { response: body, clsiServerId }
  629. } catch (err) {
  630. if (err instanceof RequestFailedError) {
  631. if (err.response.status === 413) {
  632. return { response: { compile: { status: 'project-too-large' } } }
  633. } else if (err.response.status === 409) {
  634. try {
  635. const body = JSON.parse(err.body || '{}')
  636. if (body.compile?.status === 'missing-updates') {
  637. return { response: body }
  638. }
  639. } catch {}
  640. return { response: { compile: { status: 'conflict' } } }
  641. } else if (err.response.status === 423) {
  642. return { response: { compile: { status: 'compile-in-progress' } } }
  643. } else if (err.response.status === 502 || err.response.status === 503) {
  644. enableCompileFromCacheUntil =
  645. Date.now() + ENABLE_COMPILE_FROM_CACHE_ON_503_MS
  646. return { response: { compile: { status: 'unavailable' } } }
  647. } else if (err.response.status === 504) {
  648. return { response: { compile: { status: 'timedout' } } }
  649. } else {
  650. throw new OError('CLSI returned non-success code', {
  651. projectId,
  652. userId,
  653. compileOptions: req.compile.options,
  654. rootResourcePath: req.compile.rootResourcePath,
  655. clsiResponse: err.body,
  656. statusCode: err.response.status,
  657. })
  658. }
  659. } else {
  660. throw new OError(
  661. 'failed to make request to CLSI',
  662. {
  663. projectId,
  664. userId,
  665. compileOptions: req.compile.options,
  666. rootResourcePath: req.compile.rootResourcePath,
  667. },
  668. err
  669. )
  670. }
  671. }
  672. }
  673. function _parseOutputFiles(projectId, rawOutputFiles = []) {
  674. const outputFiles = []
  675. for (const file of rawOutputFiles) {
  676. const f = {
  677. path: file.path, // the clsi is now sending this to web
  678. url: new URL(file.url).pathname, // the location of the file on the clsi, excluding the host part
  679. type: file.type,
  680. build: file.build,
  681. }
  682. if (file.path === 'output.pdf') {
  683. f.contentId = file.contentId
  684. f.ranges = file.ranges || []
  685. f.size = file.size
  686. f.startXRefTable = file.startXRefTable
  687. f.createdAt = new Date()
  688. }
  689. outputFiles.push(f)
  690. }
  691. return outputFiles
  692. }
  693. async function _buildRequest(projectId, userId, options) {
  694. const project = await ProjectGetter.promises.getProject(projectId, {
  695. compiler: 1,
  696. imageName: 1,
  697. 'overleaf.history.id': 1,
  698. ...(options.compileFromHistory ? {} : { rootDoc_id: 1, rootFolder: 1 }),
  699. })
  700. if (project == null) {
  701. throw new Errors.NotFoundError(`project does not exist: ${projectId}`)
  702. }
  703. if (!VALID_COMPILERS.includes(project.compiler)) {
  704. project.compiler = Settings.defaultLatexCompiler
  705. }
  706. const historyId = project.overleaf.history.id
  707. let { baseHistoryVersion } = options
  708. if (options.compileFromHistory && !baseHistoryVersion) {
  709. baseHistoryVersion = await getBaseHistoryVersion(projectId, userId)
  710. }
  711. if (options.compileFromHistory && baseHistoryVersion === -1) {
  712. // full sync
  713. try {
  714. return await _buildRequestFromHistoryFull(
  715. projectId,
  716. historyId,
  717. options,
  718. project
  719. )
  720. } catch (err) {
  721. logger.warn(
  722. { err, projectId, historyId },
  723. 'failed to compose history-full request'
  724. )
  725. // fall back to old compile mode
  726. return await _buildRequest(projectId, userId, {
  727. ...options,
  728. compileFromHistory: false,
  729. })
  730. }
  731. } else if (options.compileFromHistory) {
  732. // incremental sync
  733. try {
  734. return await _buildRequestFromHistoryIncremental(
  735. projectId,
  736. historyId,
  737. options,
  738. project,
  739. baseHistoryVersion
  740. )
  741. } catch (err) {
  742. logger.warn(
  743. { err, projectId, historyId, baseHistoryVersion },
  744. 'failed to compose history-incremental request'
  745. )
  746. // fall back to old compile mode
  747. return await _buildRequest(projectId, userId, {
  748. ...options,
  749. compileFromHistory: false,
  750. })
  751. }
  752. }
  753. if (options.incrementalCompilesEnabled || options.syncType != null) {
  754. // new way, either incremental or full
  755. const timer = new Metrics.Timer('editor.compile-getdocs-redis')
  756. let projectStateHash, docUpdaterDocs
  757. try {
  758. ;({ projectStateHash, docs: docUpdaterDocs } =
  759. await getContentFromDocUpdaterIfMatch(projectId, project, options))
  760. } catch (err) {
  761. logger.error({ err, projectId }, 'error checking project state')
  762. // note: we don't bail out when there's an error getting
  763. // incremental files from the docupdater, we just fall back
  764. // to a normal compile below
  765. }
  766. timer.done()
  767. // see if we can send an incremental update to the CLSI
  768. if (docUpdaterDocs != null && options.syncType !== 'full') {
  769. Metrics.inc('compile-from-redis')
  770. return _buildRequestFromDocupdater(
  771. projectId,
  772. options,
  773. project,
  774. projectStateHash,
  775. docUpdaterDocs
  776. )
  777. } else {
  778. Metrics.inc('compile-from-mongo')
  779. return await _buildRequestFromMongo(
  780. projectId,
  781. options,
  782. project,
  783. projectStateHash
  784. )
  785. }
  786. } else {
  787. // old way, always from mongo
  788. const timer = new Metrics.Timer('editor.compile-getdocs-mongo')
  789. const { docs, files } = await _getContentFromMongo(projectId)
  790. timer.done()
  791. return _finaliseRequest(projectId, options, project, docs, files)
  792. }
  793. }
  794. async function getContentFromDocUpdaterIfMatch(projectId, project, options) {
  795. const projectStateHash = ClsiStateManager.computeHash(project, options)
  796. const docs = await DocumentUpdaterHandler.promises.getProjectDocsIfMatch(
  797. projectId,
  798. projectStateHash
  799. )
  800. return { projectStateHash, docs }
  801. }
  802. async function getOutputFileStream(
  803. projectId,
  804. userId,
  805. clsiServerId,
  806. buildId,
  807. outputFilePath
  808. ) {
  809. const url = getOutputFileURL(
  810. projectId,
  811. userId,
  812. buildId,
  813. outputFilePath,
  814. clsiServerId
  815. )
  816. try {
  817. const stream = await fetchStream(url, {
  818. signal: AbortSignal.timeout(OUTPUT_FILE_TIMEOUT_MS),
  819. })
  820. return stream
  821. } catch (err) {
  822. throw new Errors.OutputFileFetchFailedError(
  823. 'failed to fetch output file from CLSI',
  824. {
  825. projectId,
  826. userId,
  827. url,
  828. status: err.response?.status,
  829. }
  830. )
  831. }
  832. }
  833. /**
  834. * @param {import('overleaf-editor-core/lib/types.js').RawChange[]} changes
  835. * @return {import('overleaf-editor-core/lib/types.js').RawOperation[][]}
  836. * @private
  837. */
  838. function _rawChangeOperationsFromChanges(changes) {
  839. // omit timestamp (required, back-filled in clsi)
  840. // omit authors (optional)
  841. // omit v2Authors (optional)
  842. // omit origin (optional)
  843. // omit projectVersion (optional)
  844. // omit v2DocVersions (optional)
  845. return changes.map(change => change.operations)
  846. }
  847. /**
  848. * @param {import('overleaf-editor-core/lib/types.js').RawOperation[][]} rawChangeOperations
  849. * @return {Set<string>}
  850. * @private
  851. */
  852. function _collectGlobalBlobs(rawChangeOperations) {
  853. const globalBlobs = new Set()
  854. for (const operations of rawChangeOperations) {
  855. for (const operation of operations) {
  856. const hash = operation?.file?.hash
  857. if (hash && HistoryManager.isGlobalBlob(hash)) {
  858. globalBlobs.add(hash)
  859. }
  860. }
  861. }
  862. return globalBlobs
  863. }
  864. function collectGlobalBlobsFromRawSnapshot(rawSnapshot, globalBlobs) {
  865. for (const { hash, rangesHash } of Object.values(rawSnapshot.files)) {
  866. if (hash && HistoryManager.isGlobalBlob(hash)) {
  867. globalBlobs.add(hash)
  868. }
  869. if (rangesHash && HistoryManager.isGlobalBlob(rangesHash)) {
  870. globalBlobs.add(rangesHash)
  871. }
  872. }
  873. }
  874. async function _buildRequestFromHistoryFull(
  875. projectId,
  876. historyId,
  877. options,
  878. project
  879. ) {
  880. await HistoryManager.promises.flushProject(projectId)
  881. const [
  882. {
  883. chunk: {
  884. history: { snapshot: rawSnapshot, changes: rawChanges },
  885. startVersion,
  886. },
  887. },
  888. /* ensureNoResyncPending throws */
  889. ] = await Promise.all([
  890. HistoryManager.promises.getLatestHistoryWithHistoryId(historyId),
  891. HistoryManager.promises.ensureNoResyncPending(projectId),
  892. ])
  893. const rawChangeOperations = _rawChangeOperationsFromChanges(rawChanges)
  894. const globalBlobs = _collectGlobalBlobs(rawChangeOperations)
  895. collectGlobalBlobsFromRawSnapshot(rawSnapshot, globalBlobs)
  896. options = {
  897. ...options,
  898. syncType: 'history-full',
  899. historyId,
  900. baseHistoryVersion: startVersion,
  901. rawSnapshot,
  902. rawChangeOperations,
  903. globalBlobs: Array.from(globalBlobs),
  904. }
  905. return _finaliseRequest(projectId, options, project, [], [])
  906. }
  907. async function _buildRequestFromHistoryIncremental(
  908. projectId,
  909. historyId,
  910. options,
  911. project,
  912. baseHistoryVersion
  913. ) {
  914. await HistoryManager.promises.flushProject(projectId)
  915. const rawChangeOperations = []
  916. let hasMore = true
  917. let since = baseHistoryVersion
  918. let size = 0
  919. while (hasMore) {
  920. let changes
  921. ;[{ changes, hasMore } /* resyncPending throws */] = await Promise.all([
  922. HistoryManager.promises.getChangesWithHistoryId(historyId, { since }),
  923. HistoryManager.promises.ensureNoResyncPending(projectId),
  924. ])
  925. since += changes.length
  926. const newRawChangeOperations = _rawChangeOperationsFromChanges(changes)
  927. size += Buffer.from(JSON.stringify(newRawChangeOperations)).byteLength
  928. if (size > 6.5 * 1024 * 1024) {
  929. // clsi has a payload limit of 7MiB. Do not send too many operations.
  930. // Fall back to sending the latest snapshot instead.
  931. try {
  932. return await _buildRequestFromHistoryFull(
  933. projectId,
  934. historyId,
  935. options,
  936. project
  937. )
  938. } catch (err) {
  939. throw OError.tag(err, 'upgrade to history-full failed', { size })
  940. }
  941. }
  942. rawChangeOperations.push(...newRawChangeOperations)
  943. }
  944. const globalBlobs = _collectGlobalBlobs(rawChangeOperations)
  945. options = {
  946. ...options,
  947. syncType: 'history-incremental',
  948. historyId,
  949. baseHistoryVersion,
  950. rawChangeOperations,
  951. globalBlobs: Array.from(globalBlobs),
  952. }
  953. return _finaliseRequest(projectId, options, project, [], [])
  954. }
  955. function _buildRequestFromDocupdater(
  956. projectId,
  957. options,
  958. project,
  959. projectStateHash,
  960. docUpdaterDocs
  961. ) {
  962. const docPath = ProjectEntityHandler.getAllDocPathsFromProject(project)
  963. const docs = {}
  964. for (const doc of docUpdaterDocs || []) {
  965. const path = docPath[doc._id]
  966. docs[path] = doc
  967. }
  968. // send new docs but not files as those are already on the clsi
  969. options = _.clone(options)
  970. options.syncType = 'incremental'
  971. options.syncState = projectStateHash
  972. // create stub doc entries for any possible root docs, if not
  973. // present in the docupdater. This allows finaliseRequest to
  974. // identify the root doc.
  975. const possibleRootDocIds = [options.rootDoc_id, project.rootDoc_id]
  976. for (const rootDocId of possibleRootDocIds) {
  977. if (rootDocId != null && rootDocId in docPath) {
  978. const path = docPath[rootDocId]
  979. if (docs[path] == null) {
  980. docs[path] = { _id: rootDocId, path }
  981. }
  982. }
  983. }
  984. return _finaliseRequest(projectId, options, project, docs, [])
  985. }
  986. async function _buildRequestFromMongo(
  987. projectId,
  988. options,
  989. project,
  990. projectStateHash
  991. ) {
  992. const { docs, files } = await _getContentFromMongo(projectId)
  993. options = {
  994. ...options,
  995. syncType: 'full',
  996. syncState: projectStateHash,
  997. }
  998. return _finaliseRequest(projectId, options, project, docs, files)
  999. }
  1000. async function _getContentFromMongo(projectId) {
  1001. await DocumentUpdaterHandler.promises.flushProjectToMongo(projectId)
  1002. const docs = await ProjectEntityHandler.promises.getAllDocs(projectId)
  1003. const files = await ProjectEntityHandler.promises.getAllFiles(projectId)
  1004. return { docs, files }
  1005. }
  1006. function _finaliseRequest(projectId, options, project, docs, files) {
  1007. const resources = []
  1008. let flags
  1009. let rootResourcePath = options.rootResourcePath
  1010. let rootResourcePathOverride = null
  1011. let hasMainFile = false
  1012. let numberOfDocsInProject = 0
  1013. for (let path in docs) {
  1014. const doc = docs[path]
  1015. path = path.replace(/^\//, '') // Remove leading /
  1016. numberOfDocsInProject++
  1017. if (doc.lines != null) {
  1018. // add doc to resources unless it is just a stub entry
  1019. resources.push({
  1020. path,
  1021. content: doc.lines.join('\n'),
  1022. })
  1023. }
  1024. if (
  1025. project.rootDoc_id != null &&
  1026. doc._id.toString() === project.rootDoc_id.toString()
  1027. ) {
  1028. rootResourcePath = path
  1029. }
  1030. if (
  1031. options.rootDoc_id != null &&
  1032. doc._id.toString() === options.rootDoc_id.toString()
  1033. ) {
  1034. rootResourcePathOverride = path
  1035. }
  1036. if (path === 'main.tex') {
  1037. hasMainFile = true
  1038. }
  1039. }
  1040. if (rootResourcePathOverride != null) {
  1041. rootResourcePath = rootResourcePathOverride
  1042. }
  1043. if (rootResourcePath == null) {
  1044. if (hasMainFile) {
  1045. rootResourcePath = 'main.tex'
  1046. } else if (numberOfDocsInProject === 1) {
  1047. // only one file, must be the main document
  1048. for (const path in docs) {
  1049. // Remove leading /
  1050. rootResourcePath = path.replace(/^\//, '')
  1051. }
  1052. } else {
  1053. throw new OError('no main file specified', { projectId })
  1054. }
  1055. }
  1056. const historyId = project.overleaf.history.id
  1057. if (!historyId) {
  1058. throw new OError('project does not have a history id', { projectId })
  1059. }
  1060. for (let path in files) {
  1061. const file = files[path]
  1062. path = path.replace(/^\//, '') // Remove leading /
  1063. resources.push({
  1064. path,
  1065. url: HistoryManager.getFilestoreBlobURL(historyId, file.hash),
  1066. modified: file.created?.getTime(),
  1067. })
  1068. }
  1069. if (options.fileLineErrors) {
  1070. flags = ['-file-line-error']
  1071. }
  1072. return {
  1073. compile: {
  1074. options: {
  1075. historyId: options.historyId?.toString(), // send as string, if set
  1076. buildId: options.buildId,
  1077. editorId: options.editorId,
  1078. compiler: project.compiler,
  1079. timeout: options.timeout,
  1080. imageName: project.imageName,
  1081. draft: Boolean(options.draft),
  1082. stopOnFirstError: Boolean(options.stopOnFirstError),
  1083. check: options.check,
  1084. syncType: options.syncType,
  1085. syncState: options.syncState,
  1086. compileGroup: options.compileGroup,
  1087. // Overleaf alpha/staff users get compileGroup=alpha (via getProjectCompileLimits in CompileManager), enroll them into the premium rollout of clsi-cache.
  1088. compileFromClsiCache:
  1089. // enable for premium compiles
  1090. (['alpha', 'priority'].includes(options.compileGroup) ||
  1091. // enable for free for short period when we saw low capacity
  1092. enableCompileFromCacheUntil > Date.now()) &&
  1093. options.compileFromClsiCache,
  1094. populateClsiCache: options.populateClsiCache,
  1095. enablePdfCaching:
  1096. (Settings.enablePdfCaching && options.enablePdfCaching) || false,
  1097. pdfCachingMinChunkSize: options.pdfCachingMinChunkSize,
  1098. enableCheckpoint: Boolean(options.enableCheckpoint),
  1099. flags,
  1100. metricsMethod: options.compileGroup,
  1101. metricsPath: options.metricsPath,
  1102. },
  1103. baseHistoryVersion: options.baseHistoryVersion,
  1104. rawSnapshot: options.rawSnapshot,
  1105. rawChangeOperations: options.rawChangeOperations,
  1106. globalBlobs: options.globalBlobs,
  1107. rootResourcePath,
  1108. resources,
  1109. },
  1110. }
  1111. }
  1112. async function buildDocumentConversionRequest(projectId, userId, options) {
  1113. return await _buildRequest(projectId, userId, {
  1114. ...options,
  1115. // Use the history snapshot as populated on clsi-cache.
  1116. populateClsiCache: true,
  1117. // Read from mongo directly, skip redis.
  1118. incrementalCompilesEnabled: false,
  1119. })
  1120. }
  1121. async function wordCount(projectId, userId, file, limits, clsiserverid) {
  1122. const { compileBackendClass, compileGroup } = limits
  1123. const req = await _buildRequest(projectId, userId, limits)
  1124. const filename = file || req.compile.rootResourcePath
  1125. const url = _getCompilerUrl(
  1126. compileBackendClass,
  1127. compileGroup,
  1128. projectId,
  1129. userId,
  1130. 'wordcount'
  1131. )
  1132. url.searchParams.set('file', filename)
  1133. url.searchParams.set('image', req.compile.options.imageName)
  1134. const opts = {
  1135. method: 'GET',
  1136. }
  1137. const { body } = await _makeRequestWithClsiServerId(
  1138. projectId,
  1139. userId,
  1140. compileGroup,
  1141. compileBackendClass,
  1142. url,
  1143. opts,
  1144. clsiserverid
  1145. )
  1146. return body
  1147. }
  1148. async function syncTeX(
  1149. projectId,
  1150. userId,
  1151. {
  1152. direction,
  1153. compileFromClsiCache,
  1154. limits,
  1155. imageName,
  1156. validatedOptions,
  1157. clsiServerId,
  1158. }
  1159. ) {
  1160. const { compileBackendClass, compileGroup } = limits
  1161. const url = _getCompilerUrl(
  1162. compileBackendClass,
  1163. compileGroup,
  1164. projectId,
  1165. userId,
  1166. `sync/${direction}`
  1167. )
  1168. url.searchParams.set(
  1169. 'compileFromClsiCache',
  1170. compileFromClsiCache && ['alpha', 'priority'].includes(compileGroup)
  1171. )
  1172. url.searchParams.set('imageName', imageName)
  1173. for (const [key, value] of Object.entries(validatedOptions)) {
  1174. url.searchParams.set(key, value)
  1175. }
  1176. const opts = {
  1177. method: 'GET',
  1178. }
  1179. try {
  1180. const { body } = await _makeRequestWithClsiServerId(
  1181. projectId,
  1182. userId,
  1183. compileGroup,
  1184. compileBackendClass,
  1185. url,
  1186. opts,
  1187. clsiServerId
  1188. )
  1189. return body
  1190. } catch (err) {
  1191. if (err instanceof RequestFailedError && err.response.status === 404) {
  1192. throw new Errors.NotFoundError()
  1193. }
  1194. throw err
  1195. }
  1196. }
  1197. function getClsiServerIdFromResponse(response) {
  1198. const setCookieHeaders = response.headers.raw()['set-cookie'] ?? []
  1199. for (const header of setCookieHeaders) {
  1200. const cookie = Cookie.parse(header)
  1201. if (cookie.key === Settings.clsiCookie.key) {
  1202. return cookie.value
  1203. }
  1204. }
  1205. return null
  1206. }
  1207. export default {
  1208. collectGlobalBlobsFromRawSnapshot,
  1209. _finaliseRequest,
  1210. sendRequest: callbackifyMultiResult(sendRequest, [
  1211. 'status',
  1212. 'outputFiles',
  1213. 'clsiServerId',
  1214. 'validationProblems',
  1215. 'stats',
  1216. 'timings',
  1217. 'outputUrlPrefix',
  1218. 'buildId',
  1219. 'clsiCacheShard',
  1220. 'instanceType',
  1221. ]),
  1222. sendExternalRequest: callbackifyMultiResult(sendExternalRequest, [
  1223. 'status',
  1224. 'outputFiles',
  1225. 'clsiServerId',
  1226. 'validationProblems',
  1227. 'stats',
  1228. 'timings',
  1229. 'outputUrlPrefix',
  1230. ]),
  1231. stopCompile: callbackify(stopCompile),
  1232. deleteAuxFiles: callbackify(deleteAuxFiles),
  1233. getOutputFileStream: callbackify(getOutputFileStream),
  1234. wordCount: callbackify(wordCount),
  1235. syncTeX: callbackify(syncTeX),
  1236. getClsiServerIdFromResponse,
  1237. CLSI_COOKIES_ENABLED,
  1238. promises: {
  1239. sendRequest,
  1240. sendExternalRequest,
  1241. stopCompile,
  1242. deleteAuxFiles,
  1243. getOutputFileStream,
  1244. wordCount,
  1245. syncTeX,
  1246. buildDocumentConversionRequest,
  1247. },
  1248. }