app.js 7.9 KB

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