All files / src/impl StateMachine.impl.ts

100% Statements 82/82
94.11% Branches 32/34
100% Functions 27/27
100% Lines 80/80

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 20312x       12x   12x         12x             12x 136x                 60x         46x         46x 23x 23x 23x   21x         66x         69x         61x 59x 58x 58x 39x 39x 36x   3x   19x         8x 6x 4x 4x   2x     2x           67x         2x         1x         1x       136x       666x 666x 666x 666x       666x 531x   666x       8x 7x 6x 6x       6x       4x 2x 2x       2x 2x   2x 1x   1x           2x 2x   2x 1x   1x         4x 3x         7x 7x       23x 23x 21x 21x 16x 16x             136x 136x   135x 135x 135x 135x 531x         136x 136x 136x  
import { ConcurrencyException } from "@jonloucks/concurrency-ts/api/ConcurrencyException";
import { Rule } from "@jonloucks/concurrency-ts/api/Rule";
import { Config, StateMachine } from "@jonloucks/concurrency-ts/api/StateMachine";
import { Transition } from "@jonloucks/concurrency-ts/api/Transition";
import { Duration, isPresent, OptionalType, RequiredType } from "@jonloucks/concurrency-ts/api/Types";
import { Waitable } from "@jonloucks/concurrency-ts/api/Waitable";
import { eventCheck, illegalCheck, initialValueCheck, presentCheck, ruleCheck, rulesCheck, stateCheck } from "@jonloucks/concurrency-ts/auxiliary/Checks";
import { Type as ConsumerType } from "@jonloucks/concurrency-ts/auxiliary/Consumer";
import { Type as PredicateType } from "@jonloucks/concurrency-ts/auxiliary/Predicate";
import { AutoClose } from "@jonloucks/contracts-ts/api/AutoClose";
 
import { create as createWaitable } from "./Waitable.impl";
 
/** 
 * Create a new StateMachine
 *
 * @return the new StateMachine
 */
export function create<T>(config: RequiredType<Config<T>>): StateMachine<T> {
  return StateMachineImpl.internalCreate(config);
}
 
// ---- Implementation details below ----
 
class StateMachineImpl<S> implements StateMachine<S> {
 
  // Statemachine.open
  open(): AutoClose {
    return this.#currentState.open();
  }
 
  // IsCompleted.
  isCompleted(): boolean {
    return this.#isCompleted;
  }
 
  // StateMachine.setState implementation
  setState(event: string, state: S): boolean {
    if (this.isTransitionAllowed(event, stateCheck(state))) {
      this.#currentState.consume(state);
      this.updateIsCompleted(state);
      return true;
    }
    return false;
  }
 
  // StateMachine.getState implementation
  getState(): S {
    return this.supply();
  }
 
  // StateMachine.hasState implementation
  hasState(state: S): boolean {
    return this.#stateToRulesLookup.has(stateCheck(state));
  }
 
  // StateMachine.isTransitionAllowed implementation
  isTransitionAllowed(event: string, state: S): boolean {
    const validEvent: string = eventCheck(event);
    const toState: S = stateCheck(state);
    const fromState: S = this.getState();
    if (this.hasState(toState) && fromState !== toState) {
      const rules: Set<Rule<S>> | undefined = this.#stateToRulesLookup.get(fromState);
      if (isPresent(rules) && rules.size > 0) {
        return Array.from(rules).every((r) => r.canTransition(validEvent, toState));
      }
      return true;
    }
    return false;
  }
 
  // StateMachine.transition implementation
  transition<R>(transition: Transition<S, R>): OptionalType<R> {
    const t: Transition<S, R> = this.transitionCheck(transition);
    if (this.isAllowed(t)) {
      try {
        return this.handleSuccess(t);
      } catch (thrown) {
        return this.handleError(t, thrown);
      }
    } else {
      return this.handleFailure(t);
    }
  }
 
  // StateMachine.supply implementations
  supply(): S {
    return this.#currentState.supply();
  }
 
  // StateMachine.supplyIf implementation
  supplyIf(predicate: PredicateType<S>): OptionalType<S> {
    return this.#currentState.supplyIf(predicate);
  }
 
