• Stars
    star
    232
  • Rank 172,847 (Top 4 %)
  • Language
    C#
  • License
    Apache License 2.0
  • Created about 10 years ago
  • Updated about 4 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Efficient asynchronous and synchronous state machines for .NET

LiquidState

Efficient state machines for .NET with both synchronous and asynchronous support. Heavily inspired by the excellent state machine library Stateless by Nicholas Blumhardt.

NuGet badge

Installation

NuGet:

Install-Package LiquidState

Supported Platforms:

.NETPlatform 1.0 (Formerly PCL259 profile - Supports .NETCore, .NETDesktop, Xamarin and Mono)

Highlights

  • Zero heap allocations during the machine execution - GC friendly and high-performance. (Awaitable machines still incur the async/await costs).
  • Fully supports async/await methods everywhere => OnEntry, OnExit, during trigger, and even trigger conditions.
  • Builds a linked object graph internally during configuration making it a much faster and more efficient implementation than regular dictionary based implementations.
  • Both synchronous, and asynchronous machines with full support for async-await.
  • MoveToState, to move freely between states, without triggers.
  • PermitDynamic to support selection of states dynamically on-the-fly.
  • Diagnostics in-built to check for validity of triggers, and currently available triggers.

Release Notes

How To Use

You only ever create machines with the StateMachineFactory static class. This is the factory for both configurations and the machines. The different types of machines given above are automatically chosen based on the parameters specified from the factory.

Step 1: Create a configuration:

var config = StateMachineFactory.CreateConfiguration<State, Trigger>();

or for awaitable, or async machine:

var config = StateMachineFactory.CreateAwaitableConfiguration<State, Trigger>();

Step 2: Setup the machine configurations using the fluent API.

    config.ForState(State.Off)
        .OnEntry(() => Console.WriteLine("OnEntry of Off"))
        .OnExit(() => Console.WriteLine("OnExit of Off"))
        .PermitReentry(Trigger.TurnOn)
        .Permit(Trigger.Ring, State.Ringing,
                () => { Console.WriteLine("Attempting to ring"); })
        .Permit(Trigger.Connect, State.Connected,
                () => { Console.WriteLine("Connecting"); });

    var connectTriggerWithParameter =
                config.SetTriggerParameter<string>(Trigger.Connect);

    config.ForState(State.Ringing)
        .OnEntry(() => Console.WriteLine("OnEntry of Ringing"))
        .OnExit(() => Console.WriteLine("OnExit of Ringing"))
        .Permit(connectTriggerWithParameter, State.Connected,
                name => { 
                 Console.WriteLine("Attempting to connect to {0}", name);
                })
        .Permit(Trigger.Talk, State.Talking,
                () => { Console.WriteLine("Attempting to talk"); });

Step 3: Create the machine with the configuration:

var machine = StateMachineFactory.Create(State.Ringing, config);

Step 4: Use them!

  • Using triggers:
machine.Fire(Trigger.On);

or

await machine.FireAsync(Trigger.On);
  • Using direct states:
machine.MoveToState(State.Ringing);

or its async variant.

  • To use parameterized triggers, have a look at the example below.

Examples

A synchronous machine example:

    var config = StateMachineFactory.CreateConfiguration<State, Trigger>();

    config.ForState(State.Off)
        .OnEntry(() => Console.WriteLine("OnEntry of Off"))
        .OnExit(() => Console.WriteLine("OnExit of Off"))
        .PermitReentry(Trigger.TurnOn)
        .Permit(Trigger.Ring, State.Ringing,
                () => { Console.WriteLine("Attempting to ring"); })
        .Permit(Trigger.Connect, State.Connected,
                () => { Console.WriteLine("Connecting"); });

    var connectTriggerWithParameter =
                config.SetTriggerParameter<string>(Trigger.Connect);

    config.ForState(State.Ringing)
        .OnEntry(() => Console.WriteLine("OnEntry of Ringing"))
        .OnExit(() => Console.WriteLine("OnExit of Ringing"))
        .Permit(connectTriggerWithParameter, State.Connected,
                name => { Console.WriteLine("Attempting to connect to {0}", name); })
        .Permit(Trigger.Talk, State.Talking,
                () => { Console.WriteLine("Attempting to talk"); });

    config.ForState(State.Connected)
        .OnEntry(() => Console.WriteLine("AOnEntry of Connected"))
        .OnExit(() => Console.WriteLine("AOnExit of Connected"))
        .PermitReentry(Trigger.Connect)
        .Permit(Trigger.Talk, State.Talking,
            () => { Console.WriteLine("Attempting to talk"); })
        .Permit(Trigger.TurnOn, State.Off,
            () => { Console.WriteLine("Turning off"); });


    config.ForState(State.Talking)
        .OnEntry(() => Console.WriteLine("OnEntry of Talking"))
        .OnExit(() => Console.WriteLine("OnExit of Talking"))
        .Permit(Trigger.TurnOn, State.Off,
            () => { Console.WriteLine("Turning off"); })
        .Permit(Trigger.Ring, State.Ringing,
            () => { Console.WriteLine("Attempting to ring"); });

    var machine = StateMachineFactory.Create(State.Ringing, config);

    machine.Fire(Trigger.Talk);
    machine.Fire(Trigger.Ring);
    machine.Fire(connectTriggerWithParameter, "John Doe");

