batchedUpdate.mjs 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281
  1. // @ts-check
  2. import mongodb from 'mongodb-legacy'
  3. import {
  4. db,
  5. READ_PREFERENCE_SECONDARY,
  6. } from '../../app/src/infrastructure/mongodb.js'
  7. const { ObjectId } = mongodb
  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").Document} Document
  20. * @typedef {import("mongodb").FindOptions} FindOptions
  21. * @typedef {import("mongodb").UpdateFilter<Document>} UpdateDocument
  22. * @typedef {import("mongodb").ObjectId} ObjectId
  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 = new ObjectId(options.BATCH_LAST_ID)
  44. } else if (options.BATCH_RANGE_START) {
  45. BATCH_RANGE_START = new ObjectId(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 = new ObjectId(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} 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} 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 {number} ms
  116. * @return {ObjectId}
  117. */
  118. function objectIdFromMs(ms) {
  119. return ObjectId.createFromTime(ms / 1000)
  120. }
  121. /**
  122. * @param {ObjectId} id
  123. * @return {number}
  124. */
  125. function getMsFromObjectId(id) {
  126. return id.getTimestamp().getTime()
  127. }
  128. /**
  129. * @param {ObjectId} start
  130. * @return {ObjectId}
  131. */
  132. function getNextEnd(start) {
  133. let end
  134. if (BATCH_DESCENDING) {
  135. end = objectIdFromMs(getMsFromObjectId(start) - BATCH_MAX_TIME_SPAN_IN_MS)
  136. if (getMsFromObjectId(end) <= getMsFromObjectId(BATCH_RANGE_END)) {
  137. end = BATCH_RANGE_END
  138. }
  139. } else {
  140. end = objectIdFromMs(getMsFromObjectId(start) + BATCH_MAX_TIME_SPAN_IN_MS)
  141. if (getMsFromObjectId(end) >= getMsFromObjectId(BATCH_RANGE_END)) {
  142. end = BATCH_RANGE_END
  143. }
  144. }
  145. return end
  146. }
  147. /**
  148. * @param {Collection} collection
  149. * @return {Promise<ObjectId|null>}
  150. */
  151. async function getIdEdgePast(collection) {
  152. const [first] = await collection
  153. .find({})
  154. .project({ _id: 1 })
  155. .sort({ _id: 1 })
  156. .limit(1)
  157. .toArray()
  158. if (!first) return null
  159. // Go one second further into the past in order to include the first entry via
  160. // first._id > ID_EDGE_PAST
  161. return objectIdFromMs(Math.max(0, getMsFromObjectId(first._id) - 1000))
  162. }
  163. /**
  164. * @param {string} collectionName
  165. * @param {Document} query
  166. * @param {UpdateDocument | ((batch: Array<Document>) => Promise<void>)} update
  167. * @param {Document} [projection]
  168. * @param {FindOptions} [findOptions]
  169. * @param {BatchedUpdateOptions} [batchedUpdateOptions]
  170. */
  171. async function batchedUpdate(
  172. collectionName,
  173. query,
  174. update,
  175. projection,
  176. findOptions,
  177. batchedUpdateOptions
  178. ) {
  179. const collection = db[collectionName]
  180. ID_EDGE_PAST = await getIdEdgePast(collection)
  181. if (!ID_EDGE_PAST) {
  182. console.warn(`The collection ${collectionName} appears to be empty.`)
  183. return 0
  184. }
  185. refreshGlobalOptionsForBatchedUpdate(batchedUpdateOptions)
  186. findOptions = findOptions || {}
  187. findOptions.readPreference = READ_PREFERENCE_SECONDARY
  188. projection = projection || { _id: 1 }
  189. let nextBatch
  190. let updated = 0
  191. let start = BATCH_RANGE_START
  192. while (start !== BATCH_RANGE_END) {
  193. let end = getNextEnd(start)
  194. nextBatch = await getNextBatch(
  195. collection,
  196. query,
  197. start,
  198. end,
  199. projection,
  200. findOptions
  201. )
  202. if (nextBatch.length > 0) {
  203. end = nextBatch[nextBatch.length - 1]._id
  204. updated += nextBatch.length
  205. if (VERBOSE_LOGGING) {
  206. console.log(
  207. `Running update on batch with ids ${JSON.stringify(
  208. nextBatch.map(entry => entry._id)
  209. )}`
  210. )
  211. } else {
  212. console.error(`Running update on batch ending ${end}`)
  213. }
  214. if (typeof update === 'function') {
  215. await update(nextBatch)
  216. } else {
  217. await performUpdate(collection, nextBatch, update)
  218. }
  219. }
  220. console.error(`Completed batch ending ${end}`)
  221. start = end
  222. }
  223. return updated
  224. }
  225. /**
  226. * @param {string} collectionName
  227. * @param {Document} query
  228. * @param {UpdateDocument | ((batch: Array<Object>) => Promise<void>)} update
  229. * @param {Document} [projection]
  230. * @param {FindOptions} [findOptions]
  231. * @param {BatchedUpdateOptions} [batchedUpdateOptions]
  232. */
  233. function batchedUpdateWithResultHandling(
  234. collectionName,
  235. query,
  236. update,
  237. projection,
  238. findOptions,
  239. batchedUpdateOptions
  240. ) {
  241. batchedUpdate(
  242. collectionName,
  243. query,
  244. update,
  245. projection,
  246. findOptions,
  247. batchedUpdateOptions
  248. )
  249. .then(processed => {
  250. console.error({ processed })
  251. process.exit(0)
  252. })
  253. .catch(error => {
  254. console.error({ error })
  255. process.exit(1)
  256. })
  257. }
  258. export default {
  259. batchedUpdate,
  260. batchedUpdateWithResultHandling,
  261. }