index.js 4.7 KB

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