project_import.js 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197
  1. // @ts-check
  2. 'use strict'
  3. const { expressify } = require('@overleaf/promise-utils')
  4. const HTTPStatus = require('http-status')
  5. const core = require('overleaf-editor-core')
  6. const Change = core.Change
  7. const Chunk = core.Chunk
  8. const File = core.File
  9. const FileMap = core.FileMap
  10. const Snapshot = core.Snapshot
  11. const TextOperation = core.TextOperation
  12. const logger = require('@overleaf/logger')
  13. const storage = require('../../storage')
  14. const BatchBlobStore = storage.BatchBlobStore
  15. const BlobStore = storage.BlobStore
  16. const chunkStore = storage.chunkStore
  17. const HashCheckBlobStore = storage.HashCheckBlobStore
  18. const commitChanges = storage.commitChanges
  19. const persistBuffer = storage.persistBuffer
  20. const InvalidChangeError = storage.InvalidChangeError
  21. const render = require('./render')
  22. const config = require('config')
  23. // The history buffer level is used to determine whether to queue changes
  24. // in Redis or persist them directly to the chunk store.
  25. // If defaults to 0 (no queuing) if not set.
  26. const historyBufferLevel = config.has('historyBufferLevel')
  27. ? parseInt(config.historyBufferLevel, 10)
  28. : 0
  29. // The forcePersistBuffer flag will ensure the buffer is fully persisted before
  30. // any persist operation. Set this to true if you want to make the persisted-version
  31. // in Redis match the endVersion of the latest chunk. This should be set to true
  32. // when downgrading from a history buffer level that queues changes in Redis
  33. // without persisting them immediately.
  34. const forcePersistBuffer = config.has('forcePersistBuffer')
  35. ? config.get('forcePersistBuffer') === 'true'
  36. : false
  37. logger.info(
  38. { historyBufferLevel, forcePersistBuffer },
  39. historyBufferLevel > 0 || forcePersistBuffer
  40. ? 'using history buffer'
  41. : 'history buffer disabled'
  42. )
  43. async function importSnapshot(req, res) {
  44. const projectId = req.swagger.params.project_id.value
  45. const rawSnapshot = req.swagger.params.snapshot.value
  46. let snapshot
  47. try {
  48. snapshot = Snapshot.fromRaw(rawSnapshot)
  49. } catch (err) {
  50. logger.warn({ err, projectId }, 'failed to import snapshot')
  51. return render.unprocessableEntity(res)
  52. }
  53. let historyId
  54. try {
  55. historyId = await chunkStore.initializeProject(projectId, snapshot)
  56. } catch (err) {
  57. if (err instanceof chunkStore.AlreadyInitialized) {
  58. logger.warn({ err, projectId }, 'already initialized')
  59. return render.conflict(res)
  60. } else {
  61. throw err
  62. }
  63. }
  64. res.status(HTTPStatus.OK).json({ projectId: historyId })
  65. }
  66. async function importChanges(req, res, next) {
  67. const projectId = req.swagger.params.project_id.value
  68. const rawChanges = req.swagger.params.changes.value
  69. const endVersion = req.swagger.params.end_version.value
  70. const returnSnapshot = req.swagger.params.return_snapshot.value || 'none'
  71. let changes
  72. try {
  73. changes = rawChanges.map(Change.fromRaw)
  74. } catch (err) {
  75. logger.warn({ err, projectId }, 'failed to parse changes')
  76. return render.unprocessableEntity(res)
  77. }
  78. // Set limits to force us to persist all of the changes.
  79. const farFuture = new Date()
  80. farFuture.setTime(farFuture.getTime() + 7 * 24 * 3600 * 1000)
  81. const limits = {
  82. maxChanges: 0,
  83. minChangeTimestamp: farFuture,
  84. maxChangeTimestamp: farFuture,
  85. }
  86. const blobStore = new BlobStore(projectId)
  87. const batchBlobStore = new BatchBlobStore(blobStore)
  88. const hashCheckBlobStore = new HashCheckBlobStore(blobStore)
  89. async function loadFiles() {
  90. const blobHashes = new Set()
  91. for (const change of changes) {
  92. // This populates the set blobHashes with blobs referred to in the change
  93. change.findBlobHashes(blobHashes)
  94. }
  95. await batchBlobStore.preload(Array.from(blobHashes))
  96. for (const change of changes) {
  97. await change.loadFiles('lazy', batchBlobStore)
  98. }
  99. }
  100. async function buildResultSnapshot(resultChunk) {
  101. const chunk =
  102. resultChunk ||
  103. (await chunkStore.loadLatest(projectId, { persistedOnly: true }))
  104. const snapshot = chunk.getSnapshot()
  105. snapshot.applyAll(chunk.getChanges())
  106. const rawSnapshot = await snapshot.store(hashCheckBlobStore)
  107. return rawSnapshot
  108. }
  109. await loadFiles()
  110. let result
  111. try {
  112. result = await commitChanges(projectId, changes, limits, endVersion, {
  113. historyBufferLevel,
  114. forcePersistBuffer,
  115. })
  116. } catch (err) {
  117. if (
  118. err instanceof Chunk.ConflictingEndVersion ||
  119. err instanceof TextOperation.UnprocessableError ||
  120. err instanceof File.NotEditableError ||
  121. err instanceof FileMap.PathnameError ||
  122. err instanceof Snapshot.EditMissingFileError ||
  123. err instanceof chunkStore.ChunkVersionConflictError ||
  124. err instanceof InvalidChangeError
  125. ) {
  126. // If we failed to apply operations, that's probably because they were
  127. // invalid.
  128. logger.warn({ err, projectId, endVersion }, 'changes rejected by history')
  129. return render.unprocessableEntity(res)
  130. } else if (err instanceof Chunk.NotFoundError) {
  131. logger.warn({ err, projectId }, 'chunk not found')
  132. return render.notFound(res)
  133. } else {
  134. throw err
  135. }
  136. }
  137. if (returnSnapshot === 'none') {
  138. res.status(HTTPStatus.CREATED).json({
  139. resyncNeeded: result.resyncNeeded,
  140. })
  141. } else {
  142. const rawSnapshot = await buildResultSnapshot(result && result.currentChunk)
  143. res.status(HTTPStatus.CREATED).json(rawSnapshot)
  144. }
  145. }
  146. async function flushChanges(req, res, next) {
  147. const projectId = req.swagger.params.project_id.value
  148. // Use the same limits importChanges, since these are passed to persistChanges
  149. const farFuture = new Date()
  150. farFuture.setTime(farFuture.getTime() + 7 * 24 * 3600 * 1000)
  151. const limits = {
  152. maxChanges: 0,
  153. minChangeTimestamp: farFuture,
  154. maxChangeTimestamp: farFuture,
  155. }
  156. try {
  157. await persistBuffer(projectId, limits)
  158. res.status(HTTPStatus.OK).end()
  159. } catch (err) {
  160. if (err instanceof Chunk.NotFoundError) {
  161. render.notFound(res)
  162. } else {
  163. throw err
  164. }
  165. }
  166. }
  167. exports.importSnapshot = expressify(importSnapshot)
  168. exports.importChanges = expressify(importChanges)
  169. exports.flushChanges = expressify(flushChanges)