project_import.js 5.6 KB

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