  // StateMachine.supplyWhen implementation
  async supplyWhen(predicate: RequiredType<PredicateType<S>>, timeout?: Duration): Promise<S> {
    return this.#currentState.supplyWhen(predicate, timeout);
  }
 
  // StateMachine.notifyWhile implementation
  notifyWhile(predicate: RequiredType<PredicateType<S>>, listener: RequiredType<ConsumerType<S>>): RequiredType<AutoClose> {
    return this.#currentState.notifyWhile(predicate, listener);
  }
 
  static internalCreate<T>(config: Config<T>): StateMachine<T> {
    return new StateMachineImpl<T>(config);
  }
 
  private addStateAndRules(state: S, rules: readonly Rule<S>[]): void {
    const validState = stateCheck(state);
    const validRules = rulesCheck(rules);
    const knownRules = this.getStateRules(validState);
    validRules.forEach(rule => knownRules.add(ruleCheck(rule)));
  }
 
  private getStateRules(state: S): Set<Rule<S>> {
    if (!this.#stateToRulesLookup.has(state)) {
      this.#stateToRulesLookup.set(state, new Set<Rule<S>>());
    }
    return this.#stateToRulesLookup.get(state)!;
  }
 
  private transitionCheck<R>(transition: Transition<S, R>): Transition<S, R> {
    const validTransition: Transition<S, R> = presentCheck(transition, "Transition must be present.");
    this.existsCheck(validTransition.successState);
    eventCheck(validTransition.event);
    return validTransition;
  }
 
  private isAllowed<R>(transition: Transition<S, R>): boolean {
    return this.isTransitionAllowed(transition.event, transition.successState);
  }
 
  private handleSuccess<R>(transition: Transition<S, R>): OptionalType<R> {
    const value: OptionalType<R> = transition.getSuccessValue?.();
    this.setState(transition.event, transition.successState);
    return value;
  }
 
  private handleFailure<R>(transition: Transition<S, R>): R {
    this.setOptionalState(transition.failedState, transition.event);
    const value: OptionalType<R> = transition.getFailedValue?.();
 
    if (isPresent(value)) {
      return value;
    } else {
      throw new ConcurrencyException("Illegal state transition from " + String(this.getState()) +
        " to " + String(transition.successState) + ".");
    }
  }
 
  private handleError<R>(transition: Transition<S, R>, thrown: unknown): R {
    this.setOptionalState(transition.errorState, transition.event);
    const value: OptionalType<R> = transition.getErrorValue?.();
 
    if (isPresent(value)) {
      return value;
    } else {
      throw ConcurrencyException.rethrow(thrown);
    }
  }
 
  private setOptionalState(optional: OptionalType<S>, event: string): void {
    if (isPresent(optional)) {
      this.setState(event, optional);
    }
  }
 
  private existsCheck(state: S): S {
    const validState = stateCheck(state);
    return illegalCheck(validState, !this.hasState(validState), "State must be known.");
  }
 
  private updateIsCompleted(state: S): void {
    const rules: Set<Rule<S>> | undefined = this.#stateToRulesLookup.get(state);
    if (isPresent(rules) && rules.size > 0) {
      for (const rule of rules) {
        if (rule.isTerminal) {
          this.#isCompleted = true;
          return;
        }
      }
    }
  }
 
  private constructor(config: Config<S>) {
    const validConfig: Config<S> = config ?? {};
    const initialState: S = initialValueCheck(validConfig.initialValue);
 
    this.#currentState = createWaitable<S>({ initialValue: initialState });
    this.addStateAndRules(initialState, []);
    Eif (isPresent(validConfig.states) && validConfig.states.length > 0) {
      validConfig.states.forEach(state => {
        this.addStateAndRules(state, validConfig.getStateRules?.(state) ?? []);
      });
    }
  }
 
  readonly #stateToRulesLookup: Map<S, Set<Rule<S>>> = new Map<S, Set<Rule<S>>>();
  readonly #currentState: Waitable<S>;
  #isCompleted: boolean = false;
};