All files / src/util/state StateMaschineBase.ts

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171                                    1x   1x     24x 72x 72x   1x 25x   1x   1x   12x   36x 12x 12x 12x 12x 12x     12x       1x 9x     5x 4x 4x 1x     1x     1x 34x     1x 13x 13x 13x           3x 3x     3x 3x 3x 3x 2x     2x           3x 3x                       7x 7x 7x 7x 7x 7x 7x 7x 14x 3x 3x 7x 7x   7x 14x 3x 3x 7x                   3x 2x 3x 3x       2x 2x 2x 2x       1x 2x 2x       1x   10x     10x     1x 24x 24x       1x 22x     1x
/**
 * Copyright 2017-2020 Plexus Interop Deutsche Bank AG
 * SPDX-License-Identifier: Apache-2.0
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
import { Transition, Transitions, StateMaschine, Handlers } from './StateMaschine';
import { Logger } from '../../logger/Logger';
import { LoggerFactory } from '../../logger/LoggerFactory';
 
class StateDescriptor<T> {
 
    constructor(
        public state: T,
        public EinTransitions: Transitions<T> = [],
        public EoutTransitions: Transitions<T> = []) { }
 
    public hasOutTransition(state: T): boolean {
        return this.outTransitions.filter(transtion => transtion.to === state).length > 0;
    }
}
 
export class StateMaschineBase<T> implements StateMaschine<T> {
 
    private readonly stateDescriptorsMap: Map<T, StateDescriptor<T>> = new Map<T, StateDescriptor<T>>();
 
    constructor(private current: T, transitions: Transitions<T>, private Elogger: Logger = LoggerFactory.getLogger('StateMaschine')) {
        transitions.forEach(transition => {
            this.putIfAbsent(transition.from);
            this.putIfAbsent(transition.to);
            const fromDescriptor = this.lookup(transition.from);
            Iif (fromDescriptor.hasOutTransition(transition.to)) {
                throw `Transition ${transition.from} -> ${transition.to} already exists`;
            }
            fromDescriptor.outTransitions.push(transition);
        });
    }
 
    public is(state: T): boolean {
        return this.current === state;
    }
 
    public isOneOf(...states: T[]): boolean {
        for (const state of states) {
            if (this.is(state)) {
                return true;
            }
        }
        return false;
    }
 
    public getCurrent(): T {
        return this.current;
    }
 
    public canGo(state: T): boolean {
        const descriptor = this.stateDescriptorsMap.get(this.getCurrent());
        Eif (descriptor) {
            return descriptor.hasOutTransition(state);
        } else {
            return false;
        }
    }
 
    public go(to: T): void {
        Iif (!this.canGo(to)) {
            throw new Error(`Transition ${this.getCurrent()} -> ${to} does not exist`);
        }
        const descriptor = this.lookup(this.getCurrent());        
        const transition = descriptor.outTransitions.find(transition => transition.to === to) as Transition<T>;
        const old = this.getCurrent();
        if (transition.preHandler) {
            transition.preHandler()
                .then(() => {
                    /* istanbul ignore if */
                    if (this.logger.isTraceEnabled()) {
                        this.logger.trace(`Finished pre-handler for ${old} -> ${to}`);
                    }
                })
                .catch(e => this.logger.error(`Pre-handler for ${this.getCurrent()} -> ${to} failed`, e));
        }
        this.switchInternal(to);
        Iif (transition.postHandler) {
            transition.postHandler()
                .then(() => {
                    /* istanbul ignore if */
                    Iif (this.logger.isTraceEnabled()) {
                        this.logger.trace(`Finished post-handler for ${this.getCurrent()} -> ${to}`);
                    }
                })
                .catch(e => this.logger.error(`Post-handler for ${this.getCurrent()} -> ${to} failed`, e));
        }
    }
 
    public goAsync(to: T, dynamicHandlers?: Handlers): Promise<void> {
        Eif (this.canGo(to)) {
            const descriptor = this.lookup(this.getCurrent());                    
            const transition = descriptor.outTransitions.find(transition => transition.to === to) as Transition<T>;
            return new Promise<void>((resolve, reject) => {
                const preHandlePassed = () => {
                    this.switchInternal(transition.to);
                    const postHandlerPromises = [dynamicHandlers ? dynamicHandlers.postHandler : null, transition.postHandler]
                        .filter(handler => !!handler)
                        .map(handler => handler as () => Promise<void>)
                        .map(handler => handler());
                    Promise.all(postHandlerPromises)
                        .then(() => resolve(), reject);
                };
                const preHandlePromises = [dynamicHandlers ? dynamicHandlers.preHandler : null, transition.preHandler]
                    .filter(handler => !!handler)
                    .map(handler => handler as () => Promise<void>)
                    .map(handler => handler());
                Promise.all(preHandlePromises)
                    .then(preHandlePassed.bind(this), reject);
            });
        } else {
            const error = `Transition ${this.getCurrent()} -> ${to} does not exist`;
            this.logError(error);
            return Promise.reject(error);
        }
    }
 
    public throwIfNot(...states: T[]): void {
        let result = false;
        for (const state of states) {
            Iif (this.is(state)) {
                result = true;
            }
        }
        Eif (!result) {
            const error = `Current state is ${this.current} not one of [${states.join(',')}]`;
            this.logError(error);
            throw new Error(error);
        }
    }
 
    private logError(m: string): void {
        Eif (this.logger) {
            this.logger.error(m);
        }
    }
    
    private switchInternal(to: T): void {
        /* istanbul ignore if */
        if (this.logger.isTraceEnabled()) {
            this.logger.trace(`${this.getCurrent()} -> ${to}`);
        }
        this.current = to;
    }
 
    private putIfAbsent(state: T): void {
        Eif (!this.stateDescriptorsMap.has(state)) {
            this.stateDescriptorsMap.set(state, new StateDescriptor(state));
        }
    }
 
    private lookup(state: T): StateDescriptor<T> {
        return this.stateDescriptorsMap.get(state) as StateDescriptor<T>;
    }
 
}