core.js 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. const EventEmitter = require('events');
  2. const bus = new EventEmitter();
  3. module.exports = class {
  4. constructor(name, moduleManager) {
  5. this.name = name;
  6. this.moduleManager = moduleManager;
  7. this.lockdown = false;
  8. this.dependsOn = [];
  9. this.eventHandlers = [];
  10. this.state = "NOT_INITIALIZED";
  11. this.stage = 0;
  12. this.lastTime = 0;
  13. this.totalTimeInitialize = 0;
  14. this.timeDifferences = [];
  15. this.failed = false;
  16. }
  17. _initialize() {
  18. this.logger = this.moduleManager.modules["logger"];
  19. this.setState("INITIALIZING");
  20. this.initialize().then(() => {
  21. this.setState("INITIALIZED");
  22. this.setStage(0);
  23. this.moduleManager.printStatus();
  24. }).catch(async (err) => {
  25. if (this.moduleManager.fancyConsole) {
  26. this.moduleManager.replaceLoggerWithConsole();
  27. }
  28. this.failed = true;
  29. console.error(`${this.logger.colors.FgRed}MODULE FAILED! Module ${this.name} has failed!${this.logger.colors.Reset}`);
  30. console.error(err);
  31. if (this.moduleManager.fancyConsole) {
  32. for(let i = 0; i < this.logger.reservedLines; i++) {
  33. process.stdout.write(`\n`);
  34. }
  35. }
  36. this.moduleManager.aModuleFailed(this);
  37. });
  38. }
  39. _onInitialize() {
  40. return new Promise(resolve => bus.once(`stateChange:${this.name}:INITIALIZED`, resolve));
  41. }
  42. _isInitialized() {
  43. return new Promise(resolve => {
  44. if (this.state === "INITIALIZED") resolve();
  45. });
  46. }
  47. _isNotLocked() {
  48. return new Promise((resolve, reject) => {
  49. if (this.state === "LOCKDOWN") reject();
  50. else resolve();
  51. });
  52. }
  53. setState(state) {
  54. this.state = state;
  55. bus.emit(`stateChange:${this.name}:${state}`);
  56. this.logger.info(`MODULE_STATE`, `${state}: ${this.name}`);
  57. }
  58. setStage(stage) {
  59. if (stage !== 1)
  60. this.totalTimeInitialize += (Date.now() - this.lastTime);
  61. //this.timeDifferences.push(this.stage + ": " + (Date.now() - this.lastTime) + "ms");
  62. this.timeDifferences.push(Date.now() - this.lastTime);
  63. this.lastTime = Date.now();
  64. this.stage = stage;
  65. this.moduleManager.printStatus();
  66. }
  67. _validateHook() {
  68. return Promise.race([this._onInitialize, this._isInitialized]).then(
  69. () => this._isNotLocked()
  70. );
  71. }
  72. _lockdown() {
  73. this.lockdown = true;
  74. this.setState("LOCKDOWN");
  75. this.moduleManager.printStatus();
  76. }
  77. }