concept event in category reactive

This is an excerpt from Manning's book Reactive Application Development.
You should look to capture the intent of your users because, from a business perspective, customer behavior is paramount. Rather than model your domain as a current state model, you should look at it in the form of user behavior as a sequence of recorded transactions or events. The CRUD model of persisting current state, which you’re so familiar with, does capture behavior, but the behavior that it captures is system behavior in the form of creating, reading, updating, and deleting, which doesn’t tell you much about your users and compromises the value of your data. Most systems today rely on this model primarily because of the general acceptance of the relational database management system (RDBMS) as the center of web architecture. Fortunately, this way to view persistence isn’t the only way.
Event Sourcing, or persisting a sequence of events (behaviors)—not to be confused with message-driven, which means reacting to a message—provides a means by which you can capture the real intent of your users. In an Event Sourcing system, all data operations are viewed as a sequence of events that are recorded to an append-only store. In this section, we provide two examples that best showcase the capabilities of Event Sourcing: the canonical example of a bank account register and the CRUD shopping cart redone as a reactive shopping cart.
What’s the difference between messages, commands, and events?
The distinction between messages, commands, and events is important, and one that we need to make before going too far into our architecture discussion. Messages can come in two flavors: abstract and concrete. Following are two simple examples:
You can think of an abstract message as being a blank sheet of paper—a structure to capture a conversation between two parties. The paper in and of itself isn’t a conversation until something is written on it. To start the discussion, suppose that we write on the paper a request to borrow a book from you. The abstract message becomes (has been implemented as) a command—a request to do something. In response, you write back that you’ve mailed the book. At this point, the abstract message has become (has been implemented as) an event—a notification that something has occurred. In this example, the command and event are forms of messages. In computing lingo, they implement the message interface. A concrete message is like an envelope—a container that has a payload. That payload can be anything. In the preceding example, the payload is either a command or an event. The distinction is that a message is concrete, like a command and an event.
The order commands functionally mutate the order, but technically, no object mutation occurs, because immutable objects are first-class citizens of a reactive application. The commands should be as granular as possible, because the events derived from those commands are the building blocks of the event-driven nature of your applications. The ChangeOrder command, for example, would result in an OrderChanged event. This event provides no business insight into what happened to the order, so any other system that consumes order events must consume every OrderChanged event and interrogate it to determine whether the change of the order is of interest.
A better, more-expressive option is to break the events down as OrderShippingAddressChanged, OrderTotalChanged, and so on. The commands appear as follows:
Listing 8.3. Persistent order actor
package com.example import java.util.UUID import akka.persistence.PersistentActor import org.scalactic._ import Accumulation._ import OrderType._ object OrderActor { #1 object OrderType { type OrderType = String val Phone = new OrderType("phone") val Web = new OrderType("web") val Promo = new OrderType("promo") val OrderTypes: List[OrderType] = List(Phone, Web, Promo) } case object CommandAccepted #2 case class ExpectedVersionMismatch(expected: Long, actual: Long) #3 case class CreateOrder( #4 id: UUID, customerId: String, date: Long, orderType: OrderType, orderLines: List[OrderLine]) // The add order line command. case class AddOrderLine( id: UUID, orderLine: OrderLine, expectedVersion: Long) case class OrderCreated( #5 id: UUID, customerId: String, date: Long, orderType: OrderType, orderLines: List[OrderLine], version: Long) case class OrderLineAdded( id: UUID, orderLine: OrderLine, version: Long) } class OrderActor extends PersistentActor { #6 import OrderActor._ override def persistenceId: String = self.path.parent.name + "-" + self.path.name private case class OrderState( #7 id: UUID = null, customerId: String = null, date: Long = -1L, orderType: OrderType = null, orderLines: List[OrderLine] = Nil, version: Long = -1L) private var state = OrderState() def create: Receive = { #8 case CreateOrder(id, customerId, date, orderType, orderLines) => val validations = withGood( validateCustomerId(customerId), validateDate(date), validateOrderType(orderType), validateOrderLines(orderLines) ) { (cid, d, ot, ol) => OrderCreated(UUID.randomUUID(), cid, d, ot, ol, 0L) } sender ! validations.fold( event => { sender ! CommandAccepted persist(event) { e => state = OrderState(event.id, event.customerId, event.date, event.orderType, event.orderLines, 0L) context.system.eventStream.publish(e) #9 context.become(created) } }, bad => sender ! bad ) } def created: Receive = { #10 case AddOrderLine(id, orderLine, expectedVersion) => if (expectedVersion != state.version) sender ! ExpectedVersionMismatch(expectedVersion, state.version) else { val validations = withGood( validateOrderLines(state.orderLines :+ orderLine) ) { (ol) => OrderLineAdded(id, orderLine, state.version + 1) } .fold( event => { persist(OrderLineAdded(id, orderLine, state.version + 1)) { e => state = state.copy(orderLines = state.orderLines :+ e.orderLine, version = state.version + 1) context.system.eventStream.publish(e) } }, bad => sender ! bad ) } } override def receiveCommand = create #11 override def receiveRecover: Receive = { #12 case CreateOrder(id, customerId, date, orderType, orderLines) => state = OrderState(id, customerId, date, orderType, orderLines, 0L) context.become(created) case AddOrderLine(id, orderLine, expectedVersion) => state = state.copy(orderLines = state.orderLines :+ orderLine, version = state.version + 1) } def validateCustomerId(customerId: String): String Or Every[ValidationFailure] = if (Option(customerId).exists(_.trim.nonEmpty)) Good(customerId) else Bad(One(InvalidCustomerId(customerId))) private def validateDate(date: Long): Long Or Every[ValidationFailure] = if (date > 0) Good(date) else Bad(One(InvalidDate(date.toString))) private def validateOrderType(orderType: OrderType): OrderType Or Every[ValidationFailure] = if (OrderTypes.contains(orderType)) Good(orderType) else Bad(One(InvalidOrderType(orderType))) private def validateOrderLines(orderLines: List[OrderLine]): List[OrderLine] Or Every[ValidationFailure] = if (!orderLines.isEmpty) Good(orderLines) else Bad(One(InvalidOrderLines(orderLines.mkString))) } #1 Companion object for the order actor for neat encapsulation #2 A simple acknowledgment object signifying that command is accepted #3 Any command must specify the last known version of the order. #4 The create and add order line commands #5 The order created and order line added events #6 This actor has a single instance in the cluster. #7 The internal state of the actor, changed each time a command is processed #8 The receive to use when the order hasn’t been created, which would result in the initial state of the order #9 With successful validation, you can store the event and perform any side-affecting logic, such as emitting the event to interested parties via the event stream, transitioning to the new command handler, and updating the state. #10 The created handler handles commands other than creation. This line illustrates the add order. #11 Sets the initial command handler to the create partial function, the first state of the aggregate #12 receiveRecover builds up state from the events that took place in the past. There’s no need to validate. Recovery is executed when the actor is instantiated by the cluster. !@%STYLE%@! {"css":"{\"css\": \"font-weight: bold;\"}","target":"[[{\"line\":8,\"ch\":72},{\"line\":8,\"ch\":74}],[{\"line\":88,\"ch\":72},{\"line\":88,\"ch\":74}],[{\"line\":109,\"ch\":71},{\"line\":109,\"ch\":73}],[{\"line\":111,\"ch\":71},{\"line\":111,\"ch\":73}],[{\"line\":148,\"ch\":0},{\"line\":148,\"ch\":2}],[{\"line\":157,\"ch\":0},{\"line\":157,\"ch\":2}],[{\"line\":158,\"ch\":0},{\"line\":158,\"ch\":2}],[{\"line\":159,\"ch\":0},{\"line\":159,\"ch\":2}],[{\"line\":17,\"ch\":72},{\"line\":17,\"ch\":74}],[{\"line\":149,\"ch\":0},{\"line\":149,\"ch\":2}],[{\"line\":19,\"ch\":72},{\"line\":19,\"ch\":74}],[{\"line\":150,\"ch\":0},{\"line\":150,\"ch\":2}],[{\"line\":21,\"ch\":72},{\"line\":21,\"ch\":74}],[{\"line\":151,\"ch\":0},{\"line\":151,\"ch\":2}],[{\"line\":34,\"ch\":72},{\"line\":34,\"ch\":74}],[{\"line\":152,\"ch\":0},{\"line\":152,\"ch\":2}],[{\"line\":48,\"ch\":72},{\"line\":48,\"ch\":74}],[{\"line\":153,\"ch\":0},{\"line\":153,\"ch\":2}],[{\"line\":55,\"ch\":72},{\"line\":55,\"ch\":74}],[{\"line\":154,\"ch\":0},{\"line\":154,\"ch\":2}],[{\"line\":64,\"ch\":72},{\"line\":64,\"ch\":74}],[{\"line\":155,\"ch\":0},{\"line\":155,\"ch\":2}],[{\"line\":79,\"ch\":72},{\"line\":79,\"ch\":74}],[{\"line\":156,\"ch\":0},{\"line\":156,\"ch\":2}],[{\"line\":88,\"ch\":72},{\"line\":88,\"ch\":75}],[{\"line\":157,\"ch\":0},{\"line\":157,\"ch\":3}],[{\"line\":109,\"ch\":71},{\"line\":109,\"ch\":74}],[{\"line\":158,\"ch\":0},{\"line\":158,\"ch\":3}],[{\"line\":111,\"ch\":71},{\"line\":111,\"ch\":74}],[{\"line\":159,\"ch\":0},{\"line\":159,\"ch\":3}]]"} !@%STYLE%@!
An event represents something meaningful in the domain that has occurred and is usually in the past tense, such as OrderCreated or OrderLineAdded. Events are immutable in that they represent something that happened at a particular point in time and are persistent, meaning that they’re stored in an event log such as a distributable database like Apache Cassandra. At any point in time, it’s possible to witness the state of the domain by the ordered accumulation of the events through that point in time. These events even appear with deletes, which are also additive, like any other event. A delete doesn’t occur as it would in CRUD; the event states that the domain object no longer exists at that point in time. Events are a cornerstone of being message-driven and are a great way to provide meaningful communication among microservices. Because it’s possible to have a large number of events on some domains, increasing the amount of time it takes to replay the events to derive current state, there’s the concept of the snapshot. We talk more later about replay and in-memory state as well as projections.