persist_changes.js 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265
  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. let resyncNeeded = false
  71. limits = limits || {}
  72. _.defaults(limits, {
  73. changeBucketMinutes: 60,
  74. maxChanges: 2500,
  75. maxChangeBytes: 5 * 1024 * 1024,
  76. maxChunkChanges: 2000,
  77. maxChunkChangeBytes: 5 * 1024 * 1024,
  78. maxChunkChangeTime: 5000, // warn if total time for changes in a chunk takes longer than this
  79. })
  80. function checkElapsedTime(timer) {
  81. const timeTaken = timer.elapsed()
  82. if (timeTaken > limits.maxChunkChangeTime) {
  83. console.log('warning: slow chunk', projectId, timeTaken)
  84. }
  85. }
  86. /**
  87. * Add changes to a chunk until the chunk is full
  88. *
  89. * The chunk is full if it reaches a certain number of changes or a certain
  90. * size in bytes
  91. *
  92. * @param {core.Chunk} chunk
  93. * @param {core.Change[]} changes
  94. */
  95. async function fillChunk(chunk, changes) {
  96. let totalBytes = totalChangeBytes(chunk.getChanges())
  97. let changesPushed = false
  98. while (changes.length > 0) {
  99. if (chunk.getChanges().length >= limits.maxChunkChanges) {
  100. break
  101. }
  102. const change = changes[0]
  103. const changeBytes = countChangeBytes(change)
  104. if (totalBytes + changeBytes > limits.maxChunkChangeBytes) {
  105. break
  106. }
  107. for (const operation of change.iterativelyApplyTo(currentSnapshot, {
  108. strict: true,
  109. })) {
  110. await validateContentHash(operation)
  111. }
  112. chunk.pushChanges([change])
  113. changes.shift()
  114. totalBytes += changeBytes
  115. changesPushed = true
  116. }
  117. return changesPushed
  118. }
  119. /**
  120. * Check that the operation is valid and can be incorporated to the history.
  121. *
  122. * For now, this checks content hashes when they are provided.
  123. *
  124. * @param {core.Operation} operation
  125. */
  126. async function validateContentHash(operation) {
  127. if (operation instanceof core.EditFileOperation) {
  128. const editOperation = operation.getOperation()
  129. if (
  130. editOperation instanceof core.TextOperation &&
  131. editOperation.contentHash != null
  132. ) {
  133. const path = operation.getPathname()
  134. const file = currentSnapshot.getFile(path)
  135. if (file == null) {
  136. throw new InvalidChangeError('file not found for hash validation', {
  137. projectId,
  138. path,
  139. })
  140. }
  141. await file.load('eager', blobStore)
  142. const content = file.getContent({ filterTrackedDeletes: true })
  143. const expectedHash = editOperation.contentHash
  144. const actualHash = content != null ? getContentHash(content) : null
  145. logger.debug({ expectedHash, actualHash }, 'validating content hash')
  146. if (actualHash !== expectedHash) {
  147. // only log a warning on the first mismatch in each persistChanges call
  148. if (!resyncNeeded) {
  149. logger.warn(
  150. { projectId, path, expectedHash, actualHash },
  151. 'content hash mismatch'
  152. )
  153. }
  154. resyncNeeded = true
  155. }
  156. // Remove the content hash from the change before storing it in the chunk.
  157. // It was only useful for validation.
  158. editOperation.contentHash = null
  159. }
  160. }
  161. }
  162. async function loadLatestChunk() {
  163. const latestChunk = await chunkStore.loadLatest(projectId, {
  164. persistedOnly: true,
  165. })
  166. currentChunk = latestChunk
  167. originalEndVersion = latestChunk.getEndVersion()
  168. if (originalEndVersion !== clientEndVersion) {
  169. throw new Chunk.ConflictingEndVersion(
  170. clientEndVersion,
  171. originalEndVersion
  172. )
  173. }
  174. currentSnapshot = latestChunk.getSnapshot().clone()
  175. currentSnapshot.applyAll(currentChunk.getChanges())
  176. }
  177. async function extendLastChunkIfPossible() {
  178. const timer = new Timer()
  179. const changesPushed = await fillChunk(currentChunk, changesToPersist)
  180. if (!changesPushed) {
  181. return
  182. }
  183. checkElapsedTime(timer)
  184. await chunkStore.update(projectId, currentChunk, earliestChangeTimestamp)
  185. }
  186. async function createNewChunksAsNeeded() {
  187. while (changesToPersist.length > 0) {
  188. const endVersion = currentChunk.getEndVersion()
  189. const history = new History(currentSnapshot.clone(), [])
  190. const chunk = new Chunk(history, endVersion)
  191. const timer = new Timer()
  192. const changesPushed = await fillChunk(chunk, changesToPersist)
  193. if (changesPushed) {
  194. checkElapsedTime(timer)
  195. currentChunk = chunk
  196. await chunkStore.create(projectId, chunk, earliestChangeTimestamp)
  197. } else {
  198. throw new Error('failed to fill empty chunk')
  199. }
  200. }
  201. }
  202. function isOlderThanMinChangeTimestamp(change) {
  203. return change.getTimestamp().getTime() < limits.minChangeTimestamp
  204. }
  205. function isOlderThanMaxChangeTimestamp(change) {
  206. return change.getTimestamp().getTime() < limits.maxChangeTimestamp
  207. }
  208. const oldChanges = _.filter(allChanges, isOlderThanMinChangeTimestamp)
  209. const anyTooOld = _.some(oldChanges, isOlderThanMaxChangeTimestamp)
  210. const tooManyChanges = oldChanges.length > limits.maxChanges
  211. const tooManyBytes = totalChangeBytes(oldChanges) > limits.maxChangeBytes
  212. if (anyTooOld || tooManyChanges || tooManyBytes) {
  213. changesToPersist = oldChanges
  214. const numberOfChangesToPersist = oldChanges.length
  215. await loadLatestChunk()
  216. await extendLastChunkIfPossible()
  217. await createNewChunksAsNeeded()
  218. return {
  219. numberOfChangesPersisted: numberOfChangesToPersist,
  220. originalEndVersion,
  221. currentChunk,
  222. resyncNeeded,
  223. }
  224. } else {
  225. return null
  226. }
  227. }
  228. module.exports = persistChanges