CompileManagerTests.js 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707
  1. const Path = require('node:path')
  2. const SandboxedModule = require('sandboxed-module')
  3. const { expect } = require('chai')
  4. const sinon = require('sinon')
  5. const MODULE_PATH = require('node:path').join(
  6. __dirname,
  7. '../../../app/js/CompileManager'
  8. )
  9. describe('CompileManager', function () {
  10. beforeEach(function () {
  11. this.projectId = 'project-id-123'
  12. this.userId = '1234'
  13. this.resources = 'mock-resources'
  14. this.outputFiles = [
  15. {
  16. path: 'output.log',
  17. type: 'log',
  18. },
  19. {
  20. path: 'output.pdf',
  21. type: 'pdf',
  22. },
  23. ]
  24. this.buildFiles = [
  25. {
  26. path: 'output.log',
  27. type: 'log',
  28. build: 1234,
  29. },
  30. {
  31. path: 'output.pdf',
  32. type: 'pdf',
  33. build: 1234,
  34. },
  35. ]
  36. this.buildId = '00000000000-0000000000000000'
  37. this.commandOutput = 'Dummy output'
  38. this.compileBaseDir = '/compile/dir'
  39. this.outputBaseDir = '/output/dir'
  40. this.compileDir = `${this.compileBaseDir}/${this.projectId}-${this.userId}`
  41. this.outputDir = `${this.outputBaseDir}/${this.projectId}-${this.userId}`
  42. this.LatexRunner = {
  43. promises: {
  44. runLatex: sinon.stub().resolves({}),
  45. },
  46. }
  47. this.ResourceWriter = {
  48. promises: {
  49. syncResourcesToDisk: sinon.stub().resolves(this.resources),
  50. },
  51. }
  52. this.OutputFileFinder = {
  53. promises: {
  54. findOutputFiles: sinon.stub().resolves({
  55. outputFiles: this.outputFiles,
  56. allEntries: this.outputFiles.map(f => f.path).concat(['main.tex']),
  57. }),
  58. },
  59. }
  60. this.OutputCacheManager = {
  61. BUILD_REGEX: /^[0-9a-f]+-[0-9a-f]+$/,
  62. CACHE_SUBDIR: 'generated-files',
  63. promises: {
  64. queueDirOperation: sinon.stub().callsArg(1),
  65. saveOutputFiles: sinon
  66. .stub()
  67. .resolves({ outputFiles: this.buildFiles, buildId: this.buildId }),
  68. },
  69. }
  70. this.Settings = {
  71. path: {
  72. compilesDir: this.compileBaseDir,
  73. outputDir: this.outputBaseDir,
  74. synctexBaseDir: sinon.stub(),
  75. },
  76. clsi: {
  77. docker: {
  78. image: 'SOMEIMAGE',
  79. },
  80. },
  81. }
  82. this.Settings.path.synctexBaseDir
  83. .withArgs(`${this.projectId}-${this.userId}`)
  84. .returns(this.compileDir)
  85. this.child_process = {
  86. exec: sinon.stub(),
  87. execFile: sinon.stub().yields(),
  88. }
  89. this.CommandRunner = {
  90. canRunSyncTeXInOutputDir: sinon.stub().returns(false),
  91. promises: {
  92. run: sinon.stub().callsFake((_1, _2, _3, _4, _5, _6, compileGroup) => {
  93. if (compileGroup === 'synctex' || compileGroup === 'synctex-output') {
  94. return Promise.resolve({ stdout: this.commandOutput })
  95. } else {
  96. return Promise.resolve({
  97. stdout: 'Encoding: ascii\nWords in text: 2',
  98. })
  99. }
  100. }),
  101. },
  102. }
  103. this.DraftModeManager = {
  104. promises: {
  105. injectDraftMode: sinon.stub().resolves(),
  106. },
  107. }
  108. this.TikzManager = {
  109. promises: {
  110. checkMainFile: sinon.stub().resolves(false),
  111. },
  112. }
  113. this.lock = {
  114. release: sinon.stub(),
  115. }
  116. this.LockManager = {
  117. acquire: sinon.stub().returns(this.lock),
  118. }
  119. this.SynctexOutputParser = {
  120. parseViewOutput: sinon.stub(),
  121. parseEditOutput: sinon.stub(),
  122. }
  123. this.dirStats = {
  124. isDirectory: sinon.stub().returns(true),
  125. }
  126. this.fileStats = {
  127. isFile: sinon.stub().returns(true),
  128. }
  129. this.fsPromises = {
  130. lstat: sinon.stub(),
  131. stat: sinon.stub(),
  132. readFile: sinon.stub(),
  133. mkdir: sinon.stub().resolves(),
  134. rm: sinon.stub().resolves(),
  135. unlink: sinon.stub().resolves(),
  136. rmdir: sinon.stub().resolves(),
  137. }
  138. this.fsPromises.lstat.withArgs(this.compileDir).resolves(this.dirStats)
  139. this.fsPromises.stat
  140. .withArgs(Path.join(this.compileDir, 'output.synctex.gz'))
  141. .resolves(this.fileStats)
  142. this.CLSICacheHandler = {
  143. notifyCLSICacheAboutBuild: sinon.stub(),
  144. downloadLatestCompileCache: sinon.stub().resolves(),
  145. downloadOutputDotSynctexFromCompileCache: sinon.stub().resolves(),
  146. }
  147. this.CompileManager = SandboxedModule.require(MODULE_PATH, {
  148. requires: {
  149. './LatexRunner': this.LatexRunner,
  150. './ResourceWriter': this.ResourceWriter,
  151. './OutputFileFinder': this.OutputFileFinder,
  152. './OutputCacheManager': this.OutputCacheManager,
  153. '@overleaf/settings': this.Settings,
  154. '@overleaf/metrics': {
  155. inc: sinon.stub(),
  156. timing: sinon.stub(),
  157. gauge: sinon.stub(),
  158. Timer: sinon.stub().returns({ done: sinon.stub() }),
  159. },
  160. child_process: this.child_process,
  161. './CommandRunner': this.CommandRunner,
  162. './DraftModeManager': this.DraftModeManager,
  163. './TikzManager': this.TikzManager,
  164. './LockManager': this.LockManager,
  165. './SynctexOutputParser': this.SynctexOutputParser,
  166. 'fs/promises': this.fsPromises,
  167. './CLSICacheHandler': this.CLSICacheHandler,
  168. },
  169. })
  170. })
  171. describe('doCompileWithLock', function () {
  172. beforeEach(function () {
  173. this.request = {
  174. resources: this.resources,
  175. rootResourcePath: (this.rootResourcePath = 'main.tex'),
  176. project_id: this.projectId,
  177. user_id: this.userId,
  178. compiler: (this.compiler = 'pdflatex'),
  179. timeout: (this.timeout = 42000),
  180. imageName: (this.image = 'example.com/image'),
  181. flags: (this.flags = ['-file-line-error']),
  182. compileGroup: (this.compileGroup = 'compile-group'),
  183. stopOnFirstError: false,
  184. metricsOpts: {
  185. path: 'clsi-perf',
  186. method: 'minimal',
  187. compile: 'initial',
  188. },
  189. }
  190. this.env = {
  191. OVERLEAF_PROJECT_ID: this.projectId,
  192. }
  193. })
  194. describe('when the project is locked', function () {
  195. beforeEach(async function () {
  196. const error = new Error('locked')
  197. this.LockManager.acquire.throws(error)
  198. await expect(
  199. this.CompileManager.promises.doCompileWithLock(this.request, {}, {})
  200. ).to.be.rejectedWith(error)
  201. })
  202. it('should ensure that the compile directory exists', function () {
  203. expect(this.fsPromises.mkdir).to.have.been.calledWith(this.compileDir, {
  204. recursive: true,
  205. })
  206. })
  207. it('should not run LaTeX', function () {
  208. expect(this.LatexRunner.promises.runLatex).not.to.have.been.called
  209. })
  210. })
  211. describe('normally', function () {
  212. beforeEach(async function () {
  213. this.result = await this.CompileManager.promises.doCompileWithLock(
  214. this.request,
  215. {},
  216. {}
  217. )
  218. })
  219. it('should ensure that the compile directory exists', function () {
  220. expect(this.fsPromises.mkdir).to.have.been.calledWith(this.compileDir, {
  221. recursive: true,
  222. })
  223. })
  224. it('should write the resources to disk', function () {
  225. expect(
  226. this.ResourceWriter.promises.syncResourcesToDisk
  227. ).to.have.been.calledWith(this.request, this.compileDir)
  228. })
  229. it('should run LaTeX', function () {
  230. expect(this.LatexRunner.promises.runLatex).to.have.been.calledWith(
  231. `${this.projectId}-${this.userId}`,
  232. {
  233. directory: this.compileDir,
  234. mainFile: this.rootResourcePath,
  235. compiler: this.compiler,
  236. timeout: this.timeout,
  237. image: this.image,
  238. flags: this.flags,
  239. environment: this.env,
  240. compileGroup: this.compileGroup,
  241. stopOnFirstError: this.request.stopOnFirstError,
  242. stats: sinon.match.object,
  243. timings: sinon.match.object,
  244. }
  245. )
  246. })
  247. it('should find the output files', function () {
  248. expect(
  249. this.OutputFileFinder.promises.findOutputFiles
  250. ).to.have.been.calledWith(this.resources, this.compileDir)
  251. })
  252. it('should return the output files', function () {
  253. expect(this.result.outputFiles).to.equal(this.buildFiles)
  254. })
  255. it('should not inject draft mode by default', function () {
  256. expect(this.DraftModeManager.promises.injectDraftMode).not.to.have.been
  257. .called
  258. })
  259. })
  260. describe('with draft mode', function () {
  261. beforeEach(async function () {
  262. this.request.draft = true
  263. await this.CompileManager.promises.doCompileWithLock(
  264. this.request,
  265. {},
  266. {}
  267. )
  268. })
  269. it('should inject the draft mode header', function () {
  270. expect(
  271. this.DraftModeManager.promises.injectDraftMode
  272. ).to.have.been.calledWith(this.compileDir + '/' + this.rootResourcePath)
  273. })
  274. })
  275. describe('with a check option', function () {
  276. beforeEach(async function () {
  277. this.request.check = 'error'
  278. await this.CompileManager.promises.doCompileWithLock(
  279. this.request,
  280. {},
  281. {}
  282. )
  283. })
  284. it('should run chktex', function () {
  285. expect(this.LatexRunner.promises.runLatex).to.have.been.calledWith(
  286. `${this.projectId}-${this.userId}`,
  287. {
  288. directory: this.compileDir,
  289. mainFile: this.rootResourcePath,
  290. compiler: this.compiler,
  291. timeout: this.timeout,
  292. image: this.image,
  293. flags: this.flags,
  294. environment: {
  295. CHKTEX_OPTIONS: '-nall -e9 -e10 -w15 -w16',
  296. CHKTEX_EXIT_ON_ERROR: 1,
  297. CHKTEX_ULIMIT_OPTIONS: '-t 5 -v 64000',
  298. OVERLEAF_PROJECT_ID: this.projectId,
  299. },
  300. compileGroup: this.compileGroup,
  301. stopOnFirstError: this.request.stopOnFirstError,
  302. stats: sinon.match.object,
  303. timings: sinon.match.object,
  304. }
  305. )
  306. })
  307. })
  308. describe('with a knitr file and check options', function () {
  309. beforeEach(async function () {
  310. this.request.rootResourcePath = 'main.Rtex'
  311. this.request.check = 'error'
  312. await this.CompileManager.promises.doCompileWithLock(
  313. this.request,
  314. {},
  315. {}
  316. )
  317. })
  318. it('should not run chktex', function () {
  319. expect(this.LatexRunner.promises.runLatex).to.have.been.calledWith(
  320. `${this.projectId}-${this.userId}`,
  321. {
  322. directory: this.compileDir,
  323. mainFile: 'main.Rtex',
  324. compiler: this.compiler,
  325. timeout: this.timeout,
  326. image: this.image,
  327. flags: this.flags,
  328. environment: this.env,
  329. compileGroup: this.compileGroup,
  330. stopOnFirstError: this.request.stopOnFirstError,
  331. stats: sinon.match.object,
  332. timings: sinon.match.object,
  333. }
  334. )
  335. })
  336. })
  337. describe('when the compile times out', function () {
  338. beforeEach(async function () {
  339. const error = new Error('timed out!')
  340. error.timedout = true
  341. this.LatexRunner.promises.runLatex.rejects(error)
  342. await expect(
  343. this.CompileManager.promises.doCompileWithLock(this.request, {}, {})
  344. ).to.be.rejected
  345. })
  346. it('should clear the compile directory', function () {
  347. for (const { path } of this.buildFiles) {
  348. expect(this.fsPromises.unlink).to.have.been.calledWith(
  349. this.compileDir + '/' + path
  350. )
  351. }
  352. expect(this.fsPromises.unlink).to.have.been.calledWith(
  353. this.compileDir + '/main.tex'
  354. )
  355. expect(this.fsPromises.rmdir).to.have.been.calledWith(this.compileDir)
  356. })
  357. })
  358. describe('when the compile is manually stopped', function () {
  359. beforeEach(async function () {
  360. const error = new Error('terminated!')
  361. error.terminated = true
  362. this.LatexRunner.promises.runLatex.rejects(error)
  363. await expect(
  364. this.CompileManager.promises.doCompileWithLock(this.request, {}, {})
  365. ).to.be.rejected
  366. })
  367. it('should clear the compile directory', function () {
  368. for (const { path } of this.buildFiles) {
  369. expect(this.fsPromises.unlink).to.have.been.calledWith(
  370. this.compileDir + '/' + path
  371. )
  372. }
  373. expect(this.fsPromises.unlink).to.have.been.calledWith(
  374. this.compileDir + '/main.tex'
  375. )
  376. expect(this.fsPromises.rmdir).to.have.been.calledWith(this.compileDir)
  377. })
  378. })
  379. })
  380. describe('clearProject', function () {
  381. it('should clear the compile directory', async function () {
  382. await this.CompileManager.promises.clearProject(
  383. this.projectId,
  384. this.userId
  385. )
  386. expect(this.fsPromises.rm).to.have.been.calledWith(this.compileDir, {
  387. force: true,
  388. recursive: true,
  389. })
  390. })
  391. })
  392. describe('syncing', function () {
  393. beforeEach(function () {
  394. this.page = 1
  395. this.h = 42.23
  396. this.v = 87.56
  397. this.width = 100.01
  398. this.height = 234.56
  399. this.line = 5
  400. this.column = 3
  401. this.filename = 'main.tex'
  402. })
  403. describe('syncFromCode', function () {
  404. beforeEach(function () {
  405. this.records = [{ page: 1, h: 2, v: 3, width: 4, height: 5 }]
  406. this.SynctexOutputParser.parseViewOutput
  407. .withArgs(this.commandOutput)
  408. .returns(this.records)
  409. })
  410. describe('normal case', function () {
  411. beforeEach(async function () {
  412. this.result = await this.CompileManager.promises.syncFromCode(
  413. this.projectId,
  414. this.userId,
  415. this.filename,
  416. this.line,
  417. this.column,
  418. ''
  419. )
  420. })
  421. it('should execute the synctex binary', function () {
  422. const outputFilePath = `${this.compileDir}/output.pdf`
  423. const inputFilePath = `${this.compileDir}/${this.filename}`
  424. expect(this.CommandRunner.promises.run).to.have.been.calledWith(
  425. `${this.projectId}-${this.userId}`,
  426. [
  427. 'synctex',
  428. 'view',
  429. '-i',
  430. `${this.line}:${this.column}:${inputFilePath}`,
  431. '-o',
  432. outputFilePath,
  433. ],
  434. this.compileDir,
  435. this.Settings.clsi.docker.image,
  436. 60000,
  437. {},
  438. 'synctex'
  439. )
  440. })
  441. it('should return the parsed output', function () {
  442. expect(this.result).to.deep.equal({
  443. codePositions: this.records,
  444. downloadedFromCache: false,
  445. })
  446. })
  447. })
  448. describe('from cache in docker', function () {
  449. beforeEach(async function () {
  450. this.CommandRunner.canRunSyncTeXInOutputDir.returns(true)
  451. this.Settings.path.synctexBaseDir
  452. .withArgs(`${this.projectId}-${this.userId}`)
  453. .returns('/compile')
  454. const errNotFound = new Error()
  455. errNotFound.code = 'ENOENT'
  456. this.outputDir = `${this.outputBaseDir}/${this.projectId}-${this.userId}/${this.OutputCacheManager.CACHE_SUBDIR}/${this.buildId}`
  457. const filename = Path.join(this.outputDir, 'output.synctex.gz')
  458. this.fsPromises.stat
  459. .withArgs(this.outputDir)
  460. .onFirstCall()
  461. .rejects(errNotFound)
  462. this.fsPromises.stat
  463. .withArgs(this.outputDir)
  464. .onSecondCall()
  465. .resolves(this.dirStats)
  466. this.fsPromises.stat.withArgs(filename).resolves(this.fileStats)
  467. this.CLSICacheHandler.downloadOutputDotSynctexFromCompileCache.resolves(
  468. true
  469. )
  470. this.result = await this.CompileManager.promises.syncFromCode(
  471. this.projectId,
  472. this.userId,
  473. this.filename,
  474. this.line,
  475. this.column,
  476. {
  477. imageName: 'image',
  478. editorId: '00000000-0000-0000-0000-000000000000',
  479. buildId: this.buildId,
  480. compileFromClsiCache: true,
  481. }
  482. )
  483. })
  484. it('should run in output dir', function () {
  485. const outputFilePath = '/compile/output.pdf'
  486. const inputFilePath = `/compile/${this.filename}`
  487. expect(this.CommandRunner.promises.run).to.have.been.calledWith(
  488. `${this.projectId}-${this.userId}`,
  489. [
  490. 'synctex',
  491. 'view',
  492. '-i',
  493. `${this.line}:${this.column}:${inputFilePath}`,
  494. '-o',
  495. outputFilePath,
  496. ],
  497. this.outputDir,
  498. 'image',
  499. 60000,
  500. {},
  501. 'synctex-output'
  502. )
  503. })
  504. it('should return the parsed output', function () {
  505. expect(this.result).to.deep.equal({
  506. codePositions: this.records,
  507. downloadedFromCache: true,
  508. })
  509. })
  510. })
  511. describe('with a custom imageName', function () {
  512. const customImageName = 'foo/bar:tag-0'
  513. beforeEach(async function () {
  514. await this.CompileManager.promises.syncFromCode(
  515. this.projectId,
  516. this.userId,
  517. this.filename,
  518. this.line,
  519. this.column,
  520. { imageName: customImageName }
  521. )
  522. })
  523. it('should execute the synctex binary in a custom docker image', function () {
  524. const outputFilePath = `${this.compileDir}/output.pdf`
  525. const inputFilePath = `${this.compileDir}/${this.filename}`
  526. expect(this.CommandRunner.promises.run).to.have.been.calledWith(
  527. `${this.projectId}-${this.userId}`,
  528. [
  529. 'synctex',
  530. 'view',
  531. '-i',
  532. `${this.line}:${this.column}:${inputFilePath}`,
  533. '-o',
  534. outputFilePath,
  535. ],
  536. this.compileDir,
  537. customImageName,
  538. 60000,
  539. {},
  540. 'synctex'
  541. )
  542. })
  543. })
  544. })
  545. describe('syncFromPdf', function () {
  546. beforeEach(function () {
  547. this.records = [{ file: 'main.tex', line: 1, column: 1 }]
  548. this.SynctexOutputParser.parseEditOutput
  549. .withArgs(this.commandOutput, this.compileDir)
  550. .returns(this.records)
  551. })
  552. describe('normal case', function () {
  553. beforeEach(async function () {
  554. this.result = await this.CompileManager.promises.syncFromPdf(
  555. this.projectId,
  556. this.userId,
  557. this.page,
  558. this.h,
  559. this.v,
  560. { imageName: '' }
  561. )
  562. })
  563. it('should execute the synctex binary', function () {
  564. const outputFilePath = `${this.compileDir}/output.pdf`
  565. expect(this.CommandRunner.promises.run).to.have.been.calledWith(
  566. `${this.projectId}-${this.userId}`,
  567. [
  568. 'synctex',
  569. 'edit',
  570. '-o',
  571. `${this.page}:${this.h}:${this.v}:${outputFilePath}`,
  572. ],
  573. this.compileDir,
  574. this.Settings.clsi.docker.image,
  575. 60000,
  576. {}
  577. )
  578. })
  579. it('should return the parsed output', function () {
  580. expect(this.result).to.deep.equal({
  581. pdfPositions: this.records,
  582. downloadedFromCache: false,
  583. })
  584. })
  585. })
  586. describe('with a custom imageName', function () {
  587. const customImageName = 'foo/bar:tag-1'
  588. beforeEach(async function () {
  589. await this.CompileManager.promises.syncFromPdf(
  590. this.projectId,
  591. this.userId,
  592. this.page,
  593. this.h,
  594. this.v,
  595. { imageName: customImageName }
  596. )
  597. })
  598. it('should execute the synctex binary in a custom docker image', function () {
  599. const outputFilePath = `${this.compileDir}/output.pdf`
  600. expect(this.CommandRunner.promises.run).to.have.been.calledWith(
  601. `${this.projectId}-${this.userId}`,
  602. [
  603. 'synctex',
  604. 'edit',
  605. '-o',
  606. `${this.page}:${this.h}:${this.v}:${outputFilePath}`,
  607. ],
  608. this.compileDir,
  609. customImageName,
  610. 60000,
  611. {}
  612. )
  613. })
  614. })
  615. })
  616. })
  617. describe('wordcount', function () {
  618. beforeEach(async function () {
  619. this.timeout = 60 * 1000
  620. this.filename = 'main.tex'
  621. this.image = 'example.com/image'
  622. this.result = await this.CompileManager.promises.wordcount(
  623. this.projectId,
  624. this.userId,
  625. this.filename,
  626. this.image
  627. )
  628. })
  629. it('should run the texcount command', function () {
  630. this.filePath = `$COMPILE_DIR/${this.filename}`
  631. this.command = ['texcount', '-nocol', '-inc', this.filePath]
  632. expect(this.CommandRunner.promises.run).to.have.been.calledWith(
  633. `${this.projectId}-${this.userId}`,
  634. this.command,
  635. this.compileDir,
  636. this.image,
  637. this.timeout,
  638. {}
  639. )
  640. })
  641. it('should return the parsed output', function () {
  642. expect(this.result).to.deep.equal({
  643. encode: 'ascii',
  644. textWords: 2,
  645. headWords: 0,
  646. outside: 0,
  647. headers: 0,
  648. elements: 0,
  649. mathInline: 0,
  650. mathDisplay: 0,
  651. errors: 0,
  652. messages: '',
  653. })
  654. })
  655. })
  656. })