core.js 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  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. this.failed = true;
  26. this.logger.error(err.stack);
  27. this.moduleManager.aModuleFailed(this);
  28. });
  29. }
  30. _onInitialize() {
  31. return new Promise(resolve => bus.once(`stateChange:${this.name}:INITIALIZED`, resolve));
  32. }
  33. _isInitialized() {
  34. return new Promise(resolve => {
  35. if (this.state === "INITIALIZED") resolve();
  36. });
  37. }
  38. _isNotLocked() {
  39. return new Promise((resolve, reject) => {
  40. if (this.state === "LOCKDOWN") reject();
  41. else resolve();
  42. });
  43. }
  44. setState(state) {
  45. this.state = state;
  46. bus.emit(`stateChange:${this.name}:${state}`);
  47. this.logger.info(`MODULE_STATE`, `${state}: ${this.name}`);
  48. }
  49. setStage(stage) {
  50. if (stage !== 1)
  51. this.totalTimeInitialize += (Date.now() - this.lastTime);
  52. //this.timeDifferences.push(this.stage + ": " + (Date.now() - this.lastTime) + "ms");
  53. this.timeDifferences.push(Date.now() - this.lastTime);
  54. this.lastTime = Date.now();
  55. this.stage = stage;
  56. this.moduleManager.printStatus();
  57. }
  58. _validateHook() {
  59. return Promise.race([this._onInitialize, this._isInitialized]).then(
  60. () => this._isNotLocked()
  61. );
  62. }
  63. _lockdown() {
  64. if (this.lockdown) return;
  65. this.lockdown = true;
  66. this.setState("LOCKDOWN");
  67. this.moduleManager.printStatus();
  68. }
  69. }