index.js 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197
  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. this.modules["discord"].sendAdminAlertMessage("The backend server started successfully.", "#00AA00", "Startup", false, []);
  87. }
  88. aModuleFailed(failedModule) {
  89. this.logger.error("MODULE_MANAGER", `A module has failed, locking down. Module: ${failedModule.name}`);
  90. this.modules["discord"].sendAdminAlertMessage(`The backend server failed to start due to a failing module: ${failedModule.name}.`, "#AA0000", "Startup", false, []);
  91. this._lockdown();
  92. }
  93. replaceConsoleWithLogger() {
  94. this.oldConsole = {
  95. log: console.log,
  96. debug: console.debug,
  97. info: console.info,
  98. warn: console.warn,
  99. error: console.error
  100. };
  101. console.log = (...args) => this.logger.debug(args.map(arg => util.format(arg)));
  102. console.debug = (...args) => this.logger.debug(args.map(arg => util.format(arg)));
  103. console.info = (...args) => this.logger.debug(args.map(arg => util.format(arg)));
  104. console.warn = (...args) => this.logger.debug(args.map(arg => util.format(arg)));
  105. console.error = (...args) => this.logger.error("CONSOLE", args.map(arg => util.format(arg)));
  106. }
  107. replaceLoggerWithConsole() {
  108. console.log = this.oldConsole.log;
  109. console.debug = this.oldConsole.debug;
  110. console.info = this.oldConsole.info;
  111. console.warn = this.oldConsole.warn;
  112. console.error = this.oldConsole.error;
  113. }
  114. _lockdown() {
  115. this.lockdown = true;
  116. for (let moduleName in this.modules) {
  117. let module = this.modules[moduleName];
  118. if (module.lockdownImmune) continue;
  119. module._lockdown();
  120. }
  121. }
  122. }
  123. const moduleManager = new ModuleManager();
  124. module.exports = moduleManager;
  125. moduleManager.addModule("cache");
  126. moduleManager.addModule("db");
  127. moduleManager.addModule("mail");
  128. moduleManager.addModule("api");
  129. moduleManager.addModule("app");
  130. moduleManager.addModule("discord");
  131. moduleManager.addModule("io");
  132. moduleManager.addModule("logger");
  133. moduleManager.addModule("notifications");
  134. moduleManager.addModule("activities");
  135. moduleManager.addModule("playlists");
  136. moduleManager.addModule("punishments");
  137. moduleManager.addModule("songs");
  138. moduleManager.addModule("spotify");
  139. moduleManager.addModule("stations");
  140. moduleManager.addModule("tasks");
  141. moduleManager.addModule("utils");
  142. moduleManager.initialize();
  143. process.stdin.on("data", function (data) {
  144. if(data.toString() === "lockdown\r\n"){
  145. console.log("Locking down.");
  146. moduleManager._lockdown();
  147. }
  148. });
  149. if (fancyConsole) {
  150. const rows = process.stdout.rows;
  151. for(let i = 0; i < rows; i++) {
  152. process.stdout.write("\n");
  153. }
  154. }