HttpController.js 10 KB

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