mongo.js 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270
  1. const { ObjectId } = require('mongodb')
  2. const { Chunk } = require('overleaf-editor-core')
  3. const OError = require('@overleaf/o-error')
  4. const assert = require('../assert')
  5. const mongodb = require('../mongodb')
  6. const { ChunkVersionConflictError } = require('./errors')
  7. const DUPLICATE_KEY_ERROR_CODE = 11000
  8. /**
  9. * Get the latest chunk's metadata from the database
  10. */
  11. async function getLatestChunk(projectId) {
  12. assert.mongoId(projectId, 'bad projectId')
  13. const record = await mongodb.chunks.findOne(
  14. { projectId: ObjectId(projectId), state: 'active' },
  15. { sort: { startVersion: -1 } }
  16. )
  17. if (record == null) {
  18. return null
  19. }
  20. return chunkFromRecord(record)
  21. }
  22. /**
  23. * Get the metadata for the chunk that contains the given version.
  24. */
  25. async function getChunkForVersion(projectId, version) {
  26. assert.mongoId(projectId, 'bad projectId')
  27. assert.integer(version, 'bad version')
  28. const record = await mongodb.chunks.findOne(
  29. {
  30. projectId: ObjectId(projectId),
  31. state: 'active',
  32. startVersion: { $lte: version },
  33. endVersion: { $gte: version },
  34. },
  35. { sort: { startVersion: 1 } }
  36. )
  37. if (record == null) {
  38. throw new Chunk.VersionNotFoundError(projectId, version)
  39. }
  40. return chunkFromRecord(record)
  41. }
  42. /**
  43. * Get the metadata for the chunk that contains the version that was current at
  44. * the given timestamp.
  45. */
  46. async function getChunkForTimestamp(projectId, timestamp) {
  47. assert.mongoId(projectId, 'bad projectId')
  48. assert.date(timestamp, 'bad timestamp')
  49. const record = await mongodb.chunks.findOne(
  50. {
  51. projectId: ObjectId(projectId),
  52. state: 'active',
  53. endTimestamp: { $gte: timestamp },
  54. },
  55. // We use the index on the startVersion for sorting records. This assumes
  56. // that timestamps go up with each version.
  57. { sort: { startVersion: 1 } }
  58. )
  59. if (record == null) {
  60. // Couldn't find a chunk that had modifications after the given timestamp.
  61. // Fetch the latest chunk instead.
  62. const chunk = await getLatestChunk(projectId)
  63. if (chunk == null) {
  64. throw new Chunk.BeforeTimestampNotFoundError(projectId, timestamp)
  65. }
  66. return chunk
  67. }
  68. return chunkFromRecord(record)
  69. }
  70. /**
  71. * Get all of a project's chunk ids
  72. */
  73. async function getProjectChunkIds(projectId) {
  74. assert.mongoId(projectId, 'bad projectId')
  75. const cursor = mongodb.chunks.find(
  76. { projectId: ObjectId(projectId), state: 'active' },
  77. { projection: { _id: 1 } }
  78. )
  79. return await cursor.map(record => record._id).toArray()
  80. }
  81. /**
  82. * Insert a pending chunk before sending it to object storage.
  83. */
  84. async function insertPendingChunk(projectId, chunk) {
  85. assert.mongoId(projectId, 'bad projectId')
  86. assert.instance(chunk, Chunk, 'bad chunk')
  87. const chunkId = new ObjectId()
  88. await mongodb.chunks.insertOne({
  89. _id: chunkId,
  90. projectId: ObjectId(projectId),
  91. startVersion: chunk.getStartVersion(),
  92. endVersion: chunk.getEndVersion(),
  93. endTimestamp: chunk.getEndTimestamp(),
  94. state: 'pending',
  95. updatedAt: new Date(),
  96. })
  97. return chunkId.toString()
  98. }
  99. /**
  100. * Record that a new chunk was created.
  101. */
  102. async function confirmCreate(projectId, chunk, chunkId, mongoOpts = {}) {
  103. assert.mongoId(projectId, 'bad projectId')
  104. assert.instance(chunk, Chunk, 'bad chunk')
  105. assert.mongoId(chunkId, 'bad chunkId')
  106. let result
  107. try {
  108. result = await mongodb.chunks.updateOne(
  109. {
  110. _id: ObjectId(chunkId),
  111. projectId: ObjectId(projectId),
  112. state: 'pending',
  113. },
  114. { $set: { state: 'active', updatedAt: new Date() } },
  115. mongoOpts
  116. )
  117. } catch (err) {
  118. if (err.code === DUPLICATE_KEY_ERROR_CODE) {
  119. throw new ChunkVersionConflictError('chunk start version is not unique', {
  120. projectId,
  121. chunkId,
  122. })
  123. } else {
  124. throw err
  125. }
  126. }
  127. if (result.matchedCount === 0) {
  128. throw new OError('pending chunk not found', { projectId, chunkId })
  129. }
  130. }
  131. /**
  132. * Record that a chunk was replaced by a new one.
  133. */
  134. async function confirmUpdate(projectId, oldChunkId, newChunk, newChunkId) {
  135. assert.mongoId(projectId, 'bad projectId')
  136. assert.mongoId(oldChunkId, 'bad oldChunkId')
  137. assert.instance(newChunk, Chunk, 'bad newChunk')
  138. assert.mongoId(newChunkId, 'bad newChunkId')
  139. const session = mongodb.client.startSession()
  140. try {
  141. await session.withTransaction(async () => {
  142. await deleteChunk(projectId, oldChunkId, { session })
  143. await confirmCreate(projectId, newChunk, newChunkId, { session })
  144. })
  145. } finally {
  146. await session.endSession()
  147. }
  148. }
  149. /**
  150. * Delete a chunk.
  151. *
  152. * @param {number} projectId
  153. * @param {number} chunkId
  154. * @return {Promise}
  155. */
  156. async function deleteChunk(projectId, chunkId, mongoOpts = {}) {
  157. assert.mongoId(projectId, 'bad projectId')
  158. assert.mongoId(chunkId, 'bad chunkId')
  159. await mongodb.chunks.updateOne(
  160. { _id: ObjectId(chunkId), projectId: ObjectId(projectId) },
  161. { $set: { state: 'deleted', updatedAt: new Date() } },
  162. mongoOpts
  163. )
  164. }
  165. /**
  166. * Delete all of a project's chunks
  167. */
  168. async function deleteProjectChunks(projectId) {
  169. assert.mongoId(projectId, 'bad projectId')
  170. await mongodb.chunks.updateMany(
  171. { projectId: ObjectId(projectId), state: 'active' },
  172. { $set: { state: 'deleted', updatedAt: new Date() } }
  173. )
  174. }
  175. /**
  176. * Get a batch of old chunks for deletion
  177. */
  178. async function getOldChunksBatch(count, minAgeSecs) {
  179. const maxUpdatedAt = new Date(Date.now() - minAgeSecs * 1000)
  180. const batch = []
  181. // We need to fetch one state at a time to take advantage of the partial
  182. // indexes on the chunks collection.
  183. //
  184. // Mongo 6.0 allows partial indexes that use the $in operator. When we reach
  185. // that Mongo version, we can create a partial index on both the deleted and
  186. // pending states and simplify this logic a bit.
  187. for (const state of ['deleted', 'pending']) {
  188. if (count === 0) {
  189. // There's no more space in the batch
  190. break
  191. }
  192. const cursor = mongodb.chunks
  193. .find(
  194. { state, updatedAt: { $lt: maxUpdatedAt } },
  195. {
  196. limit: count,
  197. projection: { _id: 1, projectId: 1 },
  198. }
  199. )
  200. .map(record => ({
  201. chunkId: record._id.toString(),
  202. projectId: record.projectId.toString(),
  203. }))
  204. for await (const record of cursor) {
  205. batch.push(record)
  206. count -= 1
  207. }
  208. }
  209. return batch
  210. }
  211. /**
  212. * Delete a batch of old chunks from the database
  213. */
  214. async function deleteOldChunks(chunkIds) {
  215. await mongodb.chunks.deleteMany({
  216. _id: { $in: chunkIds.map(ObjectId) },
  217. state: { $in: ['deleted', 'pending'] },
  218. })
  219. }
  220. /**
  221. * Build a chunk metadata object from the database record
  222. */
  223. function chunkFromRecord(record) {
  224. return {
  225. id: record._id.toString(),
  226. startVersion: record.startVersion,
  227. endVersion: record.endVersion,
  228. }
  229. }
  230. module.exports = {
  231. getLatestChunk,
  232. getChunkForVersion,
  233. getChunkForTimestamp,
  234. getProjectChunkIds,
  235. insertPendingChunk,
  236. confirmCreate,
  237. confirmUpdate,
  238. deleteChunk,
  239. deleteProjectChunks,
  240. getOldChunksBatch,
  241. deleteOldChunks,
  242. }