Classic Persistent FSM
Akka Classic pertains to the original Actor APIs, which have been improved by more type safe and guided Actor APIs. Akka Classic is still fully supported and existing applications can continue to use the classic APIs. It is also possible to use the new Actor APIs together with classic actors in the same ActorSystem, see coexistence. For new projects we recommend using the new Actor API.
Dependency
Persistent FSMs are part of Akka persistence, you must add the following dependency in your project:
- sbt
val AkkaVersion = "2.7.1" libraryDependencies += "com.typesafe.akka" %% "akka-persistence" % AkkaVersion
- Maven
- Gradle
Persistent FSM is no longer actively developed and will be replaced by Akka Persistence Typed. It is not advised to build new applications with Persistent FSM. Existing users of Persistent FSM should migrate.
AbstractPersistentFSM
handles the incoming messages in an FSM like fashion. Its internal state is persisted as a sequence of changes, later referred to as domain events. Relationship between incoming messages, FSM’s states and transitions, persistence of domain events is defined by a DSL.
A Simple Example
To demonstrate the features of the AbstractPersistentFSM
, consider an actor which represents a Web store customer. The contract of our “WebStoreCustomerFSMActor” is that it accepts the following commands:
- Scala
- Java
-
source
public static final class AddItem implements Command { private final Item item; public AddItem(Item item) { this.item = item; } public Item getItem() { return item; } } public enum Buy implements Command { INSTANCE } public enum Leave implements Command { INSTANCE } public enum GetCurrentCart implements Command { INSTANCE }
AddItem
sent when the customer adds an item to a shopping cart Buy
- when the customer finishes the purchase Leave
- when the customer leaves the store without purchasing anything GetCurrentCart
allows to query the current state of customer’s shopping cart
The customer can be in one of the following states:
- Scala
- Java
-
source
enum UserState implements PersistentFSM.FSMState { LOOKING_AROUND("Looking Around"), SHOPPING("Shopping"), INACTIVE("Inactive"), PAID("Paid"); private final String stateIdentifier; UserState(String stateIdentifier) { this.stateIdentifier = stateIdentifier; } @Override public String identifier() { return stateIdentifier; } }
LookingAround
customer is browsing the site, but hasn’t added anything to the shopping cart Shopping
customer has recently added items to the shopping cart Inactive
customer has items in the shopping cart, but hasn’t added anything recently Paid
customer has purchased the items
AbstractPersistentFSM
states must implement interface PersistentFSM.FSMState
and implement the String identifier()
method. This is required in order to simplify the serialization of FSM states. String identifiers should be unique!
Customer’s actions are “recorded” as a sequence of “domain events” which are persisted. Those events are replayed on an actor’s start in order to restore the latest customer’s state:
- Scala
- Java
-
source
public static final class ItemAdded implements DomainEvent { private final Item item; public ItemAdded(Item item) { this.item = item; } public Item getItem() { return item; } } public enum OrderExecuted implements DomainEvent { INSTANCE } public enum OrderDiscarded implements DomainEvent { INSTANCE }
Customer state data represents the items in a customer’s shopping cart:
- Scala
- Java
-
source
public static class ShoppingCart { private final List<Item> items = new ArrayList<>(); public ShoppingCart(Item initialItem) { items.add(initialItem); } public ShoppingCart() {} public List<Item> getItems() { return Collections.unmodifiableList(items); } public ShoppingCart addItem(Item item) { items.add(item); return this; } public void empty() { items.clear(); } } public static class Item implements Serializable { private final String id; private final String name; private final float price; Item(String id, String name, float price) { this.id = id; this.name = name; this.price = price; } public String getId() { return id; } public float getPrice() { return price; } public String getName() { return name; } @Override public String toString() { return String.format("Item{id=%s, name=%s, price=%s}", id, price, name); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Item item = (Item) o; return item.price == price && id.equals(item.id) && name.equals(item.name); } }
Here is how everything is wired together:
- Scala
- Java
-
source
startWith(UserState.LOOKING_AROUND, new ShoppingCart()); when( UserState.LOOKING_AROUND, matchEvent( AddItem.class, (event, data) -> goTo(UserState.SHOPPING) .applying(new ItemAdded(event.getItem())) .forMax(Duration.ofSeconds(1))) .event(GetCurrentCart.class, (event, data) -> stay().replying(data))); when( UserState.SHOPPING, matchEvent( AddItem.class, (event, data) -> stay().applying(new ItemAdded(event.getItem())).forMax(Duration.ofSeconds(1))) .event( Buy.class, (event, data) -> goTo(UserState.PAID) .applying(OrderExecuted.INSTANCE) .andThen( exec( cart -> { reportActor.tell(new PurchaseWasMade(cart.getItems()), self()); saveStateSnapshot(); }))) .event( Leave.class, (event, data) -> stop() .applying(OrderDiscarded.INSTANCE) .andThen( exec( cart -> { reportActor.tell(ShoppingCardDiscarded.INSTANCE, self()); saveStateSnapshot(); }))) .event(GetCurrentCart.class, (event, data) -> stay().replying(data)) .event( StateTimeout$.class, (event, data) -> goTo(UserState.INACTIVE).forMax(Duration.ofSeconds(2)))); when( UserState.INACTIVE, matchEvent( AddItem.class, (event, data) -> goTo(UserState.SHOPPING) .applying(new ItemAdded(event.getItem())) .forMax(Duration.ofSeconds(1))) .event(GetCurrentCart.class, (event, data) -> stay().replying(data)) .event( StateTimeout$.class, (event, data) -> stop() .applying(OrderDiscarded.INSTANCE) .andThen( exec( cart -> reportActor.tell(ShoppingCardDiscarded.INSTANCE, self()))))); when( UserState.PAID, matchEvent(Leave.class, (event, data) -> stop()) .event(GetCurrentCart.class, (event, data) -> stay().replying(data)));
State data can only be modified directly on initialization. Later it’s modified only as a result of applying domain events. Override the applyEvent
method to define how state data is affected by domain events, see the example below
- Scala
- Java
-
source
@Override public ShoppingCart applyEvent(DomainEvent event, ShoppingCart currentData) { if (event instanceof ItemAdded) { currentData.addItem(((ItemAdded) event).getItem()); return currentData; } else if (event instanceof OrderExecuted) { return currentData; } else if (event instanceof OrderDiscarded) { currentData.empty(); return currentData; } throw new RuntimeException("Unhandled"); }
andThen
can be used to define actions which will be executed following event’s persistence - convenient for “side effects” like sending a message or logging. Notice that actions defined in andThen
block are not executed on recovery:
- Scala
- Java
-
source
(event, data) -> goTo(UserState.PAID) .applying(OrderExecuted.INSTANCE) .andThen( exec( cart -> { reportActor.tell(new PurchaseWasMade(cart.getItems()), self()); })))
A snapshot of state data can be persisted by calling the saveStateSnapshot()
method:
- Scala
- Java
-
source
(event, data) -> stop() .applying(OrderDiscarded.INSTANCE) .andThen( exec( cart -> { reportActor.tell(ShoppingCardDiscarded.INSTANCE, self()); saveStateSnapshot(); })))
On recovery state data is initialized according to the latest available snapshot, then the remaining domain events are replayed, triggering the applyEvent
method.
Migration to EventSourcedBehavior
Persistent FSMs can be represented using Persistence Typed. The data stored by Persistence FSM can be read by an EventSourcedBehavior
using a snapshot adapter and an event adapter. The adapters are required as Persistent FSM doesn’t store snapshots and user data directly, it wraps them in internal types that include state transition information.
Before reading the migration guide it is advised to understand Persistence Typed.
Migration steps
- Modify or create new commands to include
replyTo
ActorRef
- Typically persisted events will remain the same
- Create an
EventSourcedBehavior
that mimics the oldPersistentFSM
- Replace any state timeouts with
Behaviors.withTimers
either hard coded or stored in the state - Add an
EventAdapter
to convert state transition events added byPersistentFSM
into private events or filter them - If snapshots are used add a
SnapshotAdapter
to convert PersistentFSM snapshots into theEventSourcedBehavior
sState
The following is the shopping cart example above converted to an EventSourcedBehavior
.
The new commands, note the replyTo field for getting the current cart.
- Scala
- Java
-
source
interface Command {} public static class AddItem implements Command { public final Item item; public AddItem(Item item) { this.item = item; } } public static class GetCurrentCart implements Command { public final ActorRef<ShoppingCart> replyTo; public GetCurrentCart(ActorRef<ShoppingCart> replyTo) { this.replyTo = replyTo; } } public enum Buy implements Command { INSTANCE } public enum Leave implements Command { INSTANCE } private enum Timeout implements Command { INSTANCE }
The states of the FSM are represented using the EventSourcedBehavior
’s state parameter along with the event and command handlers. Here are the states:
- Scala
- Java
-
source
abstract static class State { public final ShoppingCart cart; protected State(ShoppingCart cart) { this.cart = cart; } } public static class LookingAround extends State { public LookingAround(ShoppingCart cart) { super(cart); } } public static class Shopping extends State { public Shopping(ShoppingCart cart) { super(cart); } } public static class Inactive extends State { public Inactive(ShoppingCart cart) { super(cart); } } public static class Paid extends State { public Paid(ShoppingCart cart) { super(cart); } }
The command handler has a separate section for each of the PersistentFSM’s states:
- Scala
- Java
-
source
CommandHandlerBuilder<Command, DomainEvent, State> builder = newCommandHandlerBuilder(); builder.forStateType(LookingAround.class).onCommand(AddItem.class, this::addItem); builder .forStateType(Shopping.class) .onCommand(AddItem.class, this::addItem) .onCommand(Buy.class, this::buy) .onCommand(Leave.class, this::discardShoppingCart) .onCommand(Timeout.class, this::timeoutShopping); builder .forStateType(Inactive.class) .onCommand(AddItem.class, this::addItem) .onCommand(Timeout.class, () -> Effect().persist(OrderDiscarded.INSTANCE).thenStop()); builder.forStateType(Paid.class).onCommand(Leave.class, () -> Effect().stop()); builder.forAnyState().onCommand(GetCurrentCart.class, this::getCurrentCart); return builder.build(); }
Note that there is no explicit support for state timeout as with PersistentFSM but the same behavior can be achieved using Behaviors.withTimers
. If the timer is the same for all events then it can be hard coded, otherwise the old PersistentFSM timeout can be taken from the StateChangeEvent
in the event adapter and is also available when constructing a SnapshotAdapter
. This can be added to an internal event and then stored in the State
. Care must also be taken to restart timers on recovery in the signal handler:
- Scala
- Java
-
source
@Override public SignalHandler<State> signalHandler() { return newSignalHandlerBuilder() .onSignal( RecoveryCompleted.class, (state, signal) -> { if (state instanceof Shopping || state instanceof Inactive) { timers.startSingleTimer(TIMEOUT_KEY, Timeout.INSTANCE, Duration.ofSeconds(1)); } }) .build(); }
Then the event handler:
- Scala
- Java
-
source
@Override public EventHandler<State, DomainEvent> eventHandler() { EventHandlerBuilder<State, DomainEvent> eventHandlerBuilder = newEventHandlerBuilder(); eventHandlerBuilder .forStateType(LookingAround.class) .onEvent(ItemAdded.class, item -> new Shopping(new ShoppingCart(item.getItem()))); eventHandlerBuilder .forStateType(Shopping.class) .onEvent( ItemAdded.class, (state, item) -> new Shopping(state.cart.addItem(item.getItem()))) .onEvent(OrderExecuted.class, (state, item) -> new Paid(state.cart)) .onEvent(OrderDiscarded.class, (state, item) -> state) // will be stopped .onEvent(CustomerInactive.class, (state, event) -> new Inactive(state.cart)); eventHandlerBuilder .forStateType(Inactive.class) .onEvent( ItemAdded.class, (state, item) -> new Shopping(state.cart.addItem(item.getItem()))) .onEvent(OrderDiscarded.class, (state, item) -> state); // will be stopped return eventHandlerBuilder.build(); }
The last step is the adapters that will allow the new EventSourcedBehavior
to read the old data:
- Scala
- Java
-
source
public static class PersistentFSMEventAdapter extends EventAdapter<DomainEvent, Object> { @Override public Object toJournal(DomainEvent domainEvent) { // leave events as is, can't roll back to PersistentFSM return domainEvent; } @Override public String manifest(DomainEvent event) { return ""; } @Override public EventSeq<DomainEvent> fromJournal(Object event, String manifest) { if (event instanceof akka.persistence.fsm.PersistentFSM.StateChangeEvent) { // In this example the state transitions can be inferred from the events // Alternatively the StateChangeEvent can be converted to a private event if either the // StateChangeEvent.stateIdentifier // or StateChangeEvent.timeout is required // Many use cases have the same timeout so it can be hard coded, otherwise it cane be stored // in the state return EventSeq.empty(); } else { // If using a new domain event model the conversion would happen here return EventSeq.single((DomainEvent) event); } }
The snapshot adapter needs to adapt an internal type of PersistentFSM so a helper function is provided to build the SnapshotAdapter
:
- Scala
- Java
-
source
@Override public SnapshotAdapter<State> snapshotAdapter() { return PersistentFSMMigration.snapshotAdapter( (stateIdentifier, snapshot, timeout) -> { ShoppingCart cart = (ShoppingCart) snapshot; switch (stateIdentifier) { case "Looking Around": return new LookingAround(cart); case "Shopping": return new Shopping(cart); case "Inactive": return new Inactive(cart); case "Paid": return new Paid(cart); default: throw new IllegalStateException("Unexpected state identifier " + stateIdentifier); } }); }
That concludes all the steps to allow an EventSourcedBehavior
to read a PersistentFSM
’s data. Once the new code has been running you can not roll back as the PersistentFSM will not be able to read data written by Persistence Typed.
There is one case where a full shutdown and startup is required.