scan.js 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202
  1. // @ts-check
  2. 'use strict'
  3. const logger = require('@overleaf/logger')
  4. const { JobNotFoundError, JobNotReadyError } = require('./chunk_store/errors')
  5. const BATCH_SIZE = 1000 // Default batch size for SCAN
  6. /**
  7. * Asynchronously scans a Redis instance or cluster for keys matching a pattern.
  8. *
  9. * This function handles both standalone Redis instances and Redis clusters.
  10. * For clusters, it iterates over all master nodes. It yields keys in batches
  11. * as they are found by the SCAN command.
  12. *
  13. * @param {object} redisClient - The Redis client instance (from @overleaf/redis-wrapper).
  14. * @param {string} pattern - The pattern to match keys against (e.g., 'user:*').
  15. * @param {number} [count=BATCH_SIZE] - Optional hint for Redis SCAN count per iteration.
  16. * @yields {string[]} A batch of matching keys.
  17. */
  18. async function* scanRedisCluster(redisClient, pattern, count = BATCH_SIZE) {
  19. const nodes = redisClient.nodes ? redisClient.nodes('master') : [redisClient]
  20. for (const node of nodes) {
  21. let cursor = '0'
  22. do {
  23. // redisClient from @overleaf/redis-wrapper uses ioredis style commands
  24. const [nextCursor, keys] = await node.scan(
  25. cursor,
  26. 'MATCH',
  27. pattern,
  28. 'COUNT',
  29. count
  30. )
  31. cursor = nextCursor
  32. if (keys.length > 0) {
  33. yield keys
  34. }
  35. } while (cursor !== '0')
  36. }
  37. }
  38. /**
  39. * Extracts the content within the first pair of curly braces {} from a string.
  40. * This is used to extract a user ID or project ID from a Redis key.
  41. *
  42. * @param {string} key - The input string containing content within curly braces.
  43. * @returns {string | null} The extracted content (the key ID) if found, otherwise null.
  44. */
  45. function extractKeyId(key) {
  46. const match = key.match(/\{(.*?)\}/)
  47. if (match && match[1]) {
  48. return match[1]
  49. }
  50. return null
  51. }
  52. /**
  53. * Fetches timestamps for a list of project IDs based on a given key name.
  54. *
  55. * @param {string[]} projectIds - Array of project identifiers.
  56. * @param {object} rclient - The Redis client instance.
  57. * @param {string} keyName - The base name for the Redis keys storing the timestamps (e.g., "expire-time", "persist-time").
  58. * @param {number} currentTime - The current time (timestamp in milliseconds) to compare against.
  59. * @returns {Promise<Array<{projectId: string, timestampValue: string}>>}
  60. * A promise that resolves to an array of objects, each containing a projectId and
  61. * its corresponding timestampValue, for due projects only.
  62. */
  63. async function fetchOverdueProjects(projectIds, rclient, keyName, currentTime) {
  64. if (!projectIds || projectIds.length === 0) {
  65. return []
  66. }
  67. const timestampKeys = projectIds.map(id => `${keyName}:{${id}}`)
  68. const timestamps = await rclient.mget(timestampKeys)
  69. const dueProjects = []
  70. for (let i = 0; i < projectIds.length; i++) {
  71. const projectId = projectIds[i]
  72. const timestampValue = timestamps[i]
  73. if (timestampValue !== null) {
  74. const timestamp = parseInt(timestampValue, 10)
  75. if (!isNaN(timestamp) && currentTime > timestamp) {
  76. dueProjects.push({ projectId, timestampValue })
  77. }
  78. }
  79. }
  80. return dueProjects
  81. }
  82. /**
  83. * Scans Redis for keys matching a pattern derived from keyName, identifies items that are "due" based on a timestamp,
  84. * and performs a specified action on them.
  85. *
  86. * @param {object} rclient - The Redis client instance.
  87. * @param {string} taskName - A descriptive name for the task (used in logging).
  88. * @param {string} keyName - The base name for the Redis keys (e.g., "expire-time", "persist-time").
  89. * The function will derive the key prefix as `${keyName}:` and scan pattern as `${keyName}:{*}`.
  90. * @param {function(string): Promise<void>} actionFn - An async function that takes a projectId and performs an action.
  91. * @param {boolean} DRY_RUN - If true, logs actions that would be taken without performing them.
  92. * @returns {Promise<{scannedKeyCount: number, processedKeyCount: number}>} Counts of scanned and processed keys.
  93. */
  94. async function scanAndProcessDueItems(
  95. rclient,
  96. taskName,
  97. keyName,
  98. actionFn,
  99. DRY_RUN
  100. ) {
  101. let scannedKeyCount = 0
  102. let processedKeyCount = 0
  103. const START_TIME = Date.now()
  104. const logContext = { taskName, dryRun: DRY_RUN }
  105. const scanPattern = `${keyName}:{*}`
  106. if (DRY_RUN) {
  107. logger.info(logContext, `Starting ${taskName} scan in DRY RUN mode`)
  108. } else {
  109. logger.info(logContext, `Starting ${taskName} scan`)
  110. }
  111. for await (const keysBatch of scanRedisCluster(rclient, scanPattern)) {
  112. scannedKeyCount += keysBatch.length
  113. const projectIds = keysBatch.map(extractKeyId).filter(id => id != null)
  114. if (projectIds.length === 0) {
  115. continue
  116. }
  117. const currentTime = Date.now()
  118. const overdueProjects = await fetchOverdueProjects(
  119. projectIds,
  120. rclient,
  121. keyName,
  122. currentTime
  123. )
  124. for (const project of overdueProjects) {
  125. const { projectId } = project
  126. if (DRY_RUN) {
  127. logger.info(
  128. { ...logContext, projectId },
  129. `[Dry Run] Would perform ${taskName} for project`
  130. )
  131. } else {
  132. try {
  133. await actionFn(projectId)
  134. logger.debug(
  135. { ...logContext, projectId },
  136. `Successfully performed ${taskName} for project`
  137. )
  138. } catch (err) {
  139. if (err instanceof JobNotReadyError) {
  140. // the project has been touched since the job was created
  141. logger.info(
  142. { ...logContext, projectId },
  143. `Job not ready for ${taskName} for project`
  144. )
  145. } else if (err instanceof JobNotFoundError) {
  146. // the project has been expired already by another worker
  147. logger.info(
  148. { ...logContext, projectId },
  149. `Job not found for ${taskName} for project`
  150. )
  151. } else {
  152. logger.error(
  153. { ...logContext, projectId, err },
  154. `Error performing ${taskName} for project`
  155. )
  156. }
  157. continue
  158. }
  159. }
  160. processedKeyCount++
  161. if (processedKeyCount % 1000 === 0 && processedKeyCount > 0) {
  162. logger.info(
  163. { ...logContext, scannedKeyCount, processedKeyCount },
  164. `${taskName} scan progress`
  165. )
  166. }
  167. }
  168. }
  169. logger.info(
  170. {
  171. ...logContext,
  172. scannedKeyCount,
  173. processedKeyCount,
  174. elapsedTimeInSeconds: Math.floor((Date.now() - START_TIME) / 1000),
  175. },
  176. `${taskName} scan complete`
  177. )
  178. return { scannedKeyCount, processedKeyCount }
  179. }
  180. module.exports = {
  181. scanRedisCluster,
  182. extractKeyId,
  183. scanAndProcessDueItems,
  184. }