Coder Social home page Coder Social logo

scottctr / nstatemanager Goto Github PK

View Code? Open in Web Editor NEW
24.0 5.0 6.0 3.84 MB

Easy to use and very flexible finite state manager for .Net.

License: Apache License 2.0

C# 100.00%
state-machine state-management stateless csharp dotnet dot-net dotnet-standard

nstatemanager's Introduction

NStateManager Build status NuGet Status Security Rating Reliability Rating Maintainability Rating

Background and Goals

NStateManager is a .Net library for managing:

This project was created while developing cloud-based solutions. We needed a state management solution made for our stateless services.

Quick Example

Managing state of a Sale for a simple point-of-sale system.

POSv1

Configuring the state machine

//State machine to manage sales for a point of sale system
stateMachine = new StateMachine<Sale, SaleState, SaleEvent>(
  stateAccessor: (sale) => sale.State,                //stateAccessor is used to retrieve the current state
  stateMutator: (sale, state) => sale.State = state); //stateMutator updates state based on transition rule below

//Log each time a sale changes state regardless of to/from state
stateMachine.RegisterOnTransitionedAction((sale, transitionDetails) 
  => Output.WriteLine($"Sale {sale.SaleID} transitioned from {transitionDetails.PreviousState} to {transitionDetails.CurrentState}."));

//Configure the Open state
stateMachine.ConfigureState(SaleState.Open)
  //Process the new item on the AddItem event 
  .AddTriggerAction<SaleItem>(SaleEvent.AddItem, (sale, saleItem) => { sale.AddItem(saleItem); })
  //Process the payment on the Pay event
  .AddTriggerAction<Payment>(SaleEvent.Pay, (sale, payment) => { sale.AddPayment(payment); })
  //Transition to the ChangeDue state on Pay event if customer over pays
  .AddTransition(SaleEvent.Pay, SaleState.ChangeDue, condition: sale => sale.Balance < 0, name: "Open2ChangeDue", priority: 1)
  //Transition to the Completed state on Pay event if customer pays exact amount
  .AddTransition(SaleEvent.Pay, SaleState.Complete, condition: sale => sale.Balance == 0, name: "Open2Complete", priority: 2);

//Configure the ChangeDue state
stateMachine.ConfigureState(SaleState.ChangeDue)
  //Process the returned change on the ChangeGiven event
  .AddTriggerAction<Payment>(SaleEvent.ChangeGiven, (sale, payment) => { sale.ReturnChange(); })
  //Transition to the Complete state on ChangeGiven -- no conditions
  .AddTransition(SaleEvent.ChangeGiven, SaleState.Complete);

//No configuration required for Complete state since it's a final state and
//no state transitions or actions are allowed at this point

Using the state machine

//Add an item to a sale
stateMachine.FireTrigger(sale, SaleEvent.AddItem, saleItem); 

//Add a payment to a sale
stateMachine.FireTrigger(sale, SaleEvent.Pay, payment);

//Give the customer their change
stateMachine.FireTrigger(sale, SaleEvent.ChangeGiven, payment);

For a walkthough of the above code, go to the Quick Start. You can also look at the Wiki for additional details.

Feedback

Feedback, questions, advice, and contributions are always welcomed so feel free to leave your thoughts in Issues.

nstatemanager's People

Contributors

pkn4645 avatar scottctr avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar

nstatemanager's Issues

AddAutoFallbackTransition?

I attempted to implement your AddAutoFallbackTransition feature, based on the Walk-Run-Jump example you provided but discovered that I couldn't compile your example because none of the four overloaded AddAutoFallbackTransition methods had argument types that matched those in your example.

Do I not have the latest code? Or did I jump the gun trying out a feature that's still under construction?

Thanks,

Paul

Add optional parameter for Entry, Exit, and Reentry events

Sample scenario:

  1. Sale.Open transitions to Sale.CardProcessing on SaleEvent.CardPayment with payment argument
  2. Sale.CardProcessing state entry event needs payment argument to send to card processor
  3. Sale.CardProcessor automatically forwards to Sale.Complete if card processing was successful and sale.Balance is now 0.

Ignore vs raise exception?

I'm just getting familiar with NStateManager. Very nice code and features. Well done!

This package appears similar to (derived from?) the Stateless package.

One thing I noticed in your package is that there is no easy way to specify which triggers (a.k.a. events) are allowed or not allowed for a given state in the configuration. If a trigger is fired while in a given state, and that trigger is not included in any .AddTransition or .AddTriggerAction in the state's configuration, no action is taken and the trigger is simply ignored. That may be the desired behavior in some state machines, but not in the one I'm designing.

