fix_oversized_docs.mjs 4.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163
  1. import fs from 'node:fs'
  2. import minimist from 'minimist'
  3. import { ObjectId } from '../app/src/infrastructure/mongodb.js'
  4. import DocstoreManager from '../app/src/Features/Docstore/DocstoreManager.js'
  5. import FileStoreHandler from '../app/src/Features/FileStore/FileStoreHandler.js'
  6. import FileWriter from '../app/src/infrastructure/FileWriter.js'
  7. import ProjectEntityMongoUpdateHandler from '../app/src/Features/Project/ProjectEntityMongoUpdateHandler.js'
  8. import ProjectLocator from '../app/src/Features/Project/ProjectLocator.js'
  9. import RedisWrapper from '@overleaf/redis-wrapper'
  10. import Settings from '@overleaf/settings'
  11. const opts = parseArgs()
  12. const redis = RedisWrapper.createClient(Settings.redis.web)
  13. function parseArgs() {
  14. const args = minimist(process.argv.slice(2), {
  15. boolean: ['commit', 'ignore-ranges'],
  16. })
  17. const projectIds = args._
  18. if (projectIds.length === 0) {
  19. console.log(`Usage: ${process.argv[1]} [OPTS] PROJECT_ID
  20. Options:
  21. --commit Actually convert oversized docs to binary files
  22. --max-doc-size Size over which docs are converted to binary files
  23. --ignore-ranges Convert docs even if they contain ranges
  24. `)
  25. process.exit(0)
  26. }
  27. const commit = args.commit
  28. const ignoreRanges = args['ignore-ranges']
  29. const maxDocSize = args['max-doc-size']
  30. ? parseInt(args['max-doc-size'], 10)
  31. : 2 * 1024 * 1024
  32. return { projectIds, commit, ignoreRanges, maxDocSize }
  33. }
  34. async function main() {
  35. for (const projectId of opts.projectIds) {
  36. await processProject(projectId)
  37. }
  38. if (!opts.commit) {
  39. console.log('This was a dry run. Re-run with --commit to apply changes')
  40. }
  41. }
  42. async function processProject(projectId) {
  43. const docIds = await getDocIds(projectId)
  44. for (const docId of docIds) {
  45. await processDoc(projectId, docId)
  46. }
  47. }
  48. async function processDoc(projectId, docId) {
  49. const doc = await getDoc(projectId, docId)
  50. const size = doc.lines.reduce((sum, line) => sum + line.length + 1, 0)
  51. if (size > opts.maxDocSize) {
  52. if (
  53. !opts.ignoreRanges &&
  54. ((doc.ranges.comments && doc.ranges.comments.length > 0) ||
  55. (doc.ranges.changes && doc.ranges.changes.length > 0))
  56. ) {
  57. console.log(
  58. `Skipping doc ${doc.path} in project ${projectId} because it has ranges`
  59. )
  60. return
  61. }
  62. console.log(
  63. `Converting doc ${doc.path} in project ${projectId} to binary (${size} bytes)`
  64. )
  65. if (opts.commit) {
  66. const fileRef = await sendDocToFilestore(projectId, doc)
  67. await ProjectEntityMongoUpdateHandler.promises.replaceDocWithFile(
  68. new ObjectId(projectId),
  69. new ObjectId(docId),
  70. fileRef,
  71. null // unset lastUpdatedBy
  72. )
  73. await deleteDocFromMongo(projectId, doc)
  74. await deleteDocFromRedis(projectId, docId)
  75. }
  76. }
  77. }
  78. async function getDocIds(projectId) {
  79. const docIds = await redis.smembers(`DocsIn:{${projectId}}`)
  80. return docIds
  81. }
  82. async function getDoc(projectId, docId) {
  83. const lines = await redis.get(`doclines:{${docId}}`)
  84. const ranges = await redis.get(`Ranges:{${docId}}`)
  85. const { path } = await ProjectLocator.promises.findElement({
  86. project_id: projectId,
  87. element_id: docId,
  88. type: 'doc',
  89. })
  90. return {
  91. id: docId,
  92. lines: JSON.parse(lines),
  93. ranges: ranges ? JSON.parse(ranges) : {},
  94. path: path.fileSystem,
  95. }
  96. }
  97. async function sendDocToFilestore(projectId, doc) {
  98. const basename = doc.path.split('/').pop()
  99. const tmpFilePath = await FileWriter.promises.writeLinesToDisk(
  100. projectId,
  101. doc.lines
  102. )
  103. try {
  104. const { fileRef } = await FileStoreHandler.promises.uploadFileFromDisk(
  105. projectId,
  106. { name: basename, rev: doc.version + 1 },
  107. tmpFilePath
  108. )
  109. return fileRef
  110. } finally {
  111. fs.promises.unlink(tmpFilePath)
  112. }
  113. }
  114. async function deleteDocFromMongo(projectId, doc) {
  115. const basename = doc.path.split('/').pop()
  116. const deletedAt = new Date()
  117. await DocstoreManager.promises.deleteDoc(
  118. projectId,
  119. doc.id,
  120. basename,
  121. deletedAt
  122. )
  123. }
  124. async function deleteDocFromRedis(projectId, docId) {
  125. await redis.del(
  126. `Blocking:{${docId}}`,
  127. `doclines:{${docId}}`,
  128. `DocOps:{${docId}}`,
  129. `DocVersion:{${docId}}`,
  130. `DocHash:{${docId}}`,
  131. `ProjectId:{${docId}}`,
  132. `Ranges:{${docId}}`,
  133. `UnflushedTime:{${docId}}`,
  134. `Pathname:{${docId}}`,
  135. `ProjectHistoryId:{${docId}}`,
  136. `PendingUpdates:{${docId}}`,
  137. `lastUpdatedAt:{${docId}}`,
  138. `lastUpdatedBy:{${docId}}`
  139. )
  140. await redis.srem(`DocsIn:{${projectId}}`, projectId)
  141. }
  142. try {
  143. await main()
  144. process.exit(0)
  145. } catch (error) {
  146. console.error(error)
  147. process.exit(1)
  148. }