downgrade_project.js 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. const VERBOSE_LOGGING = process.env.VERBOSE_LOGGING === 'true'
  2. const DRY_RUN = process.env.DRY_RUN !== 'false'
  3. process.env.MONGO_SOCKET_TIMEOUT =
  4. parseInt(process.env.MONGO_SOCKET_TIMEOUT, 10) || 3600000
  5. const PROJECT_ID = process.env.PROJECT_ID
  6. const { ReadPreference, ObjectId } = require('mongodb')
  7. const { db, waitForDb } = require('../../app/src/infrastructure/mongodb')
  8. const ProjectHistoryHandler = require('../../app/src/Features/Project/ProjectHistoryHandler')
  9. console.log({
  10. DRY_RUN,
  11. VERBOSE_LOGGING,
  12. PROJECT_ID,
  13. })
  14. let INTERRUPT = false
  15. async function processProject(project) {
  16. if (INTERRUPT) {
  17. return
  18. }
  19. if (!shouldPreserveHistory(project)) {
  20. console.log(
  21. `project ${project._id} does not have preserveHistory:true, skipping`
  22. )
  23. return
  24. }
  25. if (!DRY_RUN) {
  26. await ProjectHistoryHandler.promises.downgradeHistory(project._id)
  27. }
  28. if (VERBOSE_LOGGING) {
  29. console.log(`project ${project._id} downgraded to track-changes`)
  30. }
  31. }
  32. async function shouldPreserveHistory(project) {
  33. return await db.projectHistoryMetaData.findOne(
  34. {
  35. $and: [
  36. { project_id: { $eq: project._id } },
  37. { preserveHistory: { $eq: true } },
  38. ],
  39. },
  40. { readPreference: ReadPreference.SECONDARY }
  41. )
  42. }
  43. async function main() {
  44. if (PROJECT_ID) {
  45. await waitForDb()
  46. const project = await db.projects.findOne({ _id: ObjectId(PROJECT_ID) })
  47. await processProject(project)
  48. } else {
  49. console.log('PROJECT_ID environment value is needed.')
  50. process.exit(1)
  51. }
  52. }
  53. // Upgrading history is not atomic, if we quit out mid-initialisation
  54. // then history could get into a broken state
  55. // Instead, skip any unprocessed projects and exit() at end of the batch.
  56. process.on('SIGINT', function () {
  57. console.log('Caught SIGINT, waiting for in process downgrades to complete')
  58. INTERRUPT = true
  59. })
  60. main()
  61. .then(() => {
  62. console.error('Done.')
  63. process.exit(0)
  64. })
  65. .catch(error => {
  66. console.error({ error })
  67. process.exit(1)
  68. })