I discovered this playing around with the Sale Console example, by firing a ChangeGiven trigger while in the Open state (that trigger should only be fired while in the ChangeDue state). The program'a output was identical with or without my extra firing of the ChangeGiven trigger, with no indication that an attempt had been made to fire that trigger. No harm was done, since the trigger was ignored, but the fact that I was able to fire a trigger while in a 'wrong' state is my concern.

The Stateless package takes a different approach, where you must include a Permit (or PermitIf) method for each allowed trigger within a given state's configuration. Without a Permit method for the ChangeGiven trigger in the Open state's configuration, Stateless would have thrown an exception in the above situation.

Is there another way within the state manager's Configure method, to indicate which triggers are allowed or not allowed for a given state?

Allow multiple Auto forward/fallback transitions per state

As demonstrated below, we may want to forward/fallback to different states based on different conditions.

public enum SaleEvent { AddItem, CashPayment, CardPayment, ChangeGiven }
public enum SaleState { Open, CardProcessing, ChangeDue, Complete }

//Configure the Open state to transition to the CardProcessing state when a CardPayment is received
_stateMachine.ConfigureState(SaleState.Open)
.AddTransition(trigger: SaleEvent.CardPayment, toState: SaleState.CardProcessing);

//Configure the CardProcessing state to send the card payment to the processor and then transition to
//...Complete state if the card payment was successful and Balance is now 0
//...back to Open state if card payment wasn't success
_stateMachine.ConfigureState(SaleState.CardProcessing)
.AddEntryAction((sale, cardPayment) => {/* send to processor and apply to sale */ })
.AddAutoTransition(toState: SaleState.Complete, condition: sale => sale.Balance == 0)
.AddAutoTransition(toState: SaleState.Open, condition: sale => sale.Balance != 0);

AddAutoForwardTransition should require a condition

The AddAutoForwardTransition configuration method only requires the trigger and toState args (the condition, name and priority args are optional). But if don’t specify a condition arg, the state machine throws a TypeInitializationException exception (inner exception is ArgumentNullException) at the time its trigger is fired.

OnExit should not be called when moving to subState / OnEnter should not be called when moving to superState

SuperState --> SubState
SuperState OnExit *** should not fire
SubState OnEntry
SubState --> SuperState
SubState OnExit
SuperState OnEntry *** should not fire

public class Program
{
    private class TestEntity
    { public State State { get; set; } }

    private enum State { SuperState, SubState }
    private enum Trigger { X, Y }

    [Fact]
    public void Test()
    {
        IStateMachine<TestEntity, State, Trigger> stateMachine = new StateMachine<TestEntity, State, Trigger>(
            stateAccessor: entity => entity.State
          , stateMutator: (entity, newState) => entity.State = newState);
        
        stateMachine.ConfigureState(State.SuperState)
            .AddTransition(Trigger.X, State.SubState)
            .AddEntryAction(_ => Console.WriteLine("SuperState OnEntry"))
            .AddExitAction(_ => Console.WriteLine("SuperState OnExit"));

        stateMachine.ConfigureState(State.SubState)
            .IsSubStateOf(stateMachine.ConfigureState(State.SuperState))
            .AddTransition(Trigger.Y, State.SuperState)
            .AddEntryAction(_ => Console.WriteLine("SubState OnEntry"))
            .AddExitAction(_ => Console.WriteLine("SubState OnExit"));

        stateMachine.RegisterOnTransitionedEvent(((_, result) => Console.WriteLine($"{result.StartingState} --> {result.CurrentState}")));

        var testEntity = new TestEntity();
        stateMachine.FireTrigger(testEntity, Trigger.X);
        stateMachine.FireTrigger(testEntity, Trigger.Y);
    }
}

StateMachineAsync.FireTriggerAsync<TRequest> throws System.ArgumentException

ISSUE:
FireTriggerAsync<TRequest> will not run successfully (the state machine is configured to accept it and then it is invoked with an instance of TRequest).

The test below can reproduce the issue.
Currently the error raised is:

System.ArgumentException request must be of type Request.

RESOLUTION:
The issue can be resolved in StateConfigurationAsync<T, TState, TTrigger>

At the method Task<StateTransitionResult<TState, TTrigger>> FireTriggerAsync(ExecutionParameters<T, TTrigger> parameters)

ExecuteAsync is called with 'request: null', but instead should be called with 'request: parameters.Request'. ExecuteAsync (of the class FunctionActionParameterized<T, TRequest>) will compare the type of the provided request instance to the expected TRequest and when null is supplied it's never the case, and the ArgumentException is raised:

throw new ArgumentException($"{nameof(request)} must be of type {typeof(TRequest).Name}.");

