ClsiManagerTests.js 32 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007
  1. const { setTimeout } = require('timers/promises')
  2. const sinon = require('sinon')
  3. const { expect } = require('chai')
  4. const SandboxedModule = require('sandboxed-module')
  5. const tk = require('timekeeper')
  6. const { RequestFailedError } = require('@overleaf/fetch-utils')
  7. const FILESTORE_URL = 'http://filestore.example.com'
  8. const CLSI_HOST = 'clsi.example.com'
  9. const MODULE_PATH = '../../../../app/src/Features/Compile/ClsiManager.js'
  10. describe('ClsiManager', function () {
  11. beforeEach(function () {
  12. this.user_id = 'user-id'
  13. this.project = {
  14. _id: 'project-id',
  15. compiler: 'latex',
  16. rootDoc_id: 'mock-doc-id-1',
  17. imageName: 'mock-image-name',
  18. }
  19. this.docs = {
  20. '/main.tex': {
  21. name: 'main.tex',
  22. _id: 'mock-doc-id-1',
  23. lines: ['Hello', 'world'],
  24. },
  25. '/chapters/chapter1.tex': {
  26. name: 'chapter1.tex',
  27. _id: 'mock-doc-id-2',
  28. lines: ['Chapter 1'],
  29. },
  30. }
  31. this.files = {
  32. '/images/image.png': {
  33. name: 'image.png',
  34. _id: 'mock-file-id-1',
  35. created: new Date(),
  36. },
  37. }
  38. this.clsiCookieKey = 'clsiserver'
  39. this.clsiServerId = 'clsi-server-id'
  40. this.newClsiServerId = 'newserver'
  41. this.rawOutputFiles = {}
  42. this.responseBody = {
  43. compile: { status: 'success' },
  44. }
  45. this.response = {
  46. ok: true,
  47. status: 200,
  48. headers: {
  49. raw: sinon.stub().returns({
  50. 'set-cookie': [`${this.clsiCookieKey}=${this.newClsiServerId}`],
  51. }),
  52. },
  53. }
  54. this.FetchUtils = {
  55. fetchString: sinon
  56. .stub()
  57. .callsFake(() => Promise.resolve(JSON.stringify(this.responseBody))),
  58. fetchStringWithResponse: sinon.stub().callsFake(() =>
  59. Promise.resolve({
  60. body: JSON.stringify(this.responseBody),
  61. response: this.response,
  62. })
  63. ),
  64. fetchStream: sinon.stub(),
  65. RequestFailedError,
  66. }
  67. this.ClsiCookieManager = {
  68. promises: {
  69. clearServerId: sinon.stub().resolves(),
  70. getServerId: sinon.stub().resolves('clsi-server-id'),
  71. setServerId: sinon.stub().resolves(),
  72. },
  73. }
  74. this.ClsiStateManager = {
  75. computeHash: sinon.stub().returns('01234567890abcdef'),
  76. }
  77. this.ClsiFormatChecker = {
  78. promises: {
  79. checkRecoursesForProblems: sinon.stub().resolves(),
  80. },
  81. }
  82. this.Project = {}
  83. this.ProjectEntityHandler = {
  84. getAllDocPathsFromProject: sinon.stub(),
  85. promises: {
  86. getAllDocs: sinon.stub().resolves(this.docs),
  87. getAllFiles: sinon.stub().resolves(this.files),
  88. },
  89. }
  90. this.ProjectGetter = {
  91. promises: {
  92. findById: sinon.stub().resolves(this.project),
  93. getProject: sinon.stub().resolves(this.project),
  94. },
  95. }
  96. this.DocumentUpdaterHandler = {
  97. promises: {
  98. clearProjectState: sinon.stub().resolves(),
  99. flushProjectToMongo: sinon.stub().resolves(),
  100. getProjectDocsIfMatch: sinon.stub().resolves(),
  101. },
  102. }
  103. this.Metrics = {
  104. Timer: class Metrics {
  105. constructor() {
  106. this.done = sinon.stub()
  107. }
  108. },
  109. inc: sinon.stub(),
  110. count: sinon.stub(),
  111. }
  112. this.Settings = {
  113. apis: {
  114. filestore: {
  115. url: FILESTORE_URL,
  116. secret: 'secret',
  117. },
  118. clsi: {
  119. url: `http://${CLSI_HOST}`,
  120. defaultBackendClass: 'e2',
  121. submissionBackendClass: 'n2d',
  122. },
  123. clsi_priority: {
  124. url: 'https://clsipremium.example.com',
  125. },
  126. },
  127. enablePdfCaching: true,
  128. clsiCookie: { key: 'clsiserver' },
  129. }
  130. this.ClsiManager = SandboxedModule.require(MODULE_PATH, {
  131. requires: {
  132. '@overleaf/settings': this.Settings,
  133. '../../models/Project': {
  134. Project: this.Project,
  135. },
  136. '../Project/ProjectEntityHandler': this.ProjectEntityHandler,
  137. '../Project/ProjectGetter': this.ProjectGetter,
  138. '../DocumentUpdater/DocumentUpdaterHandler':
  139. this.DocumentUpdaterHandler,
  140. './ClsiCookieManager': () => this.ClsiCookieManager,
  141. './ClsiStateManager': this.ClsiStateManager,
  142. '@overleaf/fetch-utils': this.FetchUtils,
  143. './ClsiFormatChecker': this.ClsiFormatChecker,
  144. '@overleaf/metrics': this.Metrics,
  145. },
  146. })
  147. tk.freeze(Date.now())
  148. })
  149. after(function () {
  150. tk.reset()
  151. })
  152. describe('sendRequest', function () {
  153. describe('with a successful compile', function () {
  154. beforeEach(async function () {
  155. this.outputFiles = [
  156. {
  157. url: `/project/${this.project_id}/user/${this.user_id}/build/1234/output/output.pdf`,
  158. path: 'output.pdf',
  159. type: 'pdf',
  160. build: 1234,
  161. },
  162. {
  163. url: `/project/${this.project_id}/user/${this.user_id}/build/1234/output/output.log`,
  164. path: 'output.log',
  165. type: 'log',
  166. build: 1234,
  167. },
  168. ]
  169. this.responseBody.compile.outputFiles = this.outputFiles.map(
  170. outputFile => ({
  171. ...outputFile,
  172. url: `http://${CLSI_HOST}${outputFile.url}`,
  173. })
  174. )
  175. this.timeout = 100
  176. this.result = await this.ClsiManager.promises.sendRequest(
  177. this.project._id,
  178. this.user_id,
  179. {
  180. compileBackendClass: 'e2',
  181. compileGroup: 'standard',
  182. timeout: this.timeout,
  183. }
  184. )
  185. })
  186. it('should send the request to the CLSI', function () {
  187. this.FetchUtils.fetchStringWithResponse.should.have.been.calledWith(
  188. sinon.match(
  189. url =>
  190. url.host === CLSI_HOST &&
  191. url.pathname ===
  192. `/project/${this.project._id}/user/${this.user_id}/compile` &&
  193. url.searchParams.get('compileBackendClass') === 'e2' &&
  194. url.searchParams.get('compileGroup') === 'standard'
  195. ),
  196. {
  197. method: 'POST',
  198. json: sinon.match({
  199. compile: {
  200. options: {
  201. compiler: this.project.compiler,
  202. imageName: this.project.imageName,
  203. timeout: this.timeout,
  204. draft: false,
  205. compileGroup: 'standard',
  206. metricsMethod: 'standard',
  207. stopOnFirstError: false,
  208. syncType: undefined,
  209. },
  210. rootResourcePath: 'main.tex',
  211. resources: _makeResources(this.project, this.docs, this.files),
  212. },
  213. }),
  214. headers: {
  215. Accept: 'application/json',
  216. 'Content-Type': 'application/json',
  217. Cookie: `${this.clsiCookieKey}=${this.clsiServerId}`,
  218. },
  219. signal: sinon.match.instanceOf(AbortSignal),
  220. }
  221. )
  222. })
  223. it('should get the project with the required fields', function () {
  224. this.ProjectGetter.promises.getProject.should.have.been.calledWith(
  225. this.project._id,
  226. {
  227. compiler: 1,
  228. rootDoc_id: 1,
  229. imageName: 1,
  230. rootFolder: 1,
  231. }
  232. )
  233. })
  234. it('should flush the project to the database', function () {
  235. this.DocumentUpdaterHandler.promises.flushProjectToMongo.should.have.been.calledWith(
  236. this.project._id
  237. )
  238. })
  239. it('should get all the docs', function () {
  240. this.ProjectEntityHandler.promises.getAllDocs.should.have.been.calledWith(
  241. this.project._id
  242. )
  243. })
  244. it('should get all the files', function () {
  245. this.ProjectEntityHandler.promises.getAllFiles.should.have.been.calledWith(
  246. this.project._id
  247. )
  248. })
  249. it('should return the status and output files', function () {
  250. expect(this.result.status).to.equal('success')
  251. expect(this.result.outputFiles.map(f => f.path)).to.have.members(
  252. this.outputFiles.map(f => f.path)
  253. )
  254. })
  255. it('should persist the cookie from the response', function () {
  256. expect(
  257. this.ClsiCookieManager.promises.setServerId
  258. ).to.have.been.calledWith(
  259. this.project._id,
  260. this.user_id,
  261. 'standard',
  262. 'e2',
  263. this.newClsiServerId
  264. )
  265. })
  266. })
  267. describe('with ranges on the pdf and stats/timings details', function () {
  268. beforeEach(async function () {
  269. this.ranges = [{ start: 1, end: 42, hash: 'foo' }]
  270. this.startXRefTable = 123
  271. this.size = 456
  272. this.contentId = '123-321'
  273. this.outputFiles = [
  274. {
  275. url: `/project/${this.project._id}/user/${this.user_id}/build/1234/output/output.pdf`,
  276. path: 'output.pdf',
  277. type: 'pdf',
  278. build: 1234,
  279. contentId: this.contentId,
  280. ranges: this.ranges,
  281. startXRefTable: this.startXRefTable,
  282. size: this.size,
  283. },
  284. {
  285. url: `/project/${this.project._id}/user/${this.user_id}/build/1234/output/output.log`,
  286. path: 'output.log',
  287. type: 'log',
  288. build: 1234,
  289. },
  290. ]
  291. this.stats = { fooStat: 1 }
  292. this.timings = { barTiming: 2 }
  293. this.responseBody.compile.outputFiles = this.outputFiles.map(
  294. outputFile => ({
  295. ...outputFile,
  296. url: `http://${CLSI_HOST}${outputFile.url}`,
  297. })
  298. )
  299. this.responseBody.compile.stats = this.stats
  300. this.responseBody.compile.timings = this.timings
  301. this.result = await this.ClsiManager.promises.sendRequest(
  302. this.project._id,
  303. this.user_id,
  304. { compileBackendClass: 'e2', compileGroup: 'standard' }
  305. )
  306. })
  307. it('should emit the caching details and stats/timings', function () {
  308. expect(this.result.status).to.equal('success')
  309. expect(this.result.clsiServerId).to.equal(this.newClsiServerId)
  310. expect(this.result.validationError).to.be.undefined
  311. expect(this.result.stats).to.deep.equal(this.stats)
  312. expect(this.result.timings).to.deep.equal(this.timings)
  313. const outputPdf = this.result.outputFiles.find(
  314. f => f.path === 'output.pdf'
  315. )
  316. expect(outputPdf.ranges).to.deep.equal(this.ranges)
  317. expect(outputPdf.startXRefTable).to.equal(this.startXRefTable)
  318. expect(outputPdf.contentId).to.equal(this.contentId)
  319. expect(outputPdf.size).to.equal(this.size)
  320. })
  321. })
  322. describe('with the incremental compile option', function () {
  323. beforeEach(async function () {
  324. const doc = this.docs['/main.tex']
  325. this.DocumentUpdaterHandler.promises.getProjectDocsIfMatch.resolves([
  326. { _id: doc._id, lines: doc.lines, v: 123 },
  327. ])
  328. this.ProjectEntityHandler.getAllDocPathsFromProject.returns({
  329. 'mock-doc-id-1': 'main.tex',
  330. })
  331. this.result = await this.ClsiManager.promises.sendRequest(
  332. this.project._id,
  333. this.user_id,
  334. {
  335. timeout: 100,
  336. incrementalCompilesEnabled: true,
  337. compileBackendClass: 'e2',
  338. compileGroup: 'priority',
  339. enablePdfCaching: true,
  340. pdfCachingMinChunkSize: 1337,
  341. }
  342. )
  343. })
  344. it('should get the project with the required fields', function () {
  345. this.ProjectGetter.promises.getProject.should.have.been.calledWith(
  346. this.project._id,
  347. {
  348. compiler: 1,
  349. rootDoc_id: 1,
  350. imageName: 1,
  351. rootFolder: 1,
  352. }
  353. )
  354. })
  355. it('should not explicitly flush the project to the database', function () {
  356. this.DocumentUpdaterHandler.promises.flushProjectToMongo.should.not.have.been.calledWith(
  357. this.project._id
  358. )
  359. })
  360. it('should get only the live docs from the docupdater with a background flush in docupdater', function () {
  361. this.DocumentUpdaterHandler.promises.getProjectDocsIfMatch.should.have.been.calledWith(
  362. this.project._id
  363. )
  364. })
  365. it('should not get any of the files', function () {
  366. this.ProjectEntityHandler.promises.getAllFiles.should.not.have.been
  367. .called
  368. })
  369. it('should build up the CLSI request', function () {
  370. this.FetchUtils.fetchStringWithResponse.should.have.been.calledWith(
  371. sinon.match(
  372. url =>
  373. url.hostname === CLSI_HOST &&
  374. url.pathname ===
  375. `/project/${this.project._id}/user/${this.user_id}/compile` &&
  376. url.searchParams.get('compileBackendClass') === 'e2' &&
  377. url.searchParams.get('compileGroup') === 'priority'
  378. ),
  379. {
  380. method: 'POST',
  381. json: sinon.match({
  382. compile: {
  383. options: {
  384. compiler: this.project.compiler,
  385. timeout: 100,
  386. imageName: this.project.imageName,
  387. draft: false,
  388. syncType: 'incremental',
  389. syncState: '01234567890abcdef',
  390. compileGroup: 'priority',
  391. enablePdfCaching: true,
  392. pdfCachingMinChunkSize: 1337,
  393. metricsMethod: 'priority',
  394. stopOnFirstError: false,
  395. },
  396. rootResourcePath: 'main.tex',
  397. resources: [
  398. {
  399. path: 'main.tex',
  400. content: this.docs['/main.tex'].lines.join('\n'),
  401. },
  402. ],
  403. },
  404. }),
  405. headers: {
  406. Accept: 'application/json',
  407. 'Content-Type': 'application/json',
  408. Cookie: `${this.clsiCookieKey}=${this.clsiServerId}`,
  409. },
  410. signal: sinon.match.instanceOf(AbortSignal),
  411. }
  412. )
  413. })
  414. })
  415. describe('when the root doc is set and not in the docupdater', function () {
  416. beforeEach(async function () {
  417. const doc = this.docs['/main.tex']
  418. this.DocumentUpdaterHandler.promises.getProjectDocsIfMatch.resolves([
  419. { _id: doc._id, lines: doc.lines, v: 123 },
  420. ])
  421. this.ProjectEntityHandler.getAllDocPathsFromProject.returns({
  422. 'mock-doc-id-1': 'main.tex',
  423. 'mock-doc-id-2': '/chapters/chapter1.tex',
  424. })
  425. await this.ClsiManager.promises.sendRequest(
  426. this.project._id,
  427. this.user_id,
  428. {
  429. timeout: 100,
  430. incrementalCompilesEnabled: true,
  431. rootDoc_id: 'mock-doc-id-2',
  432. }
  433. )
  434. })
  435. it('should still change the root path', function () {
  436. this.FetchUtils.fetchStringWithResponse.should.have.been.calledWith(
  437. sinon.match.any,
  438. sinon.match({
  439. json: { compile: { rootResourcePath: 'chapters/chapter1.tex' } },
  440. })
  441. )
  442. })
  443. })
  444. describe('when root doc override is valid', function () {
  445. beforeEach(async function () {
  446. await this.ClsiManager.promises.sendRequest(
  447. this.project._id,
  448. this.user_id,
  449. { rootDoc_id: 'mock-doc-id-2' }
  450. )
  451. })
  452. it('should change root path', function () {
  453. this.FetchUtils.fetchStringWithResponse.should.have.been.calledWith(
  454. sinon.match.any,
  455. sinon.match({
  456. json: { compile: { rootResourcePath: 'chapters/chapter1.tex' } },
  457. })
  458. )
  459. })
  460. })
  461. describe('when root doc override is invalid', function () {
  462. beforeEach(async function () {
  463. await this.ClsiManager.promises.sendRequest(
  464. this.project._id,
  465. this.user_id,
  466. { rootDoc_id: 'invalid-id' }
  467. )
  468. })
  469. it('should fallback to default root doc', function () {
  470. this.FetchUtils.fetchStringWithResponse.should.have.been.calledWith(
  471. sinon.match.any,
  472. sinon.match({
  473. json: { compile: { rootResourcePath: 'main.tex' } },
  474. })
  475. )
  476. })
  477. })
  478. describe('when the project has an invalid compiler', function () {
  479. beforeEach(async function () {
  480. this.project.compiler = 'context'
  481. await this.ClsiManager.promises.sendRequest(
  482. this.project._id,
  483. this.user_id,
  484. {}
  485. )
  486. })
  487. it('should set the compiler to pdflatex', function () {
  488. expect(this.FetchUtils.fetchStringWithResponse).to.have.been.calledWith(
  489. sinon.match.any,
  490. sinon.match({
  491. json: { compile: { options: { compiler: 'pdflatex' } } },
  492. })
  493. )
  494. })
  495. })
  496. describe('when there is no valid root document', function () {
  497. beforeEach(async function () {
  498. this.project.rootDoc_id = 'not-valid'
  499. await this.ClsiManager.promises.sendRequest(
  500. this.project._id,
  501. this.user_id,
  502. {}
  503. )
  504. })
  505. it('should set to main.tex', function () {
  506. expect(this.FetchUtils.fetchStringWithResponse).to.have.been.calledWith(
  507. sinon.match.any,
  508. sinon.match({
  509. json: { compile: { rootResourcePath: 'main.tex' } },
  510. })
  511. )
  512. })
  513. })
  514. describe('when there is no valid root document and no main.tex document', function () {
  515. beforeEach(async function () {
  516. this.project.rootDoc_id = 'not-valid'
  517. this.docs = {
  518. '/other.tex': {
  519. name: 'other.tex',
  520. _id: 'mock-doc-id-1',
  521. lines: ['Hello', 'world'],
  522. },
  523. '/chapters/chapter1.tex': {
  524. name: 'chapter1.tex',
  525. _id: 'mock-doc-id-2',
  526. lines: ['Chapter 1'],
  527. },
  528. }
  529. this.ProjectEntityHandler.promises.getAllDocs.resolves(this.docs)
  530. this.result = await this.ClsiManager.promises.sendRequest(
  531. this.project._id,
  532. this.user_id,
  533. {}
  534. )
  535. })
  536. it('should report a validation problem', function () {
  537. expect(this.result.status).to.equal('validation-problems')
  538. })
  539. })
  540. describe('when there is no valid root document and a single document which is not main.tex', function () {
  541. beforeEach(async function () {
  542. this.project.rootDoc_id = 'not-valid'
  543. this.docs = {
  544. '/other.tex': {
  545. name: 'other.tex',
  546. _id: 'mock-doc-id-1',
  547. lines: ['Hello', 'world'],
  548. },
  549. }
  550. this.ProjectEntityHandler.promises.getAllDocs.resolves(this.docs)
  551. await this.ClsiManager.promises.sendRequest(
  552. this.project._id,
  553. this.user_id,
  554. {}
  555. )
  556. })
  557. it('should set io to the only file', function () {
  558. expect(this.FetchUtils.fetchStringWithResponse).to.have.been.calledWith(
  559. sinon.match.any,
  560. sinon.match({
  561. json: { compile: { rootResourcePath: 'other.tex' } },
  562. })
  563. )
  564. })
  565. })
  566. describe('with the draft option', function () {
  567. beforeEach(async function () {
  568. await this.ClsiManager.promises.sendRequest(
  569. this.project._id,
  570. this.user_id,
  571. {
  572. timeout: 100,
  573. draft: true,
  574. }
  575. )
  576. })
  577. it('should add the draft option into the request', function () {
  578. expect(this.FetchUtils.fetchStringWithResponse).to.have.been.calledWith(
  579. sinon.match.any,
  580. sinon.match({
  581. json: { compile: { options: { draft: true } } },
  582. })
  583. )
  584. })
  585. })
  586. describe('with a failed compile', function () {
  587. beforeEach(async function () {
  588. this.responseBody.compile.status = 'failure'
  589. this.result = await this.ClsiManager.promises.sendRequest(
  590. this.project._id,
  591. this.user_id,
  592. {}
  593. )
  594. })
  595. it('should return a failure status', function () {
  596. expect(this.result.status).to.equal('failure')
  597. })
  598. })
  599. describe('with a sync conflict', function () {
  600. beforeEach(async function () {
  601. const conflictResponseBody = { compile: { status: 'conflict' } }
  602. this.FetchUtils.fetchStringWithResponse
  603. .withArgs(
  604. sinon.match.any,
  605. sinon.match({
  606. json: sinon.match(
  607. json => json.compile.options.syncType !== 'full'
  608. ),
  609. })
  610. )
  611. .resolves({
  612. body: JSON.stringify(conflictResponseBody),
  613. response: this.response,
  614. })
  615. this.result = await this.ClsiManager.promises.sendRequest(
  616. this.project._id,
  617. this.user_id,
  618. {}
  619. )
  620. })
  621. it('should send two requests to CLSI', function () {
  622. this.FetchUtils.fetchStringWithResponse.should.have.been.calledTwice
  623. })
  624. it('should call the CLSI first without syncType:full', function () {
  625. const compileOptions =
  626. this.FetchUtils.fetchStringWithResponse.getCall(0).args[1].json
  627. .compile.options
  628. expect(compileOptions.syncType).to.be.undefined
  629. })
  630. it('should call the CLSI a second time with syncType:full', function () {
  631. const compileOptions =
  632. this.FetchUtils.fetchStringWithResponse.getCall(1).args[1].json
  633. .compile.options
  634. expect(compileOptions.syncType).to.equal('full')
  635. })
  636. it('should return a success status', function () {
  637. this.result.status.should.equal('success')
  638. })
  639. })
  640. describe('with an unavailable response', function () {
  641. beforeEach(async function () {
  642. this.FetchUtils.fetchStringWithResponse.onCall(0).resolves({
  643. body: JSON.stringify({ compile: { status: 'unavailable' } }),
  644. response: this.response,
  645. })
  646. this.result = await this.ClsiManager.promises.sendRequest(
  647. this.project._id,
  648. this.user_id,
  649. {}
  650. )
  651. })
  652. it('should send two requests to CLSI', function () {
  653. this.FetchUtils.fetchStringWithResponse.should.have.been.calledTwice
  654. })
  655. it('should call the CLSI first without syncType:full', function () {
  656. const compileOptions =
  657. this.FetchUtils.fetchStringWithResponse.getCall(0).args[1].json
  658. .compile.options
  659. expect(compileOptions.syncType).to.be.undefined
  660. })
  661. it('should call the CLSI a second time with syncType:full', function () {
  662. const compileOptions =
  663. this.FetchUtils.fetchStringWithResponse.getCall(1).args[1].json
  664. .compile.options
  665. expect(compileOptions.syncType).to.equal('full')
  666. })
  667. it('should clear the CLSI server id cookie', function () {
  668. expect(
  669. this.ClsiCookieManager.promises.clearServerId
  670. ).to.have.been.calledWith(this.project._id, this.user_id)
  671. })
  672. it('should return a success status', function () {
  673. expect(this.result.status).to.equal('success')
  674. })
  675. })
  676. describe('when the resources fail the precompile check', function () {
  677. beforeEach(function () {
  678. this.ClsiFormatChecker.promises.checkRecoursesForProblems.rejects(
  679. new Error('failed')
  680. )
  681. })
  682. it('should throw an error', async function () {
  683. await expect(
  684. this.ClsiManager.promises.sendRequest(
  685. this.project._id,
  686. this.user_id,
  687. {}
  688. )
  689. ).to.be.rejected
  690. })
  691. })
  692. describe('when a new backend is configured', function () {
  693. beforeEach(async function () {
  694. this.Settings.apis.clsi_new = { url: 'https://compiles.somewhere.test' }
  695. await this.ClsiManager.promises.sendRequest(
  696. this.project._id,
  697. this.user_id,
  698. {
  699. compileBackendClass: 'e2',
  700. compileGroup: 'standard',
  701. }
  702. )
  703. // wait for the background task to finish
  704. await setTimeout(0)
  705. })
  706. it('makes a request to the new backend', function () {
  707. expect(this.FetchUtils.fetchStringWithResponse).to.have.been.calledTwice
  708. expect(this.FetchUtils.fetchStringWithResponse).to.have.been.calledWith(
  709. sinon.match(
  710. url =>
  711. url.host === CLSI_HOST &&
  712. url.pathname ===
  713. `/project/${this.project._id}/user/${this.user_id}/compile` &&
  714. url.searchParams.get('compileBackendClass') === 'e2' &&
  715. url.searchParams.get('compileGroup') === 'standard'
  716. )
  717. )
  718. expect(this.FetchUtils.fetchStringWithResponse).to.have.been.calledWith(
  719. sinon.match(
  720. url =>
  721. url.toString() ===
  722. `${this.Settings.apis.clsi_new.url}/project/${this.project._id}/user/${this.user_id}/compile?compileBackendClass=e2&compileGroup=standard`
  723. )
  724. )
  725. })
  726. })
  727. })
  728. describe('sendExternalRequest', function () {
  729. beforeEach(function () {
  730. this.submissionId = 'submission-id'
  731. this.clsiRequest = 'mock-request'
  732. })
  733. describe('with a successful compile', function () {
  734. beforeEach(async function () {
  735. this.outputFiles = [
  736. {
  737. url: `/project/${this.submissionId}/build/1234/output/output.pdf`,
  738. path: 'output.pdf',
  739. type: 'pdf',
  740. build: 1234,
  741. },
  742. {
  743. url: `/project/${this.submissionId}/build/1234/output/output.log`,
  744. path: 'output.log',
  745. type: 'log',
  746. build: 1234,
  747. },
  748. ]
  749. this.responseBody.compile.outputFiles = this.outputFiles.map(
  750. outputFile => ({
  751. ...outputFile,
  752. url: `http://${CLSI_HOST}${outputFile.url}`,
  753. })
  754. )
  755. this.result = await this.ClsiManager.promises.sendExternalRequest(
  756. this.submissionId,
  757. this.clsiRequest,
  758. { compileBackendClass: 'e2', compileGroup: 'standard' }
  759. )
  760. })
  761. it('should send the request to the CLSI', function () {
  762. this.FetchUtils.fetchStringWithResponse.should.have.been.calledWith(
  763. sinon.match(
  764. url =>
  765. url.host === CLSI_HOST &&
  766. url.pathname === `/project/${this.submissionId}/compile` &&
  767. url.searchParams.get('compileBackendClass') === 'e2' &&
  768. url.searchParams.get('compileGroup') === 'standard'
  769. ),
  770. {
  771. method: 'POST',
  772. json: this.clsiRequest,
  773. headers: {
  774. Accept: 'application/json',
  775. 'Content-Type': 'application/json',
  776. Cookie: `${this.clsiCookieKey}=${this.clsiServerId}`,
  777. },
  778. signal: sinon.match.instanceOf(AbortSignal),
  779. }
  780. )
  781. })
  782. it('should return the status and output files', function () {
  783. expect(this.result.status).to.equal('success')
  784. expect(this.result.outputFiles.map(f => f.path)).to.have.members(
  785. this.outputFiles.map(f => f.path)
  786. )
  787. })
  788. })
  789. describe('with a failed compile', function () {
  790. beforeEach(async function () {
  791. this.responseBody.compile.status = 'failure'
  792. this.result = await this.ClsiManager.promises.sendExternalRequest(
  793. this.submissionId,
  794. this.clsiRequest,
  795. {}
  796. )
  797. })
  798. it('should return a failure status', function () {
  799. expect(this.result.status).to.equal('failure')
  800. })
  801. })
  802. describe('when the resources fail the precompile check', function () {
  803. beforeEach(async function () {
  804. this.ClsiFormatChecker.promises.checkRecoursesForProblems.rejects(
  805. new Error('failed')
  806. )
  807. this.responseBody.compile.status = 'failure'
  808. })
  809. it('should throw an error', async function () {
  810. await expect(
  811. this.ClsiManager.promises.sendExternalRequest(
  812. this.submissionId,
  813. this.clsiRequest,
  814. {}
  815. )
  816. ).to.be.rejected
  817. })
  818. })
  819. })
  820. describe('deleteAuxFiles', function () {
  821. describe('with the standard compileGroup', function () {
  822. beforeEach(async function () {
  823. await this.ClsiManager.promises.deleteAuxFiles(
  824. this.project._id,
  825. this.user_id,
  826. { compileBackendClass: 'e2', compileGroup: 'standard' },
  827. 'node-1'
  828. )
  829. })
  830. it('should call the delete method in the standard CLSI', function () {
  831. this.FetchUtils.fetchString.should.have.been.calledWith(
  832. sinon.match(
  833. url =>
  834. url.host === CLSI_HOST &&
  835. url.pathname ===
  836. `/project/${this.project._id}/user/${this.user_id}` &&
  837. url.searchParams.get('compileBackendClass') === 'e2' &&
  838. url.searchParams.get('compileGroup') === 'standard' &&
  839. url.searchParams.get('clsiserverid') === 'node-1'
  840. ),
  841. { method: 'DELETE' }
  842. )
  843. })
  844. it('should clear the project state from the docupdater', function () {
  845. this.DocumentUpdaterHandler.promises.clearProjectState
  846. .calledWith(this.project._id)
  847. .should.equal(true)
  848. })
  849. it('should clear the clsi persistance', function () {
  850. this.ClsiCookieManager.promises.clearServerId
  851. .calledWith(this.project._id, this.user_id)
  852. .should.equal(true)
  853. })
  854. it('should not persist a cookie on response', function () {
  855. expect(this.ClsiCookieManager.promises.setServerId).not.to.have.been
  856. .called
  857. })
  858. })
  859. })
  860. describe('wordCount', function () {
  861. describe('with root file', function () {
  862. beforeEach(async function () {
  863. await this.ClsiManager.promises.wordCount(
  864. this.project._id,
  865. this.user_id,
  866. false,
  867. { compileBackendClass: 'e2', compileGroup: 'standard' },
  868. 'node-1'
  869. )
  870. })
  871. it('should call wordCount with root file', function () {
  872. expect(this.FetchUtils.fetchString).to.have.been.calledWith(
  873. sinon.match(
  874. url =>
  875. url.toString() ===
  876. `http://clsi.example.com/project/${this.project._id}/user/${this.user_id}/wordcount?compileBackendClass=e2&compileGroup=standard&file=main.tex&image=mock-image-name&clsiserverid=node-1`
  877. )
  878. )
  879. })
  880. it('should not persist a cookie on response', function () {
  881. expect(this.ClsiCookieManager.promises.setServerId).not.to.have.been
  882. .called
  883. })
  884. })
  885. describe('with param file', function () {
  886. beforeEach(async function () {
  887. await this.ClsiManager.promises.wordCount(
  888. this.project._id,
  889. this.user_id,
  890. 'other.tex',
  891. { compileBackendClass: 'e2', compileGroup: 'standard' },
  892. 'node-2'
  893. )
  894. })
  895. it('should call wordCount with param file', function () {
  896. expect(this.FetchUtils.fetchString).to.have.been.calledWith(
  897. sinon.match(
  898. url =>
  899. url.host === CLSI_HOST &&
  900. url.pathname ===
  901. `/project/${this.project._id}/user/${this.user_id}/wordcount` &&
  902. url.searchParams.get('compileBackendClass') === 'e2' &&
  903. url.searchParams.get('compileGroup') === 'standard' &&
  904. url.searchParams.get('clsiserverid') === 'node-2' &&
  905. url.searchParams.get('file') === 'other.tex' &&
  906. url.searchParams.get('image') === 'mock-image-name'
  907. )
  908. )
  909. })
  910. it('should not persist a cookie on response', function () {
  911. expect(this.ClsiCookieManager.promises.setServerId).not.to.have.been
  912. .called
  913. })
  914. })
  915. })
  916. })
  917. function _makeResources(project, docs, files) {
  918. const resources = []
  919. for (const [path, doc] of Object.entries(docs)) {
  920. resources.push({
  921. path: path.replace(/^\//, ''),
  922. content: doc.lines.join('\n'),
  923. })
  924. }
  925. for (const [path, file] of Object.entries(files)) {
  926. resources.push({
  927. path: path.replace(/^\//, ''),
  928. url: `${FILESTORE_URL}/project/${project._id}/file/${file._id}`,
  929. modified: file.created.getTime(),
  930. })
  931. }
  932. return resources
  933. }