backup.test.mjs 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781
  1. import config from 'config'
  2. import { ObjectId } from 'mongodb'
  3. import { expect } from 'chai'
  4. import {
  5. backedUpBlobs,
  6. client,
  7. globalBlobs,
  8. } from '../../../../storage/lib/mongodb.js'
  9. import persistor from '../../../../storage/lib/persistor.js'
  10. import {
  11. loadGlobalBlobs,
  12. BlobStore,
  13. makeProjectKey,
  14. } from '../../../../storage/lib/blob_store/index.js'
  15. import { NotFoundError } from '@overleaf/object-persistor/src/Errors.js'
  16. import projectKey from '@overleaf/object-persistor/src/ProjectKey.js'
  17. import { getBackupStatus } from '../../../../storage/lib/backup_store/index.js'
  18. import { text, buffer } from 'node:stream/consumers'
  19. import { createGunzip } from 'node:zlib'
  20. import { Change, Operation, File, TextOperation } from 'overleaf-editor-core'
  21. import ChunkStore from '../../../../storage/lib/chunk_store/index.js'
  22. import persistChanges from '../../../../storage/lib/persist_changes.js'
  23. import { historyStore } from '../../../../storage/lib/history_store.js'
  24. import { execFile } from 'node:child_process'
  25. import { promisify } from 'node:util'
  26. import testFiles from '../storage/support/test_files.js'
  27. import fs from 'node:fs'
  28. import {
  29. backupBlob,
  30. storeBlobBackup,
  31. } from '../../../../storage/lib/backupBlob.mjs'
  32. import {
  33. backupPersistor,
  34. projectBlobsBucket,
  35. chunksBucket,
  36. } from '../../../../storage/lib/backupPersistor.mjs'
  37. import { Readable } from 'node:stream'
  38. import { ListObjectsV2Command } from '@aws-sdk/client-s3'
  39. const projectsCollection = client.db().collection('projects')
  40. /**
  41. * @param {ObjectId} projectId
  42. * @param {number} version
  43. * @return {string}
  44. */
  45. function makeChunkKey(projectId, version) {
  46. return projectKey.format(projectId) + '/' + projectKey.pad(version)
  47. }
  48. describe('backup script', function () {
  49. let project
  50. let projectId, historyId
  51. let limitsToPersistImmediately
  52. before(function () {
  53. // Used to provide a limit which forces us to persist all of the changes
  54. const farFuture = new Date()
  55. farFuture.setTime(farFuture.getTime() + 7 * 24 * 3600 * 1000)
  56. limitsToPersistImmediately = {
  57. minChangeTimestamp: farFuture,
  58. maxChangeTimestamp: farFuture,
  59. maxChanges: 10,
  60. maxChunkChanges: 10,
  61. }
  62. })
  63. beforeEach(async function () {
  64. // Set up test projects with proper history metadata
  65. projectId = new ObjectId()
  66. historyId = projectId.toString()
  67. project = {
  68. _id: projectId,
  69. overleaf: {
  70. history: {
  71. id: historyId,
  72. currentEndVersion: 0, // Will be updated as changes are made
  73. currentEndTimestamp: new Date(), // Will be updated as changes are made
  74. },
  75. backup: {
  76. // Start with no backup state
  77. },
  78. },
  79. }
  80. // Pre-load the global blobs
  81. await loadGlobalBlobs()
  82. // Clean up any pre-existing test data
  83. await projectsCollection.deleteMany({
  84. _id: projectId,
  85. })
  86. await backedUpBlobs.deleteMany({}) // Clear any existing backedUpBlobs entries
  87. })
  88. describe('with simple project content', function () {
  89. const contentString = 'hello world'
  90. const newContentString = 'hello world more'
  91. const graphPngPath = testFiles.path('graph.png')
  92. const graphPngBuf = fs.readFileSync(graphPngPath)
  93. const graphPngHash = testFiles.GRAPH_PNG_HASH
  94. const nonBmpPath = testFiles.path('non_bmp.txt')
  95. const DUMMY_HASH = '1111111111111111111111111111111111111111'
  96. beforeEach(async function () {
  97. // Create initial project
  98. await projectsCollection.insertOne(project)
  99. // Initialize project in chunk store
  100. await ChunkStore.initializeProject(historyId)
  101. const blobStore = new BlobStore(historyId)
  102. // Create the blobs and then back them up using backupBlob
  103. const graphPngBlob = await blobStore.putFile(graphPngPath)
  104. await backupBlob(historyId, graphPngBlob, graphPngPath)
  105. // Add initial content using persistChanges
  106. const file = File.fromString(contentString)
  107. const addFileOp = Operation.addFile('main.tex', file)
  108. const addGraphFileOp = Operation.addFile(
  109. 'graph.png',
  110. File.fromHash(testFiles.GRAPH_PNG_HASH)
  111. )
  112. const change1 = new Change([addFileOp, addGraphFileOp], new Date(), [])
  113. await persistChanges(historyId, [change1], limitsToPersistImmediately, 0)
  114. // Add a second change with a proper TextOperation
  115. // For text operation: first number is how many chars to retain, then the text to insert
  116. const textOp = TextOperation.fromJSON({
  117. textOperation: [contentString.length, ' more'], // Keep existing content, append ' more'
  118. })
  119. const editOp = Operation.editFile('main.tex', textOp)
  120. const change2 = new Change([editOp], new Date(), [])
  121. // store an unrelated hash in the backedUpBlobs collection,
  122. // so we can test that only the backed up hashes are cleared.
  123. await storeBlobBackup(historyId, DUMMY_HASH)
  124. await persistChanges(historyId, [change2], limitsToPersistImmediately, 1)
  125. })
  126. it('should perform an initial backup', async function () {
  127. // Run backup script for initial version
  128. const { stdout } = await runBackupScript(['--projectId', projectId])
  129. expect(stdout).to.not.include(
  130. 'warning: persistor not passed to backupBlob'
  131. )
  132. // Verify backup state
  133. const result = await getBackupStatus(projectId)
  134. expect(result.backupStatus.lastBackedUpVersion).to.equal(2)
  135. expect(result.backupStatus.lastBackedUpAt).to.be.an.instanceOf(Date)
  136. expect(result.currentEndTimestamp).to.be.an.instanceOf(Date)
  137. expect(result.backupStatus.pendingChangeAt).to.be.undefined
  138. // Verify graph.png blob was backed up
  139. const graphBlobStream = await backupPersistor.getObjectStream(
  140. projectBlobsBucket,
  141. makeProjectKey(historyId, graphPngHash),
  142. { autoGunzip: true }
  143. )
  144. const graphBlobContent = await buffer(graphBlobStream)
  145. expect(graphBlobContent.equals(graphPngBuf)).to.be.true
  146. // Verify chunk was backed up
  147. const chunkStream = await backupPersistor.getObjectStream(
  148. chunksBucket,
  149. makeChunkKey(historyId, 0)
  150. )
  151. const chunkContent = await text(chunkStream.pipe(createGunzip()))
  152. const chunkMetadata = await ChunkStore.getLatestChunkMetadata(historyId)
  153. const rawHistory = await historyStore.loadRaw(historyId, chunkMetadata.id)
  154. expect(JSON.parse(chunkContent)).to.deep.equal(rawHistory)
  155. // Unrelated entries from backedUpBlobs should be not cleared
  156. const backedUpBlobsDoc = await backedUpBlobs.findOne({
  157. _id: project._id,
  158. })
  159. expect(backedUpBlobsDoc).not.to.be.null
  160. expect(backedUpBlobsDoc.blobs).to.have.length(1)
  161. expect(backedUpBlobsDoc.blobs[0].toString('hex')).to.equal(DUMMY_HASH)
  162. })
  163. it('should perform an incremental backup', async function () {
  164. // Backup first version
  165. const { stdout: stdout1 } = await runBackupScript([
  166. '--projectId',
  167. projectId,
  168. ])
  169. expect(stdout1).to.not.include(
  170. 'warning: persistor not passed to backupBlob'
  171. )
  172. // Verify first backup
  173. const result1 = await getBackupStatus(projectId)
  174. expect(result1.backupStatus.lastBackedUpVersion).to.equal(2)
  175. // Persist additional changes
  176. const additionalTextOp = TextOperation.fromJSON({
  177. textOperation: [newContentString.length, ' even more'], // Keep existing content, append ' even more'
  178. })
  179. const additionalEditOp = Operation.editFile('main.tex', additionalTextOp)
  180. const firstTimestamp = new Date()
  181. const additionalChange = new Change(
  182. [additionalEditOp],
  183. firstTimestamp,
  184. []
  185. )
  186. // add the nonbmp file
  187. const blobStore = new BlobStore(historyId)
  188. const nonBmpBlob = await blobStore.putFile(nonBmpPath)
  189. await backupBlob(historyId, nonBmpBlob, nonBmpPath)
  190. // Verify that the non-BMP file was backed up when the file was added
  191. const newBackedUpBlobs = await backedUpBlobs.findOne({
  192. _id: project._id,
  193. })
  194. expect(newBackedUpBlobs).not.to.be.null
  195. expect(newBackedUpBlobs.blobs).to.have.length(2)
  196. expect(
  197. newBackedUpBlobs.blobs.map(b => b.toString('hex'))
  198. ).to.have.members([testFiles.NON_BMP_TXT_HASH, DUMMY_HASH])
  199. const addNonBmpFileOp = Operation.addFile(
  200. 'non_bmp.txt',
  201. File.fromHash(testFiles.NON_BMP_TXT_HASH)
  202. )
  203. const secondTimestamp = new Date()
  204. const additionalChange2 = new Change(
  205. [addNonBmpFileOp],
  206. secondTimestamp,
  207. []
  208. )
  209. await persistChanges(
  210. historyId,
  211. [additionalChange, additionalChange2],
  212. limitsToPersistImmediately,
  213. 2
  214. )
  215. const afterChangeResult = await getBackupStatus(projectId)
  216. // Verify that the currentEndVersion and currentEndTimestamp are updated
  217. expect(afterChangeResult.currentEndVersion).to.equal(4)
  218. expect(afterChangeResult.currentEndTimestamp)
  219. .to.be.an.instanceOf(Date)
  220. .and.to.be.greaterThan(result1.currentEndTimestamp)
  221. // Persisting a change should not modify the backup version and timestamp
  222. expect(afterChangeResult.backupStatus.lastBackedUpVersion).to.equal(2)
  223. expect(afterChangeResult.backupStatus.lastBackedUpAt)
  224. .to.be.an.instanceOf(Date)
  225. .and.to.deep.equal(result1.backupStatus.lastBackedUpAt)
  226. // but it should update the pendingChangeAt timestamp to the timestamp of the
  227. // first change which modified the project
  228. expect(afterChangeResult.backupStatus.pendingChangeAt)
  229. .to.be.an.instanceOf(Date)
  230. .and.to.deep.equal(firstTimestamp)
  231. // Second backup
  232. const { stdout: stdout2 } = await runBackupScript([
  233. '--projectId',
  234. projectId,
  235. ])
  236. expect(stdout2).to.not.include(
  237. 'warning: persistor not passed to backupBlob'
  238. )
  239. // Verify incremental backup
  240. const result2 = await getBackupStatus(projectId)
  241. // The backup version and timestamp should be updated
  242. expect(result2.backupStatus.lastBackedUpVersion).to.equal(4)
  243. expect(result2.backupStatus.lastBackedUpAt)
  244. .to.be.an.instanceOf(Date)
  245. .and.to.be.greaterThan(result1.backupStatus.lastBackedUpAt)
  246. // The currentEndVersion and currentEndTimestamp should not be modified
  247. expect(result2.currentEndVersion).to.equal(4)
  248. expect(result2.currentEndTimestamp)
  249. .to.be.an.instanceOf(Date)
  250. .and.to.deep.equal(afterChangeResult.currentEndTimestamp)
  251. // The pendingChangeAt timestamp should be cleared when the backup is complete
  252. expect(result2.backupStatus.pendingChangeAt).to.be.undefined
  253. // Verify additional blob was backed up
  254. const newBlobStream = await backupPersistor.getObjectStream(
  255. projectBlobsBucket,
  256. makeProjectKey(historyId, testFiles.NON_BMP_TXT_HASH),
  257. { autoGunzip: true }
  258. )
  259. const newBlobContent = await buffer(newBlobStream)
  260. expect(newBlobContent).to.deep.equal(
  261. fs.readFileSync(testFiles.path('non_bmp.txt'))
  262. )
  263. // Check chunk was backed up
  264. const chunkStream = await backupPersistor.getObjectStream(
  265. chunksBucket,
  266. makeChunkKey(historyId, 0)
  267. )
  268. const chunkContent = await text(chunkStream.pipe(createGunzip()))
  269. const chunkMetadata = await ChunkStore.getLatestChunkMetadata(historyId)
  270. const rawHistory = await historyStore.loadRaw(historyId, chunkMetadata.id)
  271. expect(JSON.parse(chunkContent)).to.deep.equal(rawHistory)
  272. // Unrelated entries from backedUpBlobs should be not cleared
  273. const backedUpBlobsDoc = await backedUpBlobs.findOne({
  274. _id: project._id,
  275. })
  276. expect(backedUpBlobsDoc).not.to.be.null
  277. expect(backedUpBlobsDoc.blobs).to.have.length(1)
  278. expect(backedUpBlobsDoc.blobs[0].toString('hex')).to.equal(DUMMY_HASH)
  279. })
  280. it('should not backup global blobs', async function () {
  281. const globalBlobString = 'a'
  282. const globalBlobHash = testFiles.STRING_A_HASH
  283. await globalBlobs.insertOne({
  284. _id: globalBlobHash,
  285. byteLength: globalBlobString.length,
  286. stringLength: globalBlobString.length,
  287. })
  288. const bucket = config.get('blobStore.globalBucket')
  289. for (const { key, content } of [
  290. {
  291. key: '2e/65/efe2a145dda7ee51d1741299f848e5bf752e',
  292. content: globalBlobString,
  293. },
  294. ]) {
  295. const stream = Readable.from([content])
  296. await persistor.sendStream(bucket, key, stream)
  297. }
  298. await loadGlobalBlobs()
  299. // Create a change using the global blob
  300. const addFileOp = Operation.addFile(
  301. 'global.tex',
  302. File.fromHash(globalBlobHash)
  303. )
  304. const change = new Change([addFileOp], new Date(), [])
  305. await persistChanges(historyId, [change], limitsToPersistImmediately, 2)
  306. // Run backup
  307. await runBackupScript(['--projectId', projectId])
  308. // Verify global blob wasn't backed up
  309. try {
  310. await backupPersistor.getObjectStream(
  311. projectBlobsBucket,
  312. makeProjectKey(historyId, globalBlobHash),
  313. { autoGunzip: true }
  314. )
  315. expect.fail('Should not find global blob in project blobs')
  316. } catch (err) {
  317. expect(err).to.be.an.instanceOf(NotFoundError)
  318. }
  319. })
  320. it('should back up global blobs if they are demoted', async function () {
  321. const demotedBlobString = 'ab'
  322. const demotedBlobHash = testFiles.STRING_AB_HASH
  323. await globalBlobs.insertOne({
  324. _id: demotedBlobHash,
  325. byteLength: demotedBlobString.length,
  326. stringLength: demotedBlobString.length,
  327. demoted: true,
  328. })
  329. const bucket = config.get('blobStore.globalBucket')
  330. for (const { key, content } of [
  331. {
  332. key: '9a/e9/e86b7bd6cb1472d9373702d8249973da0832',
  333. content: demotedBlobString,
  334. },
  335. ]) {
  336. const stream = Readable.from([content])
  337. await persistor.sendStream(bucket, key, stream)
  338. }
  339. await loadGlobalBlobs()
  340. // Create a change using the global blob
  341. const addFileOp = Operation.addFile(
  342. 'demoted.tex',
  343. File.fromHash(demotedBlobHash)
  344. )
  345. const change = new Change([addFileOp], new Date(), [])
  346. await persistChanges(historyId, [change], limitsToPersistImmediately, 2)
  347. // Run backup
  348. const { stdout } = await runBackupScript(['--projectId', projectId])
  349. expect(stdout).to.not.include(
  350. 'warning: persistor not passed to backupBlob'
  351. )
  352. // Check chunk was backed up
  353. const chunkStream = await backupPersistor.getObjectStream(
  354. chunksBucket,
  355. makeChunkKey(historyId, 0)
  356. )
  357. const chunkContent = await text(chunkStream.pipe(createGunzip()))
  358. const chunkMetadata = await ChunkStore.getLatestChunkMetadata(historyId)
  359. const rawHistory = await historyStore.loadRaw(historyId, chunkMetadata.id)
  360. expect(JSON.parse(chunkContent)).to.deep.equal(rawHistory)
  361. // Verify that the demoted global blob was backed up
  362. try {
  363. const demotedBlobStream = await backupPersistor.getObjectStream(
  364. projectBlobsBucket,
  365. makeProjectKey(historyId, demotedBlobHash),
  366. {
  367. autoGunzip: true,
  368. }
  369. )
  370. const demotedBlobContent = await buffer(demotedBlobStream)
  371. expect(demotedBlobContent).to.deep.equal(Buffer.from(demotedBlobString))
  372. } catch (err) {
  373. expect.fail('Should find demoted global blob in project blobs')
  374. }
  375. })
  376. })
  377. describe('with complex project content', function () {
  378. let beforeInitializationTimestamp
  379. let afterInitializationTimestamp
  380. beforeEach(async function () {
  381. // Create initial project
  382. await projectsCollection.insertOne(project)
  383. // Initialize project in chunk store
  384. // bracket the initialisation with two timestamps to check the pendingChangeAt field
  385. beforeInitializationTimestamp = new Date()
  386. await ChunkStore.initializeProject(historyId)
  387. afterInitializationTimestamp = new Date()
  388. const blobStore = new BlobStore(historyId)
  389. // Set up test files with varying content
  390. const testFilesData = {
  391. mainTex: { name: 'main.tex', content: 'Initial content' },
  392. chapter1: { name: 'chapter1.tex', content: 'Chapter 1 content' },
  393. chapter2: { name: 'chapter2.tex', content: 'Chapter 2 content' },
  394. bibliography: {
  395. name: 'bibliography.bib',
  396. content: '@article{key1,\n title={Title1}\n}',
  397. newContent: '@article{key2,\n title={Title2}\n}',
  398. },
  399. graph: {
  400. name: 'graph.png',
  401. path: testFiles.path('graph.png'),
  402. hash: testFiles.GRAPH_PNG_HASH,
  403. },
  404. unicodeFile: {
  405. name: 'unicodeFile.tex',
  406. path: testFiles.path('non_bmp.txt'),
  407. hash: testFiles.NON_BMP_TXT_HASH,
  408. },
  409. }
  410. const textFiles = [
  411. testFilesData.mainTex,
  412. testFilesData.chapter1,
  413. testFilesData.chapter2,
  414. testFilesData.bibliography,
  415. ]
  416. const binaryFiles = [testFilesData.graph, testFilesData.unicodeFile]
  417. // Add binary files first
  418. await Promise.all(binaryFiles.map(file => blobStore.putFile(file.path)))
  419. // Back up the binary files
  420. await Promise.all(
  421. binaryFiles.map(async file => {
  422. await backupBlob(
  423. historyId,
  424. await blobStore.putFile(file.path),
  425. file.path
  426. )
  427. })
  428. )
  429. // Create operations to add all files initially
  430. const addFileOperations = Object.values(testFilesData).map(file => {
  431. if (file.path) {
  432. return Operation.addFile(file.name, File.fromHash(file.hash))
  433. }
  434. return Operation.addFile(file.name, File.fromString(file.content))
  435. })
  436. // Initial change adding all files
  437. const initialChange = new Change(addFileOperations, new Date(), [])
  438. await persistChanges(
  439. historyId,
  440. [initialChange],
  441. limitsToPersistImmediately,
  442. 0
  443. )
  444. // Generate a series of edit operations for each text file
  445. const editOperations = []
  446. for (let i = 0; i < 50; i++) {
  447. const targetFile = textFiles[i % textFiles.length]
  448. if (!targetFile.path) {
  449. // Skip binary/unicode files
  450. const appendText = `\n\nEdit ${i + 1}`
  451. targetFile.content += appendText
  452. const textOp = TextOperation.fromJSON({
  453. textOperation: [
  454. targetFile.content.length - appendText.length,
  455. appendText,
  456. ],
  457. })
  458. const editOp = Operation.editFile(targetFile.name, textOp)
  459. editOperations.push(new Change([editOp], new Date(), []))
  460. }
  461. }
  462. // Add a delete operation
  463. const deleteChange = new Change(
  464. [Operation.removeFile(testFilesData.bibliography.name)],
  465. new Date(),
  466. []
  467. )
  468. editOperations.push(deleteChange)
  469. // Add the file back with different content
  470. const addBackChange = new Change(
  471. [
  472. Operation.addFile(
  473. testFilesData.bibliography.name,
  474. File.fromString(testFilesData.bibliography.newContent)
  475. ),
  476. ],
  477. new Date(),
  478. []
  479. )
  480. editOperations.push(addBackChange)
  481. // Persist all changes
  482. await persistChanges(
  483. historyId,
  484. editOperations,
  485. limitsToPersistImmediately,
  486. 1
  487. )
  488. })
  489. it('persistChanges should set the pendingChangeAt field to the time of snapshot initialisation', async function () {
  490. const result = await getBackupStatus(projectId)
  491. expect(result.backupStatus.pendingChangeAt).to.be.an.instanceOf(Date)
  492. expect(result.backupStatus.pendingChangeAt)
  493. .to.be.greaterThan(beforeInitializationTimestamp)
  494. .and.to.be.lessThan(afterInitializationTimestamp)
  495. })
  496. it('should backup all chunks and blobs from a complex project history', async function () {
  497. // Run backup script
  498. const { stdout } = await runBackupScript(['--projectId', projectId])
  499. expect(stdout).to.not.include(
  500. 'warning: persistor not passed to backupBlob'
  501. )
  502. // Verify backup state
  503. const result = await getBackupStatus(projectId)
  504. expect(result.backupStatus.lastBackedUpVersion).to.equal(53) // 1 initial change + 50 edits + 1 delete + 1 add back
  505. expect(result.backupStatus.lastBackedUpAt).to.be.an.instanceOf(Date)
  506. expect(result.currentEndTimestamp).to.be.an.instanceOf(Date)
  507. expect(result.backupStatus.pendingChangeAt).to.be.undefined
  508. // Verify that binary files were backed up
  509. for (const hash of [
  510. testFiles.GRAPH_PNG_HASH,
  511. testFiles.NON_BMP_TXT_HASH,
  512. ]) {
  513. const blobStream = await backupPersistor.getObjectStream(
  514. projectBlobsBucket,
  515. makeProjectKey(historyId, hash),
  516. { autoGunzip: true }
  517. )
  518. expect(blobStream).to.exist
  519. }
  520. // Get all chunks and verify they were backed up
  521. const listing = await backupPersistor
  522. ._getClientForBucket(chunksBucket)
  523. .send(
  524. new ListObjectsV2Command({
  525. Bucket: chunksBucket,
  526. Prefix: projectKey.format(historyId) + '/',
  527. })
  528. )
  529. const chunkKeys = listing.Contents.map(item => item.Key)
  530. expect(chunkKeys.length).to.equal(6) // Should have multiple chunks
  531. const localChunks = await ChunkStore.getProjectChunks(historyId)
  532. const chunksByStartVersion = new Map()
  533. for (const chunkRecord of localChunks) {
  534. chunksByStartVersion.set(chunkRecord.startVersion, chunkRecord)
  535. }
  536. // Verify the content of each chunk matches what's in the history store
  537. for (const chunkKey of chunkKeys) {
  538. const chunkStream = await backupPersistor.getObjectStream(
  539. chunksBucket,
  540. chunkKey
  541. )
  542. const chunkContent = await text(chunkStream.pipe(createGunzip()))
  543. const startVersion = parseInt(chunkKey.split('/').pop(), 10)
  544. const chunk = chunksByStartVersion.get(startVersion)
  545. const rawHistory = await historyStore.loadRaw(historyId, chunk.id)
  546. expect(JSON.parse(chunkContent)).to.deep.equal(rawHistory)
  547. }
  548. })
  549. it('should throw an error if downloading a blob fails', async function () {
  550. const blobStore = new BlobStore(historyId)
  551. const blob = await blobStore.putFile(
  552. testFiles.path('null_characters.txt')
  553. )
  554. const change = new Change(
  555. [Operation.addFile('broken-file', File.fromHash(blob.getHash()))],
  556. new Date(),
  557. []
  558. )
  559. // Persist all changes
  560. await persistChanges(historyId, [change], limitsToPersistImmediately, 53)
  561. // Delete the blob from the underlying storage to simulate a failure
  562. const bucket = config.get('blobStore.projectBucket')
  563. const key = makeProjectKey(historyId, blob.getHash())
  564. await persistor.deleteObject(bucket, key)
  565. // Run backup script - it should fail because the blob is missing
  566. let result
  567. try {
  568. result = await runBackupScript(['--projectId', projectId])
  569. expect.fail('Backup script should have failed')
  570. } catch (err) {
  571. expect(err).to.exist
  572. expect(result).to.not.exist
  573. }
  574. // Verify that backup did not complete
  575. const newBackupStatus = await getBackupStatus(projectId)
  576. expect(newBackupStatus.backupStatus.lastBackedUpVersion).to.equal(50) // backup fails on final chunk
  577. expect(newBackupStatus.currentEndVersion).to.equal(54) // backup is incomplete due to missing blob
  578. })
  579. it('can recover zip file from backup in raw mode', async function () {
  580. // First, run backup so data is available
  581. await runBackupScript(['--projectId', projectId])
  582. const zipPath = `/tmp/test-recover-raw-${historyId}.zip`
  583. try {
  584. await runRecoverZipFromBackupScript([
  585. '--historyId',
  586. historyId,
  587. '--output',
  588. zipPath,
  589. '--mode=raw',
  590. ])
  591. // Verify the zip file is valid
  592. const { stdout } = await promisify(execFile)('unzip', ['-l', zipPath], {
  593. encoding: 'utf-8',
  594. })
  595. // Raw mode includes chunk and blob keys
  596. // Verify chunks are present
  597. expect(stdout).to.include('chunk.json')
  598. // Verify blob hashes are present (hashes are stored as {hash[0:2]}/{hash[2:]})
  599. expect(stdout).to.include(testFiles.GRAPH_PNG_HASH.slice(2))
  600. expect(stdout).to.include(testFiles.NON_BMP_TXT_HASH.slice(2))
  601. } finally {
  602. await fs.promises.unlink(zipPath).catch(() => {})
  603. }
  604. })
  605. it('can recover zip file from backup in latest mode', async function () {
  606. // First, run backup so data is available
  607. await runBackupScript(['--projectId', projectId])
  608. const zipPath = `/tmp/test-recover-latest-${historyId}.zip`
  609. try {
  610. await runRecoverZipFromBackupScript([
  611. '--historyId',
  612. historyId,
  613. '--output',
  614. zipPath,
  615. '--mode=latest',
  616. ])
  617. // Verify the zip file is valid
  618. const { stdout } = await promisify(execFile)('unzip', ['-l', zipPath], {
  619. encoding: 'utf-8',
  620. })
  621. // Latest mode includes the project files
  622. expect(stdout).to.include('main.tex')
  623. expect(stdout).to.include('chapter1.tex')
  624. expect(stdout).to.include('chapter2.tex')
  625. expect(stdout).to.include('bibliography.bib')
  626. expect(stdout).to.include('graph.png')
  627. expect(stdout).to.include('unicodeFile.tex')
  628. } finally {
  629. await fs.promises.unlink(zipPath).catch(() => {})
  630. }
  631. })
  632. })
  633. })
  634. /**
  635. * Run the backup script with given arguments
  636. * @param {string[]} args
  637. */
  638. async function runBackupScript(args) {
  639. const TIMEOUT = 20 * 1000
  640. let result
  641. try {
  642. result = await promisify(execFile)(
  643. 'node',
  644. ['storage/scripts/backup.mjs', ...args],
  645. {
  646. encoding: 'utf-8',
  647. timeout: TIMEOUT,
  648. env: {
  649. ...process.env,
  650. LOG_LEVEL: 'debug', // Override LOG_LEVEL of acceptance tests
  651. },
  652. }
  653. )
  654. result.status = 0
  655. } catch (err) {
  656. const { stdout, stderr, code } = err
  657. if (typeof code !== 'number') {
  658. console.log(err)
  659. }
  660. result = { stdout, stderr, status: code }
  661. }
  662. if (result.status !== 0) {
  663. throw new Error('backup failed')
  664. }
  665. return result
  666. }
  667. /**
  668. * Run the recover_zip_from_backup script with given arguments
  669. * @param {string[]} args
  670. */
  671. async function runRecoverZipFromBackupScript(args) {
  672. const TIMEOUT = 30 * 1000
  673. let result
  674. try {
  675. result = await promisify(execFile)(
  676. 'node',
  677. ['storage/scripts/recover_zip_from_backup.mjs', ...args],
  678. {
  679. encoding: 'utf-8',
  680. timeout: TIMEOUT,
  681. env: {
  682. ...process.env,
  683. LOG_LEVEL: 'debug',
  684. },
  685. }
  686. )
  687. result.status = 0
  688. } catch (err) {
  689. const { stdout, stderr, code } = err
  690. if (typeof code !== 'number') {
  691. console.log(err)
  692. }
  693. result = { stdout, stderr, status: code }
  694. }
  695. if (result.status !== 0) {
  696. throw new Error(`recover_zip_from_backup failed: ${result.stderr}`)
  697. }
  698. return result
  699. }