persist_changes.js 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261
  1. // @ts-check
  2. 'use strict'
  3. const _ = require('lodash')
  4. const logger = require('@overleaf/logger')
  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. const { BlobStore } = require('./blob_store')
  11. const { InvalidChangeError } = require('./errors')
  12. const { getContentHash } = require('./content_hash')
  13. function countChangeBytes(change) {
  14. // Note: This is not quite accurate, because the raw change may contain raw
  15. // file info (or conceivably even content) that will not be included in the
  16. // actual stored object.
  17. return Buffer.byteLength(JSON.stringify(change.toRaw()))
  18. }
  19. function totalChangeBytes(changes) {
  20. return changes.length ? _(changes).map(countChangeBytes).sum() : 0
  21. }
  22. // provide a simple timer function
  23. function Timer() {
  24. this.t0 = process.hrtime()
  25. }
  26. Timer.prototype.elapsed = function () {
  27. const dt = process.hrtime(this.t0)
  28. const timeInMilliseconds = (dt[0] + dt[1] * 1e-9) * 1e3
  29. return timeInMilliseconds
  30. }
  31. /**
  32. * Break the given set of changes into zero or more Chunks according to the
  33. * provided limits and store them.
  34. *
  35. * Some other possible improvements:
  36. * 1. This does a lot more JSON serialization than it has to. We may know the
  37. * JSON for the changes before we call this function, so we could in that
  38. * case get the byte size of each change without doing any work. Even if we
  39. * don't know it initially, we could save some computation by caching this
  40. * info rather than recomputing it many times. TBD whether it is worthwhile.
  41. * 2. We don't necessarily have to fetch the latest chunk in order to determine
  42. * that it is full. We could store this in the chunk metadata record. It may
  43. * be worth distinguishing between a Chunk and its metadata record. The
  44. * endVersion may be better suited to the metadata record.
  45. *
  46. * @param {string} projectId
  47. * @param {core.Change[]} allChanges
  48. * @param {Object} limits
  49. * @param {number} clientEndVersion
  50. * @return {Promise.<Object?>}
  51. */
  52. async function persistChanges(projectId, allChanges, limits, clientEndVersion) {
  53. assert.projectId(projectId)
  54. assert.array(allChanges)
  55. assert.maybe.object(limits)
  56. assert.integer(clientEndVersion)
  57. const blobStore = new BlobStore(projectId)
  58. const earliestChangeTimestamp =
  59. allChanges.length > 0 ? allChanges[0].getTimestamp() : null
  60. let currentChunk
  61. /**
  62. * currentSnapshot tracks the latest change that we're applying; we use it to
  63. * check that the changes we are persisting are valid.
  64. *
  65. * @type {core.Snapshot}
  66. */
  67. let currentSnapshot
  68. let originalEndVersion
  69. let changesToPersist
  70. limits = limits || {}
  71. _.defaults(limits, {
  72. changeBucketMinutes: 60,
  73. maxChanges: 2500,
  74. maxChangeBytes: 5 * 1024 * 1024,
  75. maxChunkChanges: 2000,
  76. maxChunkChangeBytes: 5 * 1024 * 1024,
  77. maxChunkChangeTime: 5000, // warn if total time for changes in a chunk takes longer than this
  78. })
  79. function checkElapsedTime(timer) {
  80. const timeTaken = timer.elapsed()
  81. if (timeTaken > limits.maxChunkChangeTime) {
  82. console.log('warning: slow chunk', projectId, timeTaken)
  83. }
  84. }
  85. /**
  86. * Add changes to a chunk until the chunk is full
  87. *
  88. * The chunk is full if it reaches a certain number of changes or a certain
  89. * size in bytes
  90. *
  91. * @param {core.Chunk} chunk
  92. * @param {core.Change[]} changes
  93. */
  94. async function fillChunk(chunk, changes) {
  95. let totalBytes = totalChangeBytes(chunk.getChanges())
  96. let changesPushed = false
  97. while (changes.length > 0) {
  98. if (chunk.getChanges().length >= limits.maxChunkChanges) {
  99. break
  100. }
  101. const change = changes[0]
  102. const changeBytes = countChangeBytes(change)
  103. if (totalBytes + changeBytes > limits.maxChunkChangeBytes) {
  104. break
  105. }
  106. for (const operation of change.iterativelyApplyTo(currentSnapshot, {
  107. strict: true,
  108. })) {
  109. await validateContentHash(operation)
  110. }
  111. chunk.pushChanges([change])
  112. changes.shift()
  113. totalBytes += changeBytes
  114. changesPushed = true
  115. }
  116. return changesPushed
  117. }
  118. /**
  119. * Check that the operation is valid and can be incorporated to the history.
  120. *
  121. * For now, this checks content hashes when they are provided.
  122. *
  123. * @param {core.Operation} operation
  124. */
  125. async function validateContentHash(operation) {
  126. if (operation instanceof core.EditFileOperation) {
  127. const editOperation = operation.getOperation()
  128. if (
  129. editOperation instanceof core.TextOperation &&
  130. editOperation.contentHash != null
  131. ) {
  132. const path = operation.getPathname()
  133. const file = currentSnapshot.getFile(path)
  134. if (file == null) {
  135. throw new InvalidChangeError('file not found for hash validation', {
  136. projectId,
  137. path,
  138. })
  139. }
  140. await file.load('eager', blobStore)
  141. const content = file.getContent({ filterTrackedDeletes: true })
  142. const expectedHash = editOperation.contentHash
  143. const actualHash = content != null ? getContentHash(content) : null
  144. logger.debug({ expectedHash, actualHash }, 'validating content hash')
  145. if (actualHash !== expectedHash) {
  146. throw new InvalidChangeError('content hash mismatch', {
  147. projectId,
  148. path,
  149. expectedHash,
  150. actualHash,
  151. })
  152. }
  153. // Remove the content hash from the change before storing it in the chunk.
  154. // It was only useful for validation.
  155. editOperation.contentHash = null
  156. }
  157. }
  158. }
  159. async function extendLastChunkIfPossible() {
  160. const latestChunk = await chunkStore.loadLatest(projectId)
  161. currentChunk = latestChunk
  162. originalEndVersion = latestChunk.getEndVersion()
  163. if (originalEndVersion !== clientEndVersion) {
  164. throw new Chunk.ConflictingEndVersion(
  165. clientEndVersion,
  166. originalEndVersion
  167. )
  168. }
  169. currentSnapshot = latestChunk.getSnapshot().clone()
  170. const timer = new Timer()
  171. currentSnapshot.applyAll(latestChunk.getChanges())
  172. const changesPushed = await fillChunk(currentChunk, changesToPersist)
  173. if (!changesPushed) {
  174. return
  175. }
  176. checkElapsedTime(timer)
  177. await chunkStore.update(
  178. projectId,
  179. originalEndVersion,
  180. currentChunk,
  181. earliestChangeTimestamp
  182. )
  183. }
  184. async function createNewChunksAsNeeded() {
  185. while (changesToPersist.length > 0) {
  186. const endVersion = currentChunk.getEndVersion()
  187. const history = new History(currentSnapshot.clone(), [])
  188. const chunk = new Chunk(history, endVersion)
  189. const timer = new Timer()
  190. const changesPushed = await fillChunk(chunk, changesToPersist)
  191. if (changesPushed) {
  192. checkElapsedTime(timer)
  193. currentChunk = chunk
  194. await chunkStore.create(projectId, chunk, earliestChangeTimestamp)
  195. } else {
  196. throw new Error('failed to fill empty chunk')
  197. }
  198. }
  199. }
  200. function isOlderThanMinChangeTimestamp(change) {
  201. return change.getTimestamp().getTime() < limits.minChangeTimestamp
  202. }
  203. function isOlderThanMaxChangeTimestamp(change) {
  204. return change.getTimestamp().getTime() < limits.maxChangeTimestamp
  205. }
  206. const oldChanges = _.filter(allChanges, isOlderThanMinChangeTimestamp)
  207. const anyTooOld = _.some(oldChanges, isOlderThanMaxChangeTimestamp)
  208. const tooManyChanges = oldChanges.length > limits.maxChanges
  209. const tooManyBytes = totalChangeBytes(oldChanges) > limits.maxChangeBytes
  210. if (anyTooOld || tooManyChanges || tooManyBytes) {
  211. changesToPersist = oldChanges
  212. const numberOfChangesToPersist = oldChanges.length
  213. await extendLastChunkIfPossible()
  214. await createNewChunksAsNeeded()
  215. return {
  216. numberOfChangesPersisted: numberOfChangesToPersist,
  217. originalEndVersion,
  218. currentChunk,
  219. }
  220. } else {
  221. return null
  222. }
  223. }
  224. module.exports = persistChanges