batchedUpdate.js 7.4 KB

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