app.js 7.5 KB

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