HttpController.js 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364
  1. /* eslint-disable
  2. no-unused-vars,
  3. */
  4. // TODO: This file was created by bulk-decaffeinate.
  5. // Fix any style issues and re-enable lint.
  6. /*
  7. * decaffeinate suggestions:
  8. * DS101: Remove unnecessary use of Array.from
  9. * DS102: Remove unnecessary code created because of implicit returns
  10. * DS207: Consider shorter variations of null checks
  11. * Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md
  12. */
  13. let HttpController
  14. const UpdatesManager = require('./UpdatesManager')
  15. const DiffManager = require('./DiffManager')
  16. const PackManager = require('./PackManager')
  17. const RestoreManager = require('./RestoreManager')
  18. const ZipManager = require('./ZipManager')
  19. const logger = require('@overleaf/logger')
  20. const HealthChecker = require('./HealthChecker')
  21. const _ = require('underscore')
  22. const Path = require('path')
  23. const { pipeline } = require('stream')
  24. module.exports = HttpController = {
  25. flushDoc(req, res, next) {
  26. if (next == null) {
  27. next = function () {}
  28. }
  29. const { doc_id: docId } = req.params
  30. const { project_id: projectId } = req.params
  31. logger.debug({ projectId, docId }, 'compressing doc history')
  32. return UpdatesManager.processUncompressedUpdatesWithLock(
  33. projectId,
  34. docId,
  35. function (error) {
  36. if (error != null) {
  37. return next(error)
  38. }
  39. return res.sendStatus(204)
  40. }
  41. )
  42. },
  43. flushProject(req, res, next) {
  44. if (next == null) {
  45. next = function () {}
  46. }
  47. const { project_id: projectId } = req.params
  48. logger.debug({ projectId }, 'compressing project history')
  49. return UpdatesManager.processUncompressedUpdatesForProject(
  50. projectId,
  51. function (error) {
  52. if (error != null) {
  53. return next(error)
  54. }
  55. return res.sendStatus(204)
  56. }
  57. )
  58. },
  59. flushAll(req, res, next) {
  60. // limit on projects to flush or -1 for all (default)
  61. if (next == null) {
  62. next = function () {}
  63. }
  64. const limit = req.query.limit != null ? parseInt(req.query.limit, 10) : -1
  65. logger.debug({ limit }, 'flushing all projects')
  66. return UpdatesManager.flushAll(limit, function (error, result) {
  67. if (error != null) {
  68. return next(error)
  69. }
  70. const { failed, succeeded, all } = result
  71. const status = `${succeeded.length} succeeded, ${failed.length} failed`
  72. if (limit === 0) {
  73. return res
  74. .status(200)
  75. .send(`${status}\nwould flush:\n${all.join('\n')}\n`)
  76. } else if (failed.length > 0) {
  77. logger.debug({ failed, succeeded }, 'error flushing projects')
  78. return res
  79. .status(500)
  80. .send(`${status}\nfailed to flush:\n${failed.join('\n')}\n`)
  81. } else {
  82. return res
  83. .status(200)
  84. .send(
  85. `${status}\nflushed ${succeeded.length} projects of ${all.length}\n`
  86. )
  87. }
  88. })
  89. },
  90. checkDanglingUpdates(req, res, next) {
  91. if (next == null) {
  92. next = function () {}
  93. }
  94. logger.debug('checking dangling updates')
  95. return UpdatesManager.getDanglingUpdates(function (error, result) {
  96. if (error != null) {
  97. return next(error)
  98. }
  99. if (result.length > 0) {
  100. logger.debug({ dangling: result }, 'found dangling updates')
  101. return res.status(500).send(`dangling updates:\n${result.join('\n')}\n`)
  102. } else {
  103. return res.status(200).send('no dangling updates found\n')
  104. }
  105. })
  106. },
  107. checkDoc(req, res, next) {
  108. if (next == null) {
  109. next = function () {}
  110. }
  111. const { doc_id: docId } = req.params
  112. const { project_id: projectId } = req.params
  113. logger.debug({ projectId, docId }, 'checking doc history')
  114. return DiffManager.getDocumentBeforeVersion(
  115. projectId,
  116. docId,
  117. 1,
  118. function (error, document, rewoundUpdates) {
  119. if (error != null) {
  120. return next(error)
  121. }
  122. const broken = []
  123. for (const update of Array.from(rewoundUpdates)) {
  124. for (const op of Array.from(update.op)) {
  125. if (op.broken === true) {
  126. broken.push(op)
  127. }
  128. }
  129. }
  130. if (broken.length > 0) {
  131. return res.send(broken)
  132. } else {
  133. return res.sendStatus(204)
  134. }
  135. }
  136. )
  137. },
  138. getDiff(req, res, next) {
  139. let from, to
  140. if (next == null) {
  141. next = function () {}
  142. }
  143. const { doc_id: docId } = req.params
  144. const { project_id: projectId } = req.params
  145. if (req.query.from != null) {
  146. from = parseInt(req.query.from, 10)
  147. } else {
  148. from = null
  149. }
  150. if (req.query.to != null) {
  151. to = parseInt(req.query.to, 10)
  152. } else {
  153. to = null
  154. }
  155. logger.debug({ projectId, docId, from, to }, 'getting diff')
  156. return DiffManager.getDiff(
  157. projectId,
  158. docId,
  159. from,
  160. to,
  161. function (error, diff) {
  162. if (error != null) {
  163. return next(error)
  164. }
  165. return res.json({ diff })
  166. }
  167. )
  168. },
  169. getUpdates(req, res, next) {
  170. let before, minCount
  171. if (next == null) {
  172. next = function () {}
  173. }
  174. const { project_id: projectId } = req.params
  175. if (req.query.before != null) {
  176. before = parseInt(req.query.before, 10)
  177. }
  178. if (req.query.min_count != null) {
  179. minCount = parseInt(req.query.min_count, 10)
  180. }
  181. return UpdatesManager.getSummarizedProjectUpdates(
  182. projectId,
  183. { before, min_count: minCount },
  184. function (error, updates, nextBeforeTimestamp) {
  185. if (error != null) {
  186. return next(error)
  187. }
  188. return res.json({
  189. updates,
  190. nextBeforeTimestamp,
  191. })
  192. }
  193. )
  194. },
  195. zipProject(req, res, next) {
  196. const { project_id: projectId } = req.params
  197. logger.debug({ projectId }, 'exporting project history as zip file')
  198. ZipManager.makeTempDirectory((err, tmpdir) => {
  199. if (err) {
  200. return next(err)
  201. }
  202. const zipFilePath = Path.join(tmpdir, 'export.zip')
  203. ZipManager.exportProject(projectId, zipFilePath, err => {
  204. if (err) {
  205. ZipManager.cleanupTempDirectory(tmpdir)
  206. return next(err)
  207. }
  208. res.download(zipFilePath, `${projectId}-track-changes.zip`, err => {
  209. ZipManager.cleanupTempDirectory(tmpdir)
  210. if (err && !res.headersSent) {
  211. return next(err)
  212. }
  213. })
  214. })
  215. })
  216. },
  217. exportProject(req, res, next) {
  218. // The project history can be huge:
  219. // - updates can weight MBs for insert/delete of full doc
  220. // - multiple updates form a pack
  221. // Flush updates per pack onto the wire.
  222. const { project_id: projectId } = req.params
  223. logger.debug({ projectId }, 'exporting project history')
  224. UpdatesManager.exportProject(
  225. projectId,
  226. function (err, { updates, userIds }, confirmWrite) {
  227. const abortStreaming = req.destroyed || res.finished || res.destroyed
  228. if (abortStreaming) {
  229. // Tell the producer to stop emitting data
  230. if (confirmWrite) confirmWrite(new Error('stop'))
  231. return
  232. }
  233. const hasStartedStreamingResponse = res.headersSent
  234. if (err) {
  235. logger.error({ projectId, err }, 'export failed')
  236. if (!hasStartedStreamingResponse) {
  237. // Generate a nice 500
  238. return next(err)
  239. } else {
  240. // Stop streaming
  241. return res.destroy()
  242. }
  243. }
  244. // Compose the response incrementally
  245. const isFirstWrite = !hasStartedStreamingResponse
  246. const isLastWrite = updates.length === 0
  247. if (isFirstWrite) {
  248. // The first write will emit the 200 status, headers and start of the
  249. // response payload (open array)
  250. res.setHeader('Content-Type', 'application/json')
  251. res.setHeader('Trailer', 'X-User-Ids')
  252. res.writeHead(200)
  253. res.write('[')
  254. }
  255. if (!isFirstWrite && !isLastWrite) {
  256. // Starting from the 2nd non-empty write, emit a continuing comma.
  257. // write 1: [updates1
  258. // write 2: ,updates2
  259. // write 3: ,updates3
  260. // write N: ]
  261. res.write(',')
  262. }
  263. // Every write will emit a blob onto the response stream:
  264. // '[update1,update2,...]'
  265. // ^^^^^^^^^^^^^^^^^^^
  266. res.write(JSON.stringify(updates).slice(1, -1), confirmWrite)
  267. if (isLastWrite) {
  268. // The last write will have no updates and will finish the response
  269. // payload (close array) and emit the userIds as trailer.
  270. res.addTrailers({ 'X-User-Ids': JSON.stringify(userIds) })
  271. res.end(']')
  272. }
  273. }
  274. )
  275. },
  276. restore(req, res, next) {
  277. if (next == null) {
  278. next = function () {}
  279. }
  280. let { doc_id: docId, project_id: projectId, version } = req.params
  281. const userId = req.headers['x-user-id']
  282. version = parseInt(version, 10)
  283. return RestoreManager.restoreToBeforeVersion(
  284. projectId,
  285. docId,
  286. version,
  287. userId,
  288. function (error) {
  289. if (error != null) {
  290. return next(error)
  291. }
  292. return res.sendStatus(204)
  293. }
  294. )
  295. },
  296. pushDocHistory(req, res, next) {
  297. if (next == null) {
  298. next = function () {}
  299. }
  300. const { project_id: projectId } = req.params
  301. const { doc_id: docId } = req.params
  302. logger.debug({ projectId, docId }, 'pushing all finalised changes to s3')
  303. return PackManager.pushOldPacks(projectId, docId, function (error) {
  304. if (error != null) {
  305. return next(error)
  306. }
  307. return res.sendStatus(204)
  308. })
  309. },
  310. pullDocHistory(req, res, next) {
  311. if (next == null) {
  312. next = function () {}
  313. }
  314. const { project_id: projectId } = req.params
  315. const { doc_id: docId } = req.params
  316. logger.debug({ projectId, docId }, 'pulling all packs from s3')
  317. return PackManager.pullOldPacks(projectId, docId, function (error) {
  318. if (error != null) {
  319. return next(error)
  320. }
  321. return res.sendStatus(204)
  322. })
  323. },
  324. healthCheck(req, res) {
  325. return HealthChecker.check(function (err) {
  326. if (err != null) {
  327. logger.err({ err }, 'error performing health check')
  328. return res.sendStatus(500)
  329. } else {
  330. return res.sendStatus(200)
  331. }
  332. })
  333. },
  334. checkLock(req, res) {
  335. return HealthChecker.checkLock(function (err) {
  336. if (err != null) {
  337. logger.err({ err }, 'error performing lock check')
  338. return res.sendStatus(500)
  339. } else {
  340. return res.sendStatus(200)
  341. }
  342. })
  343. },
  344. }