app.js 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312
  1. // Metrics must be initialized before importing anything else
  2. require('@overleaf/metrics/initialize')
  3. const Metrics = require('@overleaf/metrics')
  4. const Settings = require('@overleaf/settings')
  5. const async = require('async')
  6. const logger = require('@overleaf/logger')
  7. logger.initialize('real-time')
  8. Metrics.event_loop.monitor(logger)
  9. Metrics.open_sockets.monitor()
  10. const express = require('express')
  11. const session = require('express-session')
  12. const redis = require('@overleaf/redis-wrapper')
  13. const sessionRedisClient = redis.createClient(Settings.redis.websessions)
  14. const RedisStore = require('connect-redis')(session)
  15. const SessionSockets = require('./app/js/SessionSockets')
  16. const CookieParser = require('cookie-parser')
  17. const DrainManager = require('./app/js/DrainManager')
  18. const HealthCheckManager = require('./app/js/HealthCheckManager')
  19. const DeploymentManager = require('./app/js/DeploymentManager')
  20. const Path = require('node:path')
  21. // NOTE: debug is invoked for every blob that is put on the wire
  22. const socketIoLogger = {
  23. error(...message) {
  24. logger.debug({ fromSocketIo: true, originalLevel: 'error' }, ...message)
  25. },
  26. warn(...message) {
  27. logger.debug({ fromSocketIo: true, originalLevel: 'warn' }, ...message)
  28. },
  29. info() {},
  30. debug() {},
  31. log() {},
  32. }
  33. // monitor status file to take dark deployments out of the load-balancer
  34. DeploymentManager.initialise()
  35. // Set up socket.io server
  36. const app = express()
  37. const server = require('node:http').createServer(app)
  38. server.keepAliveTimeout = Settings.keepAliveTimeoutMs
  39. const io = require('socket.io').listen(server, {
  40. logger: socketIoLogger,
  41. })
  42. // Bind to sessions
  43. const sessionStore = new RedisStore({ client: sessionRedisClient })
  44. if (!Settings.security.sessionSecret) {
  45. throw new Error('No SESSION_SECRET provided.')
  46. }
  47. const sessionSecrets = [
  48. Settings.security.sessionSecret,
  49. Settings.security.sessionSecretUpcoming,
  50. Settings.security.sessionSecretFallback,
  51. ].filter(Boolean)
  52. const cookieParser = CookieParser(sessionSecrets)
  53. const sessionSockets = new SessionSockets(
  54. io,
  55. sessionStore,
  56. cookieParser,
  57. Settings.cookieName
  58. )
  59. Metrics.injectMetricsRoute(app)
  60. io.configure(function () {
  61. // Don't use socket.io to serve client
  62. io.disable('browser client')
  63. // Fix for Safari 5 error of "Error during WebSocket handshake: location mismatch"
  64. // See http://answers.dotcloud.com/question/578/problem-with-websocket-over-ssl-in-safari-with
  65. io.set('match origin protocol', true)
  66. // gzip uses a Node 0.8.x method of calling the gzip program which
  67. // doesn't work with 0.6.x
  68. // io.enable('browser client gzip')
  69. io.set('transports', [
  70. 'websocket',
  71. 'flashsocket',
  72. 'htmlfile',
  73. 'xhr-polling',
  74. 'jsonp-polling',
  75. ])
  76. })
  77. // Serve socket.io.js client file from imported dist folder
  78. // The express sendFile method correctly handles conditional
  79. // requests using the last-modified time and etag (which is
  80. // a combination of mtime and size)
  81. const socketIOClientFolder = require('socket.io-client').dist
  82. app.get('/socket.io/socket.io.js', function (req, res) {
  83. res.sendFile(Path.join(socketIOClientFolder, 'socket.io.min.js'))
  84. })
  85. // a 200 response on '/' is required for load balancer health checks
  86. // these operate separately from kubernetes readiness checks
  87. app.get('/', function (req, res) {
  88. if (Settings.shutDownInProgress || DeploymentManager.deploymentIsClosed()) {
  89. res.sendStatus(503) // Service unavailable
  90. } else {
  91. res.send('real-time is open')
  92. }
  93. })
  94. app.get('/status', function (req, res) {
  95. if (Settings.shutDownInProgress) {
  96. res.sendStatus(503) // Service unavailable
  97. } else {
  98. res.send('real-time is alive')
  99. }
  100. })
  101. app.get('/debug/events', function (req, res) {
  102. Settings.debugEvents = parseInt(req.query.count, 10) || 20
  103. logger.info({ count: Settings.debugEvents }, 'starting debug mode')
  104. res.send(`debug mode will log next ${Settings.debugEvents} events`)
  105. })
  106. const rclient = require('@overleaf/redis-wrapper').createClient(
  107. Settings.redis.realtime
  108. )
  109. function healthCheck(req, res) {
  110. rclient.healthCheck(function (error) {
  111. if (error) {
  112. logger.err({ err: error }, 'failed redis health check')
  113. res.sendStatus(500)
  114. } else if (HealthCheckManager.isFailing()) {
  115. const status = HealthCheckManager.status()
  116. logger.err({ pubSubErrors: status }, 'failed pubsub health check')
  117. res.sendStatus(500)
  118. } else {
  119. res.sendStatus(200)
  120. }
  121. })
  122. }
  123. app.get(
  124. '/health_check',
  125. (req, res, next) => {
  126. if (Settings.shutDownComplete) {
  127. return res.sendStatus(503)
  128. }
  129. next()
  130. },
  131. healthCheck
  132. )
  133. app.get('/health_check/redis', healthCheck)
  134. // log http requests for routes defined from this point onwards
  135. app.use(Metrics.http.monitor(logger))
  136. const Router = require('./app/js/Router')
  137. Router.configure(app, io, sessionSockets)
  138. const WebsocketLoadBalancer = require('./app/js/WebsocketLoadBalancer')
  139. WebsocketLoadBalancer.listenForEditorEvents(io)
  140. const DocumentUpdaterController = require('./app/js/DocumentUpdaterController')
  141. DocumentUpdaterController.listenForUpdatesFromDocumentUpdater(io)
  142. const { port } = Settings.internal.realTime
  143. const { host } = Settings.internal.realTime
  144. server.listen(port, host, function (error) {
  145. if (error) {
  146. throw error
  147. }
  148. logger.info(`realtime starting up, listening on ${host}:${port}`)
  149. })
  150. // Stop huge stack traces in logs from all the socket.io parsing steps.
  151. Error.stackTraceLimit = 10
  152. function shutdownAfterAllClientsHaveDisconnected() {
  153. const connectedClients = io.sockets.clients().length
  154. if (connectedClients === 0) {
  155. logger.info({}, 'no clients connected, exiting')
  156. process.exit()
  157. } else {
  158. logger.info(
  159. { connectedClients },
  160. 'clients still connected, not shutting down yet'
  161. )
  162. setTimeout(() => shutdownAfterAllClientsHaveDisconnected(), 5_000)
  163. }
  164. }
  165. function drainAndShutdown(signal) {
  166. if (Settings.shutDownInProgress) {
  167. logger.info({ signal }, 'shutdown already in progress, ignoring signal')
  168. } else {
  169. Settings.shutDownInProgress = true
  170. const { statusCheckInterval } = Settings
  171. if (statusCheckInterval) {
  172. logger.info(
  173. { signal },
  174. `received interrupt, delay drain by ${statusCheckInterval}ms`
  175. )
  176. }
  177. setTimeout(function () {
  178. logger.info(
  179. { signal },
  180. `received interrupt, starting drain over ${shutdownDrainTimeWindow} mins`
  181. )
  182. DrainManager.startDrainTimeWindow(io, shutdownDrainTimeWindow, () => {
  183. shutdownAfterAllClientsHaveDisconnected()
  184. setTimeout(() => {
  185. const staleClients = io.sockets.clients()
  186. if (staleClients.length !== 0) {
  187. logger.info(
  188. { staleClients: staleClients.map(client => client.id) },
  189. 'forcefully disconnecting stale clients'
  190. )
  191. staleClients.forEach(client => {
  192. client.disconnect()
  193. })
  194. }
  195. // Mark the node as unhealthy.
  196. Settings.shutDownComplete = true
  197. }, Settings.gracefulReconnectTimeoutMs)
  198. })
  199. }, statusCheckInterval)
  200. }
  201. }
  202. Settings.shutDownInProgress = false
  203. const shutdownDrainTimeWindow = parseInt(Settings.shutdownDrainTimeWindow, 10)
  204. if (Settings.shutdownDrainTimeWindow) {
  205. logger.info({ shutdownDrainTimeWindow }, 'shutdownDrainTimeWindow enabled')
  206. for (const signal of [
  207. 'SIGINT',
  208. 'SIGHUP',
  209. 'SIGQUIT',
  210. 'SIGUSR1',
  211. 'SIGUSR2',
  212. 'SIGTERM',
  213. 'SIGABRT',
  214. ]) {
  215. process.on(signal, drainAndShutdown)
  216. } // signal is passed as argument to event handler
  217. // global exception handler
  218. if (Settings.errors && Settings.errors.catchUncaughtErrors) {
  219. process.removeAllListeners('uncaughtException')
  220. process.on('uncaughtException', function (error) {
  221. if (
  222. [
  223. 'ETIMEDOUT',
  224. 'EHOSTUNREACH',
  225. 'EPIPE',
  226. 'ECONNRESET',
  227. 'ERR_STREAM_WRITE_AFTER_END',
  228. ].includes(error.code)
  229. ) {
  230. Metrics.inc('disconnected_write', 1, { status: error.code })
  231. return logger.warn(
  232. { err: error },
  233. 'attempted to write to disconnected client'
  234. )
  235. }
  236. logger.error({ err: error }, 'uncaught exception')
  237. if (Settings.errors && Settings.errors.shutdownOnUncaughtError) {
  238. drainAndShutdown('SIGABRT')
  239. }
  240. })
  241. }
  242. }
  243. if (Settings.continualPubsubTraffic) {
  244. logger.debug('continualPubsubTraffic enabled')
  245. const pubsubClient = redis.createClient(Settings.redis.pubsub)
  246. const clusterClient = redis.createClient(Settings.redis.websessions)
  247. const publishJob = function (channel, callback) {
  248. const checker = new HealthCheckManager(channel)
  249. logger.debug({ channel }, 'sending pub to keep connection alive')
  250. const json = JSON.stringify({
  251. health_check: true,
  252. key: checker.id,
  253. date: new Date().toString(),
  254. })
  255. Metrics.summary(`redis.publish.${channel}`, json.length)
  256. pubsubClient.publish(channel, json, function (err) {
  257. if (err) {
  258. logger.err({ err, channel }, 'error publishing pubsub traffic to redis')
  259. }
  260. const blob = JSON.stringify({ keep: 'alive' })
  261. Metrics.summary('redis.publish.cluster-continual-traffic', blob.length)
  262. clusterClient.publish('cluster-continual-traffic', blob, callback)
  263. })
  264. }
  265. const runPubSubTraffic = () =>
  266. async.map(['applied-ops', 'editor-events'], publishJob, () =>
  267. setTimeout(runPubSubTraffic, 1000 * 20)
  268. )
  269. runPubSubTraffic()
  270. }