persist_changes.js 8.3 KB

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