app.js 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307
  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. io.set('transports', ['websocket', 'xhr-polling'])
  67. })
  68. // Serve socket.io.js client file from imported dist folder
  69. // The express sendFile method correctly handles conditional
  70. // requests using the last-modified time and etag (which is
  71. // a combination of mtime and size)
  72. const socketIOClientFolder = require('socket.io-client').dist
  73. app.get('/socket.io/socket.io.js', function (req, res) {
  74. res.sendFile(Path.join(socketIOClientFolder, 'socket.io.min.js'))
  75. })
  76. // a 200 response on '/' is required for load balancer health checks
  77. // these operate separately from kubernetes readiness checks
  78. app.get('/', function (req, res) {
  79. if (Settings.shutDownInProgress || DeploymentManager.deploymentIsClosed()) {
  80. res.sendStatus(503) // Service unavailable
  81. } else {
  82. res.send('real-time is open')
  83. }
  84. })
  85. app.get('/status', function (req, res) {
  86. if (Settings.shutDownInProgress) {
  87. res.sendStatus(503) // Service unavailable
  88. } else {
  89. res.send('real-time is alive')
  90. }
  91. })
  92. app.get('/debug/events', function (req, res) {
  93. Settings.debugEvents = parseInt(req.query.count, 10) || 20
  94. logger.info({ count: Settings.debugEvents }, 'starting debug mode')
  95. res.send(`debug mode will log next ${Settings.debugEvents} events`)
  96. })
  97. const rclient = require('@overleaf/redis-wrapper').createClient(
  98. Settings.redis.realtime
  99. )
  100. function healthCheck(req, res) {
  101. rclient.healthCheck(function (error) {
  102. if (error) {
  103. logger.err({ err: error }, 'failed redis health check')
  104. res.sendStatus(500)
  105. } else if (HealthCheckManager.isFailing()) {
  106. const status = HealthCheckManager.status()
  107. logger.err({ pubSubErrors: status }, 'failed pubsub health check')
  108. res.sendStatus(500)
  109. } else {
  110. res.sendStatus(200)
  111. }
  112. })
  113. }
  114. app.get(
  115. '/health_check',
  116. (req, res, next) => {
  117. if (Settings.shutDownComplete) {
  118. return res.sendStatus(503)
  119. }
  120. next()
  121. },
  122. healthCheck
  123. )
  124. app.get('/health_check/redis', healthCheck)
  125. // log http requests for routes defined from this point onwards
  126. app.use(Metrics.http.monitor(logger))
  127. const Router = require('./app/js/Router')
  128. Router.configure(app, io, sessionSockets)
  129. const WebsocketLoadBalancer = require('./app/js/WebsocketLoadBalancer')
  130. WebsocketLoadBalancer.listenForEditorEvents(io)
  131. const DocumentUpdaterController = require('./app/js/DocumentUpdaterController')
  132. DocumentUpdaterController.listenForUpdatesFromDocumentUpdater(io)
  133. const { port } = Settings.internal.realTime
  134. const { host } = Settings.internal.realTime
  135. server.listen(port, host, function (error) {
  136. if (error) {
  137. throw error
  138. }
  139. logger.info(`realtime starting up, listening on ${host}:${port}`)
  140. })
  141. // Stop huge stack traces in logs from all the socket.io parsing steps.
  142. Error.stackTraceLimit = 10
  143. function shutdownAfterAllClientsHaveDisconnected() {
  144. const connectedClients = io.sockets.clients().length
  145. if (connectedClients === 0) {
  146. logger.info({}, 'no clients connected, exiting')
  147. process.exit()
  148. } else {
  149. logger.info(
  150. { connectedClients },
  151. 'clients still connected, not shutting down yet'
  152. )
  153. setTimeout(() => shutdownAfterAllClientsHaveDisconnected(), 5_000)
  154. }
  155. }
  156. function drainAndShutdown(signal) {
  157. if (Settings.shutDownInProgress) {
  158. logger.info({ signal }, 'shutdown already in progress, ignoring signal')
  159. } else {
  160. Settings.shutDownInProgress = true
  161. const { statusCheckInterval } = Settings
  162. if (statusCheckInterval) {
  163. logger.info(
  164. { signal },
  165. `received interrupt, delay drain by ${statusCheckInterval}ms`
  166. )
  167. }
  168. setTimeout(function () {
  169. logger.info(
  170. { signal },
  171. `received interrupt, starting drain over ${shutdownDrainTimeWindow} mins`
  172. )
  173. DrainManager.startDrainTimeWindow(io, shutdownDrainTimeWindow, () => {
  174. shutdownAfterAllClientsHaveDisconnected()
  175. setTimeout(() => {
  176. const staleClients = io.sockets.clients()
  177. if (staleClients.length !== 0) {
  178. logger.info(
  179. { staleClients: staleClients.map(client => client.id) },
  180. 'forcefully disconnecting stale clients'
  181. )
  182. staleClients.forEach(client => {
  183. client.disconnect()
  184. })
  185. }
  186. // Mark the node as unhealthy.
  187. Settings.shutDownComplete = true
  188. }, Settings.gracefulReconnectTimeoutMs)
  189. })
  190. }, statusCheckInterval)
  191. }
  192. }
  193. Settings.shutDownInProgress = false
  194. const shutdownDrainTimeWindow = parseInt(Settings.shutdownDrainTimeWindow, 10)
  195. if (Settings.shutdownDrainTimeWindow) {
  196. logger.info({ shutdownDrainTimeWindow }, 'shutdownDrainTimeWindow enabled')
  197. for (const signal of [
  198. 'SIGINT',
  199. 'SIGHUP',
  200. 'SIGQUIT',
  201. 'SIGUSR1',
  202. 'SIGUSR2',
  203. 'SIGTERM',
  204. 'SIGABRT',
  205. ]) {
  206. process.on(signal, drainAndShutdown)
  207. } // signal is passed as argument to event handler
  208. // global exception handler
  209. if (Settings.errors && Settings.errors.catchUncaughtErrors) {
  210. process.removeAllListeners('uncaughtException')
  211. process.on('uncaughtException', function (error) {
  212. if (
  213. [
  214. 'ETIMEDOUT',
  215. 'EHOSTUNREACH',
  216. 'EPIPE',
  217. 'ECONNRESET',
  218. 'ERR_STREAM_WRITE_AFTER_END',
  219. ].includes(error.code) ||
  220. // socket.io error handler sending on polling connection again.
  221. (error.code === 'ERR_HTTP_HEADERS_SENT' &&
  222. error.stack &&
  223. error.stack.includes('Transport.error'))
  224. ) {
  225. Metrics.inc('disconnected_write', 1, { status: error.code })
  226. return logger.warn(
  227. { err: error },
  228. 'attempted to write to disconnected client'
  229. )
  230. }
  231. logger.error({ err: error }, 'uncaught exception')
  232. if (Settings.errors && Settings.errors.shutdownOnUncaughtError) {
  233. drainAndShutdown('SIGABRT')
  234. }
  235. })
  236. }
  237. }
  238. if (Settings.continualPubsubTraffic) {
  239. logger.debug('continualPubsubTraffic enabled')
  240. const pubsubClient = redis.createClient(Settings.redis.pubsub)
  241. const clusterClient = redis.createClient(Settings.redis.websessions)
  242. const publishJob = function (channel, callback) {
  243. const checker = new HealthCheckManager(channel)
  244. logger.debug({ channel }, 'sending pub to keep connection alive')
  245. const json = JSON.stringify({
  246. health_check: true,
  247. key: checker.id,
  248. date: new Date().toString(),
  249. })
  250. Metrics.summary(`redis.publish.${channel}`, json.length)
  251. pubsubClient.publish(channel, json, function (err) {
  252. if (err) {
  253. logger.err({ err, channel }, 'error publishing pubsub traffic to redis')
  254. }
  255. const blob = JSON.stringify({ keep: 'alive' })
  256. Metrics.summary('redis.publish.cluster-continual-traffic', blob.length)
  257. clusterClient.publish('cluster-continual-traffic', blob, callback)
  258. })
  259. }
  260. const runPubSubTraffic = () =>
  261. async.map(['applied-ops', 'editor-events'], publishJob, () =>
  262. setTimeout(runPubSubTraffic, 1000 * 20)
  263. )
  264. runPubSubTraffic()
  265. }