app.js 4.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172
  1. 'use strict'
  2. /* eslint-disable no-console */
  3. // Initialize metrics as early as possible because this is where the Google
  4. // profiling agents are also started.
  5. const Metrics = require('@overleaf/metrics')
  6. Metrics.initialize('history-v1')
  7. const BPromise = require('bluebird')
  8. const express = require('express')
  9. const cors = require('cors')
  10. const helmet = require('helmet')
  11. const HTTPStatus = require('http-status')
  12. const logger = require('@overleaf/logger')
  13. const cookieParser = require('cookie-parser')
  14. const bodyParser = require('body-parser')
  15. const swaggerTools = require('swagger-tools')
  16. const swaggerDoc = require('./api/swagger')
  17. const security = require('./api/app/security')
  18. const healthChecks = require('./api/controllers/health_checks')
  19. const { mongodb, loadGlobalBlobs } = require('./storage')
  20. const path = require('path')
  21. const app = express()
  22. module.exports = app
  23. logger.initialize('history-v1')
  24. Metrics.open_sockets.monitor()
  25. Metrics.injectMetricsRoute(app)
  26. app.use(Metrics.http.monitor(logger))
  27. Metrics.leaked_sockets.monitor(logger)
  28. // We may have fairly large JSON bodies when receiving large Changes. Clients
  29. // may have to handle 413 status codes and try creating files instead of sending
  30. // text content in changes.
  31. app.use(bodyParser.json({ limit: '4MB' }))
  32. app.use(
  33. bodyParser.urlencoded({
  34. extended: false,
  35. })
  36. )
  37. app.use(cookieParser())
  38. app.use(cors())
  39. security.setupSSL(app)
  40. security.setupBasicHttpAuthForSwaggerDocs(app)
  41. app.use(function (req, res, next) {
  42. // use a 5 minute timeout on all responses
  43. res.setTimeout(5 * 60 * 1000)
  44. next()
  45. })
  46. app.get('/', function (req, res) {
  47. res.send('')
  48. })
  49. app.get('/status', healthChecks.status)
  50. app.get('/health_check', healthChecks.healthCheck)
  51. function setupSwagger() {
  52. return new BPromise(function (resolve) {
  53. swaggerTools.initializeMiddleware(swaggerDoc, function (middleware) {
  54. app.use(middleware.swaggerMetadata())
  55. app.use(middleware.swaggerSecurity(security.getSwaggerHandlers()))
  56. app.use(middleware.swaggerValidator())
  57. app.use(
  58. middleware.swaggerRouter({
  59. controllers: path.join(__dirname, 'api/controllers'),
  60. useStubs: app.get('env') === 'development',
  61. })
  62. )
  63. app.use(middleware.swaggerUi())
  64. resolve()
  65. })
  66. })
  67. }
  68. function setupErrorHandling() {
  69. app.use(function (req, res, next) {
  70. const err = new Error('Not Found')
  71. err.status = HTTPStatus.NOT_FOUND
  72. return next(err)
  73. })
  74. // Handle Swagger errors.
  75. app.use(function (err, req, res, next) {
  76. if (res.headersSent) {
  77. return next(err)
  78. }
  79. if (err.code === 'SCHEMA_VALIDATION_FAILED') {
  80. logger.error(err)
  81. return res.status(HTTPStatus.UNPROCESSABLE_ENTITY).json(err.results)
  82. }
  83. if (err.code === 'INVALID_TYPE' || err.code === 'PATTERN') {
  84. logger.error(err)
  85. return res.status(HTTPStatus.UNPROCESSABLE_ENTITY).json({
  86. message: 'invalid type: ' + err.paramName,
  87. })
  88. }
  89. if (err.code === 'ENUM_MISMATCH') {
  90. return res.status(HTTPStatus.UNPROCESSABLE_ENTITY).json({
  91. message: 'invalid enum value: ' + err.paramName,
  92. })
  93. }
  94. if (err.code === 'REQUIRED') {
  95. return res.status(HTTPStatus.UNPROCESSABLE_ENTITY).json({
  96. message: err.message,
  97. })
  98. }
  99. next(err)
  100. })
  101. app.use(function (err, req, res, next) {
  102. logger.error(err)
  103. if (res.headersSent) {
  104. return next(err)
  105. }
  106. // Handle errors that specify a statusCode. Some come from our code. Some
  107. // bubble up from AWS SDK, but they sometimes have the statusCode set to
  108. // 200, notably some InternalErrors and TimeoutErrors, so we have to guard
  109. // against that. We also check `status`, but `statusCode` is preferred.
  110. const statusCode = err.statusCode || err.status
  111. if (statusCode && statusCode >= 400 && statusCode < 600) {
  112. res.status(statusCode)
  113. } else {
  114. res.status(HTTPStatus.INTERNAL_SERVER_ERROR)
  115. }
  116. const sendErrorToClient = app.get('env') === 'development'
  117. res.json({
  118. message: err.message,
  119. error: sendErrorToClient ? err : {},
  120. })
  121. })
  122. }
  123. app.setup = async function appSetup() {
  124. await mongodb.client.connect()
  125. logger.info('Connected to MongoDB')
  126. await loadGlobalBlobs()
  127. logger.info('Global blobs loaded')
  128. app.use(helmet())
  129. await setupSwagger()
  130. setupErrorHandling()
  131. }
  132. async function startApp() {
  133. await app.setup()
  134. const port = parseInt(process.env.PORT, 10) || 3100
  135. app.listen(port, err => {
  136. if (err) {
  137. console.error(err)
  138. process.exit(1)
  139. }
  140. Metrics.event_loop.monitor(logger)
  141. Metrics.memory.monitor(logger)
  142. })
  143. }
  144. // Run this if we're called directly
  145. if (!module.parent) {
  146. startApp().catch(err => {
  147. console.error(err)
  148. process.exit(1)
  149. })
  150. }