migrate_audit_logs.mjs 4.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164
  1. import BatchedUpdateModule from './helpers/batchedUpdate.mjs'
  2. import { promiseMapWithLimit, promisify } from '@overleaf/promise-utils'
  3. import { db, ObjectId, waitForDb } from '../app/src/infrastructure/mongodb.js'
  4. import _ from 'lodash'
  5. import { fileURLToPath } from 'url'
  6. const sleep = promisify(setTimeout)
  7. const { batchedUpdate } = BatchedUpdateModule
  8. async function main(options) {
  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. 'users',
  50. { auditLog: { $exists: true } },
  51. async users => {
  52. await processUsersBatch(users, options)
  53. },
  54. { _id: 1, auditLog: 1 }
  55. )
  56. }
  57. // most projects are processed after its owner has been processed, but only those
  58. // users with an existing `auditLog` have been taken into consideration, leaving
  59. // some projects orphan. This batched update processes all remaining projects.
  60. await batchedUpdate(
  61. 'projects',
  62. { auditLog: { $exists: true } },
  63. async projects => {
  64. await processProjectsBatch(projects, options)
  65. },
  66. { _id: 1, auditLog: 1 }
  67. )
  68. }
  69. }
  70. async function processUsersBatch(users, options) {
  71. if (!users || users.length <= 0) {
  72. return
  73. }
  74. const entries = users
  75. .map(user => user.auditLog.map(log => ({ ...log, userId: user._id })))
  76. .flat()
  77. if (!options.dryRun && entries?.length > 0) {
  78. await db.userAuditLogEntries.insertMany(entries)
  79. }
  80. if (!options.dryRun) {
  81. const userIds = users.map(user => user._id)
  82. await db.users.updateMany(
  83. { _id: { $in: userIds } },
  84. { $unset: { auditLog: 1 } }
  85. )
  86. }
  87. await promiseMapWithLimit(options.writeConcurrency, users, async user => {
  88. const projects = await db.projects
  89. .find(
  90. { owner_ref: user._id, auditLog: { $exists: true } },
  91. { _id: 1, auditLog: 1 }
  92. )
  93. .toArray()
  94. await processProjectsBatch(projects, options)
  95. })
  96. }
  97. async function processProjectsBatch(projects, options) {
  98. if (!projects || projects.length <= 0) {
  99. return
  100. }
  101. const entries = projects
  102. .map(project =>
  103. project.auditLog.map(log => ({ ...log, projectId: project._id }))
  104. )
  105. .flat()
  106. if (!options.dryRun && entries?.length > 0) {
  107. await db.projectAuditLogEntries.insertMany(entries)
  108. }
  109. if (!options.dryRun) {
  110. const projectIds = projects.map(project => project._id)
  111. await db.projects.updateMany(
  112. { _id: { $in: projectIds } },
  113. { $unset: { auditLog: 1 } }
  114. )
  115. }
  116. }
  117. async function letUserDoubleCheckInputs(options) {
  118. const allOptions = {
  119. ...options,
  120. // batchedUpdate() environment variables
  121. BATCH_DESCENDING: process.env.BATCH_DESCENDING,
  122. BATCH_SIZE: process.env.BATCH_SIZE,
  123. VERBOSE_LOGGING: process.env.VERBOSE_LOGGING,
  124. BATCH_LAST_ID: process.env.BATCH_LAST_ID,
  125. BATCH_RANGE_END: process.env.BATCH_RANGE_END,
  126. SKIP_USERS_MIGRATION: process.env.SKIP_USERS_MIGRATION,
  127. }
  128. console.error('Options:', JSON.stringify(allOptions, null, 2))
  129. console.error(
  130. 'Waiting for you to double check inputs for',
  131. options.letUserDoubleCheckInputsFor,
  132. 'ms'
  133. )
  134. await sleep(options.letUserDoubleCheckInputsFor)
  135. }
  136. export default main
  137. if (fileURLToPath(import.meta.url) === process.argv[1]) {
  138. try {
  139. await waitForDb()
  140. await main()
  141. console.log('Done.')
  142. process.exit(0)
  143. } catch (error) {
  144. console.error({ error })
  145. process.exit(1)
  146. }
  147. }