@mdf.js/core
Version:
MMS - API Core - Common types, classes and functions
80 lines • 2.9 kB
JavaScript
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ErrorState = void 0;
/**
* Copyright 2024 Mytra Control S.L. All rights reserved.
*
* Use of this source code is governed by an MIT-style license that can be found in the LICENSE file
* or at https://opensource.org/licenses/MIT.
*/
const crash_1 = require("@mdf.js/crash");
const Running_1 = require("./Running");
const Stopped_1 = require("./Stopped");
/**
* Provider Error state
* @category State
* @public
*/
class ErrorState {
/**
* Create a instance of the error instance
* @param instance - Port instance
* @param changeState - Provider state change function
* @param manageError - Provider error management function function
*/
constructor(instance, changeState, manageError) {
this.instance = instance;
this.changeState = changeState;
this.manageError = manageError;
/** Actual provider state */
this.state = 'error';
/** Handler for disconnected or unhealthy events */
this.errorEventHandler = (error) => this.fail(error);
/** Handler for auto-fix events */
this.fixedEventHandler = () => this.start();
/** Handler for close event */
this.closeEventHandler = () => this.stop();
this.instance.on('unhealthy', this.errorEventHandler);
this.instance.once('closed', this.closeEventHandler);
this.instance.once('healthy', this.fixedEventHandler);
}
/** Stop the process: internal jobs, external dependencies connections ... */
async stop() {
this.cleanEventHandlers();
try {
await this.instance.stop();
}
catch (error) {
await this.fail(crash_1.Crash.from(error));
throw error;
}
this.changeState(new Stopped_1.StoppedState(this.instance, this.changeState, this.manageError));
}
/** Initialize the process: internal jobs, external dependencies connections ... */
async start() {
this.cleanEventHandlers();
try {
await this.instance.start();
}
catch (error) {
await this.fail(crash_1.Crash.from(error));
throw error;
}
this.changeState(new Running_1.RunningState(this.instance, this.changeState, this.manageError));
}
/**
* Go to error state: waiting for new state o auto-fix de the problems
* @param error - incoming error from provider
*/
async fail(error) {
this.manageError(error);
}
/** Clean event handlers for error state */
cleanEventHandlers() {
this.instance.off('unhealthy', this.errorEventHandler);
this.instance.off('closed', this.closeEventHandler);
this.instance.off('healthy', this.fixedEventHandler);
}
}
exports.ErrorState = ErrorState;
//# sourceMappingURL=Error.js.map