Search code examples
persistenceworkflowstate-machinestate-machine-workflow

How can we persist states and transitions in stateless4j based State Machine?


I am working on implementing a state machine for a workflow management system based on the Stateless4j API. However, I am not able to find an effective way to persist the states and transitions in Stateless4j.

As part of our usecases, we have the requirement to keep States alive for more than 3 - 4 days until the user returns to the workflow. And we will have more than one workflow running concurrently.

Can you please share your insights on the best practices to persist states in Stateless4j based State Machine implementation?


Solution

  • It looks like what you need to do is construct your StateMachine with a custom accessor and mutator, something like this:

    public class PersistentMutator<S> implements Action1<S> {
        Foo foo = null;
    
        @Inject
        FooRepository fooRepository;
    
        public PersistentMutator(Foo foo) {
            this.foo = foo;
        }
    
        @Override
        public void doIt(S s) {
           foo.setState(s);
           fooRepository.save(foo)
        }
    }
    

    Then you want to call the constructor with your accessors and mutators:

    /**
     * Construct a state machine with external state storage.
     *
     * @param initialState  The initial state
     * @param stateAccessor State accessor
     * @param stateMutator  State mutator
     */
    public StateMachine(S initialState, Func<S> stateAccessor, Action1<S> stateMutator, StateMachineConfig<S, T> config) {
        this.config = config;
        this.stateAccessor = stateAccessor;
        this.stateMutator = stateMutator;
        stateMutator.doIt(initialState);
    }
    

    Alternatively, you may want to look at StatefulJ. It has built in support for atomically updating state in both JPA and Mongo out of the box. This may save you some time.

    Disclaimer: I'm the author of StatefulJ