index.js 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185
  1. 'use strict';
  2. const util = require("util");
  3. process.env.NODE_CONFIG_DIR = `${__dirname}/config`;
  4. const config = require("config");
  5. process.on('uncaughtException', err => {
  6. if (err.code === 'ECONNREFUSED' || err.code === 'UNCERTAIN_STATE') return;
  7. console.log(`UNCAUGHT EXCEPTION: ${err.stack}`);
  8. });
  9. const fancyConsole = config.get("fancyConsole");
  10. class ModuleManager {
  11. constructor() {
  12. this.modules = {};
  13. this.modulesInitialized = 0;
  14. this.totalModules = 0;
  15. this.modulesLeft = [];
  16. this.i = 0;
  17. this.lockdown = false;
  18. this.fancyConsole = fancyConsole;
  19. }
  20. addModule(moduleName) {
  21. console.log("add module", moduleName);
  22. const moduleClass = new require(`./logic/${moduleName}`);
  23. this.modules[moduleName] = new moduleClass(moduleName, this);
  24. this.totalModules++;
  25. this.modulesLeft.push(moduleName);
  26. }
  27. initialize() {
  28. if (!this.modules["logger"]) return console.error("There is no logger module");
  29. this.logger = this.modules["logger"];
  30. if (this.fancyConsole) {
  31. this.replaceConsoleWithLogger();
  32. this.logger.reservedLines = Object.keys(this.modules).length + 5;
  33. }
  34. for (let moduleName in this.modules) {
  35. let module = this.modules[moduleName];
  36. if (this.lockdown) break;
  37. module._onInitialize().then(() => {
  38. this.moduleInitialized(moduleName);
  39. });
  40. let dependenciesInitializedPromises = [];
  41. module.dependsOn.forEach(dependencyName => {
  42. let dependency = this.modules[dependencyName];
  43. dependenciesInitializedPromises.push(dependency._onInitialize());
  44. });
  45. module.lastTime = Date.now();
  46. Promise.all(dependenciesInitializedPromises).then((res, res2) => {
  47. if (this.lockdown) return;
  48. this.logger.info("MODULE_MANAGER", `${moduleName} dependencies have been completed`);
  49. module._initialize();
  50. });
  51. }
  52. }
  53. async printStatus() {
  54. try { await Promise.race([this.logger._onInitialize(), this.logger._isInitialized()]); } catch { return; }
  55. if (!this.fancyConsole) return;
  56. let colors = this.logger.colors;
  57. const rows = process.stdout.rows;
  58. process.stdout.cursorTo(0, rows - this.logger.reservedLines);
  59. process.stdout.clearScreenDown();
  60. process.stdout.cursorTo(0, (rows - this.logger.reservedLines) + 2);
  61. process.stdout.write(`${colors.FgYellow}Modules${colors.FgWhite}:\n`);
  62. for (let moduleName in this.modules) {
  63. let module = this.modules[moduleName];
  64. let tabsAmount = Math.max(0, Math.ceil(2 - (moduleName.length / 8)));
  65. let tabs = Array(tabsAmount).fill(`\t`).join("");
  66. let timing = module.timeDifferences.map((timeDifference) => {
  67. return `${colors.FgMagenta}${timeDifference}${colors.FgCyan}ms${colors.FgWhite}`;
  68. }).join(", ");
  69. let stateColor;
  70. if (module.state === "NOT_INITIALIZED") stateColor = colors.FgWhite;
  71. else if (module.state === "INITIALIZED") stateColor = colors.FgGreen;
  72. else if (module.state === "LOCKDOWN" && !module.failed) stateColor = colors.FgRed;
  73. else if (module.state === "LOCKDOWN" && module.failed) stateColor = colors.FgMagenta;
  74. else stateColor = colors.FgYellow;
  75. process.stdout.write(`${moduleName}${tabs}${stateColor}${module.state}\t${colors.FgYellow}Stage: ${colors.FgRed}${module.stage}${colors.FgWhite}. ${colors.FgYellow}Timing${colors.FgWhite}: [${timing}]${colors.FgWhite}${colors.FgWhite}. ${colors.FgYellow}Total time${colors.FgWhite}: ${colors.FgRed}${module.totalTimeInitialize}${colors.FgCyan}ms${colors.Reset}\n`);
  76. }
  77. }
  78. moduleInitialized(moduleName) {
  79. this.modulesInitialized++;
  80. this.modulesLeft.splice(this.modulesLeft.indexOf(moduleName), 1);
  81. this.logger.info("MODULE_MANAGER", `Initialized: ${this.modulesInitialized}/${this.totalModules}.`);
  82. if (this.modulesLeft.length === 0) this.allModulesInitialized();
  83. }
  84. allModulesInitialized() {
  85. this.logger.success("MODULE_MANAGER", "All modules have started!");
  86. }
  87. aModuleFailed(failedModule) {
  88. this.logger.error("MODULE_MANAGER", `A module has failed, locking down. Module: ${failedModule.name}`);
  89. this._lockdown();
  90. }
  91. replaceConsoleWithLogger() {
  92. this.oldConsole = {
  93. log: console.log,
  94. debug: console.debug,
  95. info: console.info,
  96. warn: console.warn,
  97. error: console.error
  98. };
  99. console.log = (...args) => this.logger.debug(args.map(arg => util.format(arg)));
  100. console.debug = (...args) => this.logger.debug(args.map(arg => util.format(arg)));
  101. console.info = (...args) => this.logger.debug(args.map(arg => util.format(arg)));
  102. console.warn = (...args) => this.logger.debug(args.map(arg => util.format(arg)));
  103. console.error = (...args) => this.logger.error("CONSOLE", args.map(arg => util.format(arg)));
  104. }
  105. replaceLoggerWithConsole() {
  106. console.log = this.oldConsole.log;
  107. console.debug = this.oldConsole.debug;
  108. console.info = this.oldConsole.info;
  109. console.warn = this.oldConsole.warn;
  110. console.error = this.oldConsole.error;
  111. }
  112. _lockdown() {
  113. this.lockdown = true;
  114. for (let moduleName in this.modules) {
  115. let module = this.modules[moduleName];
  116. if (module.lockdownImmune) continue;
  117. module._lockdown();
  118. }
  119. }
  120. }
  121. const moduleManager = new ModuleManager();
  122. module.exports = moduleManager;
  123. moduleManager.addModule("logger");
  124. moduleManager.addModule("io");
  125. moduleManager.addModule("util");
  126. moduleManager.addModule("mongo");
  127. moduleManager.addModule("account");
  128. moduleManager.addModule("accountSchema");
  129. moduleManager.addModule("convertSchema");
  130. moduleManager.initialize();
  131. process.stdin.on("data", function (data) {
  132. if(data.toString() === "lockdown\r\n"){
  133. console.log("Locking down.");
  134. moduleManager._lockdown();
  135. }
  136. });
  137. if (fancyConsole) {
  138. const rows = process.stdout.rows;
  139. for(let i = 0; i < rows; i++) {
  140. process.stdout.write("\n");
  141. }
  142. }