Akka; Passing around too many parameters with EventSourcedBehavior - scala

We are building a event sourced system based on Akka-Typed. We quickly fall in a situation where our states requires many parameters passed as implicits parameters.
There is a solution on the style guide to use an enclosing class; https://doc.akka.io/docs/akka/current/typed/style-guide.html#passing-around-too-many-parameters.
However this is for "simple" behaviors, not for EventSourcedBehaviors. This technique of using a enclosing class that produce behaviors does not work for event sourced one because an event sourced behavior is made of one command handler and one event handler.
In our case we have a State trait that define one method to received commands and another to handle events. If we apply the enclosing class technique we have to create anonymous classes for all states, but those cannot be serialized.
object SampleEventSourced {
trait State extends CborSerializable {
def execute(cmd: Command): ReplyEffect
def apply(evt: Event): State
}
def apply(
persistenceId: PersistenceId,
config: Config,
): Behavior[Command] = {
EventSourcedBehavior
.withEnforcedReplies[Command, Event, State](
persistenceId,
new SampleEventSourced(config).empty(),
(state, cmd) => state.execute(cmd),
(state, evt) => state.apply(evt)
)// ...
}
}
class SampleEventSourced private(config: Config) {
import SampleEventSourced._
private def empty(): State = new State {
override def execute(cmd: Command): ReplyEffect = cmd match {
// ..
}
override def apply(evt: Event): State = evt match {
// ..
}
}
java.lang.IllegalArgumentException: Empty State [org.acme.SampleEventSourced$$anon$1#36d7d2fe] isn't serializable.
One solution would be to duplicate the creation of the event sourced behavior in each "state" method. But that will produce a lot of duplication.
object SampleEventSourced {
def apply(
persistenceId: PersistenceId,
config: Config,
): Behavior[Command] = new SampleEventSourced(config).empty()
}
class SampleEventSourced private(config: Config) {
import SampleEventSourced._
private def empty(): Behavior[Command] = EventSourcedBehavior
.withEnforcedReplies[Command, Event, State](
persistenceId,
new State(),
(state, cmd) => state.execute(cmd),
(state, evt) => state.apply(evt)
)// ...
}
Another would be to create concrete subclasses of State but we will have to pass the parameters across all of those states.
object SampleEventSourced {
class EmptyState extends State(config:Config, otherUselessParameter:Any) {
// ...
override def apply(evt: Event): evt match {
case _ => new OtherState(config, otherUselessParameter)
}
}
class OtherState extends State(config:Config, veryImportantParameter:Any) {
// ..
}
}
Putting those state classes inside the enclosing class won't work because those non-static inner classes cannot be de-serialized.
So, what's your solution for this case, how do you deal with EventSourcedBehavior with states that require many parameters ?

The problem is that that jackson-cbor, on top of being reflection based, isn't that effective at serializing things done in an idiomatic Scala way (the only real point in its favor is that it's better than Java serialization).
So the immediately apparent solution is to:
model the state as an Algebraic Data Type (generally a sealed trait extended by case classes and maybe a case object for the empty/initial state case).
don't serialize them via Jackson, but use a native-to-Scala serializer (e.g. play-json, circe, etc.) and an Akka serializer leveraging that serializer; it's likely easier to define a marker trait (e.g. CirceSerializable) so that in the configuration you only have to worry about one binding. Events & state will want to be marked with that trait: commands and their replies (at least the ones that could be sent over the network might also as well).
One subtlety to be aware of when defining your serializer is that, the native-to-Scala serializers will generally use some form of typeclass derivation at compile time, but this will be complicated if there's a need to serialize ActorRef, as a serializer for ActorRef is best done with the aid of the ActorSystem (EntityRef can now be inspected for serialization, and conceptually makes more sense for persistence, given the lifecycle, but that's going to be fairly custom): you'll therefore probably want to delay derivation of the ActorRef serializer/deserializer until the ActorSystem starts up and also delay derivation of the events/state/commands/replies containing ActorRefs until after then.
I'd probably tend to make the handler for each event a method in the sealed trait without letting the state have any knowledge of how events are reified. The benefit of this is that you can unit test the state transitions without needing events or commands.
case class ItemAdded(name: String) extends Event
sealed trait State {
def items: Set[String]
def addItem(name: String): State.NonEmpty
}
object State {
case object Empty extends State {
def items: Set[String] = Set.empty
def addItem(name: String): NonEmpty = NonEmpty(Set(name))
}
case class NonEmpty(items: Set[String]) extends State {
def addItem(name: String): NonEmpty = copy(items = items + name)
}
}
Then your event handler is pretty thin
(state, evt) => {
evt match {
case ItemAdded(name) => state.addItem(name)
}
}
Depending on how much validation your command handlers take on, those can get complex. The operative principle is that commands are interpreted into zero-or-more events, and events are interpreted into operations (methods on state which result in a new state) on the state. The state should thus have sufficient query methods (e.g. items) to allow the command-handler to consume a state.

