core.js 1.9 KB

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