Skip to content

Add a simple Finite State Machine implementation

Thomas Randolph requested to merge rfc/fsm into master

What does this MR do?

This adds a basic Finite State Machine implementation to the frontend utils. This is to support the will-implement RFC #65.

The state implementation exports two functions intended to emulate an ultra-simplified version of xstate/fsm†:

  • transition
  • machine

machine

machine starts a "live" machine. It remembers the current state, so a consumer can do something like:

const state = machine( definition );

state.send( "valid-transition-event" );

state.is( "updated-state" ); // returns `true`

The live state machine functions can be detached from their machine:

const { send, is } = machine( definition );

send( "valid-transition-event" );

is( "updated-state" ); // return true;

machine exposes the current state as a property - .value - so the state can be read from the machine:

if( theState.value == "valid-state" ) ...

transition

transition is a stateless finite state machine (neat!).

Given some machine definition, a current state, and a transition, the machine will either return the new state, or return the current state if no valid state + transition combination exists.

const definition = {
    states: {
        initial: {
            on: {
                valid: 'resulting'
            }
        },
        resulting: null
   }
};
const transitionEvent = 'valid';
let state = 'initial';

state = transition( definition, state, transitionEvent );

// state === 'resulting'

state = transition( definition, state, 'irrelevant' );

// state === 'resulting'

† If we ever want more features in an externally-maintained product, xstate/fsm is the state of the art in finite state machines.

Why

Other than the will-implement RFC #65, consider this extremely good explanation of the mess we have without state machines.

Roadmap

Right now, this is just a base implementation.

I know of two ad hoc implementations of finite state machines in the codebase, and had MRs open to address both.
They're closed now, but I expect once this is merged, they can be re-opened.

MR Notes
We're here 👉🏻 Implement a basic Finite State Machine (that intentionally emulates xstate/fsm in many regards)
!37285 (closed) Update Cluster FSM
!37286 (closed) Update Renamed Diff Viewer FSM

Screenshots

N/A, all ~backstage

Does this MR meet the acceptance criteria?

Conformity

Availability and Testing

Security

If this MR contains changes to processing or storing of credentials or tokens, authorization and authentication methods and other items described in the security review guidelines:

  • [-] Label as security and @ mention @gitlab-com/gl-security/appsec
  • [-] The MR includes necessary changes to maintain consistency between UI, API, email, or other methods
  • [-] Security reports checked/validated by a reviewer from the AppSec team
Edited by Thomas Randolph

Merge request reports