Related

Is there any way to map a Behavior from one type to another

I have a scenario where I need to provide a Behavior of a specific type. This Behavior also needs to handle events that are published on the Event Stream. So say the specific type is:
case class DoSomething(i: Int)
and I then need to implement a function to return a Behavior to handle this type of message:
def foo(): Behavior[DoSomething]
I then also need to handle the following message on the event stream:
case class PublishedEvent(str: String)
The only solution I came up with was to spawn another actor from within my DoSomething behavior and then forward messages to it:
sealed trait Command
case class Command1(str: String) extends Command
case class Command2(str: String) extends Command
def foo(): Behavior[DoSomething] = Behaviors.setup { context =>
val actor = context.spawnAnonymous[Command](Behaviors.setup { context =>
context.system.eventStream ! EventStream.Subscribe(context.messageAdapter {
case PublishedEvent(str) => Command2(str)
})
Behaviors.receiveMessage {
case Command1(str) =>
println("Received Command1: " + str)
Behaviors.same
case Command2(str) =>
println("Received Command1: " + str)
Behaviors.same
}
})
Behaviors.receiveMessage {
case DoSomething(i) =>
actor ! Command1(i.toString)
Behaviors.same
}
}
My question is is there any means of avoiding spawning a new actor and doing it all from within the same actor? i.e. Is there a way I can map a Behavior[Command] to a Behavior[DoSomething]?
I also have this problem regularly and the best solution I found is to use the narrow[...] method on a common "super Behavior" to narrow down on a message type a client is supposed to send to the respective actor. It is possible to combine the handling of both message types in one Behavior by defining a common interface (in scala of course a trait):
sealed trait CommandOrDoSomething // #TODO find better name
final case class DoSomething(i:Int) extends CommandOrDoSomething
sealed trait Command extends CommandOrDoSomething
case class Command1(str: String) extends Command
case class Command2(str: String) extends Command
def getBehavior(): Behavior[CommandOrDoSomething] = Behaviors.setup { context =>
Behaviors.receiveMessage {
// handle all kinds of messages here
}
}
Now, if you want to pass a Behavior[DoSomething] to a client, you can simply obtain it like this:
def foo(): Behavior[DoSomething] = getBehavior().narrow[DoSomething]
You can keep the Command trait private to your current context, but I think you will have to expose at least the common super trait to the outside world. With union types as they will be available in Scala 3 this can be avoided and you won't need the artificial super trait.
The docs (as well as the signature) indicate that transformMessages on Behavior would work, provided that the externally sent messages map 1:1 to internal messages:
def transformMessages[Outer: ClassTag](matcher: PartialFunction[Outer, T]): Behavior[Outer]
i.e. an actor materialized with Behavior[T].transformMessages[Outer] { ??? } will yield an ActorRef[Outer]
sealed trait External
case class DoSomething(i: Int) extends External
private sealed trait Internal
private case class Command1(str: String) extends Internal
private case class Command2(str: String) extends Internal
private def internalBehavior: Behavior[Internal] = Behaviors.setup { context =>
// do stuff with context
Behaviors.receiveMessage {
case Command1(s) => ???
case Command2(s) => ???
}
}
import akka.actor.typed.Behavior.BehaviorDecorators
def externalBehavior: Behavior[External] =
internalBehavior.transformMessages {
case DoSomething(i) => Command1(i.toString)
}
In this case, the internal commands are invisible outside of their scope. The main potential drawback I see (beyond the slight ickiness of bringing a PartialFunction into typed) is that within an actor with Behavior[Internal], you can't get the ActorRef for actor's external "personality", unless you have something crazy like
case class DoSomething(i: Int, recipient: ActorRef[External]) extends External
private case class Command1(str: String, externalPersonality: ActorRef[External]) extends Internal
It's worth noting that in the case where the internal messages are under your control, the 1:1 restriction can be worked around.

