fix_oversized_docs.mjs 4.6 KB

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