attach_dangling_comments_to_doc.mjs 4.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146
  1. // @ts-check
  2. import minimist from 'minimist'
  3. import process from 'node:process'
  4. import ChatApiHandler from '../app/src/Features/Chat/ChatApiHandler.js'
  5. import DocumentUpdaterHandler from '../app/src/Features/DocumentUpdater/DocumentUpdaterHandler.js'
  6. import DocstoreManager from '../app/src/Features/Docstore/DocstoreManager.js'
  7. import HistoryManager from '../app/src/Features/History/HistoryManager.js'
  8. import { db, ObjectId } from '../app/src/infrastructure/mongodb.js'
  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. const ensureDocExists = async (projectId, docId) => {
  58. const doc = await DocstoreManager.promises.getDoc(projectId, docId)
  59. if (!doc) {
  60. console.error(`Document ${docId} not found`)
  61. process.exit(1)
  62. }
  63. }
  64. /**
  65. * @param {Thread[]} threads
  66. */
  67. const ensureThreadsHaveMessages = async threads => {
  68. const threadsWithoutMessages = threads.filter(
  69. thread => !thread.messages || thread.messages.length === 0
  70. )
  71. if (threadsWithoutMessages.length > 0) {
  72. console.error(`The following threads have no messages:`)
  73. console.error(threadsWithoutMessages.join(','))
  74. process.exit(1)
  75. }
  76. }
  77. /**
  78. * @param {string} projectId
  79. * @param {string} docId
  80. */
  81. async function processProject(projectId, docId) {
  82. console.log(`Processing project ${projectId}`)
  83. await DocumentUpdaterHandler.promises.flushProjectToMongoAndDelete(projectId)
  84. const danglingThreads = await getDanglingThreads(projectId)
  85. await ensureDocExists(projectId, docId)
  86. await ensureThreadsHaveMessages(danglingThreads)
  87. for (const thread of danglingThreads) {
  88. const firstMessage = thread.messages[0]
  89. if (!firstMessage) {
  90. console.error(`Thread ${thread.id} has no messages`)
  91. continue
  92. }
  93. const rangeComment = newRangeComment(thread, firstMessage)
  94. console.log(`Attaching thread ${thread.id} to doc ${docId}`)
  95. if (OPTS.commit) {
  96. await db.docs.updateOne(
  97. { _id: new ObjectId(docId) },
  98. { $push: { 'ranges.comments': rangeComment } }
  99. )
  100. }
  101. }
  102. if (OPTS.commit) {
  103. console.log(`Resyncing history for project ${projectId}`)
  104. await HistoryManager.promises.resyncProject(projectId)
  105. }
  106. }
  107. /**
  108. * @param {Thread} thread
  109. * @param {Message} message
  110. */
  111. const newRangeComment = (thread, message) => ({
  112. id: new ObjectId(thread.id),
  113. op: { t: new ObjectId(thread.id), p: 0, c: '' },
  114. metadata: {
  115. user_id: new ObjectId(message.user_id),
  116. ts: new Date(message.timestamp),
  117. },
  118. })
  119. await processProject(OPTS.projectId, OPTS.docId)
  120. if (!OPTS.commit) {
  121. console.log('This was a dry run. Rerun with --commit to apply changes')
  122. }
  123. process.exit(0)