split_writefull_disabled_from_unset.mjs 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. import { db } from '../app/src/infrastructure/mongodb.js'
  2. import { batchedUpdate } from '@overleaf/mongo-utils/batchedUpdate.js'
  3. import mongodb from 'mongodb-legacy'
  4. import fs from 'node:fs'
  5. import { fileURLToPath } from 'node:url'
  6. const { ObjectId } = mongodb
  7. const CHUNK_SIZE = 1000
  8. // Function to chunk the array
  9. function chunkArray(array, size) {
  10. const result = []
  11. for (let i = 0; i < array.length; i += size) {
  12. result.push(array.slice(i, i + size))
  13. }
  14. return result
  15. }
  16. async function main() {
  17. // search for file of users who already explicitly opted out first
  18. const optOutPath = process.argv[2]
  19. const optedOutFile = fs.readFileSync(optOutPath, 'utf8')
  20. let optedOutList = optedOutFile
  21. optedOutList = optedOutFile.split('\n').map(id => new ObjectId(id))
  22. console.log(`preserving opt-outs of ${optedOutList.length} users`)
  23. // update all applicable user models
  24. await batchedUpdate(
  25. db.users,
  26. { 'writefull.enabled': false }, // and is false
  27. { $set: { 'writefull.enabled': null } }
  28. )
  29. const chunks = chunkArray(optedOutList, CHUNK_SIZE)
  30. // then reset any explicit false back to being false
  31. // Iterate over each chunk and perform the query
  32. for (const chunkedIds of chunks) {
  33. console.log('batch update started')
  34. await db.users.updateMany(
  35. { _id: { $in: chunkedIds } },
  36. { $set: { 'writefull.enabled': false } }
  37. )
  38. console.log('batch completed')
  39. }
  40. }
  41. export default main
  42. if (fileURLToPath(import.meta.url) === process.argv[1]) {
  43. try {
  44. await main()
  45. process.exit(0)
  46. } catch (error) {
  47. console.error({ error })
  48. process.exit(1)
  49. }
  50. }