batchedUpdate.mjs 4.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201
  1. import mongodb from 'mongodb-legacy'
  2. import {
  3. db,
  4. READ_PREFERENCE_SECONDARY,
  5. } from '../../app/src/infrastructure/mongodb.js'
  6. const { ObjectId } = 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. const collection = db[collectionName]
  118. ID_EDGE_PAST = await getIdEdgePast(collection)
  119. if (!ID_EDGE_PAST) {
  120. console.warn(`The collection ${collectionName} appears to be empty.`)
  121. return 0
  122. }
  123. refreshGlobalOptionsForBatchedUpdate(batchedUpdateOptions)
  124. findOptions = findOptions || {}
  125. findOptions.readPreference = READ_PREFERENCE_SECONDARY
  126. projection = projection || { _id: 1 }
  127. let nextBatch
  128. let updated = 0
  129. let start = BATCH_RANGE_START
  130. while (start !== BATCH_RANGE_END) {
  131. let end = getNextEnd(start)
  132. nextBatch = await getNextBatch({
  133. collection,
  134. query,
  135. start,
  136. end,
  137. projection,
  138. findOptions,
  139. })
  140. if (nextBatch.length > 0) {
  141. end = nextBatch[nextBatch.length - 1]._id
  142. updated += nextBatch.length
  143. if (VERBOSE_LOGGING) {
  144. console.log(
  145. `Running update on batch with ids ${JSON.stringify(
  146. nextBatch.map(entry => entry._id)
  147. )}`
  148. )
  149. } else {
  150. console.error(`Running update on batch ending ${end}`)
  151. }
  152. if (typeof update === 'function') {
  153. await update(nextBatch)
  154. } else {
  155. await performUpdate(collection, nextBatch, update)
  156. }
  157. }
  158. console.error(`Completed batch ending ${end}`)
  159. start = end
  160. }
  161. return updated
  162. }
  163. function batchedUpdateWithResultHandling(
  164. collection,
  165. query,
  166. update,
  167. projection,
  168. options
  169. ) {
  170. batchedUpdate(collection, query, update, projection, options)
  171. .then(processed => {
  172. console.error({ processed })
  173. process.exit(0)
  174. })
  175. .catch(error => {
  176. console.error({ error })
  177. process.exit(1)
  178. })
  179. }
  180. export default {
  181. batchedUpdate,
  182. batchedUpdateWithResultHandling,
  183. }