Now, let's take the same dumb, and terrible example, but now do it asynchronously! (Mix and match synchronous code when you don't need asynchrony to avoid the costs.)

    // Note the "CreateAwaitableConfiguration"
    var config = StateMachineFactory.CreateAwaitableConfiguration<State, Trigger>();

    config.ForState(State.Off)
        .OnEntry(async () => Console.WriteLine("OnEntry of Off"))
        .OnExit(async () => Console.WriteLine("OnExit of Off"))
        .PermitReentry(Trigger.TurnOn)
        .Permit(Trigger.Ring, State.Ringing,
            async () => { Console.WriteLine("Attempting to ring"); })
        .Permit(Trigger.Connect, State.Connected,
            async () => { Console.WriteLine("Connecting"); });

    var connectTriggerWithParameter =
                config.SetTriggerParameter<string>(Trigger.Connect);

    config.ForState(State.Ringing)
        .OnEntry(() => Console.WriteLine("OnEntry of Ringing"))
        .OnExit(() => Console.WriteLine("OnExit of Ringing"))
        .Permit(connectTriggerWithParameter, State.Connected,
                name => { Console.WriteLine("Attempting to connect to {0}", name); })
        .Permit(Trigger.Talk, State.Talking,
                () => { Console.WriteLine("Attempting to talk"); });

    config.ForState(State.Connected)
        .OnEntry(async () => Console.WriteLine("AOnEntry of Connected"))
        .OnExit(async () => Console.WriteLine("AOnExit of Connected"))
        .PermitReentry(Trigger.Connect)
        .Permit(Trigger.Talk, State.Talking,
            async () => { Console.WriteLine("Attempting to talk"); })
        .Permit(Trigger.TurnOn, State.Off,
            async () => { Console.WriteLine("Turning off"); });

    config.ForState(State.Talking)
        .OnEntry(() => Console.WriteLine("OnEntry of Talking"))
        .OnExit(() => Console.WriteLine("OnExit of Talking"))
        .Permit(Trigger.TurnOn, State.Off,
            () => { Console.WriteLine("Turning off"); })
        .Permit(Trigger.Ring, State.Ringing,
            () => { Console.WriteLine("Attempting to ring"); });

    var machine = StateMachineFactory.Create(State.Ringing, config);

    await machine.FireAsync(Trigger.Talk);
    await machine.FireAsync(Trigger.Ring);
    await machine.FireAsync(connectTriggerWithParameter, "John Doe");

Core APIs

IStateMachineCore:

public interface IStateMachineCore<TState, TTrigger>
{
    TState CurrentState { get; }
    bool IsEnabled { get; }
    void Pause();
    void Resume();

    event Action<TriggerStateEventArgs<TState, TTrigger>> UnhandledTrigger;
    event Action<TransitionEventArgs<TState, TTrigger>> InvalidState;
    event Action<TransitionEventArgs<TState, TTrigger>> TransitionStarted;
    event Action<TransitionExecutedEventArgs<TState, TTrigger>>
                                                       TransitionExecuted;
}

Synchronous:

public interface IStateMachine<TState, TTrigger> 
        : IStateMachineCore<TState, TTrigger>
{
    IStateMachineDiagnostics<TState, TTrigger> Diagnostics { get; }

    void Fire<TArgument>(
            ParameterizedTrigger<TTrigger, TArgument> parameterizedTrigger, 
            TArgument argument);
    void Fire(TTrigger trigger);
    void MoveToState(TState state, 
            StateTransitionOption option = StateTransitionOption.Default);
}

Awaitable:

