projects.js 12 KB

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