migrate_audit_logs.mjs 4.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169
  1. import { batchedUpdate } from '@overleaf/mongo-utils/batchedUpdate.js'
  2. import { promiseMapWithLimit, promisify } from '@overleaf/promise-utils'
  3. import { db, ObjectId } from '../app/src/infrastructure/mongodb.js'
  4. import _ from 'lodash'
  5. import { fileURLToPath } from 'node:url'
  6. import { scriptRunner } from './lib/ScriptRunner.mjs'
  7. const sleep = promisify(setTimeout)
  8. async function main(options, trackProgress) {
  9. if (!options) {
  10. options = {}
  11. }
  12. _.defaults(options, {
  13. dryRun: process.env.DRY_RUN !== 'false',
  14. projectId: process.env.PROJECT_ID,
  15. userId: process.env.USER_ID,
  16. skipUsersMigration: process.env.SKIP_USERS_MIGRATION === 'true',
  17. writeConcurrency: parseInt(process.env.WRITE_CONCURRENCY, 10) || 10,
  18. letUserDoubleCheckInputsFor: parseInt(
  19. process.env.LET_USER_DOUBLE_CHECK_INPUTS_FOR || 10 * 1000,
  20. 10
  21. ),
  22. })
  23. await letUserDoubleCheckInputs(options)
  24. if (options.projectId) {
  25. console.log('migrating projectId=' + options.projectId)
  26. const project = await db.projects.findOne(
  27. { _id: new ObjectId(options.projectId) },
  28. { _id: 1, auditLog: 1 }
  29. )
  30. if (!project || !project.auditLog) {
  31. console.error('unable to process project', project)
  32. return
  33. }
  34. await processProjectsBatch([project], options)
  35. } else if (options.userId) {
  36. console.log('migrating userId=' + options.userId)
  37. const user = await db.users.findOne(
  38. { _id: new ObjectId(options.userId) },
  39. { _id: 1, auditLog: 1 }
  40. )
  41. if (!user || !user.auditLog) {
  42. console.error('unable to process user', user)
  43. return
  44. }
  45. await processUsersBatch([user], options)
  46. } else {
  47. if (!options.skipUsersMigration) {
  48. await batchedUpdate(
  49. db.users,
  50. { auditLog: { $exists: true } },
  51. async users => {
  52. await processUsersBatch(users, options)
  53. },
  54. { _id: 1, auditLog: 1 },
  55. undefined,
  56. { trackProgress }
  57. )
  58. }
  59. // most projects are processed after its owner has been processed, but only those
  60. // users with an existing `auditLog` have been taken into consideration, leaving
  61. // some projects orphan. This batched update processes all remaining projects.
  62. await batchedUpdate(
  63. db.projects,
  64. { auditLog: { $exists: true } },
  65. async projects => {
  66. await processProjectsBatch(projects, options)
  67. },
  68. { _id: 1, auditLog: 1 },
  69. undefined,
  70. { trackProgress }
  71. )
  72. }
  73. }
  74. async function processUsersBatch(users, options) {
  75. if (!users || users.length <= 0) {
  76. return
  77. }
  78. const entries = users
  79. .map(user => user.auditLog.map(log => ({ ...log, userId: user._id })))
  80. .flat()
  81. if (!options.dryRun && entries?.length > 0) {
  82. await db.userAuditLogEntries.insertMany(entries)
  83. }
  84. if (!options.dryRun) {
  85. const userIds = users.map(user => user._id)
  86. await db.users.updateMany(
  87. { _id: { $in: userIds } },
  88. { $unset: { auditLog: 1 } }
  89. )
  90. }
  91. await promiseMapWithLimit(options.writeConcurrency, users, async user => {
  92. const projects = await db.projects
  93. .find(
  94. { owner_ref: user._id, auditLog: { $exists: true } },
  95. { _id: 1, auditLog: 1 }
  96. )
  97. .toArray()
  98. await processProjectsBatch(projects, options)
  99. })
  100. }
  101. async function processProjectsBatch(projects, options) {
  102. if (!projects || projects.length <= 0) {
  103. return
  104. }
  105. const entries = projects
  106. .map(project =>
  107. project.auditLog.map(log => ({ ...log, projectId: project._id }))
  108. )
  109. .flat()
  110. if (!options.dryRun && entries?.length > 0) {
  111. await db.projectAuditLogEntries.insertMany(entries)
  112. }
  113. if (!options.dryRun) {
  114. const projectIds = projects.map(project => project._id)
  115. await db.projects.updateMany(
  116. { _id: { $in: projectIds } },
  117. { $unset: { auditLog: 1 } }
  118. )
  119. }
  120. }
  121. async function letUserDoubleCheckInputs(options) {
  122. const allOptions = {
  123. ...options,
  124. // batchedUpdate() environment variables
  125. BATCH_DESCENDING: process.env.BATCH_DESCENDING,
  126. BATCH_SIZE: process.env.BATCH_SIZE,
  127. VERBOSE_LOGGING: process.env.VERBOSE_LOGGING,
  128. BATCH_LAST_ID: process.env.BATCH_LAST_ID,
  129. BATCH_RANGE_END: process.env.BATCH_RANGE_END,
  130. SKIP_USERS_MIGRATION: process.env.SKIP_USERS_MIGRATION,
  131. }
  132. console.error('Options:', JSON.stringify(allOptions, null, 2))
  133. console.error(
  134. 'Waiting for you to double check inputs for',
  135. options.letUserDoubleCheckInputsFor,
  136. 'ms'
  137. )
  138. await sleep(options.letUserDoubleCheckInputsFor)
  139. }
  140. export default main
  141. if (fileURLToPath(import.meta.url) === process.argv[1]) {
  142. try {
  143. await scriptRunner(
  144. async trackProgress => await main(undefined, trackProgress)
  145. )
  146. console.log('Done.')
  147. process.exit(0)
  148. } catch (error) {
  149. console.error({ error })
  150. process.exit(1)
  151. }
  152. }