downgrade_project.js 2.0 KB

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