migrate_audit_logs.mjs 4.5 KB

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