app.js 4.6 KB

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