force_doc_flush.mjs 2.0 KB

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