flush_projects_with_no_history_id.js 4.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211
  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(/ProjectHistoryId:\{(.*?)\}/)
  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 historyIds = await node.mget(
  80. docIds.map(docId => docUpdaterKeys.projectHistoryId({ doc_id: docId }))
  81. )
  82. const results = []
  83. for (const index in docIds) {
  84. const historyId = historyIds[index]
  85. const docId = docIds[index]
  86. if (!historyId) {
  87. try {
  88. const { projectId, historyId } = await getHistoryId(docId)
  89. results.push({ projectId, historyId, docId })
  90. } catch (error) {
  91. logger.warn(
  92. { error },
  93. 'Error gathering data for doc with missing history id'
  94. )
  95. }
  96. }
  97. }
  98. return results
  99. }
  100. /**
  101. *
  102. * @param {Array<UpdateableDoc>} updates
  103. * @return {Promise<void>}
  104. */
  105. async function fixAndFlushProjects(updates) {
  106. for (const update of updates) {
  107. if (commit) {
  108. try {
  109. await rclient.set(
  110. docUpdaterKeys.projectHistoryId({ doc_id: update.docId }),
  111. update.historyId
  112. )
  113. logger.debug({ ...update }, 'Set history id in redis')
  114. await ProjectManager.promises.flushAndDeleteProjectWithLocks(
  115. update.projectId,
  116. {}
  117. )
  118. logger.debug({ ...update }, 'Flushed project')
  119. } catch (err) {
  120. logger.error({ err, ...update }, 'Error fixing and flushing project')
  121. }
  122. } else {
  123. logger.debug(
  124. { ...update },
  125. 'Would have set history id in redis and flushed'
  126. )
  127. }
  128. }
  129. }
  130. /**
  131. *
  132. * @param {Array<Redis>} nodes
  133. * @param {number} batchSize
  134. * @return {Promise<void>}
  135. */
  136. async function scanNodes(nodes, batchSize = 1000) {
  137. let scanned = 0
  138. for (const node of nodes) {
  139. const stream = node.scanStream({
  140. match: docUpdaterKeys.projectHistoryId({ doc_id: '*' }),
  141. count: batchSize,
  142. })
  143. for await (const docKeys of stream) {
  144. if (docKeys.length === 0) {
  145. continue
  146. }
  147. stream.pause()
  148. scanned += docKeys.length
  149. const docIds = docKeys
  150. .map((/** @type {string} */ docKey) => extractDocId(docKey))
  151. .filter(Boolean)
  152. try {
  153. const updates = await findDocsWithMissingHistoryIds(node, docIds)
  154. if (updates.length > 0) {
  155. logger.info({ updates }, 'Found doc(s) with missing history ids')
  156. await fixAndFlushProjects(updates)
  157. }
  158. } catch (error) {
  159. logger.error({ docKeys }, 'Error processing batch')
  160. } finally {
  161. stream.resume()
  162. }
  163. }
  164. logger.info({ scanned, server: node.serverInfo.role }, 'Scanned node')
  165. }
  166. }
  167. async function main({ batchSize }) {
  168. const nodes = (typeof rclient.nodes === 'function'
  169. ? rclient.nodes('master')
  170. : undefined) || [rclient]
  171. await scanNodes(nodes, batchSize)
  172. }
  173. let code = 0
  174. main({ batchSize })
  175. .then(() => {
  176. logger.info({}, 'done')
  177. })
  178. .catch(error => {
  179. logger.error({ error }, 'error')
  180. code = 1
  181. })
  182. .finally(() => {
  183. rclient.quit().then(() => process.exit(code))
  184. })