app.js 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196
  1. /*
  2. * decaffeinate suggestions:
  3. * DS101: Remove unnecessary use of Array.from
  4. * DS102: Remove unnecessary code created because of implicit returns
  5. * DS103: Rewrite code to no longer use __guard__
  6. * DS207: Consider shorter variations of null checks
  7. * Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md
  8. */
  9. const Metrics = require("metrics-sharelatex");
  10. Metrics.initialize("doc-updater");
  11. const express = require('express');
  12. const http = require("http");
  13. const Settings = require('settings-sharelatex');
  14. const logger = require('logger-sharelatex');
  15. logger.initialize("document-updater");
  16. logger.logger.addSerializers(require("./app/js/LoggerSerializers"));
  17. if ((Settings.sentry != null ? Settings.sentry.dsn : undefined) != null) {
  18. logger.initializeErrorReporting(Settings.sentry.dsn);
  19. }
  20. const RedisManager = require('./app/js/RedisManager');
  21. const DispatchManager = require('./app/js/DispatchManager');
  22. const DeleteQueueManager = require('./app/js/DeleteQueueManager');
  23. const Errors = require("./app/js/Errors");
  24. const HttpController = require("./app/js/HttpController");
  25. const mongojs = require("./app/js/mongojs");
  26. const async = require("async");
  27. const Path = require("path");
  28. const bodyParser = require("body-parser");
  29. Metrics.mongodb.monitor(Path.resolve(__dirname + "/node_modules/mongojs/node_modules/mongodb"), logger);
  30. Metrics.event_loop.monitor(logger, 100);
  31. const app = express();
  32. app.use(Metrics.http.monitor(logger));
  33. app.use(bodyParser.json({limit: (Settings.max_doc_length + (64 * 1024))}));
  34. Metrics.injectMetricsRoute(app);
  35. DispatchManager.createAndStartDispatchers(Settings.dispatcherCount || 10);
  36. app.param('project_id', function(req, res, next, project_id) {
  37. if ((project_id != null ? project_id.match(/^[0-9a-f]{24}$/) : undefined)) {
  38. return next();
  39. } else {
  40. return next(new Error("invalid project id"));
  41. }
  42. });
  43. app.param('doc_id', function(req, res, next, doc_id) {
  44. if ((doc_id != null ? doc_id.match(/^[0-9a-f]{24}$/) : undefined)) {
  45. return next();
  46. } else {
  47. return next(new Error("invalid doc id"));
  48. }
  49. });
  50. app.get('/project/:project_id/doc/:doc_id', HttpController.getDoc);
  51. // temporarily keep the GET method for backwards compatibility
  52. app.get('/project/:project_id/doc', HttpController.getProjectDocsAndFlushIfOld);
  53. // will migrate to the POST method of get_and_flush_if_old instead
  54. app.post('/project/:project_id/get_and_flush_if_old', HttpController.getProjectDocsAndFlushIfOld);
  55. app.post('/project/:project_id/clearState', HttpController.clearProjectState);
  56. app.post('/project/:project_id/doc/:doc_id', HttpController.setDoc);
  57. app.post('/project/:project_id/doc/:doc_id/flush', HttpController.flushDocIfLoaded);
  58. app.delete('/project/:project_id/doc/:doc_id', HttpController.deleteDoc);
  59. app.delete('/project/:project_id', HttpController.deleteProject);
  60. app.delete('/project', HttpController.deleteMultipleProjects);
  61. app.post('/project/:project_id', HttpController.updateProject);
  62. app.post('/project/:project_id/history/resync', HttpController.resyncProjectHistory);
  63. app.post('/project/:project_id/flush', HttpController.flushProject);
  64. app.post('/project/:project_id/doc/:doc_id/change/:change_id/accept', HttpController.acceptChanges);
  65. app.post('/project/:project_id/doc/:doc_id/change/accept', HttpController.acceptChanges);
  66. app.delete('/project/:project_id/doc/:doc_id/comment/:comment_id', HttpController.deleteComment);
  67. app.get('/flush_all_projects', HttpController.flushAllProjects);
  68. app.get('/flush_queued_projects', HttpController.flushQueuedProjects);
  69. app.get('/total', function(req, res){
  70. const timer = new Metrics.Timer("http.allDocList");
  71. return RedisManager.getCountOfDocsInMemory(function(err, count){
  72. timer.done();
  73. return res.send({total:count});});
  74. });
  75. app.get('/status', function(req, res){
  76. if (Settings.shuttingDown) {
  77. return res.sendStatus(503); // Service unavailable
  78. } else {
  79. return res.send('document updater is alive');
  80. }
  81. });
  82. const pubsubClient = require("redis-sharelatex").createClient(Settings.redis.pubsub);
  83. app.get("/health_check/redis", (req, res, next) => pubsubClient.healthCheck(function(error) {
  84. if (error != null) {
  85. logger.err({err: error}, "failed redis health check");
  86. return res.sendStatus(500);
  87. } else {
  88. return res.sendStatus(200);
  89. }
  90. }));
  91. const docUpdaterRedisClient = require("redis-sharelatex").createClient(Settings.redis.documentupdater);
  92. app.get("/health_check/redis_cluster", (req, res, next) => docUpdaterRedisClient.healthCheck(function(error) {
  93. if (error != null) {
  94. logger.err({err: error}, "failed redis cluster health check");
  95. return res.sendStatus(500);
  96. } else {
  97. return res.sendStatus(200);
  98. }
  99. }));
  100. app.get("/health_check", (req, res, next) => async.series([
  101. cb => pubsubClient.healthCheck(function(error) {
  102. if (error != null) {
  103. logger.err({err: error}, "failed redis health check");
  104. }
  105. return cb(error);
  106. }),
  107. cb => docUpdaterRedisClient.healthCheck(function(error) {
  108. if (error != null) {
  109. logger.err({err: error}, "failed redis cluster health check");
  110. }
  111. return cb(error);
  112. }),
  113. cb => mongojs.healthCheck(function(error) {
  114. if (error != null) {
  115. logger.err({err: error}, "failed mongo health check");
  116. }
  117. return cb(error);
  118. })
  119. ] , function(error) {
  120. if (error != null) {
  121. return res.sendStatus(500);
  122. } else {
  123. return res.sendStatus(200);
  124. }
  125. }));
  126. app.use(function(error, req, res, next) {
  127. if (error instanceof Errors.NotFoundError) {
  128. return res.sendStatus(404);
  129. } else if (error instanceof Errors.OpRangeNotAvailableError) {
  130. return res.sendStatus(422); // Unprocessable Entity
  131. } else if (error.statusCode === 413) {
  132. return res.status(413).send("request entity too large");
  133. } else {
  134. logger.error({err: error, req}, "request errored");
  135. return res.status(500).send("Oops, something went wrong");
  136. }
  137. });
  138. const shutdownCleanly = signal => (function() {
  139. logger.log({signal}, "received interrupt, cleaning up");
  140. Settings.shuttingDown = true;
  141. return setTimeout(function() {
  142. logger.log({signal}, "shutting down");
  143. return process.exit();
  144. }
  145. , 10000);
  146. });
  147. const watchForEvent = eventName => docUpdaterRedisClient.on(eventName, e => console.log(`redis event: ${eventName} ${e}`));
  148. const events = ["connect", "ready", "error", "close", "reconnecting", "end"];
  149. for (let eventName of Array.from(events)) {
  150. watchForEvent(eventName);
  151. }
  152. const port = __guard__(Settings.internal != null ? Settings.internal.documentupdater : undefined, x => x.port) || __guard__(Settings.apis != null ? Settings.apis.documentupdater : undefined, x1 => x1.port) || 3003;
  153. const host = Settings.internal.documentupdater.host || "localhost";
  154. if (!module.parent) { // Called directly
  155. app.listen(port, host, function() {
  156. logger.info(`Document-updater starting up, listening on ${host}:${port}`);
  157. if (Settings.continuousBackgroundFlush) {
  158. logger.info("Starting continuous background flush");
  159. return DeleteQueueManager.startBackgroundFlush();
  160. }
  161. });
  162. }
  163. module.exports = app;
  164. for (let signal of ['SIGINT', 'SIGHUP', 'SIGQUIT', 'SIGUSR1', 'SIGUSR2', 'SIGTERM', 'SIGABRT']) {
  165. process.on(signal, shutdownCleanly(signal));
  166. }
  167. function __guard__(value, transform) {
  168. return (typeof value !== 'undefined' && value !== null) ? transform(value) : undefined;
  169. }