core.js 1.8 KB

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