server.ts 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. #!/usr/bin/env node
  2. /**
  3. * Copyright (c) 2018-2019 mol* contributors, licensed under MIT, See LICENSE file for more info.
  4. *
  5. * Taken/adapted from DensityServer (https://github.com/dsehnal/DensityServer)
  6. *
  7. * @author David Sehnal <david.sehnal@gmail.com>
  8. * @author Alexander Rose <alexander.rose@weirdbyte.de>
  9. */
  10. import compression from 'compression';
  11. import express from 'express';
  12. import { ConsoleLogger } from '../../mol-util/console-logger';
  13. import { configureServer, ServerConfig } from './config';
  14. import { State } from './server/state';
  15. import { VOLUME_SERVER_HEADER } from './server/version';
  16. import { init } from './server/web-api';
  17. function setupShutdown() {
  18. if (ServerConfig.shutdownTimeoutVarianceMinutes > ServerConfig.shutdownTimeoutMinutes) {
  19. ConsoleLogger.log('Server', 'Shutdown timeout variance is greater than the timer itself, ignoring.');
  20. } else {
  21. let tVar = 0;
  22. if (ServerConfig.shutdownTimeoutVarianceMinutes > 0) {
  23. tVar = 2 * (Math.random() - 0.5) * ServerConfig.shutdownTimeoutVarianceMinutes;
  24. }
  25. const tMs = (ServerConfig.shutdownTimeoutMinutes + tVar) * 60 * 1000;
  26. console.log(`----------------------------------------------------------------------------`);
  27. console.log(` The server will shut down in ${ConsoleLogger.formatTime(tMs)} to prevent slow performance.`);
  28. console.log(` Please make sure a daemon is running that will automatically restart it.`);
  29. console.log(`----------------------------------------------------------------------------`);
  30. console.log();
  31. setTimeout(() => {
  32. if (State.pendingQueries > 0) {
  33. State.shutdownOnZeroPending = true;
  34. } else {
  35. ConsoleLogger.log('Server', `Shut down due to timeout.`);
  36. process.exit(0);
  37. }
  38. }, tMs);
  39. }
  40. }
  41. configureServer();
  42. const port = process.env.port || ServerConfig.defaultPort;
  43. const app = express();
  44. app.use(compression({ level: 6, memLevel: 9, chunkSize: 16 * 16384, filter: () => true }));
  45. init(app);
  46. app.listen(port);
  47. console.log(VOLUME_SERVER_HEADER);
  48. console.log(``);
  49. console.log(`The server is running on port ${port}.`);
  50. console.log(``);
  51. if (ServerConfig.shutdownTimeoutMinutes > 0) {
  52. setupShutdown();
  53. }