backup.mjs 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095
  1. // @ts-check
  2. import logger from '@overleaf/logger'
  3. import commandLineArgs from 'command-line-args'
  4. import { Chunk, History, Snapshot } from 'overleaf-editor-core'
  5. import {
  6. getProjectChunks,
  7. loadLatestRaw,
  8. create,
  9. } from '../lib/chunk_store/index.js'
  10. import { client } from '../lib/mongodb.js'
  11. import knex from '../lib/knex.js'
  12. import { historyStore } from '../lib/history_store.js'
  13. import pLimit from 'p-limit'
  14. import {
  15. GLOBAL_BLOBS,
  16. loadGlobalBlobs,
  17. makeProjectKey,
  18. BlobStore,
  19. } from '../lib/blob_store/index.js'
  20. import {
  21. listPendingBackups,
  22. getBackupStatus,
  23. setBackupVersion,
  24. updateCurrentMetadataIfNotSet,
  25. updatePendingChangeTimestamp,
  26. getBackedUpBlobHashes,
  27. unsetBackedUpBlobHashes,
  28. } from '../lib/backup_store/index.js'
  29. import { backupBlob, downloadBlobToDir } from '../lib/backupBlob.mjs'
  30. import {
  31. backupPersistor,
  32. chunksBucket,
  33. projectBlobsBucket,
  34. } from '../lib/backupPersistor.mjs'
  35. import { backupGenerator } from '../lib/backupGenerator.mjs'
  36. import { promises as fs, createWriteStream } from 'node:fs'
  37. import os from 'node:os'
  38. import path from 'node:path'
  39. import projectKey from '../lib/project_key.js'
  40. import Crypto from 'node:crypto'
  41. import Stream from 'node:stream'
  42. import { EventEmitter } from 'node:events'
  43. import {
  44. objectIdFromInput,
  45. batchedUpdate,
  46. READ_PREFERENCE_SECONDARY,
  47. } from '@overleaf/mongo-utils/batchedUpdate.js'
  48. import { createGunzip } from 'node:zlib'
  49. import { text } from 'node:stream/consumers'
  50. import { fromStream as blobHashFromStream } from '../lib/blob_hash.js'
  51. import { NotFoundError } from '@overleaf/object-persistor/src/Errors.js'
  52. // Create a singleton promise that loads global blobs once
  53. let globalBlobsPromise = null
  54. function ensureGlobalBlobsLoaded() {
  55. if (!globalBlobsPromise) {
  56. globalBlobsPromise = loadGlobalBlobs()
  57. }
  58. return globalBlobsPromise
  59. }
  60. EventEmitter.defaultMaxListeners = 20
  61. logger.initialize('history-v1-backup')
  62. // Settings shared between command-line and module usage
  63. let DRY_RUN = false
  64. let RETRY_LIMIT = 3
  65. const RETRY_DELAY = 1000
  66. let CONCURRENCY = 4
  67. let BATCH_CONCURRENCY = 1
  68. let BLOB_LIMITER = pLimit(CONCURRENCY)
  69. let USE_SECONDARY = false
  70. /**
  71. * Configure backup settings
  72. * @param {Object} options Backup configuration options
  73. */
  74. export function configureBackup(options = {}) {
  75. DRY_RUN = options.dryRun || false
  76. RETRY_LIMIT = options.retries || 3
  77. CONCURRENCY = options.concurrency || 1
  78. BATCH_CONCURRENCY = options.batchConcurrency || 1
  79. BLOB_LIMITER = pLimit(CONCURRENCY)
  80. USE_SECONDARY = options.useSecondary || false
  81. }
  82. let gracefulShutdownInitiated = false
  83. process.on('SIGINT', handleSignal)
  84. process.on('SIGTERM', handleSignal)
  85. function handleSignal() {
  86. gracefulShutdownInitiated = true
  87. logger.info({}, 'graceful shutdown initiated, draining queue')
  88. }
  89. async function retry(fn, times, delayMs) {
  90. let attempts = times
  91. while (attempts > 0) {
  92. try {
  93. const result = await fn()
  94. return result
  95. } catch (err) {
  96. attempts--
  97. if (attempts === 0) throw err
  98. await new Promise(resolve => setTimeout(resolve, delayMs))
  99. }
  100. }
  101. }
  102. function wrapWithRetry(fn, retries, delayMs) {
  103. return async (...args) => {
  104. const result = await retry(() => fn(...args), retries, delayMs)
  105. return result
  106. }
  107. }
  108. const downloadWithRetry = wrapWithRetry(
  109. downloadBlobToDir,
  110. RETRY_LIMIT,
  111. RETRY_DELAY
  112. )
  113. // FIXME: this creates a new backupPersistor for each blob
  114. // so there is no caching of the DEK
  115. const backupWithRetry = wrapWithRetry(backupBlob, RETRY_LIMIT, RETRY_DELAY)
  116. async function findNewBlobs(projectId, blobs) {
  117. const newBlobs = []
  118. const existingBackedUpBlobHashes = await getBackedUpBlobHashes(projectId)
  119. for (const blob of blobs) {
  120. const hash = blob.getHash()
  121. if (existingBackedUpBlobHashes.has(blob.getHash())) {
  122. logger.debug({ projectId, hash }, 'Blob is already backed up, skipping')
  123. continue
  124. }
  125. const globalBlob = GLOBAL_BLOBS.get(hash)
  126. if (globalBlob && !globalBlob.demoted) {
  127. logger.debug(
  128. { projectId, hash },
  129. 'Blob is a global blob and not demoted, skipping'
  130. )
  131. continue
  132. }
  133. newBlobs.push(blob)
  134. }
  135. return newBlobs
  136. }
  137. async function cleanBackedUpBlobs(projectId, blobs) {
  138. const hashes = blobs.map(blob => blob.getHash())
  139. if (DRY_RUN) {
  140. console.log(
  141. 'Would remove blobs',
  142. hashes.join(' '),
  143. 'from project',
  144. projectId
  145. )
  146. return
  147. }
  148. await unsetBackedUpBlobHashes(projectId, hashes)
  149. }
  150. async function backupSingleBlob(projectId, historyId, blob, tmpDir, persistor) {
  151. if (DRY_RUN) {
  152. console.log(
  153. 'Would back up blob',
  154. JSON.stringify(blob),
  155. 'in history',
  156. historyId,
  157. 'for project',
  158. projectId
  159. )
  160. return
  161. }
  162. logger.debug({ blob, historyId }, 'backing up blob')
  163. const blobPath = await downloadWithRetry(historyId, blob, tmpDir)
  164. await backupWithRetry(historyId, blob, blobPath, persistor)
  165. }
  166. async function backupBlobs(projectId, historyId, blobs, limiter, persistor) {
  167. let tmpDir
  168. try {
  169. tmpDir = await fs.mkdtemp(path.join(os.tmpdir(), 'blob-backup-'))
  170. const blobBackupOperations = blobs.map(blob =>
  171. limiter(backupSingleBlob, projectId, historyId, blob, tmpDir, persistor)
  172. )
  173. // Reject if any blob backup fails
  174. await Promise.all(blobBackupOperations)
  175. } finally {
  176. if (tmpDir) {
  177. await fs.rm(tmpDir, { recursive: true, force: true })
  178. }
  179. }
  180. }
  181. async function backupChunk(
  182. projectId,
  183. historyId,
  184. chunkBackupPersistorForProject,
  185. chunkToBackup,
  186. chunkRecord,
  187. chunkBuffer
  188. ) {
  189. if (DRY_RUN) {
  190. console.log(
  191. 'Would back up chunk',
  192. JSON.stringify(chunkRecord),
  193. 'in history',
  194. historyId,
  195. 'for project',
  196. projectId,
  197. 'key',
  198. makeChunkKey(historyId, chunkToBackup.startVersion)
  199. )
  200. return
  201. }
  202. const key = makeChunkKey(historyId, chunkToBackup.startVersion)
  203. logger.debug({ chunkRecord, historyId, projectId, key }, 'backing up chunk')
  204. const md5 = Crypto.createHash('md5').update(chunkBuffer)
  205. await chunkBackupPersistorForProject.sendStream(
  206. chunksBucket,
  207. makeChunkKey(historyId, chunkToBackup.startVersion),
  208. Stream.Readable.from([chunkBuffer]),
  209. {
  210. contentType: 'application/json',
  211. contentEncoding: 'gzip',
  212. contentLength: chunkBuffer.byteLength,
  213. sourceMd5: md5.digest('hex'),
  214. }
  215. )
  216. }
  217. async function updateBackupStatus(
  218. projectId,
  219. lastBackedUpVersion,
  220. chunkRecord,
  221. startOfBackupTime
  222. ) {
  223. if (DRY_RUN) {
  224. console.log(
  225. 'Would set backup version to',
  226. chunkRecord.endVersion,
  227. 'with lastBackedUpTimestamp',
  228. startOfBackupTime
  229. )
  230. return
  231. }
  232. logger.debug(
  233. { projectId, chunkRecord, startOfBackupTime },
  234. 'setting backupVersion and lastBackedUpTimestamp'
  235. )
  236. await setBackupVersion(
  237. projectId,
  238. lastBackedUpVersion,
  239. chunkRecord.endVersion,
  240. startOfBackupTime
  241. )
  242. }
  243. // Define command-line options
  244. const optionDefinitions = [
  245. {
  246. name: 'projectId',
  247. alias: 'p',
  248. type: String,
  249. description: 'The ID of the project to backup',
  250. defaultOption: true,
  251. },
  252. {
  253. name: 'help',
  254. alias: 'h',
  255. type: Boolean,
  256. description: 'Display this usage guide.',
  257. },
  258. {
  259. name: 'status',
  260. alias: 's',
  261. type: Boolean,
  262. description: 'Display project status.',
  263. },
  264. {
  265. name: 'list',
  266. alias: 'l',
  267. type: Boolean,
  268. description: 'List projects that need to be backed up',
  269. },
  270. {
  271. name: 'dry-run',
  272. alias: 'n',
  273. type: Boolean,
  274. description: 'Perform a dry run without making any changes.',
  275. },
  276. {
  277. name: 'retries',
  278. alias: 'r',
  279. type: Number,
  280. description: 'Number of retries, default is 3.',
  281. },
  282. {
  283. name: 'concurrency',
  284. alias: 'c',
  285. type: Number,
  286. description: 'Number of concurrent blob downloads (default: 1)',
  287. },
  288. {
  289. name: 'batch-concurrency',
  290. alias: 'b',
  291. type: Number,
  292. description: 'Number of concurrent project operations (default: 1)',
  293. },
  294. {
  295. name: 'pending',
  296. alias: 'P',
  297. type: Boolean,
  298. description: 'Backup all pending projects.',
  299. },
  300. {
  301. name: 'interval',
  302. alias: 'i',
  303. type: Number,
  304. description: 'Time interval in seconds for pending backups (default: 3600)',
  305. defaultValue: 3600,
  306. },
  307. {
  308. name: 'fix',
  309. type: Number,
  310. description: 'Fix projects without chunks',
  311. },
  312. {
  313. name: 'init',
  314. alias: 'I',
  315. type: Boolean,
  316. description: 'Initialize backups for all projects.',
  317. },
  318. { name: 'output', alias: 'o', type: String, description: 'Output file' },
  319. {
  320. name: 'start-date',
  321. type: String,
  322. description: 'Start date for initialization (ISO format)',
  323. },
  324. {
  325. name: 'end-date',
  326. type: String,
  327. description: 'End date for initialization (ISO format)',
  328. },
  329. {
  330. name: 'use-secondary',
  331. type: Boolean,
  332. description: 'Use secondary read preference for backup status',
  333. },
  334. {
  335. name: 'compare',
  336. alias: 'C',
  337. type: Boolean,
  338. description:
  339. 'Compare backup with original chunks. With --start-date and --end-date compares all projects in range.',
  340. },
  341. ]
  342. function handleOptions() {
  343. const options = commandLineArgs(optionDefinitions)
  344. if (options.help) {
  345. console.log('Usage:')
  346. optionDefinitions.forEach(option => {
  347. console.log(` --${option.name}, -${option.alias}: ${option.description}`)
  348. })
  349. process.exit(0)
  350. }
  351. const projectIdRequired =
  352. !options.list &&
  353. !options.pending &&
  354. !options.init &&
  355. !(options.fix >= 0) &&
  356. !(options.compare && options['start-date'] && options['end-date'])
  357. if (projectIdRequired && !options.projectId) {
  358. console.error('Error: projectId is required')
  359. process.exit(1)
  360. }
  361. if (options.pending && options.projectId) {
  362. console.error('Error: --pending cannot be specified with projectId')
  363. process.exit(1)
  364. }
  365. if (options.pending && (options.list || options.status)) {
  366. console.error('Error: --pending is exclusive with --list and --status')
  367. process.exit(1)
  368. }
  369. if (options.init && options.pending) {
  370. console.error('Error: --init cannot be specified with --pending')
  371. process.exit(1)
  372. }
  373. if (
  374. (options['start-date'] || options['end-date']) &&
  375. !options.init &&
  376. !options.compare
  377. ) {
  378. console.error(
  379. 'Error: date options can only be used with --init or --compare'
  380. )
  381. process.exit(1)
  382. }
  383. if (options['use-secondary']) {
  384. USE_SECONDARY = true
  385. }
  386. if (
  387. options.compare &&
  388. !options.projectId &&
  389. !(options['start-date'] && options['end-date'])
  390. ) {
  391. console.error(
  392. 'Error: --compare requires either projectId or both --start-date and --end-date'
  393. )
  394. process.exit(1)
  395. }
  396. DRY_RUN = options['dry-run'] || false
  397. RETRY_LIMIT = options.retries || 3
  398. CONCURRENCY = options.concurrency || 1
  399. BATCH_CONCURRENCY = options['batch-concurrency'] || 1
  400. BLOB_LIMITER = pLimit(CONCURRENCY)
  401. return options
  402. }
  403. async function displayBackupStatus(projectId) {
  404. const result = await analyseBackupStatus(projectId)
  405. console.log('Backup status:', JSON.stringify(result))
  406. }
  407. async function analyseBackupStatus(projectId) {
  408. const { backupStatus, historyId, currentEndVersion, currentEndTimestamp } =
  409. await getBackupStatus(projectId)
  410. // TODO: when we have confidence that the latestChunkMetadata always matches
  411. // the values from the backupStatus we can skip loading it here
  412. const latestChunkMetadata = await loadLatestRaw(historyId, {
  413. readOnly: Boolean(USE_SECONDARY),
  414. })
  415. if (
  416. currentEndVersion &&
  417. currentEndVersion !== latestChunkMetadata.endVersion
  418. ) {
  419. // compare the current end version with the latest chunk metadata to check that
  420. // the updates to the project collection are reliable
  421. // expect some failures due to the time window between getBackupStatus and
  422. // loadLatestRaw where the project is being actively edited.
  423. logger.warn(
  424. {
  425. projectId,
  426. historyId,
  427. currentEndVersion,
  428. currentEndTimestamp,
  429. latestChunkMetadata,
  430. },
  431. 'currentEndVersion does not match latest chunk metadata'
  432. )
  433. }
  434. if (DRY_RUN) {
  435. console.log('Project:', projectId)
  436. console.log('History ID:', historyId)
  437. console.log('Latest Chunk Metadata:', JSON.stringify(latestChunkMetadata))
  438. console.log('Current end version:', currentEndVersion)
  439. console.log('Current end timestamp:', currentEndTimestamp)
  440. console.log('Backup status:', backupStatus ?? 'none')
  441. }
  442. if (!backupStatus) {
  443. if (DRY_RUN) {
  444. console.log('No backup status found - doing full backup')
  445. }
  446. }
  447. const lastBackedUpVersion = backupStatus?.lastBackedUpVersion
  448. const endVersion = latestChunkMetadata.endVersion
  449. if (endVersion >= 0 && endVersion === lastBackedUpVersion) {
  450. if (DRY_RUN) {
  451. console.log(
  452. 'Project is up to date, last backed up at version',
  453. lastBackedUpVersion
  454. )
  455. }
  456. } else if (endVersion < lastBackedUpVersion) {
  457. throw new Error('backup is ahead of project')
  458. } else {
  459. if (DRY_RUN) {
  460. console.log(
  461. 'Project needs to be backed up from',
  462. lastBackedUpVersion,
  463. 'to',
  464. endVersion
  465. )
  466. }
  467. }
  468. return {
  469. historyId,
  470. lastBackedUpVersion,
  471. currentVersion: latestChunkMetadata.endVersion || 0,
  472. upToDate: endVersion >= 0 && lastBackedUpVersion === endVersion,
  473. pendingChangeAt: backupStatus?.pendingChangeAt,
  474. currentEndVersion,
  475. currentEndTimestamp,
  476. latestChunkMetadata,
  477. }
  478. }
  479. async function displayPendingBackups(options) {
  480. const intervalMs = options.interval * 1000
  481. for await (const project of listPendingBackups(intervalMs)) {
  482. console.log(
  483. 'Project:',
  484. project._id.toHexString(),
  485. 'backup status:',
  486. JSON.stringify(project.overleaf.backup),
  487. 'history status:',
  488. JSON.stringify(project.overleaf.history, [
  489. 'currentEndVersion',
  490. 'currentEndTimestamp',
  491. ])
  492. )
  493. }
  494. }
  495. function makeChunkKey(projectId, startVersion) {
  496. return path.join(projectKey.format(projectId), projectKey.pad(startVersion))
  497. }
  498. export async function backupProject(projectId, options) {
  499. if (gracefulShutdownInitiated) {
  500. return
  501. }
  502. await ensureGlobalBlobsLoaded()
  503. // FIXME: flush the project first!
  504. // Let's assume the the flush happens externally and triggers this backup
  505. const backupStartTime = new Date()
  506. // find the last backed up version
  507. const {
  508. historyId,
  509. lastBackedUpVersion,
  510. currentVersion,
  511. upToDate,
  512. pendingChangeAt,
  513. currentEndVersion,
  514. latestChunkMetadata,
  515. } = await analyseBackupStatus(projectId)
  516. if (upToDate) {
  517. logger.debug(
  518. {
  519. projectId,
  520. historyId,
  521. lastBackedUpVersion,
  522. currentVersion,
  523. pendingChangeAt,
  524. },
  525. 'backup is up to date'
  526. )
  527. if (
  528. currentEndVersion === undefined &&
  529. latestChunkMetadata.endVersion >= 0
  530. ) {
  531. if (DRY_RUN) {
  532. console.log('Would update current metadata to', latestChunkMetadata)
  533. } else {
  534. await updateCurrentMetadataIfNotSet(projectId, latestChunkMetadata)
  535. }
  536. }
  537. // clear the pending changes timestamp if the backup is complete
  538. if (pendingChangeAt) {
  539. if (DRY_RUN) {
  540. console.log(
  541. 'Would update or clear pending changes timestamp',
  542. backupStartTime
  543. )
  544. } else {
  545. await updatePendingChangeTimestamp(projectId, backupStartTime)
  546. }
  547. }
  548. return
  549. }
  550. logger.debug(
  551. {
  552. projectId,
  553. historyId,
  554. lastBackedUpVersion,
  555. currentVersion,
  556. pendingChangeAt,
  557. },
  558. 'backing up project'
  559. )
  560. // this persistor works for both the chunks and blobs buckets,
  561. // because they use the same DEK
  562. const backupPersistorForProject = await backupPersistor.forProject(
  563. chunksBucket,
  564. makeProjectKey(historyId, '')
  565. )
  566. let previousBackedUpVersion = lastBackedUpVersion
  567. const backupVersions = [previousBackedUpVersion]
  568. for await (const {
  569. blobsToBackup,
  570. chunkToBackup,
  571. chunkRecord,
  572. chunkBuffer,
  573. } of backupGenerator(historyId, lastBackedUpVersion)) {
  574. // backup the blobs first
  575. // this can be done in parallel but must fail if any blob cannot be backed up
  576. // if the blob already exists in the backup then that is allowed
  577. const newBlobs = await findNewBlobs(projectId, blobsToBackup)
  578. await backupBlobs(
  579. projectId,
  580. historyId,
  581. newBlobs,
  582. BLOB_LIMITER,
  583. backupPersistorForProject
  584. )
  585. // then backup the original compressed chunk using the startVersion as the key
  586. await backupChunk(
  587. projectId,
  588. historyId,
  589. backupPersistorForProject,
  590. chunkToBackup,
  591. chunkRecord,
  592. chunkBuffer
  593. )
  594. // persist the backup status in mongo for the current chunk
  595. try {
  596. await updateBackupStatus(
  597. projectId,
  598. previousBackedUpVersion,
  599. chunkRecord,
  600. backupStartTime
  601. )
  602. } catch (err) {
  603. logger.error(
  604. { projectId, chunkRecord, err, backupVersions },
  605. 'error updating backup status'
  606. )
  607. throw err
  608. }
  609. previousBackedUpVersion = chunkRecord.endVersion
  610. backupVersions.push(previousBackedUpVersion)
  611. await cleanBackedUpBlobs(projectId, blobsToBackup)
  612. }
  613. // update the current end version and timestamp if they are not set
  614. if (currentEndVersion === undefined && latestChunkMetadata.endVersion >= 0) {
  615. if (DRY_RUN) {
  616. console.log('Would update current metadata to', latestChunkMetadata)
  617. } else {
  618. await updateCurrentMetadataIfNotSet(projectId, latestChunkMetadata)
  619. }
  620. }
  621. // clear the pending changes timestamp if the backup is complete, otherwise set it to the time
  622. // when the backup started (to pick up the new changes on the next backup)
  623. if (DRY_RUN) {
  624. console.log(
  625. 'Would update or clear pending changes timestamp',
  626. backupStartTime
  627. )
  628. } else {
  629. await updatePendingChangeTimestamp(projectId, backupStartTime)
  630. }
  631. }
  632. function convertToISODate(dateStr) {
  633. // Expecting YYYY-MM-DD format
  634. if (!/^\d{4}-\d{2}-\d{2}$/.test(dateStr)) {
  635. throw new Error('Date must be in YYYY-MM-DD format')
  636. }
  637. return new Date(dateStr + 'T00:00:00.000Z').toISOString()
  638. }
  639. export async function fixProjectsWithoutChunks(options) {
  640. const limit = options.fix || 1
  641. const query = {
  642. 'overleaf.history.id': { $exists: true },
  643. 'overleaf.backup.lastBackedUpVersion': { $in: [null] },
  644. }
  645. const cursor = client
  646. .db()
  647. .collection('projects')
  648. .find(query, {
  649. projection: { _id: 1, 'overleaf.history.id': 1 },
  650. readPreference: READ_PREFERENCE_SECONDARY,
  651. })
  652. .limit(limit)
  653. for await (const project of cursor) {
  654. const historyId = project.overleaf.history.id.toString()
  655. const chunks = await getProjectChunks(historyId)
  656. if (chunks.length > 0) {
  657. continue
  658. }
  659. if (DRY_RUN) {
  660. console.log(
  661. 'Would create new chunk for Project ID:',
  662. project._id.toHexString(),
  663. 'History ID:',
  664. historyId,
  665. 'Chunks:',
  666. chunks
  667. )
  668. } else {
  669. console.log(
  670. 'Creating new chunk for Project ID:',
  671. project._id.toHexString(),
  672. 'History ID:',
  673. historyId,
  674. 'Chunks:',
  675. chunks
  676. )
  677. const snapshot = new Snapshot()
  678. const history = new History(snapshot, [])
  679. const chunk = new Chunk(history, 0)
  680. await create(historyId, chunk)
  681. const newChunks = await getProjectChunks(historyId)
  682. console.log('New chunk:', newChunks)
  683. }
  684. }
  685. }
  686. export async function initializeProjects(options) {
  687. await ensureGlobalBlobsLoaded()
  688. let totalErrors = 0
  689. let totalProjects = 0
  690. const query = {
  691. 'overleaf.backup.lastBackedUpVersion': { $in: [null] },
  692. }
  693. if (options['start-date'] && options['end-date']) {
  694. query._id = {
  695. $gte: objectIdFromInput(convertToISODate(options['start-date'])),
  696. $lt: objectIdFromInput(convertToISODate(options['end-date'])),
  697. }
  698. }
  699. const cursor = client
  700. .db()
  701. .collection('projects')
  702. .find(query, {
  703. projection: { _id: 1 },
  704. readPreference: READ_PREFERENCE_SECONDARY,
  705. })
  706. if (options.output) {
  707. console.log("Writing project IDs to file: '" + options.output + "'")
  708. const output = createWriteStream(options.output)
  709. for await (const project of cursor) {
  710. output.write(project._id.toHexString() + '\n')
  711. totalProjects++
  712. }
  713. output.end()
  714. console.log('Wrote ' + totalProjects + ' project IDs to file')
  715. return
  716. }
  717. for await (const project of cursor) {
  718. if (gracefulShutdownInitiated) {
  719. console.warn('graceful shutdown: stopping project initialization')
  720. break
  721. }
  722. totalProjects++
  723. const projectId = project._id.toHexString()
  724. try {
  725. await backupProject(projectId, options)
  726. } catch (err) {
  727. totalErrors++
  728. logger.error({ projectId, err }, 'error backing up project')
  729. }
  730. }
  731. return { errors: totalErrors, projects: totalProjects }
  732. }
  733. async function backupPendingProjects(options) {
  734. const intervalMs = options.interval * 1000
  735. for await (const project of listPendingBackups(intervalMs)) {
  736. if (gracefulShutdownInitiated) {
  737. console.warn('graceful shutdown: stopping pending project backups')
  738. break
  739. }
  740. const projectId = project._id.toHexString()
  741. console.log(`Backing up pending project with ID: ${projectId}`)
  742. await backupProject(projectId, options)
  743. }
  744. }
  745. class BlobComparator {
  746. constructor(backupPersistorForProject) {
  747. this.cache = new Map()
  748. this.backupPersistorForProject = backupPersistorForProject
  749. }
  750. async compareBlob(historyId, blob) {
  751. let computedHash = this.cache.get(blob.hash)
  752. const fromCache = !!computedHash
  753. if (!computedHash) {
  754. const blobKey = makeProjectKey(historyId, blob.hash)
  755. const backupBlobStream =
  756. await this.backupPersistorForProject.getObjectStream(
  757. projectBlobsBucket,
  758. blobKey,
  759. { autoGunzip: true }
  760. )
  761. computedHash = await blobHashFromStream(blob.byteLength, backupBlobStream)
  762. this.cache.set(blob.hash, computedHash)
  763. }
  764. const matches = computedHash === blob.hash
  765. return {
  766. matches,
  767. computedHash,
  768. fromCache,
  769. }
  770. }
  771. }
  772. async function compareBackups(projectId, options) {
  773. console.log(`Comparing backups for project ${projectId}`)
  774. const { historyId } = await getBackupStatus(projectId)
  775. const chunks = await getProjectChunks(historyId)
  776. const blobStore = new BlobStore(historyId)
  777. const backupPersistorForProject = await backupPersistor.forProject(
  778. chunksBucket,
  779. makeProjectKey(historyId, '')
  780. )
  781. let totalChunkMatches = 0
  782. let totalChunkMismatches = 0
  783. let totalChunksNotFound = 0
  784. let totalBlobMatches = 0
  785. let totalBlobMismatches = 0
  786. let totalBlobsNotFound = 0
  787. const errors = []
  788. const blobComparator = new BlobComparator(backupPersistorForProject)
  789. for (const chunk of chunks) {
  790. try {
  791. // Compare chunk content
  792. const originalChunk = await historyStore.loadRaw(historyId, chunk.id)
  793. const key = makeChunkKey(historyId, chunk.startVersion)
  794. try {
  795. const backupChunkStream =
  796. await backupPersistorForProject.getObjectStream(chunksBucket, key)
  797. const backupStr = await text(backupChunkStream.pipe(createGunzip()))
  798. const originalStr = JSON.stringify(originalChunk)
  799. const backupChunk = JSON.parse(backupStr)
  800. const backupStartVersion = chunk.startVersion
  801. const backupEndVersion = chunk.startVersion + backupChunk.changes.length
  802. if (originalStr === backupStr) {
  803. console.log(
  804. `✓ Chunk ${chunk.id} (v${chunk.startVersion}-v${chunk.endVersion}) matches`
  805. )
  806. totalChunkMatches++
  807. } else if (originalStr === JSON.stringify(JSON.parse(backupStr))) {
  808. console.log(
  809. `✓ Chunk ${chunk.id} (v${chunk.startVersion}-v${chunk.endVersion}) matches (after normalisation)`
  810. )
  811. totalChunkMatches++
  812. } else if (backupEndVersion < chunk.endVersion) {
  813. console.log(
  814. `✗ Chunk ${chunk.id} is ahead of backup (v${chunk.startVersion}-v${chunk.endVersion} vs v${backupStartVersion}-v${backupEndVersion})`
  815. )
  816. totalChunkMismatches++
  817. errors.push({ chunkId: chunk.id, error: 'Chunk ahead of backup' })
  818. } else {
  819. console.log(
  820. `✗ Chunk ${chunk.id} (v${chunk.startVersion}-v${chunk.endVersion}) MISMATCH`
  821. )
  822. totalChunkMismatches++
  823. errors.push({ chunkId: chunk.id, error: 'Chunk mismatch' })
  824. }
  825. } catch (err) {
  826. if (err instanceof NotFoundError) {
  827. console.log(`✗ Chunk ${chunk.id} not found in backup`, err.cause)
  828. totalChunksNotFound++
  829. errors.push({ chunkId: chunk.id, error: `Chunk not found` })
  830. } else {
  831. throw err
  832. }
  833. }
  834. const history = History.fromRaw(originalChunk)
  835. // Compare blobs in chunk
  836. const blobHashes = new Set()
  837. history.findBlobHashes(blobHashes)
  838. const blobs = await blobStore.getBlobs(Array.from(blobHashes))
  839. for (const blob of blobs) {
  840. if (GLOBAL_BLOBS.has(blob.hash)) {
  841. const globalBlob = GLOBAL_BLOBS.get(blob.hash)
  842. console.log(
  843. ` ✓ Blob ${blob.hash} is a global blob`,
  844. globalBlob.demoted ? '(demoted)' : ''
  845. )
  846. continue
  847. }
  848. try {
  849. const { matches, computedHash, fromCache } =
  850. await blobComparator.compareBlob(historyId, blob)
  851. if (matches) {
  852. console.log(
  853. ` ✓ Blob ${blob.hash} hash matches (${blob.byteLength} bytes)` +
  854. (fromCache ? ' (from cache)' : '')
  855. )
  856. totalBlobMatches++
  857. } else {
  858. console.log(
  859. ` ✗ Blob ${blob.hash} hash mismatch (original: ${blob.hash}, backup: ${computedHash}) (${blob.byteLength} bytes, ${blob.stringLength} string length)` +
  860. (fromCache ? ' (from cache)' : '')
  861. )
  862. totalBlobMismatches++
  863. errors.push({
  864. chunkId: chunk.id,
  865. error: `Blob ${blob.hash} hash mismatch`,
  866. })
  867. }
  868. } catch (err) {
  869. if (err instanceof NotFoundError) {
  870. console.log(` ✗ Blob ${blob.hash} not found in backup`, err.cause)
  871. totalBlobsNotFound++
  872. errors.push({
  873. chunkId: chunk.id,
  874. error: `Blob ${blob.hash} not found`,
  875. })
  876. } else {
  877. throw err
  878. }
  879. }
  880. }
  881. } catch (err) {
  882. console.error(`Error comparing chunk ${chunk.id}:`, err)
  883. errors.push({ chunkId: chunk.id, error: err })
  884. }
  885. }
  886. // Print summary
  887. console.log('\nComparison Summary:')
  888. console.log('==================')
  889. console.log(`Total chunks: ${chunks.length}`)
  890. console.log(`Chunk matches: ${totalChunkMatches}`)
  891. console.log(`Chunk mismatches: ${totalChunkMismatches}`)
  892. console.log(`Chunk not found: ${totalChunksNotFound}`)
  893. console.log(`Blob matches: ${totalBlobMatches}`)
  894. console.log(`Blob mismatches: ${totalBlobMismatches}`)
  895. console.log(`Blob not found: ${totalBlobsNotFound}`)
  896. console.log(`Errors: ${errors.length}`)
  897. if (errors.length > 0) {
  898. console.log('\nErrors:')
  899. errors.forEach(({ chunkId, error }) => {
  900. console.log(` Chunk ${chunkId}: ${error}`)
  901. })
  902. throw new Error('Backup comparison FAILED')
  903. } else {
  904. console.log('Backup comparison successful')
  905. }
  906. }
  907. async function compareAllProjects(options) {
  908. const limiter = pLimit(BATCH_CONCURRENCY)
  909. let totalErrors = 0
  910. let totalProjects = 0
  911. async function processBatch(batch) {
  912. if (gracefulShutdownInitiated) {
  913. throw new Error('graceful shutdown')
  914. }
  915. const batchOperations = batch.map(project =>
  916. limiter(async () => {
  917. const projectId = project._id.toHexString()
  918. totalProjects++
  919. try {
  920. console.log(`\nComparing project ${projectId} (${totalProjects})`)
  921. await compareBackups(projectId, options)
  922. } catch (err) {
  923. totalErrors++
  924. console.error(`Failed to compare project ${projectId}:`, err)
  925. }
  926. })
  927. )
  928. await Promise.allSettled(batchOperations)
  929. }
  930. const query = {
  931. 'overleaf.history.id': { $exists: true },
  932. 'overleaf.backup.lastBackedUpVersion': { $exists: true },
  933. }
  934. await batchedUpdate(
  935. client.db().collection('projects'),
  936. query,
  937. processBatch,
  938. {
  939. _id: 1,
  940. 'overleaf.history': 1,
  941. 'overleaf.backup': 1,
  942. },
  943. { readPreference: 'secondary' },
  944. {
  945. BATCH_RANGE_START: convertToISODate(options['start-date']),
  946. BATCH_RANGE_END: convertToISODate(options['end-date']),
  947. }
  948. )
  949. console.log('\nComparison Summary:')
  950. console.log('==================')
  951. console.log(`Total projects processed: ${totalProjects}`)
  952. console.log(`Projects with errors: ${totalErrors}`)
  953. if (totalErrors > 0) {
  954. throw new Error('Some project comparisons failed')
  955. }
  956. }
  957. async function main() {
  958. const options = handleOptions()
  959. await ensureGlobalBlobsLoaded()
  960. const projectId = options.projectId
  961. if (options.status) {
  962. await displayBackupStatus(projectId)
  963. } else if (options.list) {
  964. await displayPendingBackups(options)
  965. } else if (options.fix !== undefined) {
  966. await fixProjectsWithoutChunks(options)
  967. } else if (options.pending) {
  968. await backupPendingProjects(options)
  969. } else if (options.init) {
  970. await initializeProjects(options)
  971. } else if (options.compare) {
  972. if (options['start-date'] && options['end-date']) {
  973. await compareAllProjects(options)
  974. } else {
  975. await compareBackups(projectId, options)
  976. }
  977. } else {
  978. await backupProject(projectId, options)
  979. }
  980. }
  981. // Only run command-line interface when script is run directly
  982. if (import.meta.url === `file://${process.argv[1]}`) {
  983. main()
  984. .then(() => {
  985. console.log(
  986. gracefulShutdownInitiated ? 'Exited - graceful shutdown' : 'Completed'
  987. )
  988. })
  989. .catch(err => {
  990. console.error('Error backing up project:', err)
  991. process.exit(1)
  992. })
  993. .finally(() => {
  994. knex
  995. .destroy()
  996. .then(() => {
  997. console.log('Postgres connection closed')
  998. })
  999. .catch(err => {
  1000. console.error('Error closing Postgres connection:', err)
  1001. })
  1002. client
  1003. .close()
  1004. .then(() => {
  1005. console.log('MongoDB connection closed')
  1006. })
  1007. .catch(err => {
  1008. console.error('Error closing MongoDB connection:', err)
  1009. })
  1010. })
  1011. }