convert_archived_state.mjs 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. import _ from 'lodash'
  2. import { db } from '../app/src/infrastructure/mongodb.js'
  3. import { batchedUpdate } from '@overleaf/mongo-utils/batchedUpdate.js'
  4. import { promiseMapWithLimit } from '@overleaf/promise-utils'
  5. import { fileURLToPath } from 'node:url'
  6. const WRITE_CONCURRENCY = parseInt(process.env.WRITE_CONCURRENCY, 10) || 10
  7. // $ node scripts/convert_archived_state.mjs FIRST,SECOND
  8. async function main(STAGE) {
  9. for (const FIELD of ['archived', 'trashed']) {
  10. if (STAGE.includes('FIRST')) {
  11. await batchedUpdate(
  12. db.projects,
  13. { [FIELD]: false },
  14. {
  15. $set: { [FIELD]: [] },
  16. }
  17. )
  18. console.error('Done, with first part for field:', FIELD)
  19. }
  20. if (STAGE.includes('SECOND')) {
  21. await batchedUpdate(
  22. db.projects,
  23. { [FIELD]: true },
  24. async function performUpdate(nextBatch) {
  25. await promiseMapWithLimit(
  26. WRITE_CONCURRENCY,
  27. nextBatch,
  28. async project => {
  29. try {
  30. await upgradeFieldToArray({ project, FIELD })
  31. } catch (err) {
  32. console.error(project._id, err)
  33. throw err
  34. }
  35. }
  36. )
  37. },
  38. {
  39. _id: 1,
  40. owner_ref: 1,
  41. collaberator_refs: 1,
  42. readOnly_refs: 1,
  43. tokenAccessReadAndWrite_refs: 1,
  44. tokenAccessReadOnly_refs: 1,
  45. }
  46. )
  47. console.error('Done, with second part for field:', FIELD)
  48. }
  49. }
  50. }
  51. async function upgradeFieldToArray({ project, FIELD }) {
  52. return db.projects.updateOne(
  53. { _id: project._id },
  54. {
  55. $set: { [FIELD]: getAllUserIds(project) },
  56. }
  57. )
  58. }
  59. function getAllUserIds(project) {
  60. return _.unionWith(
  61. [project.owner_ref],
  62. project.collaberator_refs,
  63. project.readOnly_refs,
  64. project.tokenAccessReadAndWrite_refs,
  65. project.tokenAccessReadOnly_refs,
  66. _objectIdEquals
  67. )
  68. }
  69. function _objectIdEquals(firstVal, secondVal) {
  70. // For use as a comparator for unionWith
  71. return firstVal.toString() === secondVal.toString()
  72. }
  73. if (fileURLToPath(import.meta.url) === process.argv[1]) {
  74. try {
  75. await main(process.argv.pop())
  76. process.exit(0)
  77. } catch (error) {
  78. console.error({ error })
  79. process.exit(1)
  80. }
  81. }
  82. export default main