batchedUpdate.js 4.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201
  1. const { ObjectId } = require('mongodb')
  2. const {
  3. db,
  4. waitForDb,
  5. READ_PREFERENCE_SECONDARY,
  6. } = require('../../app/src/infrastructure/mongodb')
  7. const ONE_MONTH_IN_MS = 1000 * 60 * 60 * 24 * 31
  8. let ID_EDGE_PAST
  9. const ID_EDGE_FUTURE = objectIdFromMs(Date.now() + 1000)
  10. let BATCH_DESCENDING
  11. let BATCH_SIZE
  12. let VERBOSE_LOGGING
  13. let BATCH_RANGE_START
  14. let BATCH_RANGE_END
  15. let BATCH_MAX_TIME_SPAN_IN_MS
  16. function refreshGlobalOptionsForBatchedUpdate(options = {}) {
  17. options = Object.assign({}, options, process.env)
  18. BATCH_DESCENDING = options.BATCH_DESCENDING === 'true'
  19. BATCH_SIZE = parseInt(options.BATCH_SIZE, 10) || 1000
  20. VERBOSE_LOGGING = options.VERBOSE_LOGGING === 'true'
  21. if (options.BATCH_LAST_ID) {
  22. BATCH_RANGE_START = new ObjectId(options.BATCH_LAST_ID)
  23. } else if (options.BATCH_RANGE_START) {
  24. BATCH_RANGE_START = new ObjectId(options.BATCH_RANGE_START)
  25. } else {
  26. if (BATCH_DESCENDING) {
  27. BATCH_RANGE_START = ID_EDGE_FUTURE
  28. } else {
  29. BATCH_RANGE_START = ID_EDGE_PAST
  30. }
  31. }
  32. BATCH_MAX_TIME_SPAN_IN_MS =
  33. parseInt(options.BATCH_MAX_TIME_SPAN_IN_MS, 10) || ONE_MONTH_IN_MS
  34. if (options.BATCH_RANGE_END) {
  35. BATCH_RANGE_END = new ObjectId(options.BATCH_RANGE_END)
  36. } else {
  37. if (BATCH_DESCENDING) {
  38. BATCH_RANGE_END = ID_EDGE_PAST
  39. } else {
  40. BATCH_RANGE_END = ID_EDGE_FUTURE
  41. }
  42. }
  43. }
  44. async function getNextBatch({
  45. collection,
  46. query,
  47. start,
  48. end,
  49. projection,
  50. findOptions,
  51. }) {
  52. if (BATCH_DESCENDING) {
  53. query._id = {
  54. $gt: end,
  55. $lt: start,
  56. }
  57. } else {
  58. query._id = {
  59. $gt: start,
  60. $lt: end,
  61. }
  62. }
  63. return await collection
  64. .find(query, findOptions)
  65. .project(projection)
  66. .sort({ _id: BATCH_DESCENDING ? -1 : 1 })
  67. .limit(BATCH_SIZE)
  68. .toArray()
  69. }
  70. async function performUpdate(collection, nextBatch, update) {
  71. return collection.updateMany(
  72. { _id: { $in: nextBatch.map(entry => entry._id) } },
  73. update
  74. )
  75. }
  76. function objectIdFromMs(ms) {
  77. return ObjectId.createFromTime(ms / 1000)
  78. }
  79. function getMsFromObjectId(id) {
  80. return id.getTimestamp().getTime()
  81. }
  82. function getNextEnd(start) {
  83. let end
  84. if (BATCH_DESCENDING) {
  85. end = objectIdFromMs(getMsFromObjectId(start) - BATCH_MAX_TIME_SPAN_IN_MS)
  86. if (getMsFromObjectId(end) <= getMsFromObjectId(BATCH_RANGE_END)) {
  87. end = BATCH_RANGE_END
  88. }
  89. } else {
  90. end = objectIdFromMs(getMsFromObjectId(start) + BATCH_MAX_TIME_SPAN_IN_MS)
  91. if (getMsFromObjectId(end) >= getMsFromObjectId(BATCH_RANGE_END)) {
  92. end = BATCH_RANGE_END
  93. }
  94. }
  95. return end
  96. }
  97. async function getIdEdgePast(collection) {
  98. const [first] = await collection
  99. .find({})
  100. .project({ _id: 1 })
  101. .sort({ _id: 1 })
  102. .limit(1)
  103. .toArray()
  104. if (!first) return null
  105. // Go 1s further into the past in order to include the first entry via
  106. // first._id > ID_EDGE_PAST
  107. return objectIdFromMs(Math.max(0, getMsFromObjectId(first._id) - 1000))
  108. }
  109. async function batchedUpdate(
  110. collectionName,
  111. query,
  112. update,
  113. projection,
  114. findOptions,
  115. batchedUpdateOptions
  116. ) {
  117. await waitForDb()
  118. const collection = db[collectionName]
  119. ID_EDGE_PAST = await getIdEdgePast(collection)
  120. if (!ID_EDGE_PAST) {
  121. console.warn(`The collection ${collectionName} appears to be empty.`)
  122. return 0
  123. }
  124. refreshGlobalOptionsForBatchedUpdate(batchedUpdateOptions)
  125. findOptions = findOptions || {}
  126. findOptions.readPreference = READ_PREFERENCE_SECONDARY
  127. projection = projection || { _id: 1 }
  128. let nextBatch
  129. let updated = 0
  130. let start = BATCH_RANGE_START
  131. while (start !== BATCH_RANGE_END) {
  132. let end = getNextEnd(start)
  133. nextBatch = await getNextBatch({
  134. collection,
  135. query,
  136. start,
  137. end,
  138. projection,
  139. findOptions,
  140. })
  141. if (nextBatch.length > 0) {
  142. end = nextBatch[nextBatch.length - 1]._id
  143. updated += nextBatch.length
  144. if (VERBOSE_LOGGING) {
  145. console.log(
  146. `Running update on batch with ids ${JSON.stringify(
  147. nextBatch.map(entry => entry._id)
  148. )}`
  149. )
  150. } else {
  151. console.error(`Running update on batch ending ${end}`)
  152. }
  153. if (typeof update === 'function') {
  154. await update(nextBatch)
  155. } else {
  156. await performUpdate(collection, nextBatch, update)
  157. }
  158. }
  159. console.error(`Completed batch ending ${end}`)
  160. start = end
  161. }
  162. return updated
  163. }
  164. function batchedUpdateWithResultHandling(
  165. collection,
  166. query,
  167. update,
  168. projection,
  169. options
  170. ) {
  171. batchedUpdate(collection, query, update, projection, options)
  172. .then(processed => {
  173. console.error({ processed })
  174. process.exit(0)
  175. })
  176. .catch(error => {
  177. console.error({ error })
  178. process.exit(1)
  179. })
  180. }
  181. module.exports = {
  182. batchedUpdate,
  183. batchedUpdateWithResultHandling,
  184. }