app.js 10 KB

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