flush_projects_with_no_history_id.js 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220
  1. // @ts-check
  2. const Settings = require('@overleaf/settings')
  3. const logger = require('@overleaf/logger')
  4. const RedisManager = require('../app/js/RedisManager')
  5. const minimist = require('minimist')
  6. const { db, ObjectId } = require('../app/js/mongodb')
  7. const ProjectManager = require('../app/js/ProjectManager')
  8. const OError = require('@overleaf/o-error')
  9. const docUpdaterKeys = Settings.redis.documentupdater.key_schema
  10. const rclient = RedisManager.rclient
  11. const { verbose, commit, ...args } = minimist(process.argv.slice(2), {
  12. boolean: ['verbose', 'commit'],
  13. string: ['batchSize'],
  14. default: {
  15. batchSize: '1000',
  16. },
  17. })
  18. logger.logger.level(verbose ? 'debug' : 'warn')
  19. const batchSize = parseInt(args.batchSize, 10)
  20. /**
  21. * @typedef {import('ioredis').Redis} Redis
  22. */
  23. /**
  24. *
  25. * @param {string} key
  26. * @return {string|void}
  27. */
  28. function extractDocId(key) {
  29. const matches = key.match(/DocVersion:\{(.*?)\}/)
  30. if (matches) {
  31. return matches[1]
  32. }
  33. }
  34. /**
  35. *
  36. * @param {string} docId
  37. * @return {Promise<{projectId: string, historyId: string}>}
  38. */
  39. async function getHistoryId(docId) {
  40. const doc = await db.docs.findOne(
  41. { _id: new ObjectId(docId) },
  42. { projection: { project_id: 1 }, readPreference: 'secondaryPreferred' }
  43. )
  44. if (!doc) {
  45. throw new OError('Doc not present in mongo', { docId })
  46. }
  47. const project = await db.projects.findOne(
  48. { _id: doc.project_id },
  49. {
  50. projection: { 'overleaf.history': 1 },
  51. readPreference: 'secondaryPreferred',
  52. }
  53. )
  54. if (!project?.overleaf?.history?.id) {
  55. throw new OError('Project not present in mongo (or has no history id)', {
  56. docId,
  57. project,
  58. doc,
  59. })
  60. }
  61. return {
  62. historyId: project?.overleaf?.history?.id,
  63. projectId: doc.project_id.toString(),
  64. }
  65. }
  66. /**
  67. * @typedef {Object} UpdateableDoc
  68. * @property {string} docId
  69. * @property {string} projectId
  70. * @property {string} historyId
  71. */
  72. /**
  73. *
  74. * @param {Redis} node
  75. * @param {Array<string>} docIds
  76. * @return {Promise<Array<UpdateableDoc>>}
  77. */
  78. async function findDocsWithMissingHistoryIds(node, docIds) {
  79. const fromRedis = await node.mget(
  80. docIds
  81. .map(docId => [
  82. docUpdaterKeys.docVersion({ doc_id: docId }),
  83. docUpdaterKeys.projectHistoryId({ doc_id: docId }),
  84. ])
  85. .flat()
  86. )
  87. const results = []
  88. for (const [index, docId] of docIds.entries()) {
  89. const docVersion = fromRedis[index * 2]
  90. const historyId = fromRedis[index * 2 + 1]
  91. if (!docVersion) {
  92. // Already removed from redis.
  93. continue
  94. }
  95. if (!historyId) {
  96. try {
  97. const { projectId, historyId } = await getHistoryId(docId)
  98. results.push({ projectId, historyId, docId, docVersion })
  99. } catch (error) {
  100. logger.warn(
  101. { error },
  102. 'Error gathering data for doc with missing history id'
  103. )
  104. }
  105. }
  106. }
  107. return results
  108. }
  109. /**
  110. *
  111. * @param {Array<UpdateableDoc>} updates
  112. * @return {Promise<void>}
  113. */
  114. async function fixAndFlushProjects(updates) {
  115. for (const update of updates) {
  116. if (commit) {
  117. try {
  118. await rclient.set(
  119. docUpdaterKeys.projectHistoryId({ doc_id: update.docId }),
  120. update.historyId
  121. )
  122. logger.debug({ ...update }, 'Set history id in redis')
  123. await ProjectManager.promises.flushAndDeleteProjectWithLocks(
  124. update.projectId,
  125. {}
  126. )
  127. logger.debug({ ...update }, 'Flushed project')
  128. } catch (err) {
  129. logger.error({ err, ...update }, 'Error fixing and flushing project')
  130. }
  131. } else {
  132. logger.debug(
  133. { ...update },
  134. 'Would have set history id in redis and flushed'
  135. )
  136. }
  137. }
  138. }
  139. /**
  140. *
  141. * @param {Array<Redis>} nodes
  142. * @param {number} batchSize
  143. * @return {Promise<void>}
  144. */
  145. async function scanNodes(nodes, batchSize = 1000) {
  146. let scanned = 0
  147. for (const node of nodes) {
  148. const stream = node.scanStream({
  149. match: docUpdaterKeys.docVersion({ doc_id: '*' }),
  150. count: batchSize,
  151. })
  152. for await (const docKeys of stream) {
  153. if (docKeys.length === 0) {
  154. continue
  155. }
  156. stream.pause()
  157. scanned += docKeys.length
  158. const docIds = docKeys
  159. .map((/** @type {string} */ docKey) => extractDocId(docKey))
  160. .filter(Boolean)
  161. try {
  162. const updates = await findDocsWithMissingHistoryIds(node, docIds)
  163. if (updates.length > 0) {
  164. logger.info({ updates }, 'Found doc(s) with missing history ids')
  165. await fixAndFlushProjects(updates)
  166. }
  167. } catch (error) {
  168. logger.error({ docKeys }, 'Error processing batch')
  169. } finally {
  170. stream.resume()
  171. }
  172. }
  173. logger.info({ scanned, server: node.serverInfo.role }, 'Scanned node')
  174. }
  175. }
  176. async function main({ batchSize }) {
  177. const nodes = (typeof rclient.nodes === 'function'
  178. ? rclient.nodes('master')
  179. : undefined) || [rclient]
  180. await scanNodes(nodes, batchSize)
  181. }
  182. let code = 0
  183. main({ batchSize })
  184. .then(() => {
  185. logger.info({}, 'done')
  186. })
  187. .catch(error => {
  188. logger.error({ error }, 'error')
  189. code = 1
  190. })
  191. .finally(() => {
  192. rclient.quit().then(() => process.exit(code))
  193. })