commit_changes.js 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172
  1. // @ts-check
  2. 'use strict'
  3. const metrics = require('@overleaf/metrics')
  4. const redisBackend = require('./chunk_store/redis')
  5. const logger = require('@overleaf/logger')
  6. const queueChanges = require('./queue_changes')
  7. const persistChanges = require('./persist_changes')
  8. const persistBuffer = require('./persist_buffer')
  9. /**
  10. * @typedef {import('overleaf-editor-core').Change} Change
  11. */
  12. /**
  13. * Handle incoming changes by processing them according to the specified options.
  14. * @param {string} projectId
  15. * @param {Change[]} changes
  16. * @param {Object} limits
  17. * @param {number} endVersion
  18. * @param {Object} options
  19. * @param {number} [options.historyBufferLevel] - The history buffer level to use for processing changes.
  20. * @param {Boolean} [options.forcePersistBuffer] - If true, forces the buffer to be persisted before any operation.
  21. * @return {Promise.<Object?>}
  22. */
  23. async function commitChanges(
  24. projectId,
  25. changes,
  26. limits,
  27. endVersion,
  28. options = {}
  29. ) {
  30. const { historyBufferLevel, forcePersistBuffer } = options
  31. // Force the buffer to be persisted if specified.
  32. if (forcePersistBuffer) {
  33. try {
  34. const status = await redisBackend.expireProject(projectId) // clear the project from Redis if it is persisted, returns 'not-persisted' if it was not persisted
  35. if (status === 'not-persisted') {
  36. await persistBuffer(projectId, limits)
  37. await redisBackend.expireProject(projectId) // clear the project from Redis after persisting
  38. metrics.inc('persist_buffer_force', 1, { status: 'persisted' })
  39. }
  40. } catch (err) {
  41. metrics.inc('persist_buffer_force', 1, { status: 'error' })
  42. logger.error(
  43. { err, projectId },
  44. 'failed to persist buffer before committing changes'
  45. )
  46. }
  47. }
  48. metrics.inc('commit_changes', 1, {
  49. history_buffer_level: historyBufferLevel || 0,
  50. })
  51. // Now handle the changes based on the configured history buffer level.
  52. switch (historyBufferLevel) {
  53. case 4: // Queue changes and only persist them in the background
  54. await queueChanges(projectId, changes, endVersion)
  55. return {}
  56. case 3: // Queue changes and immediately persist with persistBuffer
  57. await queueChanges(projectId, changes, endVersion)
  58. return await persistBuffer(projectId, limits)
  59. case 2: // Equivalent to queueChangesInRedis:true
  60. await queueChangesFake(projectId, changes, limits, endVersion)
  61. return await persistChanges(projectId, changes, limits, endVersion)
  62. case 1: // Queue changes with fake persist only for projects in redis already
  63. await queueChangesFakeOnlyIfExists(projectId, changes, limits, endVersion)
  64. return await persistChanges(projectId, changes, limits, endVersion)
  65. case 0: // Persist changes directly to the chunk store
  66. return await persistChanges(projectId, changes, limits, endVersion)
  67. default:
  68. throw new Error(`Invalid history buffer level: ${historyBufferLevel}`)
  69. }
  70. }
  71. /**
  72. * Queues a set of changes in redis as if they had been persisted, ignoring any errors.
  73. * @param {string} projectId
  74. * @param {Change[]} changes
  75. * @param {Object} limits
  76. * @param {number} endVersion
  77. * @param {Object} [options]
  78. * @param {boolean} [options.onlyIfExists] - If true, only queue changes if the project
  79. * already exists in Redis.
  80. */
  81. async function queueChangesFake(
  82. projectId,
  83. changes,
  84. limits,
  85. endVersion,
  86. options = {}
  87. ) {
  88. try {
  89. await queueChanges(projectId, changes, endVersion)
  90. await fakePersistRedisChanges(projectId, changes, endVersion)
  91. } catch (err) {
  92. logger.error({ err }, 'Chunk buffer verification failed')
  93. }
  94. }
  95. /**
  96. * Queues changes in Redis, simulating persistence, but only if the project already exists.
  97. * @param {string} projectId - The ID of the project.
  98. * @param {Change[]} changes - An array of changes to be queued.
  99. * @param {Object} limits - Limits for the changes.
  100. * @param {number} endVersion - The expected version of the project before these changes are applied.
  101. */
  102. async function queueChangesFakeOnlyIfExists(
  103. projectId,
  104. changes,
  105. limits,
  106. endVersion
  107. ) {
  108. await queueChangesFake(projectId, changes, limits, endVersion, {
  109. onlyIfExists: true,
  110. })
  111. }
  112. /**
  113. * Simulates the persistence of changes by verifying a given set of changes against
  114. * what is currently stored as non-persisted in Redis, and then updates the
  115. * persisted version number in Redis.
  116. *
  117. * @async
  118. * @param {string} projectId - The ID of the project.
  119. * @param {Change[]} changesToPersist - An array of changes that are expected to be
  120. * persisted. These are used for verification
  121. * against the changes currently in Redis.
  122. * @param {number} baseVersion - The base version number from which to calculate
  123. * the new persisted version.
  124. * @returns {Promise<void>} A promise that resolves when the persisted version
  125. * in Redis has been updated.
  126. */
  127. async function fakePersistRedisChanges(
  128. projectId,
  129. changesToPersist,
  130. baseVersion
  131. ) {
  132. const nonPersistedChanges = await redisBackend.getNonPersistedChanges(
  133. projectId,
  134. baseVersion
  135. )
  136. if (
  137. serializeChanges(nonPersistedChanges) === serializeChanges(changesToPersist)
  138. ) {
  139. metrics.inc('persist_redis_changes_verification', 1, { status: 'match' })
  140. } else {
  141. logger.warn({ projectId }, 'mismatch of non-persisted changes from Redis')
  142. metrics.inc('persist_redis_changes_verification', 1, {
  143. status: 'mismatch',
  144. })
  145. }
  146. const persistedVersion = baseVersion + nonPersistedChanges.length
  147. await redisBackend.setPersistedVersion(projectId, persistedVersion)
  148. }
  149. /**
  150. * @param {Change[]} changes
  151. */
  152. function serializeChanges(changes) {
  153. return JSON.stringify(changes.map(change => change.toRaw()))
  154. }
  155. module.exports = commitChanges