app.js 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255
  1. /*
  2. * decaffeinate suggestions:
  3. * DS101: Remove unnecessary use of Array.from
  4. * DS102: Remove unnecessary code created because of implicit returns
  5. * DS103: Rewrite code to no longer use __guard__
  6. * DS207: Consider shorter variations of null checks
  7. * Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md
  8. */
  9. const Metrics = require('metrics-sharelatex')
  10. Metrics.initialize('doc-updater')
  11. const express = require('express')
  12. const http = require('http')
  13. const Settings = require('settings-sharelatex')
  14. const logger = require('logger-sharelatex')
  15. logger.initialize('document-updater')
  16. logger.logger.addSerializers(require('./app/js/LoggerSerializers'))
  17. if ((Settings.sentry != null ? Settings.sentry.dsn : undefined) != null) {
  18. logger.initializeErrorReporting(Settings.sentry.dsn)
  19. }
  20. const RedisManager = require('./app/js/RedisManager')
  21. const DispatchManager = require('./app/js/DispatchManager')
  22. const DeleteQueueManager = require('./app/js/DeleteQueueManager')
  23. const Errors = require('./app/js/Errors')
  24. const HttpController = require('./app/js/HttpController')
  25. const mongojs = require('./app/js/mongojs')
  26. const async = require('async')
  27. const Path = require('path')
  28. const bodyParser = require('body-parser')
  29. Metrics.mongodb.monitor(
  30. Path.resolve(__dirname + '/node_modules/mongojs/node_modules/mongodb'),
  31. logger
  32. )
  33. Metrics.event_loop.monitor(logger, 100)
  34. const app = express()
  35. app.use(Metrics.http.monitor(logger))
  36. app.use(bodyParser.json({ limit: Settings.max_doc_length + 64 * 1024 }))
  37. Metrics.injectMetricsRoute(app)
  38. DispatchManager.createAndStartDispatchers(Settings.dispatcherCount || 10)
  39. app.param('project_id', function (req, res, next, project_id) {
  40. if (project_id != null ? project_id.match(/^[0-9a-f]{24}$/) : undefined) {
  41. return next()
  42. } else {
  43. return next(new Error('invalid project id'))
  44. }
  45. })
  46. app.param('doc_id', function (req, res, next, doc_id) {
  47. if (doc_id != null ? doc_id.match(/^[0-9a-f]{24}$/) : undefined) {
  48. return next()
  49. } else {
  50. return next(new Error('invalid doc id'))
  51. }
  52. })
  53. app.get('/project/:project_id/doc/:doc_id', HttpController.getDoc)
  54. // temporarily keep the GET method for backwards compatibility
  55. app.get('/project/:project_id/doc', HttpController.getProjectDocsAndFlushIfOld)
  56. // will migrate to the POST method of get_and_flush_if_old instead
  57. app.post(
  58. '/project/:project_id/get_and_flush_if_old',
  59. HttpController.getProjectDocsAndFlushIfOld
  60. )
  61. app.post('/project/:project_id/clearState', HttpController.clearProjectState)
  62. app.post('/project/:project_id/doc/:doc_id', HttpController.setDoc)
  63. app.post(
  64. '/project/:project_id/doc/:doc_id/flush',
  65. HttpController.flushDocIfLoaded
  66. )
  67. app.delete('/project/:project_id/doc/:doc_id', HttpController.deleteDoc)
  68. app.delete('/project/:project_id', HttpController.deleteProject)
  69. app.delete('/project', HttpController.deleteMultipleProjects)
  70. app.post('/project/:project_id', HttpController.updateProject)
  71. app.post(
  72. '/project/:project_id/history/resync',
  73. HttpController.resyncProjectHistory
  74. )
  75. app.post('/project/:project_id/flush', HttpController.flushProject)
  76. app.post(
  77. '/project/:project_id/doc/:doc_id/change/:change_id/accept',
  78. HttpController.acceptChanges
  79. )
  80. app.post(
  81. '/project/:project_id/doc/:doc_id/change/accept',
  82. HttpController.acceptChanges
  83. )
  84. app.delete(
  85. '/project/:project_id/doc/:doc_id/comment/:comment_id',
  86. HttpController.deleteComment
  87. )
  88. app.get('/flush_all_projects', HttpController.flushAllProjects)
  89. app.get('/flush_queued_projects', HttpController.flushQueuedProjects)
  90. app.get('/total', function (req, res) {
  91. const timer = new Metrics.Timer('http.allDocList')
  92. return RedisManager.getCountOfDocsInMemory(function (err, count) {
  93. timer.done()
  94. return res.send({ total: count })
  95. })
  96. })
  97. app.get('/status', function (req, res) {
  98. if (Settings.shuttingDown) {
  99. return res.sendStatus(503) // Service unavailable
  100. } else {
  101. return res.send('document updater is alive')
  102. }
  103. })
  104. const pubsubClient = require('redis-sharelatex').createClient(
  105. Settings.redis.pubsub
  106. )
  107. app.get('/health_check/redis', (req, res, next) =>
  108. pubsubClient.healthCheck(function (error) {
  109. if (error != null) {
  110. logger.err({ err: error }, 'failed redis health check')
  111. return res.sendStatus(500)
  112. } else {
  113. return res.sendStatus(200)
  114. }
  115. })
  116. )
  117. const docUpdaterRedisClient = require('redis-sharelatex').createClient(
  118. Settings.redis.documentupdater
  119. )
  120. app.get('/health_check/redis_cluster', (req, res, next) =>
  121. docUpdaterRedisClient.healthCheck(function (error) {
  122. if (error != null) {
  123. logger.err({ err: error }, 'failed redis cluster health check')
  124. return res.sendStatus(500)
  125. } else {
  126. return res.sendStatus(200)
  127. }
  128. })
  129. )
  130. app.get('/health_check', (req, res, next) =>
  131. async.series(
  132. [
  133. (cb) =>
  134. pubsubClient.healthCheck(function (error) {
  135. if (error != null) {
  136. logger.err({ err: error }, 'failed redis health check')
  137. }
  138. return cb(error)
  139. }),
  140. (cb) =>
  141. docUpdaterRedisClient.healthCheck(function (error) {
  142. if (error != null) {
  143. logger.err({ err: error }, 'failed redis cluster health check')
  144. }
  145. return cb(error)
  146. }),
  147. (cb) =>
  148. mongojs.healthCheck(function (error) {
  149. if (error != null) {
  150. logger.err({ err: error }, 'failed mongo health check')
  151. }
  152. return cb(error)
  153. })
  154. ],
  155. function (error) {
  156. if (error != null) {
  157. return res.sendStatus(500)
  158. } else {
  159. return res.sendStatus(200)
  160. }
  161. }
  162. )
  163. )
  164. app.use(function (error, req, res, next) {
  165. if (error instanceof Errors.NotFoundError) {
  166. return res.sendStatus(404)
  167. } else if (error instanceof Errors.OpRangeNotAvailableError) {
  168. return res.sendStatus(422) // Unprocessable Entity
  169. } else if (error.statusCode === 413) {
  170. return res.status(413).send('request entity too large')
  171. } else {
  172. logger.error({ err: error, req }, 'request errored')
  173. return res.status(500).send('Oops, something went wrong')
  174. }
  175. })
  176. const shutdownCleanly = (signal) =>
  177. function () {
  178. logger.log({ signal }, 'received interrupt, cleaning up')
  179. Settings.shuttingDown = true
  180. return setTimeout(function () {
  181. logger.log({ signal }, 'shutting down')
  182. return process.exit()
  183. }, 10000)
  184. }
  185. const watchForEvent = (eventName) =>
  186. docUpdaterRedisClient.on(eventName, (e) =>
  187. console.log(`redis event: ${eventName} ${e}`)
  188. )
  189. const events = ['connect', 'ready', 'error', 'close', 'reconnecting', 'end']
  190. for (const eventName of Array.from(events)) {
  191. watchForEvent(eventName)
  192. }
  193. const port =
  194. __guard__(
  195. Settings.internal != null ? Settings.internal.documentupdater : undefined,
  196. (x) => x.port
  197. ) ||
  198. __guard__(
  199. Settings.apis != null ? Settings.apis.documentupdater : undefined,
  200. (x1) => x1.port
  201. ) ||
  202. 3003
  203. const host = Settings.internal.documentupdater.host || 'localhost'
  204. if (!module.parent) {
  205. // Called directly
  206. app.listen(port, host, function () {
  207. logger.info(`Document-updater starting up, listening on ${host}:${port}`)
  208. if (Settings.continuousBackgroundFlush) {
  209. logger.info('Starting continuous background flush')
  210. return DeleteQueueManager.startBackgroundFlush()
  211. }
  212. })
  213. }
  214. module.exports = app
  215. for (const signal of [
  216. 'SIGINT',
  217. 'SIGHUP',
  218. 'SIGQUIT',
  219. 'SIGUSR1',
  220. 'SIGUSR2',
  221. 'SIGTERM',
  222. 'SIGABRT'
  223. ]) {
  224. process.on(signal, shutdownCleanly(signal))
  225. }
  226. function __guard__(value, transform) {
  227. return typeof value !== 'undefined' && value !== null
  228. ? transform(value)
  229. : undefined
  230. }