index.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455
  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. // }
  124. // aModuleFailed(failedModule) {
  125. // this.logger.error("MODULE_MANAGER", `A module has failed, locking down. Module: ${failedModule.name}`);
  126. // this._lockdown();
  127. // }
  128. // replaceConsoleWithLogger() {
  129. // this.oldConsole = {
  130. // log: console.log,
  131. // debug: console.debug,
  132. // info: console.info,
  133. // warn: console.warn,
  134. // error: console.error
  135. // };
  136. // console.log = (...args) => this.logger.debug(args.map(arg => util.format(arg)));
  137. // console.debug = (...args) => this.logger.debug(args.map(arg => util.format(arg)));
  138. // console.info = (...args) => this.logger.debug(args.map(arg => util.format(arg)));
  139. // console.warn = (...args) => this.logger.debug(args.map(arg => util.format(arg)));
  140. // console.error = (...args) => this.logger.error("CONSOLE", args.map(arg => util.format(arg)));
  141. // }
  142. // replaceLoggerWithConsole() {
  143. // console.log = this.oldConsole.log;
  144. // console.debug = this.oldConsole.debug;
  145. // console.info = this.oldConsole.info;
  146. // console.warn = this.oldConsole.warn;
  147. // console.error = this.oldConsole.error;
  148. // }
  149. // _lockdown() {
  150. // this.lockdown = true;
  151. // for (let moduleName in this.modules) {
  152. // let module = this.modules[moduleName];
  153. // if (module.lockdownImmune) continue;
  154. // module._lockdown();
  155. // }
  156. // }
  157. // }
  158. // const moduleManager = new ModuleManager();
  159. // module.exports = moduleManager;
  160. // moduleManager.addModule("cache");
  161. // moduleManager.addModule("db");
  162. // moduleManager.addModule("mail");
  163. // moduleManager.addModule("api");
  164. // moduleManager.addModule("app");
  165. // moduleManager.addModule("io");
  166. // moduleManager.addModule("logger");
  167. // moduleManager.addModule("notifications");
  168. // moduleManager.addModule("activities");
  169. // moduleManager.addModule("playlists");
  170. // moduleManager.addModule("punishments");
  171. // moduleManager.addModule("songs");
  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. this.name = "MODULE_MANAGER";
  204. }
  205. /**
  206. * Adds a new module to the backend server/module manager
  207. *
  208. * @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")
  209. */
  210. async addModule(moduleName) {
  211. this.log("INFO", "Adding module", moduleName);
  212. // import(`./logic/${moduleName}`).then(Module => {
  213. // // eslint-disable-next-line new-cap
  214. // const instantiatedModule = new Module.default();
  215. // this.modules[moduleName] = instantiatedModule;
  216. // this.modulesNotInitialized.push(instantiatedModule);
  217. // if (moduleName === "cache") console.log(56, this.modules);
  218. // });
  219. this.modules[moduleName] = import(`./logic/${moduleName}`);
  220. }
  221. /**
  222. * Initialises a new module to the backend server/module manager
  223. *
  224. */
  225. async initialize() {
  226. // if (!this.modules["logger"]) return console.error("There is no logger module");
  227. // this.logger = this.modules["logger"];
  228. // if (this.fancyConsole) {
  229. // this.replaceConsoleWithLogger();
  230. this.reservedLines = Object.keys(this.modules).length + 5;
  231. // }
  232. await Promise.all(Object.values(this.modules)).then(modules => {
  233. for (let module = 0; module < modules.length; module += 1) {
  234. this.modules[modules[module].default.name] = modules[module].default;
  235. this.modulesNotInitialized.push(modules[module].default);
  236. }
  237. }); // ensures all modules are imported, then converts promise to the default export of the import
  238. Object.keys(this.modules).every(moduleKey => {
  239. const module = this.modules[moduleKey];
  240. module.setModuleManager(this);
  241. if (this.lockdown) return false;
  242. module._initialize();
  243. // let dependenciesInitializedPromises = [];
  244. // module.dependsOn.forEach(dependencyName => {
  245. // let dependency = this.modules[dependencyName];
  246. // dependenciesInitializedPromises.push(dependency._onInitialize());
  247. // });
  248. // module.lastTime = Date.now();
  249. // Promise.all(dependenciesInitializedPromises).then((res, res2) => {
  250. // if (this.lockdown) return;
  251. // this.logger.info("MODULE_MANAGER", `${moduleName} dependencies have been completed`);
  252. // module._initialize();
  253. // });
  254. return true;
  255. });
  256. }
  257. /**
  258. * Called when a module is initialised
  259. *
  260. * @param {object} module - the module object/class
  261. */
  262. onInitialize(module) {
  263. if (this.modulesNotInitialized.indexOf(module) !== -1) {
  264. this.modulesNotInitialized.splice(this.modulesNotInitialized.indexOf(module), 1);
  265. this.log(
  266. "INFO",
  267. `Initialized: ${Object.keys(this.modules).length - this.modulesNotInitialized.length}/${
  268. Object.keys(this.modules).length
  269. }.`
  270. );
  271. if (this.modulesNotInitialized.length === 0) this.onAllModulesInitialized();
  272. }
  273. }
  274. /**
  275. * Called when a module fails to initialise
  276. *
  277. * @param {object} module - the module object/class
  278. */
  279. onFail(module) {
  280. if (this.modulesNotInitialized.indexOf(module) !== -1) {
  281. this.log("ERROR", "A module failed to initialize!");
  282. }
  283. }
  284. /**
  285. * Called when every module has initialised
  286. *
  287. */
  288. onAllModulesInitialized() {
  289. this.log("INFO", "All modules initialized!");
  290. }
  291. /**
  292. * Creates a new log message
  293. *
  294. * @param {...any} args - anything to be included in the log message, the first argument is the type of log
  295. */
  296. log(...args) {
  297. const _arguments = Array.from(args);
  298. const type = _arguments[0];
  299. _arguments.splice(0, 1);
  300. const start = `|${this.name.toUpperCase()}|`;
  301. const numberOfSpacesNeeded = 20 - start.length;
  302. _arguments.unshift(`${start}${Array(numberOfSpacesNeeded).join(" ")}`);
  303. if (type === "INFO") {
  304. _arguments[0] += "\x1b[36m";
  305. _arguments.push("\x1b[0m");
  306. console.log.apply(null, _arguments);
  307. } else if (type === "ERROR") {
  308. _arguments[0] += "\x1b[31m";
  309. _arguments.push("\x1b[0m");
  310. console.error.apply(null, _arguments);
  311. }
  312. }
  313. }
  314. const moduleManager = new ModuleManager();
  315. moduleManager.addModule("cache");
  316. moduleManager.addModule("db");
  317. moduleManager.addModule("mail");
  318. moduleManager.addModule("activities");
  319. moduleManager.addModule("api");
  320. moduleManager.addModule("app");
  321. moduleManager.addModule("io");
  322. moduleManager.addModule("notifications");
  323. moduleManager.addModule("playlists");
  324. moduleManager.addModule("punishments");
  325. moduleManager.addModule("songs");
  326. moduleManager.addModule("stations");
  327. moduleManager.addModule("tasks");
  328. moduleManager.addModule("utils");
  329. moduleManager.initialize();
  330. process.stdin.on("data", data => {
  331. const command = data.toString().replace(/\r?\n|\r/g, "");
  332. if (command === "lockdown") {
  333. console.log("Locking down.");
  334. moduleManager._lockdown();
  335. }
  336. if (command === "status") {
  337. console.log("Status:");
  338. Object.keys(moduleManager.modules).forEach(moduleName => {
  339. const module = moduleManager.modules[moduleName];
  340. const tabsNeeded = 4 - Math.ceil((moduleName.length + 1) / 8);
  341. console.log(
  342. `${moduleName.toUpperCase()}${Array(tabsNeeded).join(
  343. "\t"
  344. )}${module.getStatus()}. Jobs in queue: ${module.jobQueue.lengthQueue()}. Jobs in progress: ${module.jobQueue.lengthRunning()}. Jobs paused: ${module.jobQueue.lengthPaused()} Concurrency: ${
  345. module.jobQueue.concurrency
  346. }. Stage: ${module.getStage()}`
  347. );
  348. });
  349. // moduleManager._lockdown();
  350. }
  351. if (command.startsWith("running")) {
  352. const parts = command.split(" ");
  353. console.log(moduleManager.modules[parts[1]].jobQueue.runningTasks);
  354. }
  355. if (command.startsWith("queued")) {
  356. const parts = command.split(" ");
  357. console.log(moduleManager.modules[parts[1]].jobQueue.queue);
  358. }
  359. if (command.startsWith("paused")) {
  360. const parts = command.split(" ");
  361. console.log(moduleManager.modules[parts[1]].jobQueue.pausedTasks);
  362. }
  363. if (command.startsWith("stats")) {
  364. const parts = command.split(" ");
  365. console.log(moduleManager.modules[parts[1]].jobStatistics);
  366. }
  367. if (command.startsWith("debug")) {
  368. moduleManager.modules.utils.runJob("DEBUG");
  369. }
  370. if (command.startsWith("eval")) {
  371. const evalCommand = command.replace("eval ", "");
  372. console.log(`Running eval command: ${evalCommand}`);
  373. const response = eval(evalCommand);
  374. console.log(`Eval response: `, response);
  375. }
  376. });
  377. export default moduleManager;