server.js 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. import Settings from '@overleaf/settings'
  2. import Metrics from '@overleaf/metrics'
  3. import logger from '@overleaf/logger'
  4. import express from 'express'
  5. import bodyParser from 'body-parser'
  6. import * as Errors from './Errors.js'
  7. import * as Router from './Router.js'
  8. import * as Validation from './Validation.js'
  9. const HistoryLogger = logger.initialize('project-history').logger
  10. if (Settings.sentry.dsn) {
  11. logger.initializeErrorReporting(Settings.sentry.dsn)
  12. }
  13. Metrics.initialize('project-history')
  14. Metrics.event_loop.monitor(logger)
  15. Metrics.memory.monitor(logger)
  16. Metrics.leaked_sockets.monitor(logger)
  17. Metrics.open_sockets.monitor()
  18. // log updates as truncated strings
  19. function truncateFn(updates) {
  20. return JSON.parse(
  21. JSON.stringify(updates, function (key, value) {
  22. let len
  23. if (typeof value === 'string' && (len = value.length) > 80) {
  24. return (
  25. value.substr(0, 32) +
  26. `...(message of length ${len} truncated)...` +
  27. value.substr(-32)
  28. )
  29. } else {
  30. return value
  31. }
  32. })
  33. )
  34. }
  35. HistoryLogger.addSerializers({
  36. rawUpdate: truncateFn,
  37. rawUpdates: truncateFn,
  38. newUpdates: truncateFn,
  39. lastUpdate: truncateFn,
  40. })
  41. export const app = express()
  42. app.use(bodyParser.json())
  43. app.use(bodyParser.urlencoded({ extended: true }))
  44. app.use(Metrics.http.monitor(logger))
  45. Router.initialize(app)
  46. Metrics.injectMetricsRoute(app)
  47. app.use(Validation.errorMiddleware)
  48. app.use(function (error, req, res, next) {
  49. if (error instanceof Errors.NotFoundError) {
  50. res.sendStatus(404)
  51. } else if (error instanceof Errors.BadRequestError) {
  52. res.sendStatus(400)
  53. } else if (error instanceof Errors.InconsistentChunkError) {
  54. res.sendStatus(422)
  55. } else if (error instanceof Errors.TooManyRequestsError) {
  56. res.status(429).set('Retry-After', 300).end()
  57. } else {
  58. logger.error({ err: error, req }, error.message)
  59. res.status(500).json({ message: 'an internal error occurred' })
  60. }
  61. })