server.js 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  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. // log updates as truncated strings
  17. function truncateFn(updates) {
  18. return JSON.parse(
  19. JSON.stringify(updates, function (key, value) {
  20. let len
  21. if (typeof value === 'string' && (len = value.length) > 80) {
  22. return (
  23. value.substr(0, 32) +
  24. `...(message of length ${len} truncated)...` +
  25. value.substr(-32)
  26. )
  27. } else {
  28. return value
  29. }
  30. })
  31. )
  32. }
  33. HistoryLogger.addSerializers({
  34. rawUpdate: truncateFn,
  35. rawUpdates: truncateFn,
  36. newUpdates: truncateFn,
  37. lastUpdate: truncateFn,
  38. })
  39. export const app = express()
  40. app.use(bodyParser.json())
  41. app.use(bodyParser.urlencoded({ extended: true }))
  42. app.use(Metrics.http.monitor(logger))
  43. Router.initialize(app)
  44. Metrics.injectMetricsRoute(app)
  45. app.use(Validation.errorMiddleware)
  46. app.use(function (error, req, res, next) {
  47. if (error instanceof Errors.NotFoundError) {
  48. res.sendStatus(404)
  49. } else if (error instanceof Errors.BadRequestError) {
  50. res.sendStatus(400)
  51. } else if (error instanceof Errors.InconsistentChunkError) {
  52. res.sendStatus(422)
  53. } else if (error instanceof Errors.TooManyRequestsError) {
  54. res.status(429).set('Retry-After', 300).end()
  55. } else {
  56. logger.error({ err: error, req }, error.message)
  57. res.status(500).json({ message: 'an internal error occurred' })
  58. }
  59. })