Giter Site home page Giter Site logo

markciliavincenti / asyncstatemachine Goto Github PK

View Code? Open in Web Editor NEW

This project forked from dschreib42/asyncstatemachine

0.0 1.0 0.0 338 KB

A framework for creating state machines and lightweight state machine-based workflows for Microsoft .NET

License: Other

C# 100.00%

asyncstatemachine's Introduction

AsyncStateMachine Continuous NuGet Status

A framework for creating state machines and lightweight state machine-based workflows for Microsoft .NET

// Create a state machine configuration with the initial Open state.
var config = new StateMachineConfiguration<Trigger, State>(State.Open);

// Configure the Open state
config.Configure(State.Open)
    .Permit(Trigger.assign, State.Assigned);

// Configure the Assigned state
config.Configure(State.Assigned)
    .PermitReentry(Trigger.assign)
    .Permit(Trigger.close, State.Closed)
    .Permit(Trigger.defer, State.Deferred)
    .OnEntry<string>(assignee => OnAssignedAsync(assignee)) // asynchronous with parameter
    .OnExit(OnDeassignedAsync); // asynchronous without parameter

// Configure the Deferred state
config.Configure(State.Deferred)
    .OnEntry(() => _assignee = null) // synchronous
    .Permit(Trigger.assign, State.Assigned);

// Configure the Closed state
config.Configure(State.Closed)
    .OnEntry(() => Console.WriteLine("Bug is closed"));

// ...

// Instantiate a new state machine using the previously created configuration.
var stateMachine = new StateMachine<Trigger, State>(config);

// initialize the state machine to invoke the OnEntry callback for the initial state.
await stateMachine.IntializeAsync();

await stateMachine.FireAsync(Trigger.assign); // asynchronous
Assert.AreEqual(State.Assigned, stateMachine.CurrentState);

This project, as well as the example above, was inspired by Stateless. The aim of this project is not to provide a one-to-one replacement of stateless. The goal was to provide a state machine providing an asynchronous interface, lightweight implementation, easy to maintain and easy to extend.

Features

Most standard state machine constructs are supported:

  • Generic support for states and triggers of type struct (numbers, chars, enums, etc.)
  • Entry/exit actions for states (synchronous and asynchronous)
  • Guard clauses to support conditional transitions
  • Hierarchical states
  • Unit tested (code coverage >80%)

Some useful extensions are also provided:

  • Parameterized triggers
  • Reentrant states
  • Export state machine as graph (Graphviz/DOT, Mermaid Flow-Chart or Mermaid State-Diagram)

Entry/Exit actions

// Configure the Assigned state
config.Configure(State.Assigned)
    .Permit(Trigger.assign, State.Assigned)
    .Permit(Trigger.close, State.Closed)
    .Permit(Trigger.defer, State.Deferred)
    .OnEntry<string>(assignee => OnAssignedAsync(assignee)) // asynchronous with parameter
    .OnExit(OnDeassignedAsync); // asynchronous without parameter

Entry/Exit actions can be used to apply certain functionality when a certain state is reached. The OnEntry() calls are all invoked when the state is reached and all OnExit() calls are invoked, when the state is changed. OnEntry() calls support synchronous and asynchronous functions as well as parameterized versions. Currently, only a single parameter is supported. If several parameters are needed, then these must be encapsulated in a class/struct/pair. When multiple OnEntry/OnExit callbacks are registered, then all of them are executed in the order of registration.

Guard Clauses

The state machine will choose between multiple transitions based on guard clauses, e.g.:

config.Configure(State.SomeState)
    .PermitIf(Trigger.ab, State.A, () => Condition)
    .PermitIf(Trigger.ab, State.B, () => !Condition);

Depending on the guard clause, the trigger either transitions to state A or state B. Guard clauses within a state must be mutually exclusive (multiple guard clauses cannot be valid at the same time). The guard clauses will be evaluated whenever a trigger is fired. Guards should therefor be made side effect free.

Parameterised Triggers

A strongly-typed parameter can be assigned to trigger:

config.Configure(State.Assigned)
    .OnEntry<string>(email => OnAssigned(email));

// ...

await stateMachine.FireAsync(assignTrigger, "[email protected]");

If no callback can be found handling the given type of argument, an ArgumentException is thrown. If multiple parameters have to be passed into the attached callback, then wrap the parameters into a new class and pass a strongly-typed instance of that class into the FireAsync() call. It doesn't matter if the callback is synchronous or asynchronous, both versions are supported out of the box.

Ignored Transitions and Reentrant States

Firing a trigger that does not have an allowed transition associated with it will cause an exception (InvalidOperationException) to be thrown.

To ignore triggers within certain states, use the Ignore(...) directive:

config.Configure(State.Closed)
    .Ignore(Trigger.close);

Alternatively, a state can be marked reentrant so its entry and exit actions will fire even when transitioning from/to itself:

config.Configure(State.Assigned)
    .PermitReentry(Trigger.assign)
    .OnEntry(() => SendEmailToAssignee());

By default, triggers must be ignored explicitly. Otherwise an exception (InvalidOperationException) is thrown.

State Hierarchy

config.Configure(State.A);
config.Configure(State.B)
    .SubstateOf(A);
config.Configure(State.C)
    .SubstateOf(B);

Defines a multi-level hierarchy where C and B are sub-states of A. The CurrentState property always returns the current state. But with InStateAsync(...) can be checked, if the machine is in a sub-state and in the super-/parent-state.

The max. supported depth of hierarchies is limited to InStateAsync(...) by ushort.MaxValue = 65535.

Observation

AsyncStateMachine provides an observable to propagate state changes:

IDisposable subscription = stateMachine.Observable.Subscribe(
    (source, trigger, destination) => Console.WriteLine($"{source} --{trigger}--> {destination}"));

// ...

subscription.Dispose();

The observable is invoked, whenever the state machine state has changed.

Export as graph

It can be useful to visualize state machines. With this approach the code is the authoritative source and state diagrams are always up-to-date. Therefore AsyncStateMachine supports different graph engines like: Graphviz and Mermaid

Graphviz

string graph = DotGraph.Format(config, GraphOptions.Default);

The DotGraph.Format() method returns a string representation of the state machine in the DOT graph language.

This can then be rendered by tools that support the DOT graph language, such as the dot command line tool from graphviz.org or use http://www.webgraphviz.com for instant viewing.

The rendered bug StateMachine looks like this:

Mermaid

string graph = MermaidStateGraph.Format(config);

The rendered mermaid state graph looks like this:

or

string graph = MermaidFlowChartGraph.Format(config);

The rendered mermaid flow graph looks like this:

The Mermaid*Graph.Format() methods return a string representation of the state machine in the Mermaid graph language).

This string representation can then be rendered by tools that support the mermaid graph language, such as Azure DevOPS or https://mermaid.live for instant viewing.

Building

AsyncStateMachine runs on .NET NetCore platforms targeting .NET 6.0 or 7.0. Visual Studio 2022 or Visual Code is required to build the solution.

Project Goals

This page is an almost-complete description of AsyncStateMachine, and its explicit aim is to remain minimal.

Please use the issue tracker if you'd like to report problems or discuss features.

asyncstatemachine's People

Contributors

dschreib42 avatar silverdark avatar

Watchers

 avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.