fix_malformed_filetree.mjs 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306
  1. /**
  2. * This script fixes problems found by the find_malformed_filetrees.js script.
  3. *
  4. * The script takes a single argument --logs pointing at the output of a
  5. * previous run of the find_malformed_filetrees.js script.
  6. *
  7. * Alternatively, use an adhoc file: --logs=<(echo '{"projectId":"...","path":"..."}')
  8. */
  9. import mongodb from 'mongodb-legacy'
  10. import { db } from '../app/src/infrastructure/mongodb.mjs'
  11. import ProjectLocator from '../app/src/Features/Project/ProjectLocator.mjs'
  12. import minimist from 'minimist'
  13. import readline from 'node:readline'
  14. import fs from 'node:fs'
  15. import logger from '@overleaf/logger'
  16. import { scriptRunner } from './lib/ScriptRunner.mjs'
  17. const { ObjectId } = mongodb
  18. const { findDeep } = ProjectLocator
  19. const lastUpdated = new Date()
  20. const argv = minimist(process.argv.slice(2), {
  21. string: ['logs'],
  22. })
  23. let gracefulShutdownInitiated = false
  24. process.on('SIGINT', handleSignal)
  25. process.on('SIGTERM', handleSignal)
  26. function handleSignal() {
  27. gracefulShutdownInitiated = true
  28. console.warn('graceful shutdown initiated, draining queue')
  29. }
  30. const STATS = {
  31. processedLines: 0,
  32. success: 0,
  33. alreadyProcessed: 0,
  34. hash: 0,
  35. failed: 0,
  36. unmatched: 0,
  37. }
  38. function logStats() {
  39. console.log(
  40. JSON.stringify({
  41. time: new Date(),
  42. gracefulShutdownInitiated,
  43. ...STATS,
  44. })
  45. )
  46. }
  47. setInterval(logStats, 10_000)
  48. async function main() {
  49. const rl = readline.createInterface({
  50. input: fs.createReadStream(argv.logs),
  51. })
  52. for await (const line of rl) {
  53. if (gracefulShutdownInitiated) break
  54. STATS.processedLines++
  55. if (!line.startsWith('{')) continue
  56. try {
  57. const { projectId, path, _id } = JSON.parse(line)
  58. await processBadPath(projectId, path, _id)
  59. } catch (err) {
  60. STATS.failed++
  61. logger.err({ line, err }, 'failed to fix tree')
  62. }
  63. }
  64. }
  65. async function processBadPath(projectId, mongoPath, _id) {
  66. let modifiedCount
  67. if (isRootFolder(mongoPath)) {
  68. modifiedCount = await fixRootFolder(projectId)
  69. } else if (isArrayElement(mongoPath)) {
  70. modifiedCount = await removeNulls(projectId, _id)
  71. } else if (isArray(mongoPath)) {
  72. modifiedCount = await fixArray(projectId, mongoPath)
  73. } else if (isFolderId(mongoPath)) {
  74. modifiedCount = await fixFolderId(projectId, mongoPath)
  75. } else if (isDocOrFileId(mongoPath)) {
  76. modifiedCount = await removeElementsWithoutIds(
  77. projectId,
  78. parentPath(parentPath(mongoPath))
  79. )
  80. } else if (isName(mongoPath)) {
  81. modifiedCount = await fixName(projectId, _id)
  82. } else if (isHash(mongoPath)) {
  83. console.error(`Missing file hash: ${projectId}/${_id} (${mongoPath})`)
  84. console.error('SaaS: likely needs filestore restore')
  85. console.error('Server Pro: please reach out to support')
  86. STATS.hash++
  87. return
  88. } else {
  89. console.error(`Unexpected mongo path: ${mongoPath}`)
  90. STATS.unmatched++
  91. return
  92. }
  93. if (modifiedCount === 0) {
  94. STATS.alreadyProcessed++
  95. } else {
  96. STATS.success++
  97. }
  98. }
  99. function isRootFolder(path) {
  100. return path === 'rootFolder.0'
  101. }
  102. function isArray(path) {
  103. return /\.(docs|folders|fileRefs)$/.test(path)
  104. }
  105. function isArrayElement(path) {
  106. return /\.\d+$/.test(path)
  107. }
  108. function isFolderId(path) {
  109. return /\.folders\.\d+\._id$/.test(path)
  110. }
  111. function isDocOrFileId(path) {
  112. return /\.(docs|fileRefs)\.\d+\._id$/.test(path)
  113. }
  114. function isName(path) {
  115. return /\.name$/.test(path)
  116. }
  117. function isHash(path) {
  118. return /\.hash$/.test(path)
  119. }
  120. function parentPath(path) {
  121. return path.slice(0, path.lastIndexOf('.'))
  122. }
  123. /**
  124. * If the root folder structure is missing, set it up
  125. */
  126. async function fixRootFolder(projectId) {
  127. const result = await db.projects.updateOne(
  128. {
  129. _id: new ObjectId(projectId),
  130. rootFolder: { $size: 0 },
  131. },
  132. {
  133. $set: {
  134. rootFolder: [
  135. {
  136. _id: new ObjectId(),
  137. name: 'rootFolder',
  138. folders: [],
  139. docs: [],
  140. fileRefs: [],
  141. },
  142. ],
  143. lastUpdated,
  144. lastUpdatedBy: null, // unset lastUpdatedBy
  145. },
  146. }
  147. )
  148. return result.modifiedCount
  149. }
  150. /**
  151. * Remove all nulls from the given docs/files/folders array
  152. */
  153. async function removeNulls(projectId, _id) {
  154. if (!_id) {
  155. throw new Error('missing _id')
  156. }
  157. const project = await db.projects.findOne(
  158. { _id: new ObjectId(projectId) },
  159. { projection: { rootFolder: 1 } }
  160. )
  161. const foundResult = findDeep(project, obj => obj?._id?.toString() === _id)
  162. if (!foundResult) return
  163. const { path } = foundResult
  164. const result = await db.projects.updateOne(
  165. { _id: new ObjectId(projectId) },
  166. {
  167. $pull: {
  168. [`${path}.folders`]: null,
  169. [`${path}.docs`]: null,
  170. [`${path}.fileRefs`]: null,
  171. },
  172. $set: {
  173. lastUpdated,
  174. lastUpdatedBy: null, // unset lastUpdatedBy
  175. },
  176. }
  177. )
  178. return result.modifiedCount
  179. }
  180. /**
  181. * If the element at the given path is not an array, set it to an empty array
  182. */
  183. async function fixArray(projectId, path) {
  184. const result = await db.projects.updateOne(
  185. { _id: new ObjectId(projectId), [path]: { $not: { $type: 'array' } } },
  186. { $set: { [path]: [], lastUpdated, lastUpdatedBy: null } }
  187. )
  188. return result.modifiedCount
  189. }
  190. /**
  191. * Generate a missing id for a folder
  192. */
  193. async function fixFolderId(projectId, path) {
  194. const result = await db.projects.updateOne(
  195. { _id: new ObjectId(projectId), [path]: { $exists: false } },
  196. {
  197. $set: {
  198. [path]: new ObjectId(),
  199. lastUpdated,
  200. lastUpdatedBy: null, // unset lastUpdatedBy
  201. },
  202. }
  203. )
  204. return result.modifiedCount
  205. }
  206. /**
  207. * Remove elements that don't have ids in the array at the given path
  208. */
  209. async function removeElementsWithoutIds(projectId, path) {
  210. const result = await db.projects.updateOne(
  211. { _id: new ObjectId(projectId), [path]: { $type: 'array' } },
  212. {
  213. $pull: { [path]: { _id: null } },
  214. $set: {
  215. lastUpdated,
  216. lastUpdatedBy: null, // unset lastUpdatedBy
  217. },
  218. }
  219. )
  220. return result.modifiedCount
  221. }
  222. /**
  223. * Give a name to a file/doc/folder that doesn't have one
  224. */
  225. async function fixName(projectId, _id) {
  226. if (!_id) {
  227. throw new Error('missing _id')
  228. }
  229. const project = await db.projects.findOne(
  230. { _id: new ObjectId(projectId) },
  231. { projection: { rootFolder: 1 } }
  232. )
  233. const foundResult = findDeep(project, obj => obj?._id?.toString() === _id)
  234. if (!foundResult) return
  235. const { path } = foundResult
  236. const array = ProjectLocator.findElementByMongoPath(project, parentPath(path))
  237. const name =
  238. path === 'rootFolder.0'
  239. ? 'rootFolder'
  240. : findUniqueName(new Set(array.map(x => x?.name)))
  241. const pathToName = `${path}.name`
  242. const result = await db.projects.updateOne(
  243. { _id: new ObjectId(projectId), [pathToName]: { $in: [null, ''] } },
  244. {
  245. $set: {
  246. [pathToName]: name,
  247. lastUpdated,
  248. lastUpdatedBy: null, // unset lastUpdatedBy
  249. },
  250. }
  251. )
  252. return result.modifiedCount
  253. }
  254. function findUniqueName(existingFilenames) {
  255. let index = 0
  256. let filename = 'untitled'
  257. while (existingFilenames.has(filename)) {
  258. index += 1
  259. filename = `untitled-${index}`
  260. }
  261. return filename
  262. }
  263. try {
  264. try {
  265. await scriptRunner(main)
  266. } finally {
  267. logStats()
  268. }
  269. if (STATS.failed > 0) {
  270. process.exit(Math.min(STATS.failed, 99))
  271. } else if (STATS.hash > 0) {
  272. process.exit(100)
  273. } else if (STATS.unmatched > 0) {
  274. process.exit(101)
  275. } else {
  276. process.exit(0)
  277. }
  278. } catch (error) {
  279. console.error(error)
  280. process.exit(1)
  281. }