persist_changes.js 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171
  1. /** @module */
  2. 'use strict'
  3. const _ = require('lodash')
  4. const BPromise = require('bluebird')
  5. const core = require('overleaf-editor-core')
  6. const Chunk = core.Chunk
  7. const History = core.History
  8. const assert = require('./assert')
  9. const chunkStore = require('./chunk_store')
  10. function countChangeBytes(change) {
  11. // Note: This is not quite accurate, because the raw change may contain raw
  12. // file info (or conceivably even content) that will not be included in the
  13. // actual stored object.
  14. return Buffer.byteLength(JSON.stringify(change.toRaw()))
  15. }
  16. function totalChangeBytes(changes) {
  17. return changes.length ? _(changes).map(countChangeBytes).sum() : 0
  18. }
  19. // provide a simple timer function
  20. function Timer() {
  21. this.t0 = process.hrtime()
  22. }
  23. Timer.prototype.elapsed = function () {
  24. const dt = process.hrtime(this.t0)
  25. const timeInMilliseconds = (dt[0] + dt[1] * 1e-9) * 1e3
  26. return timeInMilliseconds
  27. }
  28. /**
  29. * Break the given set of changes into zero or more Chunks according to the
  30. * provided limits and store them.
  31. *
  32. * Some other possible improvements:
  33. * 1. This does a lot more JSON serialization than it has to. We may know the
  34. * JSON for the changes before we call this function, so we could in that
  35. * case get the byte size of each change without doing any work. Even if we
  36. * don't know it initially, we could save some computation by caching this
  37. * info rather than recomputing it many times. TBD whether it is worthwhile.
  38. * 2. We don't necessarily have to fetch the latest chunk in order to determine
  39. * that it is full. We could store this in the chunk metadata record. It may
  40. * be worth distinguishing between a Chunk and its metadata record. The
  41. * endVersion may be better suited to the metadata record.
  42. *
  43. * @param {string} projectId
  44. * @param {Array.<Change>} allChanges
  45. * @param {Object} limits
  46. * @param {number} clientEndVersion
  47. * @return {Promise.<Object?>}
  48. */
  49. module.exports = function persistChanges(
  50. projectId,
  51. allChanges,
  52. limits,
  53. clientEndVersion
  54. ) {
  55. assert.projectId(projectId)
  56. assert.array(allChanges)
  57. assert.maybe.object(limits)
  58. assert.integer(clientEndVersion)
  59. let currentChunk
  60. // currentSnapshot tracks the latest change that we're applying; we use it to
  61. // check that the changes we are persisting are valid.
  62. let currentSnapshot
  63. let originalEndVersion
  64. let changesToPersist
  65. limits = limits || {}
  66. _.defaults(limits, {
  67. changeBucketMinutes: 60,
  68. maxChanges: 2500,
  69. maxChangeBytes: 5 * 1024 * 1024,
  70. maxChunkChanges: 2000,
  71. maxChunkChangeBytes: 5 * 1024 * 1024,
  72. maxChunkChangeTime: 5000, // warn if total time for changes in a chunk takes longer than this
  73. })
  74. function checkElapsedTime(timer) {
  75. const timeTaken = timer.elapsed()
  76. if (timeTaken > limits.maxChunkChangeTime) {
  77. console.log('warning: slow chunk', projectId, timeTaken)
  78. }
  79. }
  80. function fillChunk(chunk, changes) {
  81. let totalBytes = totalChangeBytes(chunk.getChanges())
  82. let changesPushed = false
  83. while (changes.length > 0) {
  84. if (chunk.getChanges().length >= limits.maxChunkChanges) break
  85. const changeBytes = countChangeBytes(changes[0])
  86. if (totalBytes + changeBytes > limits.maxChunkChangeBytes) break
  87. const changesToFill = changes.splice(0, 1)
  88. currentSnapshot.applyAll(changesToFill, { strict: true })
  89. chunk.pushChanges(changesToFill)
  90. totalBytes += changeBytes
  91. changesPushed = true
  92. }
  93. return changesPushed
  94. }
  95. function extendLastChunkIfPossible() {
  96. return chunkStore.loadLatest(projectId).then(function (latestChunk) {
  97. currentChunk = latestChunk
  98. originalEndVersion = latestChunk.getEndVersion()
  99. if (originalEndVersion !== clientEndVersion) {
  100. throw new Chunk.ConflictingEndVersion(
  101. clientEndVersion,
  102. originalEndVersion
  103. )
  104. }
  105. currentSnapshot = latestChunk.getSnapshot().clone()
  106. const timer = new Timer()
  107. currentSnapshot.applyAll(latestChunk.getChanges())
  108. if (!fillChunk(currentChunk, changesToPersist)) return
  109. checkElapsedTime(timer)
  110. return chunkStore.update(projectId, originalEndVersion, currentChunk)
  111. })
  112. }
  113. function createNewChunksAsNeeded() {
  114. if (changesToPersist.length === 0) return
  115. const endVersion = currentChunk.getEndVersion()
  116. const history = new History(currentSnapshot.clone(), [])
  117. const chunk = new Chunk(history, endVersion)
  118. const timer = new Timer()
  119. if (fillChunk(chunk, changesToPersist)) {
  120. checkElapsedTime(timer)
  121. currentChunk = chunk
  122. return chunkStore.create(projectId, chunk).then(createNewChunksAsNeeded)
  123. }
  124. throw new Error('failed to fill empty chunk')
  125. }
  126. function isOlderThanMinChangeTimestamp(change) {
  127. return change.getTimestamp().getTime() < limits.minChangeTimestamp
  128. }
  129. function isOlderThanMaxChangeTimestamp(change) {
  130. return change.getTimestamp().getTime() < limits.maxChangeTimestamp
  131. }
  132. const oldChanges = _.filter(allChanges, isOlderThanMinChangeTimestamp)
  133. const anyTooOld = _.some(oldChanges, isOlderThanMaxChangeTimestamp)
  134. const tooManyChanges = oldChanges.length > limits.maxChanges
  135. const tooManyBytes = totalChangeBytes(oldChanges) > limits.maxChangeBytes
  136. if (anyTooOld || tooManyChanges || tooManyBytes) {
  137. changesToPersist = oldChanges
  138. const numberOfChangesToPersist = oldChanges.length
  139. return extendLastChunkIfPossible()
  140. .then(createNewChunksAsNeeded)
  141. .then(function () {
  142. return {
  143. numberOfChangesPersisted: numberOfChangesToPersist,
  144. originalEndVersion,
  145. currentChunk,
  146. }
  147. })
  148. }
  149. return BPromise.resolve(null)
  150. }