Scala: How to extend an Akka actor?

I wrote an Akka base-actor that can handle some common messages. I want to reuse this basic behavior in a sub-actor, by extending the base-actor (not by composition of the base-actor).
I have seen several approaches in previous questions. They are all valid but also may be improved:
How extend behaviour of super actor in akka
and
How do I best share behavior among Akka actors?
To make the implementation cleaner, I am trying to achieve the following:
When defining the sub-actor, I try to extend only the base-actor (not both Actor and sub-actor). However, I was not able to force the compiler to do this.
I also try to not rename the receive partial function, because it is a kind of convention.
Here is a sample of my implementation:
//This is the base-actor that implements the common behavior
trait BetterActor extends Actor {
abstract override def receive = {
super.receive orElse { case _ => println("Missing pattern!") }
}
}
//This is the actor that implements the additional behavior.
//I actually wanted to extend BetterActor. It was not possible.
class MyActor extends Actor {
def receive = {
case i: Int =>
println(s"Yay!!! Got $i")
}
}
Here are two alternative ways how I can create an instance of the sub-actor, which combines both the common and the additional behaviors:
//1.
val myBetterActor = system.actorOf(Props(new MyActor with BetterActor), "myBetterActor")
//2.
class MyBetterActor extends MyActor with BetterActor
val myBetterActor = system.actorOf(Props[MyBetterActor], "myBetterActor")
Finally, I may invoke the sub-actor by:
myBetterActor ! 2
myBetterActor ! "a"
Problems with my implementation:
When I create an instance of the sub-actor, only then I can mix in the base-actor, either directly (1) or by defining a new class that mixes in the base-actor.
Like I said before, I would prefer to mix in the base-actor when I define the sub-actor. Not when I try to create an instance of the sub-actor.
P.S. It's fascinating that the designers of this framework did not see it necessary to make this common requirement easy to accomplish.
i suppose as long as you're not trying to override behavior with BetterActor, you could try something like this:
trait BetterActor extends Actor {
override def unhandled(message: Any): Unit = message match {
case e: CommonMessage => println("COMMON!")
case e => super.unhandled(e)
}
}
class MyActor extends BetterActor {
override def receive = {
case i: Int => println(s"Yay!!! Got $i")
}
}

Strategy pattern in Akka