public interface IAwaitableStateMachine<TState, TTrigger> 
        : IStateMachineCore<TState, TTrigger>
{
    IAwaitableStateMachineDiagnostics<TState, TTrigger> Diagnostics { get; }

    Task FireAsync<TArgument>(
            ParameterizedTrigger<TTrigger, TArgument> parameterizedTrigger,
            TArgument argument);
    Task FireAsync(TTrigger trigger);
    Task MoveToStateAsync(TState state, 
            StateTransitionOption option = StateTransitionOption.Default);
}

In-built Machines

  • Common Roots:

    • AbstractStateMachineCore - All machines derive from this. This mostly just provide the common boiler plates.
  • Synchronous:

    • RawStateMachine - Direct, fully functional raw state machine. No protective abstractions or overheads. Typically only used as a base for other machines.
    • GuardedStateMachine - Lock-free protection over raw state machine. Minimal statemachine for independent usage.
    • BlockingStateMachine - Synchronized using Monitor and blocks until all of the requests are completed one by one. Order is not guaranteed, when parallel triggers are fired due to the nature of locks.
  • Awaitable:

    • RawAwaitableStateMachine - Direct, fully functional raw state machine. No protective abstractions or overheads. Typically only used as a base for other machines.
    • GuardedAwaitableStateMachine - Lock-free protection over raw state machine. Minimal statemachine for independent usage.
    • ScheduledAwaitableStateMachine - Schedules the machine implementation to an external TaskScheduler. Thread-safety, order, and synchronization are the responsibility of the scheduler.
    • QueuedAwaitableStateMachine - A lock-free implementation of a fully asynchronous queued statemachine. Order is guaranteed.

Notes:

  • Awaitable state machines are a superset of asynchronous machines. All async machines are awaitable, but the opposite may or may not be true.
  • Most of the above machines come with both their own sealed classes as well as Base classes, for extending them.

Dynamic Triggers

A simple implementation of the dynamic trigger is a part of the sample. For more information or if you want to understand in detail the choices leading up to the design, please have a look at: #20, and #7

Support

Please use the GitHub issue tracker here if you'd like to report problems or discuss features. As always, do a preliminary search in the issue tracker before opening new ones - (Tip: include pull requests, closed, and open issues: Exhaustive search ).

Credits

Thanks to JetBrains for the OSS license of Resharper Ultimate.

Proudly developed using:

Resharper logo

License

This project is licensed under either of the following, at your choice:

Code of Conduct

Contribution to the LiquidState project is organized under the terms of the Contributor Covenant, and as such the maintainer @prasannavl promises to intervene to uphold that code of conduct.

More Repositories

1

WinApi

A simple, direct, ultra-thin CLR library for high-performance Win32 Native Interop
C#
786
star
2

icomponent

A super simple, render-agnostic component library for the modern web that emphasizes framework and renderer freedom
TypeScript
29
star
3

mchain

A super tiny go package that handles middleware chaining in it's most minimal form
Go
28
star
4

Liara

High-performance, highly modular, fully asynchronous .NET/Mono framework for building HTTP services and web sites.
C#
14
star
5

go-errors

A super tiny package for error encapsulation in idiomatic Go
Go
14
star
6

MongoSessionProvider

ASP.NET Session Provider for MongoDB
C#
7
star
7

rust-away

Rust - Are We Auto-complete Yet?
Rust
5
star
8

NetCoreEx

Extended collection of packages that provide common structures, extensions, and helpers that can be used across many libraries, and applications.
C#
4
star
9

SharpLog

A simple high-peformance portable logging framework.
C#
4
star
10

go-gluons

A grab bag of personal go packages, and templates to hold things together
Go
3
star
11

MSP430-IR-Based-Codes

IR Transceiver based codes that can be public - NEC/RC5 Algorithms
C
3
star
12

knowledge

Document everything!
2
star
13

ConsoleUtils

Console application helpers and utilities.
C#
2
star
14

prasannavl.com

Prasanna's Weblog
JavaScript
2
star
15

Wrex

Event-based asynchronous http-load testing library.
C#
2
star
16

waldo

A personal helper experiment in Rust
Rust
1
star
17

rs-gluons

A grab bag of personal rust modules, and templates to hold things together
Rust
1
star
18

RedScooby

1
star
19

history-next

A history component that providers asynchronous listeners with promises and provides a view of history for each listener with a context
TypeScript
1
star
20

scripts

Personal scripts
PowerShell
1
star
21

dfi-emissions-handler-bot

DFI emissions handler bot
TypeScript
1
star