force_doc_flush.mjs 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. import mongodb from 'mongodb-legacy'
  2. import { db } from '../app/src/infrastructure/mongodb.js'
  3. import DocumentUpdaterHandler from '../app/src/Features/DocumentUpdater/DocumentUpdaterHandler.js'
  4. const { ObjectId } = mongodb
  5. const PROJECT_ID = process.env.PROJECT_ID
  6. const DOC_ID = process.env.DOC_ID
  7. const VERBOSE_LOGGING = process.env.VERBOSE_LOGGING === 'true'
  8. const DRY_RUN = process.env.DRY_RUN !== 'false'
  9. console.log({
  10. PROJECT_ID,
  11. DOC_ID,
  12. VERBOSE_LOGGING,
  13. DRY_RUN,
  14. })
  15. async function main() {
  16. const { lines, version, ranges } = await getDocument()
  17. const size = lines.reduce((size, line) => size + line.length + 1, 0)
  18. console.log('doc stats:', {
  19. lineCount: lines.length,
  20. size,
  21. version,
  22. })
  23. if (!DRY_RUN) {
  24. console.log(`updating doc ${DOC_ID} in mongo for project ${PROJECT_ID}`)
  25. const result = await db.docs.updateOne(
  26. { _id: new ObjectId(DOC_ID), project_id: new ObjectId(PROJECT_ID) },
  27. {
  28. $set: { lines, version, ranges },
  29. $inc: { rev: 1 }, // maintain same behaviour as Docstore upsertIntoDocCollection
  30. $unset: {
  31. inS3: true,
  32. },
  33. }
  34. )
  35. console.log('mongo result', result)
  36. if (
  37. result.matchedCount !== 1 ||
  38. result.modifiedCount !== 1 ||
  39. !result.acknowledged
  40. ) {
  41. throw new Error('unexpected result from mongo update')
  42. }
  43. console.log(`deleting doc ${DOC_ID} from redis for project ${PROJECT_ID}`)
  44. await DocumentUpdaterHandler.promises.deleteDoc(PROJECT_ID, DOC_ID, true)
  45. }
  46. }
  47. function getDocument() {
  48. return new Promise((resolve, reject) => {
  49. DocumentUpdaterHandler.getDocument(
  50. PROJECT_ID,
  51. DOC_ID,
  52. -1,
  53. (error, lines, version, ranges) => {
  54. if (error) {
  55. reject(error)
  56. } else {
  57. resolve({ lines, version, ranges })
  58. }
  59. }
  60. )
  61. })
  62. }
  63. try {
  64. await main()
  65. console.error('Done.')
  66. process.exit(0)
  67. } catch (error) {
  68. console.error({ error })
  69. process.exit(1)
  70. }