ClsiManager.js 28 KB

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