index.js 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164
  1. 'use strict';
  2. process.env.NODE_CONFIG_DIR = `${__dirname}/config`;
  3. process.on('uncaughtException', err => {
  4. if (err.code === 'ECONNREFUSED' || err.code === 'UNCERTAIN_STATE') return;
  5. console.log(`UNCAUGHT EXCEPTION: ${err.stack}`);
  6. });
  7. class ModuleManager {
  8. constructor() {
  9. this.modules = {};
  10. this.modulesInitialized = 0;
  11. this.totalModules = 0;
  12. this.modulesLeft = [];
  13. this.i = 0;
  14. this.lockdown = false;
  15. }
  16. addModule(moduleName) {
  17. console.log("add module", moduleName);
  18. const moduleClass = new require(`./logic/${moduleName}`);
  19. this.modules[moduleName] = new moduleClass(moduleName, this);
  20. this.totalModules++;
  21. this.modulesLeft.push(moduleName);
  22. }
  23. initialize() {
  24. if (!this.modules["logger"]) return console.error("There is no logger module");
  25. this.logger = this.modules["logger"];
  26. console.log = (...args) => this.logger.debug(args.join(" "));
  27. console.debug = (...args) => this.logger.debug(args.join(" "));
  28. console.info = (...args) => this.logger.debug(args.join(" "));
  29. console.warn = (...args) => this.logger.debug(args.join(" "));
  30. console.error = (...args) => this.logger.error("CONSOLE", args.join(" "));
  31. this.logger.reservedLines = Object.keys(this.modules).length + 5;
  32. for (let moduleName in this.modules) {
  33. let module = this.modules[moduleName];
  34. if (this.lockdown) break;
  35. module._onInitialize().then(() => {
  36. this.moduleInitialized(moduleName);
  37. });
  38. let dependenciesInitializedPromises = [];
  39. module.dependsOn.forEach(dependencyName => {
  40. let dependency = this.modules[dependencyName];
  41. dependenciesInitializedPromises.push(dependency._onInitialize());
  42. });
  43. module.lastTime = Date.now();
  44. Promise.all(dependenciesInitializedPromises).then((res, res2) => {
  45. if (this.lockdown) return;
  46. this.logger.info("MODULE_MANAGER", `${moduleName} dependencies have been completed`);
  47. module._initialize();
  48. });
  49. }
  50. }
  51. async printStatus() {
  52. try { await Promise.race([this.logger._onInitialize, this.logger._isInitialized]); } catch { return; }
  53. let colors = this.logger.colors;
  54. const rows = process.stdout.rows;
  55. process.stdout.cursorTo(0, rows - this.logger.reservedLines);
  56. process.stdout.clearScreenDown();
  57. process.stdout.cursorTo(0, (rows - this.logger.reservedLines) + 2);
  58. process.stdout.write(`${colors.FgYellow}Modules${colors.FgWhite}:\n`);
  59. for (let moduleName in this.modules) {
  60. let module = this.modules[moduleName];
  61. let tabsAmount = 2 - (moduleName.length / 8);
  62. let tabs = "";
  63. for(let i = 0; i < tabsAmount; i++)
  64. tabs += "\t";
  65. let timing = module.timeDifferences.map((timeDifference) => {
  66. return `${colors.FgMagenta}${timeDifference}${colors.FgCyan}ms${colors.FgWhite}`;
  67. }).join(", ");
  68. let stateColor;
  69. if (module.state === "NOT_INITIALIZED") stateColor = colors.FgWhite;
  70. if (module.state === "INITIALIZING") stateColor = colors.FgYellow;
  71. if (module.state === "INITIALIZED") stateColor = colors.FgGreen;
  72. if (module.state === "LOCKDOWN") stateColor = colors.FgRed;
  73. 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`);
  74. }
  75. }
  76. moduleInitialized(moduleName) {
  77. this.modulesInitialized++;
  78. this.modulesLeft.splice(this.modulesLeft.indexOf(moduleName), 1);
  79. this.logger.info("MODULE_MANAGER", `Initialized: ${this.modulesInitialized}/${this.totalModules}.`);
  80. if (this.modulesLeft.length === 0) this.allModulesInitialized();
  81. }
  82. allModulesInitialized() {
  83. this.logger.success("MODULE_MANAGER", "All modules have started!");
  84. this.modules["discord"].sendAdminAlertMessage("The backend server started successfully.", "#00AA00", "Startup", false, []);
  85. }
  86. aModuleFailed(failedModule) {
  87. this.logger.error("MODULE_MANAGER", `A module has failed, locking down. Module: ${failedModule.name}`);
  88. this.modules["discord"].sendAdminAlertMessage(`The backend server failed to start due to a failing module: ${failedModule.name}.`, "#AA0000", "Startup", false, []);
  89. this._lockdown();
  90. }
  91. _lockdown() {
  92. this.lockdown = true;
  93. for (let moduleName in this.modules) {
  94. let module = this.modules[moduleName];
  95. module._lockdown();
  96. }
  97. }
  98. }
  99. const moduleManager = new ModuleManager();
  100. module.exports = moduleManager;
  101. moduleManager.addModule("cache");
  102. moduleManager.addModule("db");
  103. moduleManager.addModule("mail");
  104. moduleManager.addModule("api");
  105. moduleManager.addModule("app");
  106. moduleManager.addModule("discord");
  107. moduleManager.addModule("io");
  108. moduleManager.addModule("logger");
  109. moduleManager.addModule("notifications");
  110. moduleManager.addModule("playlists");
  111. moduleManager.addModule("punishments");
  112. moduleManager.addModule("songs");
  113. moduleManager.addModule("spotify");
  114. moduleManager.addModule("stations");
  115. moduleManager.addModule("tasks");
  116. moduleManager.addModule("utils");
  117. moduleManager.initialize();
  118. process.stdin.on("data", function (data) {
  119. if(data.toString() === "lockdown\r\n"){
  120. console.log("Locking down.");
  121. moduleManager._lockdown();
  122. }
  123. });
  124. const rows = process.stdout.rows;
  125. for(let i = 0; i < rows; i++) {
  126. process.stdout.write("\n");
  127. }