downgrade_project.js 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  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(
  30. `project ${project._id} converted and upgraded to full project history`
  31. )
  32. }
  33. }
  34. async function shouldPreserveHistory(project) {
  35. return await db.projectHistoryMetaData.findOne(
  36. {
  37. $and: [
  38. { project_id: { $eq: project._id } },
  39. { preserveHistory: { $eq: true } },
  40. ],
  41. },
  42. { readPreference: ReadPreference.SECONDARY }
  43. )
  44. }
  45. async function main() {
  46. if (PROJECT_ID) {
  47. await waitForDb()
  48. const project = await db.projects.findOne({ _id: ObjectId(PROJECT_ID) })
  49. await processProject(project)
  50. } else {
  51. console.log('PROJECT_ID environment value is needed.')
  52. process.exit(1)
  53. }
  54. }
  55. // Upgrading history is not atomic, if we quit out mid-initialisation
  56. // then history could get into a broken state
  57. // Instead, skip any unprocessed projects and exit() at end of the batch.
  58. process.on('SIGINT', function () {
  59. console.log('Caught SIGINT, waiting for in process upgrades to complete')
  60. INTERRUPT = true
  61. })
  62. main()
  63. .then(() => {
  64. console.error('Done.')
  65. process.exit(0)
  66. })
  67. .catch(error => {
  68. console.error({ error })
  69. process.exit(1)
  70. })