Persistent FSM
Dependency
Persistent FSMs are part of Akka persistence, you must add the following dependency in your project:
Persistent FSM
Persistent FSM is no longer actively developed and will be replaced by Akka Typed Persistence. It is not advised to build new applications with Persistent FSM.
PersistentFSM
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 PersistentFSM
trait , consider an actor which represents a Web store customer. The contract of our “WebStoreCustomerFSMActor” is that it accepts the following commands:
- Scala
-
source
sealed trait Command case class AddItem(item: Item) extends Command case object Buy extends Command case object Leave extends Command case object GetCurrentCart extends Command
- Java
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
-
source
sealed trait UserState extends FSMState case object LookingAround extends UserState { override def identifier: String = "Looking Around" } case object Shopping extends UserState { override def identifier: String = "Shopping" } case object Inactive extends UserState { override def identifier: String = "Inactive" } case object Paid extends UserState { override def identifier: String = "Paid" }
- Java
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
PersistentFSM
states must inherit from trait PersistentFSM.FSMState
and implement the def identifier: String
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
-
source
sealed trait DomainEvent case class ItemAdded(item: Item) extends DomainEvent case object OrderExecuted extends DomainEvent case object OrderDiscarded extends DomainEvent
- Java
Customer state data represents the items in a customer’s shopping cart:
- Scala
-
source
case class Item(id: String, name: String, price: Float) sealed trait ShoppingCart { def addItem(item: Item): ShoppingCart def empty(): ShoppingCart } case object EmptyShoppingCart extends ShoppingCart { def addItem(item: Item) = NonEmptyShoppingCart(item :: Nil) def empty() = this } case class NonEmptyShoppingCart(items: Seq[Item]) extends ShoppingCart { def addItem(item: Item) = NonEmptyShoppingCart(items :+ item) def empty() = EmptyShoppingCart }
- Java
Here is how everything is wired together:
- Scala
-
source
startWith(LookingAround, EmptyShoppingCart) when(LookingAround) { case Event(AddItem(item), _) => goto(Shopping).applying(ItemAdded(item)).forMax(1 seconds) case Event(GetCurrentCart, data) => stay.replying(data) } when(Shopping) { case Event(AddItem(item), _) => stay.applying(ItemAdded(item)).forMax(1 seconds) case Event(Buy, _) => goto(Paid).applying(OrderExecuted).andThen { case NonEmptyShoppingCart(items) => reportActor ! PurchaseWasMade(items) saveStateSnapshot() case EmptyShoppingCart => saveStateSnapshot() } case Event(Leave, _) => stop.applying(OrderDiscarded).andThen { case _ => reportActor ! ShoppingCardDiscarded saveStateSnapshot() } case Event(GetCurrentCart, data) => stay.replying(data) case Event(StateTimeout, _) => goto(Inactive).forMax(2 seconds) } when(Inactive) { case Event(AddItem(item), _) => goto(Shopping).applying(ItemAdded(item)).forMax(1 seconds) case Event(StateTimeout, _) => stop.applying(OrderDiscarded).andThen { case _ => reportActor ! ShoppingCardDiscarded } } when(Paid) { case Event(Leave, _) => stop() case Event(GetCurrentCart, data) => stay.replying(data) }
- Java
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
-
source
override def applyEvent(event: DomainEvent, cartBeforeEvent: ShoppingCart): ShoppingCart = { event match { case ItemAdded(item) => cartBeforeEvent.addItem(item) case OrderExecuted => cartBeforeEvent case OrderDiscarded => cartBeforeEvent.empty() } }
- Java
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
-
source
goto(Paid).applying(OrderExecuted).andThen { case NonEmptyShoppingCart(items) => reportActor ! PurchaseWasMade(items) }
- Java
A snapshot of state data can be persisted by calling the saveStateSnapshot()
method:
- Scala
-
source
stop.applying(OrderDiscarded).andThen { case _ => reportActor ! ShoppingCardDiscarded saveStateSnapshot() }
- Java
On recovery state data is initialized according to the latest available snapshot, then the remaining domain events are replayed, triggering the applyEvent
method.