persist_changes.js 8.1 KB

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