This is an continuation of my previous question How do I get around type erasure on Akka receive method
I have 10 type of events which extends from Event that I need to handle.
I want to implement business logic for each event in separate trait, because because mixing all 10 event handler functions will produce several hundreds(if not thousands) lines of code.
I don't want to create different Actor types for each event. For example:
class Event1Actor extend Actor{
def receive ={
case Event1(e) => //event1 Business Logic
}
}
class Event2Actor extend Actor{
def receive ={
case Event2(e) => //event2 Business Logic
}
}
and the same Event3Actor, Event4Actor,etc....
Such code seems ugly to me, because I need to implement business Logic inside each Actor.
Implementing 10 different traits and 10 different Actor classes seems also as bad design.
I'm seeking for some kind generic solution based on design pattern, for example strategy pattern.
case class EventOperation[T <: Event](eventType: T)
class OperationActor extends Actor {
def receive = {
case EventOperation(eventType) => eventType.execute
}
}
trait Event {
def execute //implement execute in specific event class
}
class Event1 extends Event {/*execute implemented with business logic*/}
class Event2 extends Event {/*execute implemented with business logic*/}
hope this is what you are looking for and helps, I have used this patternt to remove the redundant amount of actors wrapping all actions under a single actor executing different type of events.
You could try something like this, which involves auto-composing receive functionality via a base trait. First the code:
case class Event1(s:String)
case class Event2(i:Int)
case class Event3(f:Float)
trait EventHandlingActor extends Actor{
var handlers:List[Receive] = List.empty
override def preStart = {
val composedReceive = handlers.foldLeft(receive)((r,h) => r.orElse(h))
context.become(composedReceive)
}
def addHandler(r:Receive) {
handlers = r :: handlers
}
def receive = PartialFunction.empty[Any,Unit]
}
trait Event1Handling{ me:EventHandlingActor =>
addHandler{
case Event1(s) => println(s"${self.path.name} handling event1: $s")
}
}
trait Event2Handling{ me:EventHandlingActor =>
addHandler{
case Event2(i) => println(s"${self.path.name} handling event2: $i")
}
}
trait Event3Handling{ me:EventHandlingActor =>
addHandler{
case Event3(f) => println(s"${self.path.name} handling event3: $f")
}
}
So you can see in the EventHandlingActor trait we set up a List of type Receive that can be added to by each specific handling trait that we stack into a concrete actor. Then you can see the definitions of the handling functionality for each event defined in a separate trait that is calling addHandler to add another piece of handling functionality. In preStart for any kind of EventHandlingActor impl the receive functions will be composed together with receive being the starting point (empty by default) before hot-swapping out the receive impl with context.become.
Now for a couple of impl actors as an example:
class MyEventHandlingActor extends EventHandlingActor
with Event1Handling with Event2Handling with Event3Handling
case class SomeOtherMessage(s:String)
class MyOtherEventHandlingActor extends EventHandlingActor with Event1Handling{
override def receive = {
case SomeOtherMessage(s) => println(s"otherHandler handling some other message: $s")
}
}
The first one only handles events, so all it needs to do is define which ones it handles my mixing in the appropriate traits. The second one handles one type of event but also some other message that is not an event. This class overrides the default empty receive and provides functionality to handle the non-event message.
If we tested the code like so:
val system = ActorSystem("test")
val handler = system.actorOf(Props[MyEventHandlingActor], "handler")
handler ! Event1("foo")
handler ! Event2(123)
handler ! Event3(123.456f)
val otherHandler = system.actorOf(Props[MyOtherEventHandlingActor], "otherHandler")
otherHandler ! Event1("bar")
otherHandler ! SomeOtherMessage("baz")
Then we would see output similar to this (with the order changing due to asynch handling of messages):
otherHandler handling event1: bar
handler handling event1: foo
handler handling event2: 123
handler handling event3: 123.456

Is it possible to compose FSMs in Akka?

For regular actors, they can be composed. But, I can't seem to find anything about doing it with FSMs. And there isn't a receive block to use += to add things to. Does anyone have any experience trying to generalize an FSM?
I can't provide a code example, because I don't have any code yet because I don't know if I can compose FSMs.
You can compose state behaviour using partial functions in the same way that you compose Actor partial functions. The when() function requires a partial function of type scala.PartialFunction[FSM.this.Event, FSM.this.State]). In the example below, I extend the state Jibber with a partial function (e.g. some common behaviour) declared in the trait. You can use exactly the same technique to extend the onTermination behaviour from a trait using a PF declared as scala.PartialFunction[StopEvent, Unit].
I have lifted significant common behaviour out of some complex FSMs using this technique.
package monster
import akka.actor._
import monster.FlyingSpaghetti._
// State and data objects
object FlyingSpaghetti {
trait State
object Jibber extends State
object Jabber extends State
object Ping
object Done
}
// Trait with common behaviour behaviour
trait FlyingSpaghetti extends Actor with FSM[State,String]{
val layer: StateFunction = {
case Event(Done,s) ⇒
println("Done behaviour layered")
stop()
}
}
class Monster() extends FlyingSpaghetti {
startWith(Jibber,"jabber")
self ! Ping
println("Starting")
// First, do the common behaviour PF then do specialised behaviour
when(Jibber) (layer orElse {
case Event(Ping,"jabber") ⇒
println("jabber")
goto(Jabber) using "jibber"
case Event(Done,s) ⇒
println("Done jabbering")
stop()
})
when(Jabber) {
case Event(Ping,"jibber") ⇒
println("jibber")
goto(Jibber) using "jabber"
case Event(Done,s) ⇒
println("Done jibbering")
stop()
}
}
object Run extends App {
val system = ActorSystem("mySystem")
val rattle = system.actorOf(Props[Monster])
rattle ! Ping
rattle ! Ping
rattle ! Done
Thread.sleep(100)
system.shutdown()
}

