persist_changes.js 10.0 KB

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