attach_dangling_comments_to_doc.mjs 4.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150
  1. // @ts-check
  2. import minimist from 'minimist'
  3. import process from 'node:process'
  4. import ChatApiHandler from '../app/src/Features/Chat/ChatApiHandler.mjs'
  5. import DocumentUpdaterHandler from '../app/src/Features/DocumentUpdater/DocumentUpdaterHandler.mjs'
  6. import DocstoreManager from '../app/src/Features/Docstore/DocstoreManager.mjs'
  7. import HistoryManager from '../app/src/Features/History/HistoryManager.mjs'
  8. import { db, ObjectId } from '../app/src/infrastructure/mongodb.mjs'
  9. const OPTS = parseArgs()
  10. function usage() {
  11. console.error('Attach dangling threads to the beginning of a document')
  12. console.error('')
  13. console.error('Usage: node attach_dangling_comments_to_doc.mjs')
  14. console.error(' --project PROJECT_ID')
  15. console.error(' --doc DOC_ID')
  16. console.error(' [--commit]')
  17. }
  18. function parseArgs() {
  19. const args = minimist(process.argv.slice(2), {
  20. boolean: ['commit'],
  21. string: ['project', 'doc'],
  22. })
  23. const projectId = args.project
  24. const docId = args.doc
  25. if (!projectId || !docId) {
  26. usage()
  27. process.exit(0)
  28. }
  29. return { projectId, docId, commit: args.commit }
  30. }
  31. /**
  32. * @typedef {{ id: string, content: string, timestamp: number, user_id: string }} Message
  33. * @typedef {{ id: string, messages: Message[] }} Thread
  34. */
  35. /**
  36. * @param {string} projectId
  37. * @returns {Promise<Thread[]>}
  38. */
  39. async function getDanglingThreads(projectId) {
  40. const docRanges = await DocstoreManager.promises.getAllRanges(projectId)
  41. const threads = await ChatApiHandler.promises.getThreads(projectId)
  42. const threadsInDoc = new Set()
  43. for (const doc of docRanges) {
  44. for (const comment of doc.ranges?.comments ?? []) {
  45. threadsInDoc.add(comment.op.t)
  46. }
  47. }
  48. const danglingThreads = Object.keys(threads)
  49. .filter(threadId => !threadsInDoc.has(threadId))
  50. .map(id => ({ ...threads[id], id }))
  51. console.log(`Found:`)
  52. console.log(` - ${Object.keys(threads).length} threads`)
  53. console.log(` - ${threadsInDoc.size} threads in docRanges`)
  54. console.log(` - ${danglingThreads.length} dangling threads`)
  55. return danglingThreads
  56. }
  57. /**
  58. * @param {any} projectId
  59. * @param {any} docId
  60. */
  61. const ensureDocExists = async (projectId, docId) => {
  62. const doc = await DocstoreManager.promises.getDoc(projectId, docId)
  63. if (!doc) {
  64. console.error(`Document ${docId} not found`)
  65. process.exit(1)
  66. }
  67. }
  68. /**
  69. * @param {Thread[]} threads
  70. */
  71. const ensureThreadsHaveMessages = async threads => {
  72. const threadsWithoutMessages = threads.filter(
  73. thread => !thread.messages || thread.messages.length === 0
  74. )
  75. if (threadsWithoutMessages.length > 0) {
  76. console.error(`The following threads have no messages:`)
  77. console.error(threadsWithoutMessages.join(','))
  78. process.exit(1)
  79. }
  80. }
  81. /**
  82. * @param {string} projectId
  83. * @param {string} docId
  84. */
  85. async function processProject(projectId, docId) {
  86. console.log(`Processing project ${projectId}`)
  87. await DocumentUpdaterHandler.promises.flushProjectToMongoAndDelete(projectId)
  88. const danglingThreads = await getDanglingThreads(projectId)
  89. await ensureDocExists(projectId, docId)
  90. await ensureThreadsHaveMessages(danglingThreads)
  91. for (const thread of danglingThreads) {
  92. const firstMessage = thread.messages[0]
  93. if (!firstMessage) {
  94. console.error(`Thread ${thread.id} has no messages`)
  95. continue
  96. }
  97. const rangeComment = newRangeComment(thread, firstMessage)
  98. console.log(`Attaching thread ${thread.id} to doc ${docId}`)
  99. if (OPTS.commit) {
  100. await db.docs.updateOne(
  101. { _id: new ObjectId(docId) },
  102. { $push: { 'ranges.comments': rangeComment } }
  103. )
  104. }
  105. }
  106. if (OPTS.commit) {
  107. console.log(`Resyncing history for project ${projectId}`)
  108. await HistoryManager.promises.resyncProject(projectId)
  109. }
  110. }
  111. /**
  112. * @param {Thread} thread
  113. * @param {Message} message
  114. */
  115. const newRangeComment = (thread, message) => ({
  116. id: new ObjectId(thread.id),
  117. op: { t: new ObjectId(thread.id), p: 0, c: '' },
  118. metadata: {
  119. user_id: new ObjectId(message.user_id),
  120. ts: new Date(message.timestamp),
  121. },
  122. })
  123. await processProject(OPTS.projectId, OPTS.docId)
  124. if (!OPTS.commit) {
  125. console.log('This was a dry run. Rerun with --commit to apply changes')
  126. }
  127. process.exit(0)