commit_changes.js 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159
  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, 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, 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 {number} endVersion
  76. * @param {Object} [options]
  77. * @param {boolean} [options.onlyIfExists] - If true, only queue changes if the project
  78. * already exists in Redis.
  79. */
  80. async function queueChangesFake(projectId, changes, endVersion, options = {}) {
  81. try {
  82. await queueChanges(projectId, changes, endVersion)
  83. await fakePersistRedisChanges(projectId, changes, endVersion)
  84. } catch (err) {
  85. logger.error({ err }, 'Chunk buffer verification failed')
  86. }
  87. }
  88. /**
  89. * Queues changes in Redis, simulating persistence, but only if the project already exists.
  90. * @param {string} projectId - The ID of the project.
  91. * @param {Change[]} changes - An array of changes to be queued.
  92. * @param {number} endVersion - The expected version of the project before these changes are applied.
  93. */
  94. async function queueChangesFakeOnlyIfExists(projectId, changes, endVersion) {
  95. await queueChangesFake(projectId, changes, endVersion, {
  96. onlyIfExists: true,
  97. })
  98. }
  99. /**
  100. * Simulates the persistence of changes by verifying a given set of changes against
  101. * what is currently stored as non-persisted in Redis, and then updates the
  102. * persisted version number in Redis.
  103. *
  104. * @async
  105. * @param {string} projectId - The ID of the project.
  106. * @param {Change[]} changesToPersist - An array of changes that are expected to be
  107. * persisted. These are used for verification
  108. * against the changes currently in Redis.
  109. * @param {number} baseVersion - The base version number from which to calculate
  110. * the new persisted version.
  111. * @returns {Promise<void>} A promise that resolves when the persisted version
  112. * in Redis has been updated.
  113. */
  114. async function fakePersistRedisChanges(
  115. projectId,
  116. changesToPersist,
  117. baseVersion
  118. ) {
  119. const nonPersistedChanges = await redisBackend.getNonPersistedChanges(
  120. projectId,
  121. baseVersion
  122. )
  123. if (
  124. serializeChanges(nonPersistedChanges) === serializeChanges(changesToPersist)
  125. ) {
  126. metrics.inc('persist_redis_changes_verification', 1, { status: 'match' })
  127. } else {
  128. logger.warn({ projectId }, 'mismatch of non-persisted changes from Redis')
  129. metrics.inc('persist_redis_changes_verification', 1, {
  130. status: 'mismatch',
  131. })
  132. }
  133. const persistedVersion = baseVersion + nonPersistedChanges.length
  134. await redisBackend.setPersistedVersion(projectId, persistedVersion)
  135. }
  136. /**
  137. * @param {Change[]} changes
  138. */
  139. function serializeChanges(changes) {
  140. return JSON.stringify(changes.map(change => change.toRaw()))
  141. }
  142. module.exports = commitChanges