TEST:

        [Fact]
        public async Task FireTriggerAsyncWRequest_withReferenceTypeInstance_triggerExecutes()
        {
            var testRequest = new Request(123.45);

            var sut = new StateMachineAsync<Sale, SaleState, SaleEvent>(
                stateAccessor: sale2 => sale2.State
                , stateMutator: (sale3, newState) => sale3.State = newState);

            sut.ConfigureState(SaleState.Open)
                .AddTriggerAction<Request>(SaleEvent.Pay, async (saleInstance, request, token) =>
                {
                    saleInstance.Balance = request.Value;
                    await Task.Delay(100);
                })
                .AddTransition(SaleEvent.Pay, SaleState.Complete);

            var sale = new Sale(saleID: 45) { State = SaleState.Open };
            var stateTransitionResult = await sut.FireTriggerAsync<Request>(sale, SaleEvent.Pay, testRequest);

            Assert.NotNull(stateTransitionResult);
            Assert.Equal(SaleState.Complete, stateTransitionResult.CurrentState);
            Assert.Equal(SaleState.Complete, sale.State);
            Assert.Equal(sale.Balance, testRequest.Value);
        }

And the request is defined as:

    public sealed class Request
    {
        public double Value { get; }
        public Request(double value)
        {
            Value = value;
        }
    }

AddTransition<Request> never runs when triggered in async StateMachine.

AddTransition<Request> never runs when triggered in async StateMachine.
The transition is registered ultimately with an instance of StateTransitionAutoFallbackParameterizedAsync. When its method ExecuteAsync is called from StateConfigurationAsync.FireTriggerPrimAsync() the second optional parameter is not supplied and becomes null. The check to execute the condition delegate does not execute (thus the problem) as the check requires currentResult != null.

A way to get the tests passing is to make the condition:

currentResult == null ||

rather than:

currentResult != null &&

but this would ignore the importance of the check, and maybe its better to properly supply the second parameter currentResult from the caller.

Tests below show the issue - the synchronous state machine works ok in this scenario and its corresponding tests are available from my current pull request.

        [Fact]
        public async Task FireTriggerAsyncWRequest_addTransitionSignatureWRequest_transitionExecutesWithRequestInstance()
        {
            var testRequest = new TestRequest(123.45);

            var sut = new StateMachineAsync<Sale, SaleState, SaleEvent>(
                stateAccessor: sale2 => sale2.State
                , stateMutator: (sale3, newState) => sale3.State = newState);

            var result = default(double);

            sut.ConfigureState(SaleState.Open)
                .AddTransition<TestRequest>(SaleEvent.Pay, SaleState.Complete, (saleInstance, request, token) =>
                {
                    result = request.Value;
                    return Task.FromResult(true);
                });

            var sale = new Sale(saleID: 45) { State = SaleState.Open };
            var stateTransitionResult = await sut.FireTriggerAsync<TestRequest>(sale, SaleEvent.Pay, testRequest);

            Assert.NotNull(stateTransitionResult);
            Assert.Equal(SaleState.Complete, stateTransitionResult.CurrentState);
            Assert.Equal(SaleState.Complete, sale.State);
            Assert.Equal(result, testRequest.Value);
        }

        [Fact]
        public async Task FireTriggerAsyncWRequest_addConsecutiveTransitionSignaturesWRequest_transitionExecutesWithRequestInstance()
        {
            var sut = new StateMachineAsync<Sale, SaleState, SaleEvent>(
                stateAccessor: sale2 => sale2.State
                , stateMutator: (sale3, newState) => sale3.State = newState);

            var result1 = default(double);
            var result2 = default(double);
            var testRequest1 = new TestRequest(123.45);
            var testRequest2 = new TestRequest(12);

            sut.ConfigureState(SaleState.Open)
                .AddTransition<TestRequest>(SaleEvent.Pay, SaleState.ChangeDue, (saleInstance, request, token) =>
                {
                    result1 = request.Value;
                    return Task.FromResult(true);
                });

            sut.ConfigureState(SaleState.ChangeDue)
	            .AddTransition<TestRequest>(SaleEvent.ChangeGiven, SaleState.Complete, (saleInstance, request, token) =>
	            {
		            result2 = request.Value;
		            return Task.FromResult(true);
	            });
			var sale = new Sale(saleID: 45) { State = SaleState.Open };
            await sut.FireTriggerAsync<TestRequest>(sale, SaleEvent.Pay, testRequest1);
            var stateTransitionResult = await sut.FireTriggerAsync<TestRequest>(sale, SaleEvent.ChangeGiven, testRequest2);

            Assert.NotNull(stateTransitionResult);
            Assert.Equal(SaleState.Complete, stateTransitionResult.CurrentState);
            Assert.Equal(SaleState.Complete, sale.State);
            Assert.Equal(result1, testRequest1.Value);
            Assert.Equal(result2, testRequest2.Value);
        }

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.