HttpController.js 10 KB

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