index.js 14 KB

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