project_import.js 5.3 KB

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