migrate_audit_logs.js 4.3 KB

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