How do I best share behavior among Akka actors?

I have two Akka actors that respond to some messages in the same way, but others in a different way. They both respond to the same set of messages. Wondering how to design my two actors with their receive methods, via inheritance, composure, etc? I tried chaining together partial functions from other traits with "orElse", which unfortunately exposes the class to its trait's functionality, plus I wasn't sure how the trait's receive could easily access the actor context. A drop-in, modularized solution would be ideal, but I'm wondering if this is a solved problem somewhere?
There's really a bunch of ways that you can go about this. I'll list two from the OO way (similar to what #Randal Schulz is suggesting) and 1 more functional way. For the first possible solution, you could do something simple like this:
case class MessageA(s:String)
case class MessageB(i:Int)
case class MessageC(d:Double)
trait MyActor extends Actor{
def receive = {
case a:MessageA =>
handleMessageA(a)
case b:MessageB =>
handleMessageB(b)
case c:MessageC =>
handleMessageC(c)
}
def handleMessageA(a:MessageA)
def handleMessageB(b:MessageB) = {
//do handling here
}
def handleMessageC(c:MessageC)
}
class MyActor1 extends MyActor{
def handleMessageA(a:MessageA) = {}
def handleMessageC(c:MessageC) = {}
}
class MyActor2 extends MyActor{
def handleMessageA(a:MessageA) = {}
def handleMessageC(c:MessageC) = {}
}
With this approach, you define basically an abstract actor impl where the receive function is defined for all messages that are handled. The messages are delegated to defs where the real business logic would be. Two are abstract, letting the concrete classes define the handling and one is fully implemented for a case where the logic does not need to differ.
Now a variant on this approach using the Strategy Pattern:
trait MessageHandlingStrategy{
def handleMessageA(a:MessageA)
def handleMessageB(b:MessageB) = {
//do handling here
}
def handleMessageC(c:MessageC)
}
class Strategy1 extends MessageHandlingStrategy{
def handleMessageA(a:MessageA) = {}
def handleMessageC(c:MessageC) = {}
}
class Strategy2 extends MessageHandlingStrategy{
def handleMessageA(a:MessageA) = {}
def handleMessageC(c:MessageC) = {}
}
class MyActor(strategy:MessageHandlingStrategy) extends Actor{
def receive = {
case a:MessageA =>
strategy.handleMessageA(a)
case b:MessageB =>
strategy.handleMessageB(b)
case c:MessageC =>
strategy.handleMessageC(c)
}
}
Here the approach is to pass in a strategy class during construction that defines the handling for a and c, with b again being handled the same regardless. The two approaches are pretty similar and accomplish the same goal. The last approach uses partial function chaining and could look like this:
trait MessageAHandling{
self: Actor =>
def handleA1:Receive = {
case a:MessageA => //handle way 1
}
def handleA2:Receive = {
case a:MessageA => //handle way 2
}
}
trait MessageBHandling{
self: Actor =>
def handleB:Receive = {
case b:MessageB => //handle b
}
}
trait MessageCHandling{
self: Actor =>
def handleC1:Receive = {
case c:MessageC => //handle way 1
}
def handleC2:Receive = {
case c:MessageC => //handle way 2
}
}
class MyActor1 extends Actor with MessageAHandling with MessageBHandling with MessageCHandling{
def receive = handleA1 orElse handleB orElse handleC1
}
class MyActor2 extends Actor with MessageAHandling with MessageBHandling with MessageCHandling{
def receive = handleA2 orElse handleB orElse handleC2
}
Here, some traits are setup that define message handling behaviors for the 3 message types. The concrete actors mix in those traits and then pick which behaviors they want when building out their receive function by using partial function chaining.
There are probably many other ways to do what you seek, but I just figured I'd throw a few options out there for you. Hope it helps.
So far I have not had reason to regret pushing as much of my services' actual functionality (the so-called "business logic") into a lower layer, "conventional" and synchronous (and sometimes blocking) library that can be unit-tested w/o the complication of actors. The only thing I place in Actor classes is the shared, long-term mutable state on which that conventional library code acts. That, of course, and the message-decoding and dispatching logic of the Akka Actor receive function.
If you do this, sharing logic in the way you seek is trivial.