export_global_blobs.mjs 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. /**
  2. * A script to export the global blobs from mongo to a CSV file.
  3. *
  4. * node storage/scripts/export_global_blobs.mjs --output global_blobs.csv
  5. *
  6. * The output CSV has the following format:
  7. *
  8. * hash,path,byteLength,stringLength,demoted
  9. *
  10. * hash: the hash of the blob
  11. * path: the path of the blob in the blob store
  12. * byteLength: the byte length of the blob, or empty if unknown
  13. * stringLength: the string length of the blob, or empty if unknown
  14. * demoted: true if the blob has been demoted to a reference, false otherwise
  15. */
  16. // @ts-check
  17. import { ObjectId } from 'mongodb'
  18. import { GLOBAL_BLOBS, loadGlobalBlobs } from '../lib/blob_store/index.js'
  19. import { client } from '../lib/mongodb.js'
  20. import commandLineArgs from 'command-line-args'
  21. import fs from 'node:fs'
  22. // Enable caching for ObjectId.toString()
  23. ObjectId.cacheHexString = true
  24. function parseArgs() {
  25. const args = commandLineArgs([
  26. {
  27. name: 'output',
  28. type: String,
  29. alias: 'o',
  30. },
  31. ])
  32. const OUTPUT_STREAM = fs.createWriteStream(args['output'], { flags: 'wx' })
  33. return {
  34. OUTPUT_STREAM,
  35. }
  36. }
  37. const { OUTPUT_STREAM } = parseArgs()
  38. async function main() {
  39. await loadGlobalBlobs()
  40. OUTPUT_STREAM.write('hash,path,byteLength,stringLength,demoted\n')
  41. for (const [hash, { blob, demoted }] of GLOBAL_BLOBS) {
  42. const { hash: blobHash, byteLength, stringLength } = blob
  43. if (blobHash !== hash) {
  44. throw new Error(`hash mismatch: ${hash} !== ${blobHash}`)
  45. }
  46. const path = blobHash.slice(0, 2) + '/' + blobHash.slice(2)
  47. const byteLengthStr = byteLength === null ? '' : byteLength
  48. const stringLengthStr = stringLength === null ? '' : stringLength
  49. OUTPUT_STREAM.write(
  50. `${hash},${path},${byteLengthStr},${stringLengthStr},${demoted}\n`
  51. )
  52. }
  53. }
  54. main()
  55. .then(() => console.log('Done.'))
  56. .catch(err => {
  57. console.error('Error:', err)
  58. process.exitCode = 1
  59. })
  60. .finally(() => {
  61. client.close().catch(err => console.error('Error closing MongoDB:', err))
  62. })