project_import.js 6.3 KB

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