app.js 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310
  1. // Metrics must be initialized before importing anything else
  2. require('@overleaf/metrics/initialize')
  3. const Metrics = require('@overleaf/metrics')
  4. const express = require('express')
  5. const Settings = require('@overleaf/settings')
  6. const logger = require('@overleaf/logger')
  7. logger.initialize('document-updater')
  8. logger.logger.addSerializers(require('./app/js/LoggerSerializers'))
  9. const RedisManager = require('./app/js/RedisManager')
  10. const DispatchManager = require('./app/js/DispatchManager')
  11. const DeleteQueueManager = require('./app/js/DeleteQueueManager')
  12. const Errors = require('./app/js/Errors')
  13. const HttpController = require('./app/js/HttpController')
  14. const mongodb = require('./app/js/mongodb')
  15. const async = require('async')
  16. const bodyParser = require('body-parser')
  17. Metrics.event_loop.monitor(logger, 100)
  18. Metrics.open_sockets.monitor()
  19. const app = express()
  20. app.use(bodyParser.json({ limit: Settings.maxJsonRequestSize }))
  21. Metrics.injectMetricsRoute(app)
  22. DispatchManager.createAndStartDispatchers(Settings.dispatcherCount)
  23. app.get('/status', (req, res) => {
  24. if (Settings.shuttingDown) {
  25. return res.sendStatus(503) // Service unavailable
  26. } else {
  27. return res.send('document updater is alive')
  28. }
  29. })
  30. const pubsubClient = require('@overleaf/redis-wrapper').createClient(
  31. Settings.redis.pubsub
  32. )
  33. app.get('/health_check/redis', (req, res, next) => {
  34. pubsubClient.healthCheck(error => {
  35. if (error) {
  36. logger.err({ err: error }, 'failed redis health check')
  37. return res.sendStatus(500)
  38. } else {
  39. return res.sendStatus(200)
  40. }
  41. })
  42. })
  43. const docUpdaterRedisClient = require('@overleaf/redis-wrapper').createClient(
  44. Settings.redis.documentupdater
  45. )
  46. app.get('/health_check/redis_cluster', (req, res, next) => {
  47. docUpdaterRedisClient.healthCheck(error => {
  48. if (error) {
  49. logger.err({ err: error }, 'failed redis cluster health check')
  50. return res.sendStatus(500)
  51. } else {
  52. return res.sendStatus(200)
  53. }
  54. })
  55. })
  56. app.get('/health_check', (req, res, next) => {
  57. async.series(
  58. [
  59. cb => {
  60. pubsubClient.healthCheck(error => {
  61. if (error) {
  62. logger.err({ err: error }, 'failed redis health check')
  63. }
  64. cb(error)
  65. })
  66. },
  67. cb => {
  68. docUpdaterRedisClient.healthCheck(error => {
  69. if (error) {
  70. logger.err({ err: error }, 'failed redis cluster health check')
  71. }
  72. cb(error)
  73. })
  74. },
  75. cb => {
  76. mongodb.healthCheck(error => {
  77. if (error) {
  78. logger.err({ err: error }, 'failed mongo health check')
  79. }
  80. cb(error)
  81. })
  82. },
  83. ],
  84. error => {
  85. if (error) {
  86. return res.sendStatus(500)
  87. } else {
  88. return res.sendStatus(200)
  89. }
  90. }
  91. )
  92. })
  93. // record http metrics for the routes below this point
  94. app.use(Metrics.http.monitor(logger))
  95. app.param('project_id', (req, res, next, projectId) => {
  96. if (projectId != null && projectId.match(/^[0-9a-f]{24}$/)) {
  97. return next()
  98. } else {
  99. return next(new Error('invalid project id'))
  100. }
  101. })
  102. app.param('doc_id', (req, res, next, docId) => {
  103. if (docId != null && docId.match(/^[0-9a-f]{24}$/)) {
  104. return next()
  105. } else {
  106. return next(new Error('invalid doc id'))
  107. }
  108. })
  109. // Record requests that come in after we've started shutting down - for investigation.
  110. app.use((req, res, next) => {
  111. if (Settings.shuttingDown) {
  112. logger.warn(
  113. { req, timeSinceShutdown: Date.now() - Settings.shutDownTime },
  114. 'request received after shutting down'
  115. )
  116. // We don't want keep-alive connections to be kept open when the server is shutting down.
  117. res.set('Connection', 'close')
  118. }
  119. next()
  120. })
  121. app.get('/project/:project_id/doc/:doc_id', HttpController.getDoc)
  122. app.get(
  123. '/project/:project_id/doc/:doc_id/comment/:comment_id',
  124. HttpController.getComment
  125. )
  126. app.get('/project/:project_id/doc/:doc_id/peek', HttpController.peekDoc)
  127. app.get('/project/:project_id/ranges', HttpController.getProjectRanges)
  128. // temporarily keep the GET method for backwards compatibility
  129. app.get('/project/:project_id/doc', HttpController.getProjectDocsAndFlushIfOld)
  130. // will migrate to the POST method of get_and_flush_if_old instead
  131. app.post(
  132. '/project/:project_id/get_and_flush_if_old',
  133. HttpController.getProjectDocsAndFlushIfOld
  134. )
  135. app.get(
  136. '/project/:project_id/last_updated_at',
  137. HttpController.getProjectLastUpdatedAt
  138. )
  139. app.post('/project/:project_id/clearState', HttpController.clearProjectState)
  140. app.post('/project/:project_id/doc/:doc_id', HttpController.setDoc)
  141. app.post('/project/:project_id/doc/:doc_id/append', HttpController.appendToDoc)
  142. app.post(
  143. '/project/:project_id/doc/:doc_id/flush',
  144. HttpController.flushDocIfLoaded
  145. )
  146. app.delete('/project/:project_id/doc/:doc_id', HttpController.deleteDoc)
  147. app.delete('/project/:project_id', HttpController.deleteProject)
  148. app.delete('/project', HttpController.deleteMultipleProjects)
  149. app.post('/project/:project_id', HttpController.updateProject)
  150. app.post(
  151. '/project/:project_id/history/resync',
  152. longerTimeout,
  153. HttpController.resyncProjectHistory
  154. )
  155. app.post('/project/:project_id/flush', HttpController.flushProject)
  156. app.post(
  157. '/project/:project_id/doc/:doc_id/change/:change_id/accept',
  158. HttpController.acceptChanges
  159. )
  160. app.post(
  161. '/project/:project_id/doc/:doc_id/change/accept',
  162. HttpController.acceptChanges
  163. )
  164. app.post(
  165. '/project/:project_id/doc/:doc_id/change/reject',
  166. HttpController.rejectChanges
  167. )
  168. app.post(
  169. '/project/:project_id/doc/:doc_id/comment/:comment_id/resolve',
  170. HttpController.resolveComment
  171. )
  172. app.post(
  173. '/project/:project_id/doc/:doc_id/comment/:comment_id/reopen',
  174. HttpController.reopenComment
  175. )
  176. app.delete(
  177. '/project/:project_id/doc/:doc_id/comment/:comment_id',
  178. HttpController.deleteComment
  179. )
  180. app.post('/project/:project_id/block', HttpController.blockProject)
  181. app.post('/project/:project_id/unblock', HttpController.unblockProject)
  182. app.get('/flush_queued_projects', HttpController.flushQueuedProjects)
  183. app.get('/total', (req, res, next) => {
  184. const timer = new Metrics.Timer('http.allDocList')
  185. RedisManager.getCountOfDocsInMemory((err, count) => {
  186. if (err) {
  187. return next(err)
  188. }
  189. timer.done()
  190. res.send({ total: count })
  191. })
  192. })
  193. app.use((error, req, res, next) => {
  194. if (error instanceof Errors.NotFoundError) {
  195. return res.sendStatus(404)
  196. } else if (error instanceof Errors.OpRangeNotAvailableError) {
  197. return res.status(422).json(error.info)
  198. } else if (error instanceof Errors.FileTooLargeError) {
  199. return res.sendStatus(413)
  200. } else if (error.statusCode === 413) {
  201. return res.status(413).send('request entity too large')
  202. } else {
  203. logger.error({ err: error, req }, 'request errored')
  204. return res.status(500).send('Oops, something went wrong')
  205. }
  206. })
  207. const shutdownCleanly = signal => () => {
  208. logger.info({ signal }, 'received interrupt, cleaning up')
  209. if (Settings.shuttingDown) {
  210. logger.warn({ signal }, 'already shutting down, ignoring interrupt')
  211. return
  212. }
  213. Settings.shuttingDown = true
  214. // record the time we started shutting down
  215. Settings.shutDownTime = Date.now()
  216. setTimeout(() => {
  217. logger.info({ signal }, 'shutting down')
  218. process.exit()
  219. }, Settings.gracefulShutdownDelayInMs)
  220. }
  221. const watchForEvent = eventName => {
  222. docUpdaterRedisClient.on(eventName, e => {
  223. console.log(`redis event: ${eventName} ${e}`) // eslint-disable-line no-console
  224. })
  225. }
  226. const events = ['connect', 'ready', 'error', 'close', 'reconnecting', 'end']
  227. for (const eventName of events) {
  228. watchForEvent(eventName)
  229. }
  230. const port =
  231. Settings.internal.documentupdater.port ||
  232. (Settings.api &&
  233. Settings.api.documentupdater &&
  234. Settings.api.documentupdater.port) ||
  235. 3003
  236. const host = Settings.internal.documentupdater.host || '127.0.0.1'
  237. if (!module.parent) {
  238. // Called directly
  239. mongodb.mongoClient
  240. .connect()
  241. .then(() => {
  242. app.listen(port, host, function (err) {
  243. if (err) {
  244. logger.fatal({ err }, `Cannot bind to ${host}:${port}. Exiting.`)
  245. process.exit(1)
  246. }
  247. logger.info(
  248. `Document-updater starting up, listening on ${host}:${port}`
  249. )
  250. if (Settings.continuousBackgroundFlush) {
  251. logger.info('Starting continuous background flush')
  252. DeleteQueueManager.startBackgroundFlush()
  253. }
  254. })
  255. })
  256. .catch(err => {
  257. logger.fatal({ err }, 'Cannot connect to mongo. Exiting.')
  258. process.exit(1)
  259. })
  260. }
  261. module.exports = app
  262. for (const signal of [
  263. 'SIGINT',
  264. 'SIGHUP',
  265. 'SIGQUIT',
  266. 'SIGUSR1',
  267. 'SIGUSR2',
  268. 'SIGTERM',
  269. 'SIGABRT',
  270. ]) {
  271. process.on(signal, shutdownCleanly(signal))
  272. }
  273. process.on('uncaughtException', function (err) {
  274. logger.error({ err }, 'uncaught exception')
  275. shutdownCleanly('uncaughtException')()
  276. })
  277. function longerTimeout(req, res, next) {
  278. res.setTimeout(6 * 60 * 1000)
  279. next()
  280. }