index.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423
  1. import "./loadEnvVariables.js";
  2. import util from "util";
  3. import config from "config";
  4. process.on("uncaughtException", err => {
  5. if (err.code === "ECONNREFUSED" || err.code === "UNCERTAIN_STATE") return;
  6. console.log(`UNCAUGHT EXCEPTION: ${err.stack}`);
  7. });
  8. const blacklistedConsoleLogs = [
  9. "Running job IO",
  10. "Ran job IO successfully",
  11. "Running job HGET",
  12. "Ran job HGET successfully",
  13. "Running job HGETALL",
  14. "Ran job HGETALL successfully",
  15. "Running job GET_ERROR",
  16. "Ran job GET_ERROR successfully",
  17. "Running job GET_SCHEMA",
  18. "Ran job GET_SCHEMA successfully",
  19. "Running job SUB",
  20. "Ran job SUB successfully",
  21. "Running job GET_MODEL",
  22. "Ran job GET_MODEL successfully",
  23. "Running job HSET",
  24. "Ran job HSET successfully",
  25. "Running job CAN_USER_VIEW_STATION",
  26. "Ran job CAN_USER_VIEW_STATION successfully"
  27. ];
  28. const oldConsole = {};
  29. oldConsole.log = console.log;
  30. console.log = (...args) => {
  31. const string = util.format.apply(null, args);
  32. let blacklisted = false;
  33. blacklistedConsoleLogs.forEach(blacklistedConsoleLog => {
  34. if (string.indexOf(blacklistedConsoleLog) !== -1) blacklisted = true;
  35. });
  36. if (!blacklisted) oldConsole.log.apply(null, args);
  37. };
  38. const fancyConsole = config.get("fancyConsole");
  39. if (config.debug && config.debug.traceUnhandledPromises === true) {
  40. console.log("Enabled trace-unhandled/register");
  41. import("trace-unhandled/register");
  42. }
  43. // class ModuleManager {
  44. // constructor() {
  45. // this.modules = {};
  46. // this.modulesInitialized = 0;
  47. // this.totalModules = 0;
  48. // this.modulesLeft = [];
  49. // this.i = 0;
  50. // this.lockdown = false;
  51. // this.fancyConsole = fancyConsole;
  52. // }
  53. // addModule(moduleName) {
  54. // console.log("add module", moduleName);
  55. // const moduleClass = new require(`./logic/${moduleName}`);
  56. // this.modules[moduleName] = new moduleClass(moduleName, this);
  57. // this.totalModules++;
  58. // this.modulesLeft.push(moduleName);
  59. // }
  60. // initialize() {
  61. // if (!this.modules["logger"]) return console.error("There is no logger module");
  62. // this.logger = this.modules["logger"];
  63. // if (this.fancyConsole) {
  64. // this.replaceConsoleWithLogger();
  65. // this.logger.reservedLines = Object.keys(this.modules).length + 5;
  66. // }
  67. // for (let moduleName in this.modules) {
  68. // let module = this.modules[moduleName];
  69. // if (this.lockdown) break;
  70. // module._onInitialize().then(() => {
  71. // this.moduleInitialized(moduleName);
  72. // });
  73. // let dependenciesInitializedPromises = [];
  74. // module.dependsOn.forEach(dependencyName => {
  75. // let dependency = this.modules[dependencyName];
  76. // dependenciesInitializedPromises.push(dependency._onInitialize());
  77. // });
  78. // module.lastTime = Date.now();
  79. // Promise.all(dependenciesInitializedPromises).then((res, res2) => {
  80. // if (this.lockdown) return;
  81. // this.logger.info("MODULE_MANAGER", `${moduleName} dependencies have been completed`);
  82. // module._initialize();
  83. // });
  84. // }
  85. // }
  86. // async printStatus() {
  87. // try { await Promise.race([this.logger._onInitialize(), this.logger._isInitialized()]); } catch { return; }
  88. // if (!this.fancyConsole) return;
  89. // let colors = this.logger.colors;
  90. // const rows = process.stdout.rows;
  91. // process.stdout.cursorTo(0, rows - this.logger.reservedLines);
  92. // process.stdout.clearScreenDown();
  93. // process.stdout.cursorTo(0, (rows - this.logger.reservedLines) + 2);
  94. // process.stdout.write(`${colors.FgYellow}Modules${colors.FgWhite}:\n`);
  95. // for (let moduleName in this.modules) {
  96. // let module = this.modules[moduleName];
  97. // let tabsAmount = Math.max(0, Math.ceil(2 - (moduleName.length / 8)));
  98. // let tabs = Array(tabsAmount).fill(`\t`).join("");
  99. // let timing = module.timeDifferences.map((timeDifference) => {
  100. // return `${colors.FgMagenta}${timeDifference}${colors.FgCyan}ms${colors.FgWhite}`;
  101. // }).join(", ");
  102. // let stateColor;
  103. // if (module.state === "NOT_INITIALIZED") stateColor = colors.FgWhite;
  104. // else if (module.state === "INITIALIZED") stateColor = colors.FgGreen;
  105. // else if (module.state === "LOCKDOWN" && !module.failed) stateColor = colors.FgRed;
  106. // else if (module.state === "LOCKDOWN" && module.failed) stateColor = colors.FgMagenta;
  107. // else stateColor = colors.FgYellow;
  108. // 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`);
  109. // }
  110. // }
  111. // moduleInitialized(moduleName) {
  112. // this.modulesInitialized++;
  113. // this.modulesLeft.splice(this.modulesLeft.indexOf(moduleName), 1);
  114. // this.logger.info("MODULE_MANAGER", `Initialized: ${this.modulesInitialized}/${this.totalModules}.`);
  115. // if (this.modulesLeft.length === 0) this.allModulesInitialized();
  116. // }
  117. // allModulesInitialized() {
  118. // this.logger.success("MODULE_MANAGER", "All modules have started!");
  119. // this.modules["discord"].sendAdminAlertMessage("The backend server started successfully.", "#00AA00", "Startup", false, []);
  120. // }
  121. // aModuleFailed(failedModule) {
  122. // this.logger.error("MODULE_MANAGER", `A module has failed, locking down. Module: ${failedModule.name}`);
  123. // this.modules["discord"].sendAdminAlertMessage(`The backend server failed to start due to a failing module: ${failedModule.name}.`, "#AA0000", "Startup", false, []);
  124. // this._lockdown();
  125. // }
  126. // replaceConsoleWithLogger() {
  127. // this.oldConsole = {
  128. // log: console.log,
  129. // debug: console.debug,
  130. // info: console.info,
  131. // warn: console.warn,
  132. // error: console.error
  133. // };
  134. // console.log = (...args) => this.logger.debug(args.map(arg => util.format(arg)));
  135. // console.debug = (...args) => this.logger.debug(args.map(arg => util.format(arg)));
  136. // console.info = (...args) => this.logger.debug(args.map(arg => util.format(arg)));
  137. // console.warn = (...args) => this.logger.debug(args.map(arg => util.format(arg)));
  138. // console.error = (...args) => this.logger.error("CONSOLE", args.map(arg => util.format(arg)));
  139. // }
  140. // replaceLoggerWithConsole() {
  141. // console.log = this.oldConsole.log;
  142. // console.debug = this.oldConsole.debug;
  143. // console.info = this.oldConsole.info;
  144. // console.warn = this.oldConsole.warn;
  145. // console.error = this.oldConsole.error;
  146. // }
  147. // _lockdown() {
  148. // this.lockdown = true;
  149. // for (let moduleName in this.modules) {
  150. // let module = this.modules[moduleName];
  151. // if (module.lockdownImmune) continue;
  152. // module._lockdown();
  153. // }
  154. // }
  155. // }
  156. // const moduleManager = new ModuleManager();
  157. // module.exports = moduleManager;
  158. // moduleManager.addModule("cache");
  159. // moduleManager.addModule("db");
  160. // moduleManager.addModule("mail");
  161. // moduleManager.addModule("api");
  162. // moduleManager.addModule("app");
  163. // moduleManager.addModule("discord");
  164. // moduleManager.addModule("io");
  165. // moduleManager.addModule("logger");
  166. // moduleManager.addModule("notifications");
  167. // moduleManager.addModule("activities");
  168. // moduleManager.addModule("playlists");
  169. // moduleManager.addModule("punishments");
  170. // moduleManager.addModule("songs");
  171. // moduleManager.addModule("spotify");
  172. // moduleManager.addModule("stations");
  173. // moduleManager.addModule("tasks");
  174. // moduleManager.addModule("utils");
  175. // moduleManager.initialize();
  176. // process.stdin.on("data", function (data) {
  177. // if(data.toString() === "lockdown\r\n"){
  178. // console.log("Locking down.");
  179. // moduleManager._lockdown();
  180. // }
  181. // });
  182. // if (fancyConsole) {
  183. // const rows = process.stdout.rows;
  184. // for(let i = 0; i < rows; i++) {
  185. // process.stdout.write("\n");
  186. // }
  187. // }
  188. class ModuleManager {
  189. // eslint-disable-next-line require-jsdoc
  190. constructor() {
  191. this.modules = {};
  192. this.modulesNotInitialized = [];
  193. this.i = 0;
  194. this.lockdown = false;
  195. this.fancyConsole = fancyConsole;
  196. this.debugLogs = {
  197. stationIssue: []
  198. };
  199. this.debugJobs = {
  200. all: [],
  201. completed: []
  202. };
  203. }
  204. /**
  205. * Adds a new module to the backend server/module manager
  206. *
  207. * @param {string} moduleName - the name of the module (also needs to be the same as the filename of a module located in the logic folder or "logic/moduleName/index.js")
  208. */
  209. async addModule(moduleName) {
  210. console.log("add module", moduleName);
  211. // import(`./logic/${moduleName}`).then(Module => {
  212. // // eslint-disable-next-line new-cap
  213. // const instantiatedModule = new Module.default();
  214. // this.modules[moduleName] = instantiatedModule;
  215. // this.modulesNotInitialized.push(instantiatedModule);
  216. // if (moduleName === "cache") console.log(56, this.modules);
  217. // });
  218. this.modules[moduleName] = import(`./logic/${moduleName}`);
  219. }
  220. /**
  221. * Initialises a new module to the backend server/module manager
  222. *
  223. */
  224. async initialize() {
  225. // if (!this.modules["logger"]) return console.error("There is no logger module");
  226. // this.logger = this.modules["logger"];
  227. // if (this.fancyConsole) {
  228. // this.replaceConsoleWithLogger();
  229. this.reservedLines = Object.keys(this.modules).length + 5;
  230. // }
  231. await Promise.all(Object.values(this.modules)).then(modules => {
  232. for (let module = 0; module < modules.length; module += 1) {
  233. this.modules[modules[module].default.name] = modules[module].default;
  234. this.modulesNotInitialized.push(modules[module].default);
  235. }
  236. }); // ensures all modules are imported, then converts promise to the default export of the import
  237. for (let moduleId = 0, moduleNames = Object.keys(this.modules); moduleId < moduleNames.length; moduleId += 1) {
  238. const module = this.modules[moduleNames[moduleId]];
  239. module.setModuleManager(this);
  240. if (this.lockdown) break;
  241. module._initialize();
  242. // let dependenciesInitializedPromises = [];
  243. // module.dependsOn.forEach(dependencyName => {
  244. // let dependency = this.modules[dependencyName];
  245. // dependenciesInitializedPromises.push(dependency._onInitialize());
  246. // });
  247. // module.lastTime = Date.now();
  248. // Promise.all(dependenciesInitializedPromises).then((res, res2) => {
  249. // if (this.lockdown) return;
  250. // this.logger.info("MODULE_MANAGER", `${moduleName} dependencies have been completed`);
  251. // module._initialize();
  252. // });
  253. }
  254. }
  255. /**
  256. * Called when a module is initialised
  257. *
  258. * @param {object} module - the module object/class
  259. */
  260. onInitialize(module) {
  261. if (this.modulesNotInitialized.indexOf(module) !== -1) {
  262. this.modulesNotInitialized.splice(this.modulesNotInitialized.indexOf(module), 1);
  263. console.log(
  264. "MODULE_MANAGER",
  265. `Initialized: ${Object.keys(this.modules).length - this.modulesNotInitialized.length}/${
  266. Object.keys(this.modules).length
  267. }.`
  268. );
  269. if (this.modulesNotInitialized.length === 0) this.onAllModulesInitialized();
  270. }
  271. }
  272. /**
  273. * Called when a module fails to initialise
  274. *
  275. * @param {object} module - the module object/class
  276. */
  277. onFail(module) {
  278. if (this.modulesNotInitialized.indexOf(module) !== -1) {
  279. console.log("A module failed to initialize!");
  280. }
  281. }
  282. /**
  283. * Called when every module has initialised
  284. *
  285. */
  286. onAllModulesInitialized() {
  287. console.log("All modules initialized!");
  288. this.modules.discord.runJob("SEND_ADMIN_ALERT_MESSAGE", {
  289. message: "The backend server started successfully.",
  290. color: "#00AA00",
  291. type: "Startup",
  292. critical: false,
  293. extraFields: []
  294. });
  295. }
  296. }
  297. const moduleManager = new ModuleManager();
  298. moduleManager.addModule("cache");
  299. moduleManager.addModule("db");
  300. moduleManager.addModule("mail");
  301. moduleManager.addModule("activities");
  302. moduleManager.addModule("api");
  303. moduleManager.addModule("app");
  304. moduleManager.addModule("discord");
  305. moduleManager.addModule("io");
  306. moduleManager.addModule("notifications");
  307. moduleManager.addModule("playlists");
  308. moduleManager.addModule("punishments");
  309. moduleManager.addModule("songs");
  310. moduleManager.addModule("spotify");
  311. moduleManager.addModule("stations");
  312. moduleManager.addModule("tasks");
  313. moduleManager.addModule("utils");
  314. moduleManager.initialize();
  315. process.stdin.on("data", data => {
  316. const command = data.toString().replace(/\r?\n|\r/g, "");
  317. if (command === "lockdown") {
  318. console.log("Locking down.");
  319. moduleManager._lockdown();
  320. }
  321. if (command === "status") {
  322. console.log("Status:");
  323. for (
  324. let moduleName = 0, moduleKeys = Object.keys(moduleManager.modules);
  325. moduleName < moduleKeys.length;
  326. moduleName += 1
  327. ) {
  328. const module = moduleManager.modules[moduleName];
  329. const tabsNeeded = 4 - Math.ceil((moduleName.length + 1) / 8);
  330. console.log(
  331. `${moduleName.toUpperCase()}${Array(tabsNeeded).join(
  332. "\t"
  333. )}${module.getStatus()}. Jobs in queue: ${module.jobQueue.length()}. Jobs in progress: ${module.jobQueue.running()}. Concurrency: ${
  334. module.jobQueue.concurrency
  335. }. Stage: ${module.getStage()}`
  336. );
  337. }
  338. // moduleManager._lockdown();
  339. }
  340. if (command.startsWith("running")) {
  341. const parts = command.split(" ");
  342. console.log(moduleManager.modules[parts[1]].runningJobs);
  343. }
  344. if (command.startsWith("stats")) {
  345. const parts = command.split(" ");
  346. console.log(moduleManager.modules[parts[1]].jobStatistics);
  347. }
  348. if (command.startsWith("debug")) {
  349. moduleManager.modules.utils.runJob("DEBUG");
  350. }
  351. });
  352. export default moduleManager;