batchedUpdate.js 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328
  1. // @ts-check
  2. /* eslint-disable no-console */
  3. const { ObjectId, ReadPreference } = require('mongodb')
  4. const READ_PREFERENCE_SECONDARY =
  5. process.env.MONGO_HAS_SECONDARIES === 'true'
  6. ? ReadPreference.secondary.mode
  7. : ReadPreference.secondaryPreferred.mode
  8. const ONE_MONTH_IN_MS = 1000 * 60 * 60 * 24 * 31
  9. /** @type {ObjectId | null} */
  10. let ID_EDGE_PAST
  11. const ID_EDGE_FUTURE = objectIdFromMs(Date.now() + 1000)
  12. /** @type {boolean} */
  13. let BATCH_DESCENDING
  14. /** @type {number} */
  15. let BATCH_SIZE
  16. /** @type {boolean} */
  17. let VERBOSE_LOGGING
  18. /** @type {ObjectId} */
  19. let BATCH_RANGE_START
  20. /** @type {ObjectId} */
  21. let BATCH_RANGE_END
  22. /** @type {number} */
  23. let BATCH_MAX_TIME_SPAN_IN_MS
  24. let BATCHED_UPDATE_RUNNING = false
  25. /**
  26. * @typedef {import("mongodb").Collection} Collection
  27. * @typedef {import("mongodb-legacy").Collection} LegacyCollection
  28. * @typedef {import("mongodb").Document} Document
  29. * @typedef {import("mongodb").FindOptions} FindOptions
  30. * @typedef {import("mongodb").UpdateFilter<Document>} UpdateDocument
  31. */
  32. /**
  33. * @typedef {Object} BatchedUpdateOptions
  34. * @property {string} [BATCH_DESCENDING]
  35. * @property {string} [BATCH_LAST_ID]
  36. * @property {string} [BATCH_MAX_TIME_SPAN_IN_MS]
  37. * @property {string} [BATCH_RANGE_END]
  38. * @property {string} [BATCH_RANGE_START]
  39. * @property {string} [BATCH_SIZE]
  40. * @property {string} [VERBOSE_LOGGING]
  41. * @property {(progress: string) => Promise<void>} [trackProgress]
  42. */
  43. /**
  44. * @param {BatchedUpdateOptions} options
  45. */
  46. function refreshGlobalOptionsForBatchedUpdate(options = {}) {
  47. options = Object.assign({}, options, process.env)
  48. BATCH_DESCENDING = options.BATCH_DESCENDING === 'true'
  49. BATCH_SIZE = parseInt(options.BATCH_SIZE || '1000', 10) || 1000
  50. VERBOSE_LOGGING = options.VERBOSE_LOGGING === 'true'
  51. if (options.BATCH_LAST_ID) {
  52. BATCH_RANGE_START = objectIdFromInput(options.BATCH_LAST_ID)
  53. } else if (options.BATCH_RANGE_START) {
  54. BATCH_RANGE_START = objectIdFromInput(options.BATCH_RANGE_START)
  55. } else {
  56. if (BATCH_DESCENDING) {
  57. BATCH_RANGE_START = ID_EDGE_FUTURE
  58. } else {
  59. BATCH_RANGE_START = /** @type {ObjectId} */ (ID_EDGE_PAST)
  60. }
  61. }
  62. BATCH_MAX_TIME_SPAN_IN_MS = parseInt(
  63. options.BATCH_MAX_TIME_SPAN_IN_MS || ONE_MONTH_IN_MS.toString(),
  64. 10
  65. )
  66. if (options.BATCH_RANGE_END) {
  67. BATCH_RANGE_END = objectIdFromInput(options.BATCH_RANGE_END)
  68. } else {
  69. if (BATCH_DESCENDING) {
  70. BATCH_RANGE_END = /** @type {ObjectId} */ (ID_EDGE_PAST)
  71. } else {
  72. BATCH_RANGE_END = ID_EDGE_FUTURE
  73. }
  74. }
  75. }
  76. /**
  77. * @param {Collection | LegacyCollection} collection
  78. * @param {Document} query
  79. * @param {ObjectId} start
  80. * @param {ObjectId} end
  81. * @param {Document} projection
  82. * @param {FindOptions} findOptions
  83. * @return {Promise<Array<Document>>}
  84. */
  85. async function getNextBatch(
  86. collection,
  87. query,
  88. start,
  89. end,
  90. projection,
  91. findOptions
  92. ) {
  93. if (BATCH_DESCENDING) {
  94. query._id = {
  95. $gt: end,
  96. $lte: start,
  97. }
  98. } else {
  99. query._id = {
  100. $gt: start,
  101. $lte: end,
  102. }
  103. }
  104. return await collection
  105. .find(query, findOptions)
  106. .project(projection)
  107. .sort({ _id: BATCH_DESCENDING ? -1 : 1 })
  108. .limit(BATCH_SIZE)
  109. .toArray()
  110. }
  111. /**
  112. * @param {Collection | LegacyCollection} collection
  113. * @param {Array<Document>} nextBatch
  114. * @param {UpdateDocument} update
  115. * @return {Promise<void>}
  116. */
  117. async function performUpdate(collection, nextBatch, update) {
  118. await collection.updateMany(
  119. { _id: { $in: nextBatch.map(entry => entry._id) } },
  120. update
  121. )
  122. }
  123. /**
  124. * @param {string} input
  125. * @return {ObjectId}
  126. */
  127. function objectIdFromInput(input) {
  128. if (input.includes('T')) {
  129. const t = new Date(input).getTime()
  130. if (Number.isNaN(t)) throw new Error(`${input} is not a valid date`)
  131. return objectIdFromMs(t)
  132. } else {
  133. return new ObjectId(input)
  134. }
  135. }
  136. /**
  137. * @param {ObjectId} objectId
  138. * @return {string}
  139. */
  140. function renderObjectId(objectId) {
  141. return `${objectId} (${objectId.getTimestamp().toISOString()})`
  142. }
  143. /**
  144. * @param {number} ms
  145. * @return {ObjectId}
  146. */
  147. function objectIdFromMs(ms) {
  148. return ObjectId.createFromTime(ms / 1000)
  149. }
  150. /**
  151. * @param {ObjectId} id
  152. * @return {number}
  153. */
  154. function getMsFromObjectId(id) {
  155. return id.getTimestamp().getTime()
  156. }
  157. /**
  158. * @param {ObjectId} start
  159. * @return {ObjectId}
  160. */
  161. function getNextEnd(start) {
  162. let end
  163. if (BATCH_DESCENDING) {
  164. end = objectIdFromMs(getMsFromObjectId(start) - BATCH_MAX_TIME_SPAN_IN_MS)
  165. if (getMsFromObjectId(end) <= getMsFromObjectId(BATCH_RANGE_END)) {
  166. end = BATCH_RANGE_END
  167. }
  168. } else {
  169. end = objectIdFromMs(getMsFromObjectId(start) + BATCH_MAX_TIME_SPAN_IN_MS)
  170. if (getMsFromObjectId(end) >= getMsFromObjectId(BATCH_RANGE_END)) {
  171. end = BATCH_RANGE_END
  172. }
  173. }
  174. return end
  175. }
  176. /**
  177. * @param {Collection | LegacyCollection} collection
  178. * @return {Promise<ObjectId|null>}
  179. */
  180. async function getIdEdgePast(collection) {
  181. const [first] = await collection
  182. .find({})
  183. .project({ _id: 1 })
  184. .sort({ _id: 1 })
  185. .limit(1)
  186. .toArray()
  187. if (!first) return null
  188. // Go one second further into the past in order to include the first entry via
  189. // first._id > ID_EDGE_PAST
  190. return objectIdFromMs(Math.max(0, getMsFromObjectId(first._id) - 1000))
  191. }
  192. /**
  193. * @param {Collection | LegacyCollection} collection
  194. * @param {Document} query
  195. * @param {UpdateDocument | ((batch: Array<Document>) => Promise<void>)} update
  196. * @param {Document} [projection]
  197. * @param {FindOptions} [findOptions]
  198. * @param {BatchedUpdateOptions} [batchedUpdateOptions]
  199. */
  200. async function batchedUpdate(
  201. collection,
  202. query,
  203. update,
  204. projection,
  205. findOptions,
  206. batchedUpdateOptions = {}
  207. ) {
  208. // only a single batchedUpdate can run at a time due to global variables
  209. if (BATCHED_UPDATE_RUNNING) {
  210. throw new Error('batchedUpdate is already running')
  211. }
  212. try {
  213. BATCHED_UPDATE_RUNNING = true
  214. ID_EDGE_PAST = await getIdEdgePast(collection)
  215. if (!ID_EDGE_PAST) {
  216. console.warn(
  217. `The collection ${collection.collectionName} appears to be empty.`
  218. )
  219. return 0
  220. }
  221. refreshGlobalOptionsForBatchedUpdate(batchedUpdateOptions)
  222. const { trackProgress = async progress => console.warn(progress) } =
  223. batchedUpdateOptions
  224. findOptions = findOptions || {}
  225. findOptions.readPreference = READ_PREFERENCE_SECONDARY
  226. projection = projection || { _id: 1 }
  227. let nextBatch
  228. let updated = 0
  229. let start = BATCH_RANGE_START
  230. while (start !== BATCH_RANGE_END) {
  231. let end = getNextEnd(start)
  232. nextBatch = await getNextBatch(
  233. collection,
  234. query,
  235. start,
  236. end,
  237. projection,
  238. findOptions
  239. )
  240. if (nextBatch.length > 0) {
  241. end = nextBatch[nextBatch.length - 1]._id
  242. updated += nextBatch.length
  243. if (VERBOSE_LOGGING) {
  244. console.log(
  245. `Running update on batch with ids ${JSON.stringify(
  246. nextBatch.map(entry => entry._id)
  247. )}`
  248. )
  249. }
  250. await trackProgress(
  251. `Running update on batch ending ${renderObjectId(end)}`
  252. )
  253. if (typeof update === 'function') {
  254. await update(nextBatch)
  255. } else {
  256. await performUpdate(collection, nextBatch, update)
  257. }
  258. }
  259. await trackProgress(`Completed batch ending ${renderObjectId(end)}`)
  260. start = end
  261. }
  262. return updated
  263. } finally {
  264. BATCHED_UPDATE_RUNNING = false
  265. }
  266. }
  267. /**
  268. * @param {Collection | LegacyCollection} collection
  269. * @param {Document} query
  270. * @param {UpdateDocument | ((batch: Array<Object>) => Promise<void>)} update
  271. * @param {Document} [projection]
  272. * @param {FindOptions} [findOptions]
  273. * @param {BatchedUpdateOptions} [batchedUpdateOptions]
  274. */
  275. function batchedUpdateWithResultHandling(
  276. collection,
  277. query,
  278. update,
  279. projection,
  280. findOptions,
  281. batchedUpdateOptions
  282. ) {
  283. batchedUpdate(
  284. collection,
  285. query,
  286. update,
  287. projection,
  288. findOptions,
  289. batchedUpdateOptions
  290. )
  291. .then(processed => {
  292. console.error({ processed })
  293. process.exit(0)
  294. })
  295. .catch(error => {
  296. console.error({ error })
  297. process.exit(1)
  298. })
  299. }
  300. module.exports = {
  301. READ_PREFERENCE_SECONDARY,
  302. objectIdFromInput,
  303. renderObjectId,
  304. batchedUpdate,
  305. batchedUpdateWithResultHandling,
  306. }