projects.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388
  1. 'use strict'
  2. const _ = require('lodash')
  3. const Path = require('node:path')
  4. const Stream = require('node:stream')
  5. const HTTPStatus = require('http-status')
  6. const fs = require('node:fs')
  7. const { promisify } = require('node:util')
  8. const config = require('config')
  9. const OError = require('@overleaf/o-error')
  10. const logger = require('@overleaf/logger')
  11. const { Chunk, ChunkResponse, Blob } = require('overleaf-editor-core')
  12. const {
  13. BlobStore,
  14. blobHash,
  15. chunkStore,
  16. HashCheckBlobStore,
  17. ProjectArchive,
  18. zipStore,
  19. chunkBuffer,
  20. } = require('../../storage')
  21. const render = require('./render')
  22. const expressify = require('./expressify')
  23. const withTmpDir = require('./with_tmp_dir')
  24. const StreamSizeLimit = require('./stream_size_limit')
  25. const pipeline = promisify(Stream.pipeline)
  26. async function initializeProject(req, res, next) {
  27. let projectId = req.swagger.params.body.value.projectId
  28. try {
  29. projectId = await chunkStore.initializeProject(projectId)
  30. res.status(HTTPStatus.OK).json({ projectId })
  31. } catch (err) {
  32. if (err instanceof chunkStore.AlreadyInitialized) {
  33. render.conflict(res)
  34. } else {
  35. throw err
  36. }
  37. }
  38. }
  39. async function getLatestContent(req, res, next) {
  40. const projectId = req.swagger.params.project_id.value
  41. const blobStore = new BlobStore(projectId)
  42. const chunk = await chunkBuffer.loadLatest(projectId)
  43. const snapshot = chunk.getSnapshot()
  44. snapshot.applyAll(chunk.getChanges())
  45. await snapshot.loadFiles('eager', blobStore)
  46. res.json(snapshot.toRaw())
  47. }
  48. async function getContentAtVersion(req, res, next) {
  49. const projectId = req.swagger.params.project_id.value
  50. const version = req.swagger.params.version.value
  51. const blobStore = new BlobStore(projectId)
  52. const snapshot = await getSnapshotAtVersion(projectId, version)
  53. await snapshot.loadFiles('eager', blobStore)
  54. res.json(snapshot.toRaw())
  55. }
  56. async function getLatestHashedContent(req, res, next) {
  57. const projectId = req.swagger.params.project_id.value
  58. const blobStore = new HashCheckBlobStore(new BlobStore(projectId))
  59. const chunk = await chunkBuffer.loadLatest(projectId)
  60. const snapshot = chunk.getSnapshot()
  61. snapshot.applyAll(chunk.getChanges())
  62. await snapshot.loadFiles('eager', blobStore)
  63. const rawSnapshot = await snapshot.store(blobStore)
  64. res.json(rawSnapshot)
  65. }
  66. async function getLatestHistory(req, res, next) {
  67. const projectId = req.swagger.params.project_id.value
  68. try {
  69. const chunk = await chunkBuffer.loadLatest(projectId)
  70. const chunkResponse = new ChunkResponse(chunk)
  71. res.json(chunkResponse.toRaw())
  72. } catch (err) {
  73. if (err instanceof Chunk.NotFoundError) {
  74. render.notFound(res)
  75. } else {
  76. throw err
  77. }
  78. }
  79. }
  80. async function getLatestHistoryRaw(req, res, next) {
  81. const projectId = req.swagger.params.project_id.value
  82. const readOnly = req.swagger.params.readOnly.value
  83. try {
  84. const { startVersion, endVersion, endTimestamp } =
  85. await chunkStore.loadLatestRaw(projectId, { readOnly })
  86. res.json({
  87. startVersion,
  88. endVersion,
  89. endTimestamp,
  90. })
  91. } catch (err) {
  92. if (err instanceof Chunk.NotFoundError) {
  93. render.notFound(res)
  94. } else {
  95. throw err
  96. }
  97. }
  98. }
  99. async function getHistory(req, res, next) {
  100. const projectId = req.swagger.params.project_id.value
  101. const version = req.swagger.params.version.value
  102. try {
  103. const chunk = await chunkStore.loadAtVersion(projectId, version)
  104. const chunkResponse = new ChunkResponse(chunk)
  105. res.json(chunkResponse.toRaw())
  106. } catch (err) {
  107. if (err instanceof Chunk.NotFoundError) {
  108. render.notFound(res)
  109. } else {
  110. throw err
  111. }
  112. }
  113. }
  114. async function getHistoryBefore(req, res, next) {
  115. const projectId = req.swagger.params.project_id.value
  116. const timestamp = req.swagger.params.timestamp.value
  117. try {
  118. const chunk = await chunkStore.loadAtTimestamp(projectId, timestamp)
  119. const chunkResponse = new ChunkResponse(chunk)
  120. res.json(chunkResponse.toRaw())
  121. } catch (err) {
  122. if (err instanceof Chunk.NotFoundError) {
  123. render.notFound(res)
  124. } else {
  125. throw err
  126. }
  127. }
  128. }
  129. /**
  130. * Get all changes since the beginning of history or since a given version
  131. */
  132. async function getChanges(req, res, next) {
  133. const projectId = req.swagger.params.project_id.value
  134. const since = req.swagger.params.since.value ?? 0
  135. if (since < 0) {
  136. // Negative values would cause an infinite loop
  137. return res.status(400).json({
  138. error: `Version out of bounds: ${since}`,
  139. })
  140. }
  141. const changes = []
  142. let chunk = await chunkBuffer.loadLatest(projectId)
  143. if (since > chunk.getEndVersion()) {
  144. return res.status(400).json({
  145. error: `Version out of bounds: ${since}`,
  146. })
  147. }
  148. // Fetch all chunks that come after the chunk that contains the start version
  149. while (chunk.getStartVersion() > since) {
  150. const changesInChunk = chunk.getChanges()
  151. changes.unshift(...changesInChunk)
  152. chunk = await chunkStore.loadAtVersion(projectId, chunk.getStartVersion())
  153. }
  154. // Extract the relevant changes from the chunk that contains the start version
  155. const changesInChunk = chunk
  156. .getChanges()
  157. .slice(since - chunk.getStartVersion())
  158. changes.unshift(...changesInChunk)
  159. res.json(changes.map(change => change.toRaw()))
  160. }
  161. async function getZip(req, res, next) {
  162. const projectId = req.swagger.params.project_id.value
  163. const version = req.swagger.params.version.value
  164. const blobStore = new BlobStore(projectId)
  165. let snapshot
  166. try {
  167. snapshot = await getSnapshotAtVersion(projectId, version)
  168. } catch (err) {
  169. if (err instanceof Chunk.NotFoundError) {
  170. return render.notFound(res)
  171. } else {
  172. throw err
  173. }
  174. }
  175. await withTmpDir('get-zip-', async tmpDir => {
  176. const tmpFilename = Path.join(tmpDir, 'project.zip')
  177. const archive = new ProjectArchive(snapshot)
  178. await archive.writeZip(blobStore, tmpFilename)
  179. res.set('Content-Type', 'application/octet-stream')
  180. res.set('Content-Disposition', 'attachment; filename=project.zip')
  181. const stream = fs.createReadStream(tmpFilename)
  182. await pipeline(stream, res)
  183. })
  184. }
  185. async function createZip(req, res, next) {
  186. const projectId = req.swagger.params.project_id.value
  187. const version = req.swagger.params.version.value
  188. try {
  189. const snapshot = await getSnapshotAtVersion(projectId, version)
  190. const zipUrl = await zipStore.getSignedUrl(projectId, version)
  191. // Do not await this; run it in the background.
  192. zipStore.storeZip(projectId, version, snapshot).catch(err => {
  193. logger.error({ err, projectId, version }, 'createZip: storeZip failed')
  194. })
  195. res.status(HTTPStatus.OK).json({ zipUrl })
  196. } catch (error) {
  197. if (error instanceof Chunk.NotFoundError) {
  198. render.notFound(res)
  199. } else {
  200. next(error)
  201. }
  202. }
  203. }
  204. async function deleteProject(req, res, next) {
  205. const projectId = req.swagger.params.project_id.value
  206. const blobStore = new BlobStore(projectId)
  207. await Promise.all([
  208. chunkStore.deleteProjectChunks(projectId),
  209. blobStore.deleteBlobs(),
  210. ])
  211. res.status(HTTPStatus.NO_CONTENT).send()
  212. }
  213. async function createProjectBlob(req, res, next) {
  214. const projectId = req.swagger.params.project_id.value
  215. const expectedHash = req.swagger.params.hash.value
  216. const maxUploadSize = parseInt(config.get('maxFileUploadSize'), 10)
  217. await withTmpDir('blob-', async tmpDir => {
  218. const tmpPath = Path.join(tmpDir, 'content')
  219. const sizeLimit = new StreamSizeLimit(maxUploadSize)
  220. await pipeline(req, sizeLimit, fs.createWriteStream(tmpPath))
  221. if (sizeLimit.sizeLimitExceeded) {
  222. return render.requestEntityTooLarge(res)
  223. }
  224. const hash = await blobHash.fromFile(tmpPath)
  225. if (hash !== expectedHash) {
  226. logger.debug({ hash, expectedHash }, 'Hash mismatch')
  227. return render.conflict(res, 'File hash mismatch')
  228. }
  229. const blobStore = new BlobStore(projectId)
  230. const newBlob = await blobStore.putFile(tmpPath)
  231. try {
  232. const { backupBlob } = await import('../../storage/lib/backupBlob.mjs')
  233. await backupBlob(projectId, newBlob, tmpPath)
  234. } catch (error) {
  235. logger.warn({ error, projectId, hash }, 'Failed to backup blob')
  236. }
  237. res.status(HTTPStatus.CREATED).end()
  238. })
  239. }
  240. async function headProjectBlob(req, res) {
  241. const projectId = req.swagger.params.project_id.value
  242. const hash = req.swagger.params.hash.value
  243. const blobStore = new BlobStore(projectId)
  244. const blob = await blobStore.getBlob(hash)
  245. if (blob) {
  246. res.set('Content-Length', blob.getByteLength())
  247. res.status(200).end()
  248. } else {
  249. res.status(404).end()
  250. }
  251. }
  252. // Support simple, singular ranges starting from zero only, up-to 2MB = 2_000_000, 7 digits
  253. const RANGE_HEADER = /^bytes=0-(\d{1,7})$/
  254. /**
  255. * @param {string} header
  256. * @return {{}|{start: number, end: number}}
  257. * @private
  258. */
  259. function _getRangeOpts(header) {
  260. if (!header) return {}
  261. const match = header.match(RANGE_HEADER)
  262. if (match) {
  263. const end = parseInt(match[1], 10)
  264. return { start: 0, end }
  265. }
  266. return {}
  267. }
  268. async function getProjectBlob(req, res, next) {
  269. const projectId = req.swagger.params.project_id.value
  270. const hash = req.swagger.params.hash.value
  271. const opts = _getRangeOpts(req.swagger.params.range.value || '')
  272. const blobStore = new BlobStore(projectId)
  273. logger.debug({ projectId, hash }, 'getProjectBlob started')
  274. try {
  275. let stream
  276. try {
  277. stream = await blobStore.getStream(hash, opts)
  278. } catch (err) {
  279. if (err instanceof Blob.NotFoundError) {
  280. logger.warn({ projectId, hash }, 'Blob not found')
  281. return res.status(404).end()
  282. } else {
  283. throw err
  284. }
  285. }
  286. res.set('Content-Type', 'application/octet-stream')
  287. try {
  288. await pipeline(stream, res)
  289. } catch (err) {
  290. if (err?.code === 'ERR_STREAM_PREMATURE_CLOSE') {
  291. res.end()
  292. } else {
  293. throw OError.tag(err, 'error transferring stream', { projectId, hash })
  294. }
  295. }
  296. } finally {
  297. logger.debug({ projectId, hash }, 'getProjectBlob finished')
  298. }
  299. }
  300. async function copyProjectBlob(req, res, next) {
  301. const sourceProjectId = req.swagger.params.copyFrom.value
  302. const targetProjectId = req.swagger.params.project_id.value
  303. const blobHash = req.swagger.params.hash.value
  304. // Check that blob exists in source project
  305. const sourceBlobStore = new BlobStore(sourceProjectId)
  306. const targetBlobStore = new BlobStore(targetProjectId)
  307. const [sourceBlob, targetBlob] = await Promise.all([
  308. sourceBlobStore.getBlob(blobHash),
  309. targetBlobStore.getBlob(blobHash),
  310. ])
  311. if (!sourceBlob) {
  312. return render.notFound(res)
  313. }
  314. // Exit early if the blob exists in the target project.
  315. // This will also catch global blobs, which always exist.
  316. if (targetBlob) {
  317. return res.status(HTTPStatus.NO_CONTENT).end()
  318. }
  319. // Otherwise, copy blob from source project to target project
  320. await sourceBlobStore.copyBlob(sourceBlob, targetProjectId)
  321. res.status(HTTPStatus.CREATED).end()
  322. }
  323. async function getSnapshotAtVersion(projectId, version) {
  324. const chunk = await chunkStore.loadAtVersion(projectId, version)
  325. const snapshot = chunk.getSnapshot()
  326. const changes = _.dropRight(
  327. chunk.getChanges(),
  328. chunk.getEndVersion() - version
  329. )
  330. snapshot.applyAll(changes)
  331. return snapshot
  332. }
  333. module.exports = {
  334. initializeProject: expressify(initializeProject),
  335. getLatestContent: expressify(getLatestContent),
  336. getContentAtVersion: expressify(getContentAtVersion),
  337. getLatestHashedContent: expressify(getLatestHashedContent),
  338. getLatestPersistedHistory: expressify(getLatestHistory),
  339. getLatestHistory: expressify(getLatestHistory),
  340. getLatestHistoryRaw: expressify(getLatestHistoryRaw),
  341. getHistory: expressify(getHistory),
  342. getHistoryBefore: expressify(getHistoryBefore),
  343. getChanges: expressify(getChanges),
  344. getZip: expressify(getZip),
  345. createZip: expressify(createZip),
  346. deleteProject: expressify(deleteProject),
  347. createProjectBlob: expressify(createProjectBlob),
  348. getProjectBlob: expressify(getProjectBlob),
  349. headProjectBlob: expressify(headProjectBlob),
  350. copyProjectBlob: expressify(copyProjectBlob),
  351. }