├── .gitignore ├── .travis.yml ├── LICENSE ├── README.md ├── build.sbt ├── project ├── Version.scala ├── build.properties └── plugins.sbt └── src ├── main ├── protobuf │ ├── EmittedFormat.proto │ └── PayloadFormat.proto ├── resources │ └── reference.conf └── scala │ ├── akka │ └── persistence │ │ └── Journal.scala │ └── com │ └── github │ └── krasserm │ └── ases │ ├── EventSourcing.scala │ ├── Protocol.scala │ ├── Router.scala │ ├── log │ ├── AkkaPersistenceEventLog.scala │ ├── KafkaEventLog.scala │ └── package.scala │ └── serializer │ ├── EmittedSerializer.scala │ └── PayloadSerializer.scala └── test ├── resources ├── logback.xml └── reference.conf └── scala └── com └── github └── krasserm └── ases ├── EventCollaborationSpec.scala ├── EventSourcingSpec.scala ├── RequestRoutingSpec.scala ├── SpecWords.scala ├── StopSystemAfterAll.scala ├── StreamSpec.scala ├── log ├── AkkaPersistenceEventLogSpec.scala ├── KafkaEventLogSpec.scala ├── KafkaServer.scala └── KafkaSpec.scala └── serializer └── EmittedSerializerSpec.scala /.gitignore: -------------------------------------------------------------------------------- 1 | .idea* 2 | target/ 3 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: 2 | - scala 3 | scala: 4 | - 2.12.2 5 | jdk: 6 | - oraclejdk8 7 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright {yyyy} {name of copyright owner} 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Event sourcing for Akka Streams 2 | 3 | [![Gitter](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/akka-stream-eventsourcing/Lobby?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge) 4 | [![Build Status](https://travis-ci.org/krasserm/akka-stream-eventsourcing.svg?branch=master)](https://travis-ci.org/krasserm/akka-stream-eventsourcing) 5 | 6 | ## General concept 7 | 8 | This project brings to [Akka Streams](http://doc.akka.io/docs/akka/2.5.2/scala/stream/index.html) what [Akka Persistence](http://doc.akka.io/docs/akka/2.5.2/scala/persistence.html) brings to [Akka Actors](http://doc.akka.io/docs/akka/2.5.2/scala/actors.html): persistence via event sourcing. It provides a stateful [`EventSourcing`](https://github.com/krasserm/akka-stream-eventsourcing/blob/master/src/main/scala/com/github/krasserm/ases/EventSourcing.scala) graph stage of type `BidiFlow[REQ, E, E, RES, _]` (simplified) which models the event sourcing message flow. An `EventSourcing` stage therefore 9 | 10 | - consumes and validates a request (command or query) 11 | - produces events (derived from a command and internal state) to be written to an event log 12 | - consumes written events for updating internal state 13 | - produces a response after internal state update 14 | 15 | An `EventSourcing` stage maintains current state and uses a request handler for validating requests and generating events and responses: 16 | 17 | ```scala 18 | import com.github.krasserm.ases.EventSourcing._ 19 | 20 | type RequestHandler[S, E, REQ, RES] = (S, REQ) => Emission[S, E, RES] 21 | ``` 22 | 23 | Request handler input is current state and a request, output is an instruction to emit events and/or a response. `emit` instructs the `EventSourcing` stage to emit `events` and call a `responseFactory` with current state after all emitted events have been written and applied to current state: 24 | 25 | ```scala 26 | def emit[S, E, RES](events: Seq[E], responseFactory: S => RES): Emission[S, E, RES] 27 | ``` 28 | 29 | `respond` instructs the `EventSourcing` stage to emit a `response` immediately without emitting any events: 30 | 31 | ```scala 32 | def respond[S, E, RES](response: RES): Emission[S, E, RES] 33 | ``` 34 | 35 | Methods `emit` and `respond` themselves are side-effect free. They only generate `Emission` values that are interpreted by the `EventSourcing` stage. 36 | 37 | For updating internal state the `EventSourcing` stage uses an event handler: 38 | 39 | ```scala 40 | type EventHandler[S, E] = (S, E) => S 41 | ``` 42 | 43 | Event handler input is current state and a written event, output is updated state. Given definitions of emitter id, initial state, a request handler and an event handler, an `EventSourcing` stage can be constructed with: 44 | 45 | ```scala 46 | import akka.stream.scaladsl.BidiFlow 47 | import com.github.krasserm.ases.EventSourcing 48 | 49 | def emitterId: String 50 | def initialState: S 51 | def requestHandler: RequestHandler[S, E, REQ, RES] 52 | def eventHandler: EventHandler[S, E] 53 | 54 | def eventSourcingStage: BidiFlow[REQ, E, E, RES, _] = 55 | EventSourcing(emitterId, initialState, requestHandler, eventHandler) 56 | ``` 57 | 58 | Event logs are modeled as `Flow[E, E, _]`. This project provides event log implementations that can use [Akka Persistence journals](http://doc.akka.io/docs/akka/2.5.2/scala/persistence.html#storage-plugins) or [Apache Kafka](http://kafka.apache.org/) as storage backends. [Eventuate event logs](http://rbmhtechnology.github.io/eventuate/architecture.html#event-logs) as storage backends will be supported later. The following example uses the Akka Persistence in-memory journal as storage backend: 59 | 60 | ```scala 61 | import akka.stream.scaladsl.Flow 62 | import com.github.krasserm.ases.log.AkkaPersistenceEventLog 63 | 64 | val provider: AkkaPersistenceEventLog = 65 | new AkkaPersistenceEventLog(journalId = "akka.persistence.journal.inmem") 66 | 67 | def persistenceId: String = 68 | emitterId 69 | 70 | def eventLog: Flow[E, E, _] = 71 | provider.flow[E](persistenceId) 72 | ``` 73 | 74 | After materialization, an event log emits replayed events to its output port before emitting newly written events that have been received from its input port. To allow `eventSourcingStage` to use `eventLog` for writing and reading events it must `join` the event log: 75 | 76 | ```scala 77 | def requestProcessor: Flow[REQ, RES, _] = 78 | eventSourcingStage.join(eventLog) 79 | ``` 80 | 81 | The result is a stateful, event-sourced request processor of type `Flow[REQ, RES, _]` that processes a request stream. It will only demand new requests from upstream if there is downstream demand for responses and events. Any slowdown in response processing or event writing will back-pressure upstream request producers. 82 | 83 | In the same way as `PersistentActor`s in Akka Persistence, request processors provide a consistency boundary around internal state but additionally provide type safety and back-pressure for the whole event sourcing message flow. 84 | 85 | The examples presented in this section are a bit simplified for better readability. Take a look at section *Event logging protocols* and the tests (e.g. [`EventSourcingSpec`](https://github.com/krasserm/akka-stream-eventsourcing/blob/master/src/test/scala/com/github/krasserm/ases/EventSourcingSpec.scala)) for further details. 86 | 87 | ## Dynamic request processor loading 88 | 89 | When applying domain-driven design, consistency boundaries are often around so-called *aggregates*. A request processor that manages a single aggregate should be dynamically loaded and recovered when the first request targeted at that aggregate arrives. 90 | 91 | This can be achieved with a [`Router`](https://github.com/krasserm/akka-stream-eventsourcing/blob/master/src/main/scala/com/github/krasserm/ases/Router.scala). A router is configured with a function that extracts the aggregate id from a request and another function that creates a request processor from an aggregate id: 92 | 93 | ```scala 94 | import com.github.krasserm.ases.Router 95 | 96 | trait Aggregate[A] { 97 | def aggregateId(a: A): String 98 | } 99 | 100 | def eventSourcingStage(aggregateId: String): BidiFlow[REQ, E, E, RES, _] = 101 | EventSourcing(aggregateId, initialState, requestHandler, eventHandler) 102 | 103 | def requestProcessor(aggregateId: String): Flow[REQ, RES, _] = 104 | eventSourcingStage(aggregateId).join(provider.flow[E](aggregateId)) 105 | 106 | def requestRouter(implicit agg: Aggregate[REQ]): Flow[REQ, RES, _] = { 107 | Router(req => agg.aggregateId(req), (aggregateId: String) => requestProcessor(aggregateId)) 108 | } 109 | ``` 110 | 111 | A running example is in [`RequestRoutingSpec`](https://github.com/krasserm/akka-stream-eventsourcing/blob/master/src/test/scala/com/github/krasserm/ases/RequestRoutingSpec.scala). Dynamic unloading of request processors (e.g. using an LRU policy) is not supported yet as this requires special support from Akka Streams. 112 | 113 | ## Request processor collaboration (microservices) 114 | 115 | In contrast to `PersistentActor`s, `EventSourcing` stages can form a group by sharing an event log. Within a group, events emitted by one member can be consumed by all members in the group i.e. stages communicate via broadcast using the ordering guarantees of the underlying event log implementation. This feature can be used to implement event-sourced microservices that collaborate via events over a shared event log. 116 | 117 | The following example defines a `requestProcessor` method that creates request processors that use a Kafka topic partition as shared event log. Request processors created with this method form a group whose members collaborate over the shared `kafkaTopicPartition`. All members consume events in the same order as a topic partition provides total ordering: 118 | 119 | ```scala 120 | import com.github.krasserm.ases.log.KafkaEventLog 121 | import org.apache.kafka.common.TopicPartition 122 | 123 | def kafkaHost: String 124 | def kafkaPort: Int 125 | def kafkaTopicPartition: TopicPartition 126 | 127 | val provider = new KafkaEventLog(kafkaHost, kafkaPort) 128 | 129 | def requestProcessor(emitterId: String): Flow[REQ, RES, _] = 130 | EventSourcing(emitterId, initialState, requestHandler, eventHandler) 131 | .join(provider.flow(kafkaTopicPartition)) 132 | 133 | // A group of request processors 134 | val requestProcessor1 = requestProcessor("processor1") 135 | val requestProcessor2 = requestProcessor("processor2") 136 | // ... 137 | ``` 138 | 139 | You can find a running example in [`EventCollaborationSpec`](https://github.com/krasserm/akka-stream-eventsourcing/blob/master/src/test/scala/com/github/krasserm/ases/EventCollaborationSpec.scala) (a replicated event-sourced counter). Collaboration of request processors is comparable to collaboration of `EventsourcedActor`s in [Eventuate](http://rbmhtechnology.github.io/eventuate/) (see [event collaboration](http://rbmhtechnology.github.io/eventuate/architecture.html#event-collaboration) for details). 140 | 141 | ## Handler switching 142 | 143 | Applications can switch request and event handlers as a function of current state by defining request and event handler *providers*: 144 | 145 | ```scala 146 | def emitterId: String 147 | def initialState: S 148 | def requestHandlerProvider: S => RequestHandler[S, E, REQ, RES] 149 | def eventHandlerProvider: S => EventHandler[S, E] 150 | 151 | def eventSourcingStage: BidiFlow[REQ, E, E, RES, _] = 152 | EventSourcing(emitterId, initialState, requestHandlerProvider, eventHandlerProvider) 153 | ``` 154 | 155 | A request handler provider is called with current state for each request, an event handler provider is called with current state for each written event. This feature will be used later to implement a state machine DSL on top of the current handler API. 156 | 157 | ## Event logging protocols 158 | 159 | The examples so far modeled event logs as `Flow[E, E, _]` and `EventSourcing` stages as `BidiFlow[REQ, E, E, RES, _]` where `E` is the type of a domain event. This is not sufficient for real-world use cases. Further event metadata are required: 160 | 161 | - Events emitted by an `EventSourcing` stage must contain the id of the emitting stage (`emitterId`). This is needed, for example, by consumers on the query side of a CQRS application to distinguish emitters when consuming events from an aggregated or shared event log. 162 | - Events emitted by an event log must additionally contain the sequence number of the written event. Sequence numbers are required to track event processing progress, for example. 163 | - An event log must also signal to an `EventSourcing` stage when event replay has been completed. Only after successful recovery, an `EventSourcing` stage is allowed to signal demand for new requests to upstream producers. 164 | 165 | For these reasons, the current implementation uses 166 | 167 | ```scala 168 | Flow[Emitted[E], Delivery[Durable[E]], _] 169 | ``` 170 | 171 | as type for event logs and 172 | 173 | ```scala 174 | BidiFlow[REQ, Emitted[E], Delivery[Durable[E]], RES, _] 175 | ``` 176 | 177 | as type for `EventSourcing` stages. `Emitted`, `Durable` and `Delivery` are defined in [`Protocol.scala`](https://github.com/krasserm/akka-stream-eventsourcing/blob/master/src/main/scala/com/github/krasserm/ases/Protocol.scala). These protocol definitions are still preliminary and expected to change. For example, an extension to `Emitted` could support the emission of event batches for atomic batch writes. 178 | 179 | ## Project status 180 | 181 | In its current state, the project is a prototype that demonstrates the basic ideas how event sourcing and event collaboration could be added to Akka Streams. It can be used for experiments but is not yet ready for production. The prototype should serve as basis for further discussions and evolve to a potential later contribution to Akka, if there is enough interest in the community. 182 | -------------------------------------------------------------------------------- /build.sbt: -------------------------------------------------------------------------------- 1 | enablePlugins(ProtobufPlugin) 2 | 3 | lazy val commonSettings = Seq( 4 | organization := "com.github.krasserm", 5 | name := "akka-stream-eventsourcing", 6 | startYear := Some(2017), 7 | version := "0.1-SNAPSHOT", 8 | scalaVersion := "2.12.3", 9 | licenses += ("Apache-2.0", new URL("https://www.apache.org/licenses/LICENSE-2.0.txt")), 10 | headerLicense := Some(HeaderLicense.ALv2("2017", "the original author or authors.")) 11 | ) 12 | 13 | lazy val testSettings = Seq( 14 | parallelExecution in Test := false, 15 | fork in Test := true 16 | ) 17 | 18 | lazy val protocSettings: Seq[Setting[_]] = Seq( 19 | version in ProtobufConfig := Version.Protobuf, 20 | protobufRunProtoc in ProtobufConfig := (args => com.github.os72.protocjar.Protoc.runProtoc("-v340" +: args.toArray)) 21 | ) 22 | 23 | lazy val dependencies = Seq( 24 | "com.typesafe.akka" %% "akka-persistence" % Version.Akka , 25 | "com.typesafe.akka" %% "akka-stream" % Version.Akka , 26 | "com.typesafe.akka" %% "akka-stream-kafka" % "0.17", 27 | "org.apache.kafka" % "kafka-clients" % Version.Kafka, 28 | "org.apache.kafka" % "kafka-streams" % Version.Kafka, 29 | 30 | "ch.qos.logback" % "logback-classic" % "1.2.3" % "test", 31 | "org.slf4j" % "log4j-over-slf4j" % "1.7.25" % "test", 32 | "org.scalatest" %% "scalatest" % "3.0.4" % "test", 33 | "com.typesafe.akka" %% "akka-slf4j" % Version.Akka % "test", 34 | "com.typesafe.akka" %% "akka-stream-testkit" % Version.Akka % "test", 35 | "com.typesafe.akka" %% "akka-testkit" % Version.Akka % "test", 36 | "net.manub" %% "scalatest-embedded-kafka" % "0.15.1" % "test" exclude("log4j", "log4j") 37 | ) 38 | 39 | lazy val root = (project in file(".")) 40 | .enablePlugins(AutomateHeaderPlugin) 41 | .settings(commonSettings: _*) 42 | .settings(testSettings: _*) 43 | .settings(protocSettings: _*) 44 | .settings(libraryDependencies ++= dependencies) 45 | -------------------------------------------------------------------------------- /project/Version.scala: -------------------------------------------------------------------------------- 1 | object Version { 2 | val Akka = "2.5.4" 3 | val Kafka = "0.11.0.0" 4 | val Protobuf = "3.4.0" 5 | } 6 | -------------------------------------------------------------------------------- /project/build.properties: -------------------------------------------------------------------------------- 1 | sbt.version=1.0.1 2 | -------------------------------------------------------------------------------- /project/plugins.sbt: -------------------------------------------------------------------------------- 1 | addSbtPlugin("de.heikoseeberger" % "sbt-header" % "3.0.1") 2 | 3 | addSbtPlugin("com.github.gseitz" % "sbt-protobuf" % "0.6.3") 4 | 5 | libraryDependencies += "com.github.os72" % "protoc-jar" % "3.4.0" 6 | -------------------------------------------------------------------------------- /src/main/protobuf/EmittedFormat.proto: -------------------------------------------------------------------------------- 1 | syntax = "proto3"; 2 | 3 | option java_package = "com.github.krasserm.ases.serializer"; 4 | option optimize_for = SPEED; 5 | 6 | import "PayloadFormat.proto"; 7 | 8 | message EmittedFormat { 9 | PayloadFormat event = 1; 10 | string emitterId = 2; 11 | string emissionUuid = 3; 12 | } -------------------------------------------------------------------------------- /src/main/protobuf/PayloadFormat.proto: -------------------------------------------------------------------------------- 1 | syntax = "proto3"; 2 | 3 | option java_package = "com.github.krasserm.ases.serializer"; 4 | option optimize_for = SPEED; 5 | 6 | message PayloadFormat { 7 | int32 serializerId = 1; 8 | bytes payload = 2; 9 | string payloadManifest = 3; 10 | bool isStringManifest = 4; 11 | } -------------------------------------------------------------------------------- /src/main/resources/reference.conf: -------------------------------------------------------------------------------- 1 | akka.actor { 2 | serializers { 3 | ases-emitted = "com.github.krasserm.ases.serializer.EmittedSerializer" 4 | } 5 | serialization-bindings { 6 | "com.github.krasserm.ases.Emitted" = ases-emitted 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /src/main/scala/akka/persistence/Journal.scala: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2017 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package akka.persistence 18 | 19 | import akka.actor._ 20 | import akka.pattern.ask 21 | import akka.persistence.JournalProtocol._ 22 | import akka.stream.scaladsl.{Flow, Keep, Sink, Source} 23 | import akka.stream.stage._ 24 | import akka.stream.{Attributes, FlowShape, Inlet, Outlet} 25 | import akka.util.Timeout 26 | import akka.{Done, NotUsed} 27 | import com.github.krasserm.ases.{Delivered, Delivery, Recovered} 28 | 29 | import scala.collection.immutable.{Seq, VectorBuilder} 30 | import scala.concurrent.Future 31 | import scala.concurrent.duration._ 32 | import scala.util._ 33 | 34 | class Journal(journalId: String)(implicit system: ActorSystem) { 35 | private val extension = Persistence(system) 36 | private val journalActor = extension.journalFor(journalId) 37 | 38 | def eventLog(persistenceId: String): Flow[PersistentRepr, Delivery[PersistentRepr], NotUsed] = 39 | Flow[PersistentRepr].batch(10, Vector(_))(_ :+ _).via(Flow.fromGraph(new EventLog(persistenceId, journalActor))) 40 | 41 | def eventSource(persistenceId: String): Source[Delivery[PersistentRepr], NotUsed] = 42 | Source.single(Seq.empty).via(Flow.fromGraph(new EventLog(persistenceId, journalActor))) 43 | 44 | def eventSink(persistenceId: String): Sink[PersistentRepr, Future[Done]] = 45 | eventLog(persistenceId).toMat(Sink.ignore)(Keep.right) 46 | } 47 | 48 | private class EventLog(persistenceId: String, journalActor: ActorRef)(implicit factory: ActorRefFactory) extends GraphStage[FlowShape[Seq[PersistentRepr], Delivery[PersistentRepr]]] { 49 | import EventReplayer.Replayed 50 | import EventWriter.Written 51 | 52 | private val writer: EventWriter = new EventWriter(persistenceId, journalActor) 53 | private val replayer: EventReplayer = new EventReplayer(persistenceId, journalActor) 54 | 55 | val in = Inlet[Seq[PersistentRepr]]("EventLogStage.in") 56 | val out = Outlet[Delivery[PersistentRepr]]("EventLogStage.out") 57 | 58 | override val shape = FlowShape.of(in, out) 59 | 60 | override def createLogic(attr: Attributes): GraphStageLogic = 61 | new GraphStageLogic(shape) { 62 | private val writeSuccessCallback = getAsyncCallback(onWriteSuccess) 63 | private val replaySuccessCallback = getAsyncCallback(onReplaySuccess) 64 | private val failureCallback = getAsyncCallback(failStage) 65 | 66 | private var completed = false 67 | private var writing = false 68 | private var replaying = true 69 | private var currentSequenceNr: Long = 0L 70 | 71 | setHandler(in, new InHandler { 72 | override def onPush(): Unit = { 73 | writing = true 74 | writer.write(grab(in).map(_.update(sequenceNr = nextSequenceNr)), currentSequenceNr + 1L).onComplete { 75 | case Success(written) => writeSuccessCallback.invoke(written) 76 | case Failure(cause) => failureCallback.invoke(cause) 77 | }(materializer.executionContext) 78 | } 79 | 80 | override def onUpstreamFinish(): Unit = 81 | if (writing) completed = true else super.onUpstreamFinish() 82 | }) 83 | 84 | setHandler(out, new OutHandler { 85 | override def onPull(): Unit = { 86 | if (replaying) replayer.replay(currentSequenceNr + 1L, 100).onComplete { 87 | case Success(replayed) => replaySuccessCallback.invoke(replayed) 88 | case Failure(cause) => failureCallback.invoke(cause) 89 | }(materializer.executionContext) else pull(in) 90 | } 91 | }) 92 | 93 | private def onReplaySuccess(replayed: Replayed): Unit = { 94 | currentSequenceNr = replayed.lastSequenceNr 95 | emitMultiple(out, replayed.events.map(Delivered(_))) 96 | if (currentSequenceNr == replayed.currentSequenceNr) { 97 | replaying = false 98 | emit(out, Recovered) 99 | } 100 | } 101 | 102 | private def onWriteSuccess(written: Written): Unit = { 103 | writing = false 104 | emitMultiple(out, written.events.map(Delivered(_))) 105 | if (completed) completeStage() 106 | } 107 | 108 | private def nextSequenceNr: Long = { 109 | currentSequenceNr = currentSequenceNr + 1L 110 | currentSequenceNr 111 | } 112 | } 113 | } 114 | 115 | private object EventWriter { 116 | case class Write(events: Seq[PersistentRepr], from: Long) 117 | case class Written(events: Seq[PersistentRepr]) 118 | } 119 | 120 | private class EventWriter(persistenceId: String, journalActor: ActorRef)(implicit factory: ActorRefFactory) { 121 | import EventWriter._ 122 | 123 | private implicit val timeout = Timeout(10.seconds) // TODO: make configurable 124 | 125 | def write(events: Seq[PersistentRepr], from: Long): Future[Written] = 126 | factory.actorOf(Props(new EventWriterActor(persistenceId, journalActor))).ask(Write(events, from)).mapTo[Written] 127 | } 128 | 129 | private class EventWriterActor(persistenceId: String, journalActor: ActorRef) extends Actor { 130 | import EventWriter._ 131 | 132 | private var written = 0 133 | private var events: Seq[PersistentRepr] = Seq() 134 | private var sdr: ActorRef = _ 135 | 136 | override def receive: Receive = { 137 | case Write(Seq(), from) => 138 | sender() ! Written(Seq()) 139 | context.stop(self) 140 | case Write(es, from) => 141 | sdr = sender() 142 | events = es 143 | journalActor ! WriteMessages(Seq(AtomicWrite(es)), self, 0) 144 | case WriteMessagesFailed(cause) => 145 | sdr ! Status.Failure(cause) 146 | context.stop(self) 147 | case WriteMessagesSuccessful => 148 | sdr ! Written(events) 149 | case WriteMessageSuccess(_, _) => 150 | written = written + 1 151 | if (written == events.size) context.stop(self) 152 | } 153 | } 154 | 155 | private object EventReplayer { 156 | case class Replay(from: Long, max: Long) 157 | case class Replayed(events: Seq[PersistentRepr], currentSequenceNr: Long) { 158 | def lastSequenceNr: Long = if (events.isEmpty) currentSequenceNr else events.last.sequenceNr 159 | } 160 | } 161 | 162 | private class EventReplayer(persistenceId: String, journalActor: ActorRef)(implicit factory: ActorRefFactory) { 163 | import EventReplayer._ 164 | 165 | private implicit val timeout = Timeout(10.seconds) // TODO: make configurable 166 | 167 | def replay(from: Long, max: Long): Future[Replayed] = 168 | factory.actorOf(Props(new EventReplayerActor(persistenceId, journalActor))).ask(Replay(from, max)).mapTo[Replayed] 169 | } 170 | 171 | private class EventReplayerActor(persistenceId: String, journal: ActorRef) extends Actor { 172 | import EventReplayer._ 173 | 174 | private val builder: VectorBuilder[PersistentRepr] = new VectorBuilder[PersistentRepr] 175 | private var sdr: ActorRef = _ 176 | 177 | override def receive: Receive = { 178 | case Replay(from, max) => 179 | sdr = context.sender() 180 | journal ! ReplayMessages(from, Long.MaxValue, max, persistenceId, self) 181 | case ReplayedMessage(p) => 182 | builder += p 183 | case ReplayMessagesFailure(cause) => 184 | sdr ! Status.Failure(cause) 185 | context.stop(self) 186 | case RecoverySuccess(snr) => 187 | sdr ! Replayed(builder.result(), snr) 188 | context.stop(self) 189 | } 190 | } 191 | 192 | 193 | -------------------------------------------------------------------------------- /src/main/scala/com/github/krasserm/ases/EventSourcing.scala: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2017 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.github.krasserm.ases 18 | 19 | import akka.NotUsed 20 | import akka.stream.scaladsl.BidiFlow 21 | import akka.stream.stage.{GraphStage, GraphStageLogic, InHandler, OutHandler} 22 | import akka.stream.{Attributes, BidiShape, Inlet, Outlet} 23 | import com.github.krasserm.ases.EventSourcing._ 24 | 25 | import scala.collection.immutable.Seq 26 | 27 | object EventSourcing { 28 | /** 29 | * Event handler. Input is the current state and an event that has been written to an 30 | * event log. Output is the updated state that is set to the current state by the 31 | * [[EventSourcing]] driver. 32 | * 33 | * @tparam S State type. 34 | * @tparam E Event type. 35 | */ 36 | type EventHandler[S, E] = 37 | (S, E) => S 38 | 39 | /** 40 | * Request handler. Input is current state and a request, output is an instruction to emit events 41 | * and/or a response: 42 | * 43 | * - [[respond]] creates an immediate response which can be either the response to a ''query'' 44 | * or the failure response to a ''command'' whose validation failed, for example. 45 | * - [[emit]] returns a sequence of events to be written to an event log and a response factory 46 | * to be called with the current state after all written events have been applied to it. 47 | * 48 | * @tparam S State type. 49 | * @tparam E Event type. 50 | * @tparam REQ Request type. 51 | * @tparam RES Response type. 52 | */ 53 | type RequestHandler[S, E, REQ, RES] = 54 | (S, REQ) => Emission[S, E, RES] 55 | 56 | sealed trait Emission[S, E, RES] 57 | 58 | private case class Respond[S, E, RES](response: RES) 59 | extends Emission[S, E, RES] 60 | 61 | private case class Emit[S, E, RES](events: Seq[E], responseFactory: S => RES) 62 | extends Emission[S, E, RES] { 63 | require(events.nonEmpty, "event sequence must not be empty") 64 | } 65 | 66 | /** 67 | * Creates a request handler result that contains an immediate response. 68 | */ 69 | def respond[S, E, RES](response: RES): Emission[S, E, RES] = 70 | Respond(response) 71 | 72 | /** 73 | * Create a request handler result that contains events to be written to an event log and a response 74 | * factory to be called with the current state after all written events have been applied to it. 75 | */ 76 | def emit[S, E, RES](events: Seq[E], responseFactory: S => RES): Emission[S, E, RES] = 77 | Emit(events, responseFactory) 78 | 79 | /** 80 | * Creates a bidi-flow that implements the driver for event sourcing logic defined by `requestHandler` 81 | * `eventHandler`. The created event sourcing stage should be joined with an event log (i.e. a flow) 82 | * for writing emitted events. Written events are delivered from the joined event log back to the stage: 83 | * 84 | * - After materialization, the stage's state is recovered with replayed events delivered by the joined 85 | * event log. 86 | * - On recovery completion (see [[Delivery]]) the stage is ready to accept requests if there is 87 | * downstream response and event demand. 88 | * - On receiving a command it calls the request handler and emits the returned events. The emitted events 89 | * are sent downstream to the joined event log. 90 | * - For each written event that is delivered from the event log back to the event sourcing stage, the 91 | * event handler is called with that event and the current state. The stage updates its current state 92 | * with the event handler result. 93 | * - After all emitted events (for a given command) have been applied, the response function, previously 94 | * created by the command handler, is called with the current state and the created response is emitted. 95 | * - After response emission, the stage is ready to accept the next request if there is downstream response 96 | * and event demand. 97 | * 98 | * @param emitterId Identifier used for [[Emitted.emitterId]]. 99 | * @param initial Initial state. 100 | * @param requestHandler The stage's request handler. 101 | * @param eventHandler The stage's event handler. 102 | * @tparam S State type. 103 | * @tparam E Event type. 104 | * @tparam REQ Request type. 105 | * @tparam RES Response type. 106 | */ 107 | def apply[S, E, REQ, RES]( 108 | emitterId: String, 109 | initial: S, 110 | requestHandler: RequestHandler[S, E, REQ, RES], 111 | eventHandler: EventHandler[S, E]): BidiFlow[REQ, Emitted[E], Delivery[Durable[E]], RES, NotUsed] = 112 | BidiFlow.fromGraph(new EventSourcing[S, E, REQ, RES](emitterId, initial, _ => requestHandler, _ => eventHandler)) 113 | 114 | /** 115 | * Creates a bidi-flow that implements the driver for event sourcing logic returned by `requestHandlerProvider` 116 | * and `eventHandlerProvider`. `requestHandlerProvider` is evaluated with current state for each received request, 117 | * `eventHandlerProvider` is evaluated with current state for each written event. This can be used by applications 118 | * to switch request and event handling logic as a function of current state. The created event sourcing stage 119 | * should be joined with an event log (i.e. a flow) for writing emitted events. Written events are delivered 120 | * from the joined event log back to the stage: 121 | * 122 | * - After materialization, the stage's state is recovered with replayed events delivered by the joined 123 | * event log. 124 | * - On recovery completion (see [[Delivery]]) the stage is ready to accept requests if there is 125 | * downstream response and event demand. 126 | * - On receiving a command it calls the request handler and emits the returned events. The emitted events 127 | * are sent downstream to the joined event log. 128 | * - For each written event that is delivered from the event log back to the event sourcing stage, the 129 | * event handler is called with that event and the current state. The stage updates its current state 130 | * with the event handler result. 131 | * - After all emitted events (for a given command) have been applied, the response function, previously 132 | * created by the command handler, is called with the current state and the created response is emitted. 133 | * - After response emission, the stage is ready to accept the next request if there is downstream response 134 | * and event demand. 135 | * 136 | * @param emitterId Identifier used for [[Emitted.emitterId]]. 137 | * @param initial Initial state. 138 | * @param requestHandlerProvider The stage's request handler provider. 139 | * @param eventHandlerProvider The stage's event handler provider. 140 | * @tparam S State type. 141 | * @tparam E Event type. 142 | * @tparam REQ Request type. 143 | * @tparam RES Response type. 144 | */ 145 | def apply[S, E, REQ, RES]( 146 | emitterId: String, 147 | initial: S, 148 | requestHandlerProvider: S => RequestHandler[S, E, REQ, RES], 149 | eventHandlerProvider: S => EventHandler[S, E]): BidiFlow[REQ, Emitted[E], Delivery[Durable[E]], RES, NotUsed] = 150 | BidiFlow.fromGraph(new EventSourcing(emitterId, initial, requestHandlerProvider, eventHandlerProvider)) 151 | } 152 | 153 | private class EventSourcing[S, E, REQ, RES]( 154 | emitterId: String, 155 | initial: S, 156 | requestHandlerProvider: S => RequestHandler[S, E, REQ, RES], 157 | eventHandlerProvider: S => EventHandler[S, E]) 158 | extends GraphStage[BidiShape[REQ, Emitted[E], Delivery[Durable[E]], RES]] { 159 | 160 | private case class Roundtrip(emissionUuids: Set[String], responseFactory: S => RES) { 161 | def delivered(emissionUuid: String): Roundtrip = copy(emissionUuids - emissionUuid) 162 | } 163 | 164 | val ri = Inlet[REQ]("EventSourcing.requestIn") 165 | val eo = Outlet[Emitted[E]]("EventSourcing.eventOut") 166 | val ei = Inlet[Delivery[Durable[E]]]("EventSourcing.eventIn") 167 | val ro = Outlet[RES]("EventSourcing.responseOut") 168 | 169 | val shape = BidiShape.of(ri, eo, ei, ro) 170 | 171 | override def createLogic(inheritedAttributes: Attributes): GraphStageLogic = 172 | new GraphStageLogic(shape) { 173 | private var requestUpstreamFinished = false 174 | private var recovered = false 175 | private var roundtrip: Option[Roundtrip] = None 176 | private var state: S = initial 177 | 178 | setHandler(ri, new InHandler { 179 | override def onPush(): Unit = { 180 | requestHandlerProvider(state)(state, grab(ri)) match { 181 | case Respond(response) => 182 | push(ro, response) 183 | tryPullRi() 184 | case Emit(events, responseFactory) => 185 | val emitted = events.map(Emitted(_, emitterId)) 186 | roundtrip = Some(Roundtrip(emitted.map(_.emissionUuid)(collection.breakOut), responseFactory)) 187 | emitMultiple(eo, emitted) 188 | } 189 | } 190 | 191 | override def onUpstreamFinish(): Unit = 192 | if (roundtrip.isEmpty) completeStage() 193 | else requestUpstreamFinished = true 194 | }) 195 | 196 | setHandler(ei, new InHandler { 197 | override def onPush(): Unit = { 198 | grab(ei) match { 199 | case Recovered => 200 | recovered = true 201 | tryPullRi() 202 | case Delivered(durable) => 203 | state = eventHandlerProvider(state)(state, durable.event) 204 | roundtrip = roundtrip.map(_.delivered(durable.emissionUuid)).flatMap { 205 | case r if r.emissionUuids.isEmpty => 206 | push(ro, r.responseFactory(state)) 207 | if (requestUpstreamFinished) completeStage() else tryPullRi() 208 | None 209 | case r => 210 | Some(r) 211 | } 212 | } 213 | tryPullEi() 214 | } 215 | }) 216 | 217 | setHandler(eo, new OutHandler { 218 | override def onPull(): Unit = 219 | tryPullRi() 220 | }) 221 | 222 | setHandler(ro, new OutHandler { 223 | override def onPull(): Unit = 224 | tryPullRi() 225 | }) 226 | 227 | override def preStart(): Unit = 228 | tryPullEi() 229 | 230 | private def tryPullEi(): Unit = 231 | if (!requestUpstreamFinished) pull(ei) 232 | 233 | private def tryPullRi(): Unit = 234 | if (!requestUpstreamFinished && recovered && roundtrip.isEmpty && isAvailable(eo) && isAvailable(ro) && !hasBeenPulled(ri)) pull(ri) 235 | } 236 | } -------------------------------------------------------------------------------- /src/main/scala/com/github/krasserm/ases/Protocol.scala: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2017 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.github.krasserm.ases 18 | 19 | import java.util.UUID 20 | 21 | /** 22 | * Event delivery protocol implemented by event logs and sources. 23 | * 24 | * - Emit 0-n replayed events as `Delivered` message. 25 | * - Emit `Recovered` to signal recovery completion. 26 | * - Emit 0-n live events as `Delivered` message. 27 | */ 28 | sealed trait Delivery[+A] 29 | 30 | /** 31 | * Emitted by an event log or source to signal recovery completion 32 | * (= all events have been replayed). 33 | */ 34 | case object Recovered extends Delivery[Nothing] 35 | 36 | /** 37 | * Emitted by an event log or source to deliver an event (replayed 38 | * or live). 39 | */ 40 | case class Delivered[A](a: A) extends Delivery[A] 41 | 42 | /** 43 | * Metadata and container of an event emitted by an `EventSourcing` stage. 44 | * 45 | * @param event Emitted event. 46 | * @param emitterId Id of the event emitter. 47 | * @param emissionUuid Emission id generated by the event emitter. 48 | * @tparam A Event type 49 | */ 50 | case class Emitted[+A](event: A, emitterId: String, emissionUuid: String = UUID.randomUUID().toString) { 51 | def durable(sequenceNr: Long): Durable[A] = Durable(event, emitterId, emissionUuid, sequenceNr) 52 | } 53 | 54 | /** 55 | * Metadata and container of a durable event emitted by an event log or source. 56 | * 57 | * @param event Durable event. 58 | * @param emitterId Id of the initial event emitter. 59 | * @param emissionUuid Emission id generated by the initial event emitter. 60 | * @param sequenceNr Sequence number of the durable event. 61 | * @tparam A Event type 62 | */ 63 | case class Durable[+A](event: A, emitterId: String, emissionUuid: String, sequenceNr: Long) 64 | -------------------------------------------------------------------------------- /src/main/scala/com/github/krasserm/ases/Router.scala: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2017 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.github.krasserm.ases 18 | 19 | import akka.NotUsed 20 | import akka.stream.scaladsl.{Flow, Source} 21 | 22 | object Router { 23 | /** 24 | * Creates a router that routes to different `processors` based on input element key `K`. 25 | * A key is computed from input elements with the `key` function. Whenever a new key is 26 | * encountered, a new key-specific processor is created with the `processor` function. 27 | * A processor processes all input elements of given key. Processor output elements 28 | * are merged back into the main flow returned by this method. 29 | * 30 | * @param key computes a key from an input element 31 | * @param processor key-specific processor factory 32 | * @param maxProcessors maximum numbers of concurrent processors. 33 | * @tparam A router and processor input type 34 | * @tparam B router and processor output type 35 | * @tparam K key type 36 | */ 37 | def apply[A, B, K](key: A => K, processor: K => Flow[A, B, _], maxProcessors: Int = Int.MaxValue): Flow[A, B, NotUsed] = 38 | Flow[A].groupBy(maxProcessors, key).prefixAndTail(1).flatMapMerge(maxProcessors, { 39 | case (h, t) => Source(h).concat(t).via(processor(key(h.head))) 40 | }).mergeSubstreams 41 | } 42 | -------------------------------------------------------------------------------- /src/main/scala/com/github/krasserm/ases/log/AkkaPersistenceEventLog.scala: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2017 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.github.krasserm.ases.log 18 | 19 | import akka.actor.ActorSystem 20 | import akka.persistence.{Journal, PersistentRepr} 21 | import akka.stream.scaladsl._ 22 | import akka.{Done, NotUsed} 23 | import com.github.krasserm.ases._ 24 | 25 | import scala.concurrent.Future 26 | import scala.reflect.ClassTag 27 | 28 | /** 29 | * Akka Stream API for events logs managed by an Akka Persistence journal. 30 | * An individual event log is identified by `persistenceId`. 31 | * 32 | * @param journalId Id of the Akka Persistence journal. 33 | */ 34 | class AkkaPersistenceEventLog(journalId: String)(implicit system: ActorSystem) { 35 | private val journal = new Journal(journalId) 36 | 37 | /** 38 | * Creates a flow representing the event log identified by `persistenceId`. 39 | * Input events are written to the journal and emitted as output events 40 | * after successful write. Before input events are requested from upstream 41 | * the flow emits events that have been previously written to the journal 42 | * (recovery phase). 43 | * 44 | * During recovery, events are emitted as [[Delivered]] messages, recovery completion 45 | * is signaled as [[Recovered]] message, both subtypes of [[Delivery]]. After recovery, 46 | * events are again emitted as [[Delivered]] messages. 47 | * 48 | * It is the application's responsibility to ensure that there is only a 49 | * single materialized instance with given `persistenceId` writing to the 50 | * journal. 51 | * 52 | * @param persistenceId persistence id of the event log. 53 | * @tparam A event type. Only events that are instances of given type are 54 | * emitted by the flow. 55 | */ 56 | def flow[A: ClassTag](persistenceId: String): Flow[Emitted[A], Delivery[Durable[A]], NotUsed] = 57 | AkkaPersistenceCodec[A](persistenceId).join(journal.eventLog(persistenceId)) 58 | 59 | /** 60 | * Creates a source that replays events of the event log identified by `persistenceId`. 61 | * The source completes when the end of the log has been reached. 62 | * 63 | * During recovery, events are emitted as [[Delivered]] messages, recovery completion 64 | * is signaled as [[Recovered]] message, both subtypes of [[Delivery]]. 65 | * 66 | * @param persistenceId persistence id of the event log. 67 | * @tparam A event type. Only events that are instances of given type are 68 | * emitted by the source. 69 | */ 70 | def source[A: ClassTag](persistenceId: String): Source[Delivery[Durable[A]], NotUsed] = 71 | journal.eventSource(persistenceId).via(AkkaPersistenceCodec.decoder) 72 | 73 | /** 74 | * Creates a sink that writes events to the event log identified by 75 | * `persistenceId`. 76 | * 77 | * @param persistenceId persistence id of the event log. 78 | */ 79 | def sink[A](persistenceId: String): Sink[Emitted[A], Future[Done]] = 80 | AkkaPersistenceCodec.encoder(persistenceId).toMat(journal.eventSink(persistenceId))(Keep.right) 81 | } 82 | 83 | /** 84 | * Codec for translating [[Emitted]] to [[PersistentRepr]] and [[PersistentRepr]] to [[Durable]]. 85 | */ 86 | private object AkkaPersistenceCodec { 87 | /** 88 | * Codec composed of [[encoder]] and [[decoder]]. 89 | */ 90 | def apply[A: ClassTag](persistenceId: String): BidiFlow[Emitted[A], PersistentRepr, Delivery[PersistentRepr], Delivery[Durable[A]], NotUsed] = 91 | BidiFlow.fromFlows(encoder(persistenceId), decoder) 92 | 93 | /** 94 | * Decodes a [[PersistentRepr]] event as [[Durable]] 95 | */ 96 | def decoder[A: ClassTag]: Flow[Delivery[PersistentRepr], Delivery[Durable[A]], NotUsed] = 97 | Flow[Delivery[PersistentRepr]].collect { 98 | case Delivered(PersistentRepr(Emitted(e: A, emitterId, emissionUuid), sequenceNr)) => 99 | Delivered(Durable(e, emitterId, emissionUuid, sequenceNr)) 100 | case Recovered => 101 | Recovered 102 | } 103 | 104 | /** 105 | * Encodes an [[Emitted]] event as [[PersistentRepr]]. 106 | */ 107 | def encoder[A](persistenceId: String): Flow[Emitted[A], PersistentRepr, NotUsed] = 108 | Flow[Emitted[A]].map(encode(persistenceId)) 109 | 110 | private def encode[A](persistenceId: String)(identified: Emitted[A]): PersistentRepr = 111 | PersistentRepr( 112 | payload = identified, 113 | sequenceNr = -1L, 114 | persistenceId = persistenceId, 115 | writerUuid = PersistentRepr.Undefined, 116 | manifest = PersistentRepr.Undefined, 117 | deleted = false, 118 | sender = null) 119 | } -------------------------------------------------------------------------------- /src/main/scala/com/github/krasserm/ases/log/KafkaEventLog.scala: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2017 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.github.krasserm.ases.log 18 | 19 | import java.util 20 | import java.util.UUID 21 | 22 | import akka.actor.ActorSystem 23 | import akka.kafka.scaladsl.{Consumer, Producer} 24 | import akka.kafka.{ConsumerSettings, ProducerSettings, Subscriptions} 25 | import akka.serialization.SerializationExtension 26 | import akka.stream.{Attributes, Outlet, SourceShape} 27 | import akka.stream.scaladsl.{BidiFlow, Flow, Keep, Sink, Source} 28 | import akka.stream.stage.{GraphStage, GraphStageLogic, OutHandler} 29 | import akka.{Done, NotUsed} 30 | import com.github.krasserm.ases._ 31 | import org.apache.kafka.clients.consumer.{ConsumerConfig, ConsumerRecord, KafkaConsumer} 32 | import org.apache.kafka.clients.producer.{KafkaProducer, ProducerRecord} 33 | import org.apache.kafka.common.TopicPartition 34 | import org.apache.kafka.common.serialization._ 35 | 36 | import scala.collection.JavaConverters._ 37 | import scala.concurrent.Future 38 | import scala.reflect.ClassTag 39 | 40 | /** 41 | * Akka Stream API for events logs managed by Apache Kafka. An individual 42 | * event log is identified by `topicPartition`. 43 | * 44 | * '''This implementation is for testing only!''' It does not prevent or 45 | * compensate duplicate or re-ordered writes to topic partitions during 46 | * failures. Also, event retention time is assumed to be infinite. 47 | * 48 | * @param host Kafka (bootstrap server) host. 49 | * @param port Kafka (bootstrap server) port. 50 | */ 51 | class KafkaEventLog(host: String, port: Int)(implicit system: ActorSystem) { 52 | private val kafkaSource = new KafkaSource(host, port) 53 | private val kafkaSink = new KafkaSink(host, port) 54 | private val kafkaCodec = new KafkaCodec() 55 | 56 | /** 57 | * Creates a flow representing the event log identified by `topicPartition`. Input 58 | * events are written to the partition and emitted as output events after they have 59 | * been re-consumed from that partition. Events that already exist in the given topic 60 | * partition at materialization time are emitted before any newly written events are 61 | * emitted (recovery phase). 62 | * 63 | * During recovery, events are emitted as [[Delivered]] messages, recovery completion 64 | * is signaled as [[Recovered]] message, both subtypes of [[Delivery]]. After recovery, 65 | * events are again emitted as [[Delivered]] messages. 66 | * 67 | * Applications may create multiple materialized instances of flows writing to and consuming 68 | * from the same topic partition. In this case, an event written by one instance is consumed 69 | * by this and all other instances (collaboration via broadcast). All collaborators on a topic 70 | * partition see events in the same order. 71 | * 72 | * @param topicPartition topic partition of the event log. 73 | * @tparam A event type. Only events that are instances of given type are 74 | * emitted by the flow. 75 | */ 76 | def flow[A: ClassTag](topicPartition: TopicPartition): Flow[Emitted[A], Delivery[Durable[A]], NotUsed] = 77 | kafkaCodec.apply[A](topicPartition).join(Flow.fromSinkAndSource(kafkaSink.apply, kafkaSource(topicPartition))) 78 | 79 | /** 80 | * Creates a source that emits all events of the event log identified by `topicPartition`. 81 | * The source not only emits replayed events (recovery phase) but also emits events that 82 | * have been newly written by others to given topic partition. 83 | * 84 | * During recovery, events are emitted as [[Delivered]] messages, recovery completion 85 | * is signaled as [[Recovered]] message, both subtypes of [[Delivery]]. After recovery, 86 | * events are again emitted as [[Delivered]] messages. 87 | * 88 | * @param topicPartition topic partition of the event log. 89 | * @tparam A event type. Only events that are instances of given type are 90 | * emitted by the source. 91 | */ 92 | def source[A: ClassTag](topicPartition: TopicPartition): Source[Delivery[Durable[A]], NotUsed] = 93 | kafkaSource(topicPartition).via(kafkaCodec.decoder) 94 | 95 | /** 96 | * Creates a sink that writes events to the event log identified by `topicPartition`. 97 | * 98 | * @param topicPartition topic partition of the event log. 99 | * @tparam A event type. Only events that are instances of given type are 100 | * emitted by the source. 101 | */ 102 | def sink[A](topicPartition: TopicPartition): Sink[Emitted[A], Future[Done]] = 103 | kafkaCodec.encoder(topicPartition).toMat(kafkaSink.apply)(Keep.right) 104 | } 105 | 106 | private object KafkaCodec { 107 | object ConsumerRecordExtractor { 108 | def unapply[A](cr: ConsumerRecord[String, A]): Option[(A, Long)] = 109 | Some(cr.value, cr.offset) 110 | } 111 | } 112 | 113 | private class KafkaCodec(implicit system: ActorSystem) { 114 | def apply[A: ClassTag](topicPartition: TopicPartition): BidiFlow[Emitted[A], ProducerRecord[String, Emitted[Any]], Delivery[ConsumerRecord[String, Emitted[Any]]], Delivery[Durable[A]], NotUsed] = 115 | BidiFlow.fromFlows(encoder(topicPartition), decoder) 116 | 117 | def decoder[A: ClassTag]: Flow[Delivery[ConsumerRecord[String, Emitted[Any]]], Delivery[Durable[A]], NotUsed] = 118 | Flow[Delivery[ConsumerRecord[String, Emitted[Any]]]].collect { 119 | case Delivered(KafkaCodec.ConsumerRecordExtractor(Emitted(e: A, emitterId, emissionUuid), sequenceNr)) => 120 | Delivered(Durable(e, emitterId, emissionUuid, sequenceNr)) 121 | case Recovered => 122 | Recovered 123 | } 124 | 125 | def encoder[A](topicPartition: TopicPartition): Flow[Emitted[A], ProducerRecord[String, Emitted[A]], NotUsed] = 126 | Flow[Emitted[A]].map(emitted => new ProducerRecord(topicPartition.topic, topicPartition.partition, emitted.emitterId, emitted)) 127 | 128 | private def eventType[A: ClassTag]: PartialFunction[Any, A] = { 129 | case event: A => event 130 | } 131 | } 132 | 133 | private class KafkaSerialization(implicit val system: ActorSystem) extends Serializer[Emitted[Any]] with Deserializer[Emitted[Any]] { 134 | val serialization = SerializationExtension(system) 135 | 136 | override def close(): Unit = () 137 | 138 | override def configure(configs: util.Map[String, _], isKey: Boolean): Unit = () 139 | 140 | override def serialize(topic: String, data: Emitted[Any]): Array[Byte] = 141 | serialization.serialize(data).get 142 | 143 | override def deserialize(topic: String, data: Array[Byte]): Emitted[Any] = 144 | serialization.deserialize(data, classOf[Emitted[Any]]).get 145 | } 146 | 147 | private class KafkaSink(host: String, port: Int)(implicit system: ActorSystem) { 148 | val producerSettings: ProducerSettings[String, Emitted[Any]] = 149 | ProducerSettings(system, new StringSerializer, new KafkaSerialization) 150 | .withBootstrapServers(s"$host:$port") 151 | 152 | private val producer: KafkaProducer[String, Emitted[Any]] = 153 | producerSettings.createKafkaProducer() 154 | 155 | def apply: Sink[ProducerRecord[String, Emitted[Any]], Future[Done]] = 156 | Producer.plainSink(producerSettings, producer) 157 | } 158 | 159 | private class KafkaSource(host: String, port: Int)(implicit system: ActorSystem) { 160 | private val kafkaMetadata: KafkaMetadata[String, Emitted[Any]] = 161 | new KafkaMetadata(consumerSettings) 162 | 163 | private def consumerSettings: ConsumerSettings[String, Emitted[Any]] = 164 | ConsumerSettings(system, new StringDeserializer, new KafkaSerialization) 165 | .withBootstrapServers(s"$host:$port") 166 | .withProperty(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "earliest") 167 | .withGroupId(UUID.randomUUID().toString) 168 | 169 | def apply(topicPartition: TopicPartition): Source[Delivery[ConsumerRecord[String, Emitted[Any]]], NotUsed] = 170 | kafkaMetadata.endOffset(topicPartition).flatMapConcat { endOffset => 171 | to(topicPartition, endOffset - 1L) 172 | .map(Delivered(_)) 173 | .concat(Source.single(Recovered)) 174 | .concat(from(topicPartition, endOffset).map(Delivered(_))) 175 | } 176 | 177 | def from(topicPartition: TopicPartition, fromOffset: Long /* inclusive */): Source[ConsumerRecord[String, Emitted[Any]], NotUsed] = 178 | Consumer.plainSource(consumerSettings, Subscriptions.assignmentWithOffset(topicPartition, fromOffset)) 179 | .mapMaterializedValue(_ => NotUsed) 180 | 181 | def to(topicPartition: TopicPartition, toOffset: Long /* inclusive */): Source[ConsumerRecord[String, Emitted[Any]], NotUsed] = 182 | if (toOffset < 0L) Source.empty else Consumer.plainSource(consumerSettings, Subscriptions.assignmentWithOffset(topicPartition, 0L)) 183 | .mapMaterializedValue(_ => NotUsed) 184 | .takeWhile(_.offset < toOffset, inclusive = true) 185 | } 186 | 187 | private class KafkaMetadata[K, V](consumerSettings: ConsumerSettings[K, V])(implicit system: ActorSystem) { 188 | def offset(f: KafkaConsumer[K, V] => Long): Source[Long, NotUsed] = 189 | Source.fromGraph(new KafkaMetadataSource(consumerSettings)(f)) 190 | 191 | def endOffset(topicPartition: TopicPartition): Source[Long, NotUsed] = 192 | offset(endOffset(_, topicPartition)) 193 | 194 | private def endOffset(consumer: KafkaConsumer[K, V], topicPartition: TopicPartition): Long = 195 | consumer.endOffsets(Seq(topicPartition).asJava).get(topicPartition) match { 196 | case null => 0L 197 | case offset => offset.toLong 198 | } 199 | } 200 | 201 | private class KafkaMetadataSource[K, V, R](consumerSettings: ConsumerSettings[K, V])(f: KafkaConsumer[K, V] ⇒ R) extends GraphStage[SourceShape[R]] { 202 | val out: Outlet[R] = Outlet("KafkaMetadataSource.out") 203 | 204 | override val shape: SourceShape[R] = SourceShape(out) 205 | 206 | override def createLogic(inheritedAttributes: Attributes): GraphStageLogic = 207 | new GraphStageLogic(shape) { 208 | var consumer: KafkaConsumer[K, V] = _ 209 | 210 | setHandler(out, new OutHandler { 211 | override def onPull(): Unit = 212 | push(out, f(consumer)) 213 | }) 214 | 215 | override def preStart(): Unit = 216 | consumer = consumerSettings.createKafkaConsumer() 217 | 218 | override def postStop(): Unit = 219 | consumer.close() 220 | } 221 | } 222 | -------------------------------------------------------------------------------- /src/main/scala/com/github/krasserm/ases/log/package.scala: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2017 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.github.krasserm.ases 18 | 19 | import akka.NotUsed 20 | import akka.stream.scaladsl.Flow 21 | 22 | package object log { 23 | def replayed[A]: Flow[Delivery[A], A, NotUsed] = 24 | Flow[Delivery[A]].takeWhile(_ != Recovered).collect { case Delivered(event) => event } 25 | } 26 | -------------------------------------------------------------------------------- /src/main/scala/com/github/krasserm/ases/serializer/EmittedSerializer.scala: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2017 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.github.krasserm.ases.serializer 18 | 19 | import java.io.NotSerializableException 20 | 21 | import akka.actor.ExtendedActorSystem 22 | import akka.serialization.Serializer 23 | import com.github.krasserm.ases.Emitted 24 | import com.github.krasserm.ases.serializer.EmittedFormatOuterClass.EmittedFormat 25 | 26 | class EmittedSerializer(system: ExtendedActorSystem) extends Serializer { 27 | 28 | private val EmittedClass = classOf[Emitted[_]] 29 | private val payloadSerializer = new PayloadSerializer(system) 30 | 31 | override def identifier: Int = 17406883 32 | 33 | override def includeManifest: Boolean = true 34 | 35 | override def toBinary(o: AnyRef): Array[Byte] = o match { 36 | case emitted: Emitted[_] => 37 | emittedFormat(emitted).toByteArray 38 | case _ => 39 | throw new IllegalArgumentException(s"Invalid object of type '${o.getClass}' supplied to serializer [id = '$identifier']") 40 | } 41 | 42 | override def fromBinary(bytes: Array[Byte], manifest: Option[Class[_]]): AnyRef = manifest match { 43 | case Some(`EmittedClass`) => 44 | emitted(EmittedFormat.parseFrom(bytes)) 45 | case None => 46 | emitted(EmittedFormat.parseFrom(bytes)) 47 | case _ => 48 | throw new NotSerializableException(s"Unknown manifest '$manifest' supplied to serializer [id = '$identifier']") 49 | } 50 | 51 | private def emittedFormat(emitted: Emitted[Any]): EmittedFormat = { 52 | EmittedFormat.newBuilder() 53 | .setEvent(payloadSerializer.payloadFormatBuilder(emitted.event.asInstanceOf[AnyRef])) 54 | .setEmitterId(emitted.emitterId) 55 | .setEmissionUuid(emitted.emissionUuid) 56 | .build() 57 | } 58 | 59 | private def emitted(format: EmittedFormat): Emitted[_] = { 60 | Emitted( 61 | payloadSerializer.payload(format.getEvent), 62 | format.getEmitterId, 63 | format.getEmissionUuid 64 | ) 65 | } 66 | } 67 | -------------------------------------------------------------------------------- /src/main/scala/com/github/krasserm/ases/serializer/PayloadSerializer.scala: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2017 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.github.krasserm.ases.serializer 18 | 19 | import akka.actor.ExtendedActorSystem 20 | import akka.serialization.{SerializationExtension, SerializerWithStringManifest} 21 | import com.github.krasserm.ases.serializer.PayloadFormatOuterClass.PayloadFormat 22 | import com.google.protobuf.ByteString 23 | 24 | import scala.util.Try 25 | 26 | class PayloadSerializer(system: ExtendedActorSystem) { 27 | 28 | def payloadFormatBuilder(payload: AnyRef): PayloadFormat.Builder = { 29 | val serializer = SerializationExtension(system).findSerializerFor(payload) 30 | val builder = PayloadFormat.newBuilder() 31 | 32 | if (serializer.includeManifest) { 33 | val (isStringManifest, manifest) = serializer match { 34 | case s: SerializerWithStringManifest => (true, s.manifest(payload)) 35 | case _ => (false, payload.getClass.getName) 36 | } 37 | builder.setIsStringManifest(isStringManifest) 38 | builder.setPayloadManifest(manifest) 39 | } 40 | builder.setSerializerId(serializer.identifier) 41 | builder.setPayload(ByteString.copyFrom(serializer.toBinary(payload))) 42 | } 43 | 44 | def payload(payloadFormat: PayloadFormat): AnyRef = { 45 | val payload = if (payloadFormat.getIsStringManifest) 46 | payloadFromStringManifest(payloadFormat) 47 | else if (payloadFormat.getPayloadManifest.nonEmpty) 48 | payloadFromClassManifest(payloadFormat) 49 | else 50 | payloadFromEmptyManifest(payloadFormat) 51 | 52 | payload.get 53 | } 54 | 55 | private def payloadFromStringManifest(payloadFormat: PayloadFormat): Try[AnyRef] = { 56 | SerializationExtension(system).deserialize( 57 | payloadFormat.getPayload.toByteArray, 58 | payloadFormat.getSerializerId, 59 | payloadFormat.getPayloadManifest 60 | ) 61 | } 62 | 63 | private def payloadFromClassManifest(payloadFormat: PayloadFormat): Try[AnyRef] = { 64 | val manifestClass = system.dynamicAccess.getClassFor[AnyRef](payloadFormat.getPayloadManifest).get 65 | SerializationExtension(system).deserialize( 66 | payloadFormat.getPayload.toByteArray, 67 | payloadFormat.getSerializerId, 68 | Some(manifestClass) 69 | ) 70 | } 71 | 72 | private def payloadFromEmptyManifest(payloadFormat: PayloadFormat): Try[AnyRef] = { 73 | SerializationExtension(system).deserialize( 74 | payloadFormat.getPayload.toByteArray, 75 | payloadFormat.getSerializerId, 76 | None 77 | ) 78 | } 79 | } -------------------------------------------------------------------------------- /src/test/resources/logback.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n 5 | 6 | 7 | 8 | 9 | 10 | 11 | -------------------------------------------------------------------------------- /src/test/resources/reference.conf: -------------------------------------------------------------------------------- 1 | akka.actor { 2 | warn-about-java-serializer-usage = on 3 | 4 | serializers { 5 | emitted-serializer-spec-string-manifest = "com.github.krasserm.ases.serializer.EmittedSerializerSpec$StringManifestEventSerializer" 6 | emitted-serializer-spec-class-manifest = "com.github.krasserm.ases.serializer.EmittedSerializerSpec$ClassManifestEventSerializer" 7 | emitted-serializer-spec-empty-manifest = "com.github.krasserm.ases.serializer.EmittedSerializerSpec$EmptyManifestEventSerializer" 8 | } 9 | 10 | serialization-bindings { 11 | "com.github.krasserm.ases.serializer.EmittedSerializerSpec$StringManifestEvent" = emitted-serializer-spec-string-manifest 12 | "com.github.krasserm.ases.serializer.EmittedSerializerSpec$ClassManifestEvent" = emitted-serializer-spec-class-manifest 13 | "com.github.krasserm.ases.serializer.EmittedSerializerSpec$EmptyManifestEvent" = emitted-serializer-spec-empty-manifest 14 | } 15 | } 16 | akka.log-dead-letters-during-shutdown = off 17 | akka.log-dead-letters = off 18 | akka.test.single-expect-default = 5s 19 | akka.stream.materializer.debug.fuzzing-mode = on -------------------------------------------------------------------------------- /src/test/scala/com/github/krasserm/ases/EventCollaborationSpec.scala: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2017 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.github.krasserm.ases 18 | 19 | import akka.NotUsed 20 | import akka.actor.ActorSystem 21 | import akka.stream.scaladsl.{Flow, Sink} 22 | import akka.testkit.TestKit 23 | import com.github.krasserm.ases.log.{KafkaEventLog, KafkaSpec} 24 | import org.apache.kafka.common.TopicPartition 25 | import org.scalatest.concurrent.ScalaFutures 26 | import org.scalatest.time.{Millis, Seconds, Span} 27 | import org.scalatest.{Matchers, WordSpecLike} 28 | 29 | import scala.collection.immutable.Seq 30 | 31 | class EventCollaborationSpec extends TestKit(ActorSystem("test")) with WordSpecLike with Matchers with ScalaFutures with StreamSpec with KafkaSpec { 32 | import EventSourcingSpec._ 33 | 34 | implicit val pc = PatienceConfig(timeout = Span(5, Seconds), interval = Span(10, Millis)) 35 | 36 | val emitterId1 = "processor1" 37 | val emitterId2 = "processor2" 38 | 39 | val kafkaEventLog: KafkaEventLog = 40 | new log.KafkaEventLog(host, port) 41 | 42 | def processor(emitterId: String, topicPartition: TopicPartition): Flow[Request, Response, NotUsed] = 43 | EventSourcing(emitterId, 0, requestHandler, eventHandler).join(kafkaEventLog.flow(topicPartition)) 44 | 45 | "A group of EventSourcing stages" when { 46 | "joined with a shared event log" can { 47 | "collaborate via publish-subscribe" in { 48 | val topicPartition = new TopicPartition("p-1", 0) // shared topic partition 49 | val (pub1, sub1) = probes(processor(emitterId1, topicPartition)) // processor 1 50 | val (pub2, sub2) = probes(processor(emitterId2, topicPartition)) // processor 2 51 | 52 | pub1.sendNext(Increment(3)) 53 | // Both processors receive event but 54 | // only processor 1 creates response 55 | sub1.requestNext(Response(3)) 56 | 57 | pub2.sendNext(Increment(-4)) 58 | // Both processors receive event but 59 | // only processor 2 creates response 60 | sub2.requestNext(Response(-1)) 61 | 62 | // consume and verify events emitted by both processors 63 | kafkaEventLog.source[Incremented](topicPartition).via(log.replayed).map { 64 | case Durable(event, eid, _, sequenceNr) => (event, eid, sequenceNr) 65 | }.runWith(Sink.seq).futureValue should be(Seq( 66 | (Incremented(3), emitterId1, 0L), 67 | (Incremented(-4), emitterId2, 1L) 68 | )) 69 | } 70 | } 71 | } 72 | } 73 | -------------------------------------------------------------------------------- /src/test/scala/com/github/krasserm/ases/EventSourcingSpec.scala: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2017 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.github.krasserm.ases 18 | 19 | import akka.NotUsed 20 | import akka.actor.ActorSystem 21 | import akka.stream.scaladsl.{Flow, Sink, Source} 22 | import akka.testkit.TestKit 23 | import com.github.krasserm.ases.log.{AkkaPersistenceEventLog, KafkaEventLog, KafkaSpec} 24 | import org.apache.kafka.common.TopicPartition 25 | import org.scalatest.concurrent.ScalaFutures 26 | import org.scalatest.time.{Millis, Seconds, Span} 27 | import org.scalatest.{Matchers, WordSpecLike} 28 | 29 | import scala.collection.immutable.Seq 30 | 31 | object EventSourcingSpec { 32 | import EventSourcing._ 33 | 34 | sealed trait Request 35 | sealed trait Event 36 | 37 | case object GetState extends Request 38 | case class Increment(delta: Int) extends Request 39 | case class ClearIfEqualTo(value: Int) extends Request 40 | case class Response(state: Int) 41 | 42 | case class Incremented(delta: Int) extends Event 43 | case object Cleared extends Event 44 | 45 | val requestHandler: RequestHandler[Int, Event, Request, Response] = { 46 | case (s, req @ GetState) => 47 | respond(Response(s)) 48 | case (s, req @ Increment(d)) => 49 | emit(Seq(Incremented(d)), Response) 50 | case (s, req @ ClearIfEqualTo(v)) => 51 | if (s == v) emit(Seq(Cleared), Response) 52 | else respond(Response(s)) 53 | } 54 | 55 | val eventHandler: EventHandler[Int, Event] = { 56 | case (s, Incremented(delta)) => 57 | s + delta 58 | case (s, Cleared) => 59 | 0 60 | } 61 | } 62 | 63 | class EventSourcingSpec extends TestKit(ActorSystem("test")) with WordSpecLike with Matchers with ScalaFutures with StreamSpec with KafkaSpec { 64 | import EventSourcingSpec._ 65 | 66 | implicit val pc = PatienceConfig(timeout = Span(5, Seconds), interval = Span(10, Millis)) 67 | 68 | val akkaPersistenceEventLog: AkkaPersistenceEventLog = 69 | new log.AkkaPersistenceEventLog(journalId = "akka.persistence.journal.inmem") 70 | 71 | val kafkaEventLog: KafkaEventLog = 72 | new log.KafkaEventLog(host, port) 73 | 74 | def testEventLog[A](emitted: Seq[Emitted[A]] = Seq.empty): Flow[Emitted[A], Delivery[Durable[A]], NotUsed] = 75 | Flow[Emitted[A]] 76 | .zipWithIndex.map { case (e, i) => e.durable(i) } 77 | .map(Delivered(_)) 78 | .prepend(Source.single(Recovered)) 79 | .prepend(Source(durables(emitted)).map(Delivered(_))) 80 | 81 | "An EventSourcing stage" when { 82 | "joined with a test event log" must { 83 | val processor: Flow[Request, Response, NotUsed] = 84 | EventSourcing(emitterId, 0, requestHandler, eventHandler).join(testEventLog()) 85 | 86 | "consume commands and produce responses" in { 87 | val commands = Seq(1, -4, 7).map(Increment) 88 | val expected = Seq(1, -3, 4).map(Response) 89 | Source(commands).via(processor).runWith(Sink.seq).futureValue should be(expected) 90 | } 91 | "consume queries and produce responses" in { 92 | val commands = Seq(1, 0, 7).map { 93 | case 0 => GetState 94 | case i => Increment(i) 95 | } 96 | val expected = Seq(1, 1, 8).map(Response) 97 | Source(commands).via(processor).runWith(Sink.seq).futureValue should be(expected) 98 | } 99 | } 100 | "joined with a non-empty test event log" must { 101 | def processor(replay: Seq[Emitted[Incremented]]): Flow[Request, Response, NotUsed] = 102 | EventSourcing(emitterId, 0, requestHandler, eventHandler).join(testEventLog(replay)) 103 | 104 | "first recover state and then consume commands and produce responses" in { 105 | val commands = Seq(-4, 7).map(Increment) 106 | val expected = Seq(-3, 4).map(Response) 107 | Source(commands).via(processor(Seq(Emitted(Incremented(1), emitterId)))).runWith(Sink.seq).futureValue should be(expected) 108 | } 109 | "first recover state and then consume state-dependent command with correct state" in { 110 | Source.single(ClearIfEqualTo(5)).via(processor(Seq(Emitted(Incremented(5), emitterId)))) 111 | .runWith(Sink.seq).futureValue should be(Seq(Response(0))) 112 | } 113 | "first recover state and then consume command followed by state dependent command with correct state" in { 114 | Source(Seq(Increment(0), ClearIfEqualTo(5))).via(processor(Seq(Emitted(Incremented(5), emitterId)))) 115 | .runWith(Sink.seq).futureValue should be(Seq(Response(5), Response(0))) 116 | } 117 | "first recover state and then consume command and produce response" in { 118 | Source.single(Increment(2)).via(processor(Seq(Emitted(Incremented(1), emitterId)))) 119 | .runWith(Sink.seq).futureValue should be(Seq(Response(3))) 120 | } 121 | "first recover state and then consume query and produce response" in { 122 | Source.single(GetState).via(processor(Seq(Emitted(Incremented(1), emitterId)))) 123 | .runWith(Sink.seq).futureValue should be(Seq(Response(1))) 124 | } 125 | } 126 | "joined with an Akka Persistence event log" must { 127 | def processor(persistenceId: String): Flow[Request, Response, NotUsed] = 128 | EventSourcing(emitterId, 0, requestHandler, eventHandler).join(akkaPersistenceEventLog.flow(persistenceId)) 129 | 130 | "consume commands and produce responses" in { 131 | val persistenceId = "pid-1" 132 | val commands = Seq(1, -4, 7).map(Increment) 133 | val expected = Seq(1, -3, 4).map(Response) 134 | Source(commands).via(processor(persistenceId)).runWith(Sink.seq).futureValue should be(expected) 135 | } 136 | "first recover state and then consume commands and produce responses" in { 137 | val persistenceId = "pid-2" 138 | Source.single(Emitted(Incremented(1), emitterId)).runWith(akkaPersistenceEventLog.sink(persistenceId)).futureValue 139 | val commands = Seq(-4, 7).map(Increment) 140 | val expected = Seq(-3, 4).map(Response) 141 | Source(commands).via(processor(persistenceId)).runWith(Sink.seq).futureValue should be(expected) 142 | } 143 | "first recover state and then consume state-dependent command with correct state" in { 144 | val persistenceId = "pid-3" 145 | Source.single(Emitted(Incremented(5), emitterId)).runWith(akkaPersistenceEventLog.sink(persistenceId)).futureValue 146 | Source.single(ClearIfEqualTo(5)).via(processor(persistenceId)).runWith(Sink.seq).futureValue should be(Seq(Response(0))) 147 | } 148 | "first recover state and then consume command followed by state dependent command with correct state" in { 149 | val persistenceId = "pid-4" 150 | Source.single(Emitted(Incremented(5), emitterId)).runWith(akkaPersistenceEventLog.sink(persistenceId)).futureValue 151 | Source(Seq(Increment(0), ClearIfEqualTo(5))).via(processor(persistenceId)).runWith(Sink.seq).futureValue should be(Seq(Response(5), Response(0))) 152 | } 153 | "first recover state and then consume command and produce response" in { 154 | val persistenceId = "pid-5" 155 | Source.single(Emitted(Incremented(1), emitterId)).runWith(akkaPersistenceEventLog.sink(persistenceId)).futureValue 156 | Source.single(Increment(2)).via(processor(persistenceId)).runWith(Sink.seq).futureValue should be(Seq(Response(3))) 157 | } 158 | "first recover state and then consume query and produce response" in { 159 | val persistenceId = "pid-6" 160 | Source.single(Emitted(Incremented(1), emitterId)).runWith(akkaPersistenceEventLog.sink(persistenceId)).futureValue 161 | Source.single(GetState).via(processor(persistenceId)).runWith(Sink.seq).futureValue should be(Seq(Response(1))) 162 | } 163 | } 164 | "joined with a Kafka event log" must { 165 | def processor(topicPartition: TopicPartition): Flow[Request, Response, NotUsed] = 166 | EventSourcing(emitterId, 0, requestHandler, eventHandler).join(kafkaEventLog.flow(topicPartition)) 167 | 168 | "consume commands and produce responses" in { 169 | val topicPartition = new TopicPartition("p-1", 0) 170 | val commands = Seq(1, -4, 7).map(Increment) 171 | val expected = Seq(1, -3, 4).map(Response) 172 | Source(commands).via(processor(topicPartition)).runWith(Sink.seq).futureValue should be(expected) 173 | } 174 | "first recover state and then consume commands and produce responses" in { 175 | val topicPartition = new TopicPartition("p-2", 0) 176 | Source.single(Emitted(Incremented(1), emitterId)).runWith(kafkaEventLog.sink(topicPartition)).futureValue 177 | val commands = Seq(-4, 7).map(Increment) 178 | val expected = Seq(-3, 4).map(Response) 179 | Source(commands).via(processor(topicPartition)).runWith(Sink.seq).futureValue should be(expected) 180 | } 181 | "first recover state and then consume state-dependent command with correct state" in { 182 | val topicPartition = new TopicPartition("p-3", 0) 183 | Source.single(Emitted(Incremented(5), emitterId)).runWith(kafkaEventLog.sink(topicPartition)).futureValue 184 | Source.single(ClearIfEqualTo(5)).via(processor(topicPartition)).runWith(Sink.seq).futureValue should be(Seq(Response(0))) 185 | } 186 | "first recover state and then consume command followed by state dependent command with correct state" in { 187 | val topicPartition = new TopicPartition("p-4", 0) 188 | Source.single(Emitted(Incremented(5), emitterId)).runWith(kafkaEventLog.sink(topicPartition)).futureValue 189 | Source(Seq(Increment(0), ClearIfEqualTo(5))).via(processor(topicPartition)).runWith(Sink.seq).futureValue should be(Seq(Response(5), Response(0))) 190 | } 191 | "first recover state and then consume command and produce response" in { 192 | val topicPartition = new TopicPartition("p-5", 0) 193 | Source.single(Emitted(Incremented(1), emitterId)).runWith(kafkaEventLog.sink(topicPartition)).futureValue 194 | Source.single(Increment(2)).via(processor(topicPartition)).runWith(Sink.seq).futureValue should be(Seq(Response(3))) 195 | } 196 | "first recover state and then consume query and produce response" in { 197 | val topicPartition = new TopicPartition("p-6", 0) 198 | Source.single(Emitted(Incremented(1), emitterId)).runWith(kafkaEventLog.sink(topicPartition)).futureValue 199 | Source.single(GetState).via(processor(topicPartition)).runWith(Sink.seq).futureValue should be(Seq(Response(1))) 200 | } 201 | } 202 | } 203 | } 204 | -------------------------------------------------------------------------------- /src/test/scala/com/github/krasserm/ases/RequestRoutingSpec.scala: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2017 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.github.krasserm.ases 18 | 19 | import akka.NotUsed 20 | import akka.actor.ActorSystem 21 | import akka.stream.scaladsl.{Flow, Sink, Source} 22 | import akka.testkit.TestKit 23 | import com.github.krasserm.ases.log.AkkaPersistenceEventLog 24 | import org.scalatest.concurrent.ScalaFutures 25 | import org.scalatest.{Matchers, WordSpecLike} 26 | import scala.collection.immutable.Seq 27 | 28 | object RequestRoutingSpec { 29 | import EventSourcing._ 30 | 31 | sealed trait Request { 32 | def aggregateId: String 33 | } 34 | case class GetState(aggregateId: String) extends Request // Query 35 | case class Increment(aggregateId: String, delta: Int) extends Request // Command 36 | case class Incremented(aggregateId: String, delta: Int) // Event 37 | case class Response(aggregateId: String, state: Int) 38 | 39 | val requestHandler: RequestHandler[Int, Incremented, Request, Response] = { 40 | case (s, GetState(aggregateId)) => respond(Response(aggregateId, s)) 41 | case (_, Increment(aggregateId, d)) => emit(Seq(Incremented(aggregateId, d)), Response(aggregateId, _)) 42 | } 43 | 44 | val eventHandler: EventHandler[Int, Incremented] = 45 | (s, e) => s + e.delta 46 | } 47 | 48 | class RequestRoutingSpec extends TestKit(ActorSystem("test")) with WordSpecLike with Matchers with ScalaFutures with StreamSpec { 49 | import RequestRoutingSpec._ 50 | 51 | val akkaPersistenceEventLog: AkkaPersistenceEventLog = 52 | new log.AkkaPersistenceEventLog(journalId = "akka.persistence.journal.inmem") 53 | 54 | def processor(aggregateId: String): Flow[Request, Response, NotUsed] = 55 | EventSourcing(aggregateId, 0, requestHandler, eventHandler).join(akkaPersistenceEventLog.flow(aggregateId)) 56 | 57 | def router: Flow[Request, Response, NotUsed] = 58 | Router(_.aggregateId, processor) 59 | 60 | "A request router" when { 61 | "configured to route based on aggregate id" must { 62 | "dynamically create a request processor for each aggregate id" in { 63 | val aggregateId1 = "a1" 64 | val aggregateId2 = "a2" 65 | 66 | val (pub, sub) = probes(router) 67 | 68 | pub.sendNext(Increment(aggregateId1, 3)) 69 | sub.requestNext(Response(aggregateId1, 3)) 70 | 71 | pub.sendNext(Increment(aggregateId2, 1)) 72 | sub.requestNext(Response(aggregateId2, 1)) 73 | 74 | pub.sendNext(Increment(aggregateId1, 2)) 75 | sub.requestNext(Response(aggregateId1, 5)) 76 | 77 | pub.sendNext(Increment(aggregateId2, -4)) 78 | sub.requestNext(Response(aggregateId2, -3)) 79 | } 80 | "handle single command using Source.single" in { 81 | val request = Increment("a3", 3) 82 | val expected = Response("a3", 3) 83 | Source.single(request) 84 | .via(router) 85 | .runWith(Sink.head) 86 | .futureValue should be(expected) 87 | } 88 | "handle single command using Source.apply(Seq)" in { 89 | val request = Increment("a4", 3) 90 | val expected = Response("a4", 3) 91 | Source(Seq(request)) 92 | .via(router) 93 | .runWith(Sink.head) 94 | .futureValue should be(expected) 95 | } 96 | "handle multiple commands" in { 97 | Source(Seq(Increment("a5", 1), Increment("a5", 2), Increment("a5", 3))) 98 | .via(router) 99 | .runWith(Sink.seq) 100 | .futureValue should be(Seq(Response("a5", 1), Response("a5", 3), Response("a5", 6))) 101 | } 102 | } 103 | } 104 | } -------------------------------------------------------------------------------- /src/test/scala/com/github/krasserm/ases/SpecWords.scala: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2017 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.github.krasserm.ases 18 | 19 | import org.scalatest.WordSpecLike 20 | 21 | trait SpecWords { 22 | this: WordSpecLike => 23 | 24 | val is = afterWord("is") 25 | val isA = afterWord("is a") 26 | val contains = afterWord("contains") 27 | val invokedWith = afterWord("invokedWith") 28 | } 29 | -------------------------------------------------------------------------------- /src/test/scala/com/github/krasserm/ases/StopSystemAfterAll.scala: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2017 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.github.krasserm.ases 18 | 19 | import akka.testkit.TestKit 20 | import org.scalatest.{BeforeAndAfterAll, Suite} 21 | 22 | trait StopSystemAfterAll extends BeforeAndAfterAll { 23 | this: TestKit with Suite => 24 | 25 | override protected def afterAll(): Unit = { 26 | TestKit.shutdownActorSystem(system) 27 | super.afterAll() 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /src/test/scala/com/github/krasserm/ases/StreamSpec.scala: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2017 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.github.krasserm.ases 18 | 19 | import akka.stream.ActorMaterializer 20 | import akka.stream.scaladsl.{Flow, Keep} 21 | import akka.stream.testkit.scaladsl.{TestSink, TestSource} 22 | import akka.stream.testkit.{TestPublisher, TestSubscriber} 23 | import akka.testkit.TestKit 24 | import org.scalatest.{BeforeAndAfterAll, Suite} 25 | 26 | import scala.collection.immutable.Seq 27 | 28 | trait StreamSpec extends BeforeAndAfterAll { this: TestKit with Suite => 29 | implicit val materializer = ActorMaterializer() 30 | 31 | val emitterId = "emitter" 32 | 33 | override def afterAll(): Unit = { 34 | materializer.shutdown() 35 | TestKit.shutdownActorSystem(system) 36 | super.afterAll() 37 | } 38 | 39 | def probes[I, O, M](flow: Flow[I, O, M]): (TestPublisher.Probe[I], TestSubscriber.Probe[O]) = 40 | TestSource.probe[I].viaMat(flow)(Keep.left).toMat(TestSink.probe[O])(Keep.both).run() 41 | 42 | def durables[A](emitted: Seq[Emitted[A]], offset: Int = 0): Seq[Durable[A]] = 43 | emitted.zipWithIndex.map { case (e, i) => e.durable(i + offset) } 44 | } 45 | -------------------------------------------------------------------------------- /src/test/scala/com/github/krasserm/ases/log/AkkaPersistenceEventLogSpec.scala: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2017 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.github.krasserm.ases.log 18 | 19 | import akka.actor.ActorSystem 20 | import akka.stream.scaladsl.{Sink, Source} 21 | import akka.testkit.TestKit 22 | import com.github.krasserm.ases._ 23 | import org.scalatest.concurrent.ScalaFutures 24 | import org.scalatest.{Matchers, WordSpecLike} 25 | 26 | import scala.collection.immutable.Seq 27 | 28 | class AkkaPersistenceEventLogSpec extends TestKit(ActorSystem("test")) with WordSpecLike with Matchers with ScalaFutures with StreamSpec { 29 | val akkaPersistenceEventLog: AkkaPersistenceEventLog = new AkkaPersistenceEventLog(journalId = "akka.persistence.journal.inmem") 30 | 31 | "An Akka Persistence event log" must { 32 | "provide a sink for writing events and a source for delivering replayed events" in { 33 | val persistenceId = "1" 34 | val events = Seq("a", "b", "c").map(Emitted(_, emitterId)) 35 | val expected = durables(events, offset = 1).map(Delivered(_)) :+ Recovered 36 | 37 | Source(events).runWith(akkaPersistenceEventLog.sink(persistenceId)).futureValue 38 | akkaPersistenceEventLog.source[String](persistenceId).runWith(Sink.seq).futureValue should be(expected) 39 | } 40 | "provide a flow with an input port for writing events and and output port for delivering replayed and live events" in { 41 | val persistenceId = "2" 42 | val events1 = Seq("a", "b", "c").map(Emitted(_, emitterId)) 43 | val events2 = Seq("d", "e", "f").map(Emitted(_, emitterId)) 44 | val expected = (durables(events1, offset = 1).map(Delivered(_)) :+ Recovered) ++ durables(events2, offset = 4).map(Delivered(_)) 45 | 46 | Source(events1).runWith(akkaPersistenceEventLog.sink(persistenceId)).futureValue 47 | Source(events2).via(akkaPersistenceEventLog.flow(persistenceId)).runWith(Sink.seq).futureValue should be(expected) 48 | } 49 | "provide a source that only delivers events of compatible types" in { 50 | val persistenceId = "3" 51 | val events = Seq("a", "b", 1, 2).map(Emitted(_, emitterId)) 52 | val expected = durables(events, offset = 1).drop(2).map(Delivered(_)) :+ Recovered 53 | 54 | Source(events).runWith(akkaPersistenceEventLog.sink(persistenceId)).futureValue 55 | akkaPersistenceEventLog.source[Int](persistenceId).runWith(Sink.seq).futureValue should be(expected) 56 | } 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /src/test/scala/com/github/krasserm/ases/log/KafkaEventLogSpec.scala: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2017 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.github.krasserm.ases.log 18 | 19 | import akka.actor.ActorSystem 20 | import akka.stream.scaladsl.{Sink, Source} 21 | import akka.testkit.TestKit 22 | import com.github.krasserm.ases._ 23 | import org.apache.kafka.common.TopicPartition 24 | import org.scalatest.concurrent.ScalaFutures 25 | import org.scalatest.time.{Millis, Seconds, Span} 26 | import org.scalatest.{Matchers, WordSpecLike} 27 | 28 | import scala.collection.immutable.Seq 29 | 30 | class KafkaEventLogSpec extends TestKit(ActorSystem("test")) with WordSpecLike with Matchers with ScalaFutures with StreamSpec with KafkaSpec { 31 | implicit val pc = PatienceConfig(timeout = Span(5, Seconds), interval = Span(10, Millis)) 32 | 33 | val kafkaEventLog: KafkaEventLog = new KafkaEventLog(host, port) 34 | 35 | "A Kafka event log" must { 36 | "provide a sink for writing events and a source for delivering replayed events" in { 37 | val topicPartition = new TopicPartition("p-1", 0) 38 | val events = Seq("a", "b", "c").map(Emitted(_, emitterId)) 39 | val expected = durables(events).map(Delivered(_)) :+ Recovered 40 | 41 | Source(events).runWith(kafkaEventLog.sink(topicPartition)).futureValue 42 | kafkaEventLog.source[String](topicPartition).take(4).runWith(Sink.seq).futureValue should be(expected) 43 | } 44 | "provide a flow with an input port for writing events and and output port for delivering replayed and live events" in { 45 | val topicPartition = new TopicPartition("p-2", 0) 46 | val events1 = Seq("a", "b", "c").map(Emitted(_, emitterId)) 47 | val events2 = Seq("d", "e", "f").map(Emitted(_, emitterId)) 48 | val expected = (durables(events1).map(Delivered(_)) :+ Recovered) ++ durables(events2, offset = 3).map(Delivered(_)) 49 | 50 | Source(events1).runWith(kafkaEventLog.sink(topicPartition)).futureValue 51 | Source(events2).via(kafkaEventLog.flow(topicPartition)).take(7).runWith(Sink.seq).futureValue should be(expected) 52 | } 53 | "provide a source that only delivers events of compatible types" in { 54 | val topicPartition = new TopicPartition("p-3", 0) 55 | val events = Seq("a", "b", 1, 2).map(Emitted(_, emitterId)) 56 | val expected = durables(events).drop(2).map(Delivered(_)) :+ Recovered 57 | 58 | Source(events).runWith(kafkaEventLog.sink(topicPartition)).futureValue 59 | kafkaEventLog.source[Int](topicPartition).take(3).runWith(Sink.seq).futureValue should be(expected) 60 | } 61 | } 62 | } 63 | -------------------------------------------------------------------------------- /src/test/scala/com/github/krasserm/ases/log/KafkaServer.scala: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2017 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.github.krasserm.ases.log 18 | 19 | import net.manub.embeddedkafka.{EmbeddedKafka, EmbeddedKafkaConfig} 20 | 21 | object KafkaServer { 22 | import EmbeddedKafkaConfig.defaultConfig 23 | 24 | def kafkaPort: Int = 25 | defaultConfig.kafkaPort 26 | 27 | def zookeeperPort: Int = 28 | defaultConfig.zooKeeperPort 29 | 30 | def start(): Unit = 31 | EmbeddedKafka.start()(defaultConfig.copy(customBrokerProperties = Map("num.partitions" -> "1"))) 32 | 33 | def stop(): Unit = 34 | EmbeddedKafka.stop() 35 | } 36 | 37 | object KafkaServerApp extends App { 38 | KafkaServer.start() 39 | } 40 | -------------------------------------------------------------------------------- /src/test/scala/com/github/krasserm/ases/log/KafkaSpec.scala: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2017 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.github.krasserm.ases.log 18 | 19 | import akka.testkit.TestKit 20 | import org.scalatest.{BeforeAndAfterAll, Suite} 21 | 22 | trait KafkaSpec extends BeforeAndAfterAll { this: TestKit with Suite => 23 | override protected def beforeAll(): Unit = { 24 | super.beforeAll() 25 | KafkaServer.start() 26 | } 27 | 28 | override def afterAll(): Unit = { 29 | KafkaServer.stop() 30 | super.afterAll() 31 | } 32 | 33 | def host: String = 34 | "localhost" 35 | 36 | def port: Int = 37 | KafkaServer.kafkaPort 38 | } 39 | -------------------------------------------------------------------------------- /src/test/scala/com/github/krasserm/ases/serializer/EmittedSerializerSpec.scala: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2017 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.github.krasserm.ases.serializer 18 | 19 | import java.io.NotSerializableException 20 | 21 | import akka.actor.ActorSystem 22 | import akka.serialization.{SerializationExtension, Serializer, SerializerWithStringManifest} 23 | import akka.testkit.TestKit 24 | import com.github.krasserm.ases.{Emitted, SpecWords, StopSystemAfterAll} 25 | import com.google.protobuf 26 | import org.scalatest.{MustMatchers, WordSpecLike} 27 | 28 | object EmittedSerializerSpec { 29 | 30 | case class StringManifestEvent(id: String) 31 | 32 | case class ClassManifestEvent(id: String) 33 | 34 | case class EmptyManifestEvent(id: String) 35 | 36 | case class PlainEvent(id: String) 37 | 38 | class StringManifestEventSerializer extends SerializerWithStringManifest { 39 | val Manifest = "v1.Event" 40 | 41 | override def identifier: Int = 11111101 42 | 43 | override def manifest(o: AnyRef): String = Manifest 44 | 45 | override def toBinary(o: AnyRef): Array[Byte] = o match { 46 | case e: StringManifestEvent => e.id.getBytes 47 | case _ => throw new IllegalArgumentException(s"Object of type '${o.getClass}' not supported") 48 | } 49 | 50 | override def fromBinary(bytes: Array[Byte], manifest: String): AnyRef = manifest match { 51 | case Manifest => StringManifestEvent(new String(bytes)) 52 | case _ => throw new IllegalArgumentException(s"Object for manifest '$manifest' not supported") 53 | } 54 | } 55 | 56 | class ClassManifestEventSerializer extends Serializer { 57 | val ClassManifest = classOf[ClassManifestEvent] 58 | 59 | override def identifier: Int = 11111102 60 | 61 | override def includeManifest: Boolean = true 62 | 63 | override def toBinary(o: AnyRef): Array[Byte] = o match { 64 | case e: ClassManifestEvent => e.id.getBytes 65 | case _ => throw new IllegalArgumentException(s"Object of type '${o.getClass}' not supported") 66 | } 67 | 68 | override def fromBinary(bytes: Array[Byte], manifest: Option[Class[_]]): AnyRef = manifest match { 69 | case Some(`ClassManifest`) => ClassManifestEvent(new String(bytes)) 70 | case None => throw new IllegalArgumentException(s"No class manifest provided") 71 | case _ => throw new IllegalArgumentException(s"Object for manifest '$manifest' not supported") 72 | } 73 | } 74 | 75 | class EmptyManifestEventSerializer extends Serializer { 76 | 77 | override def identifier: Int = 11111103 78 | 79 | override def includeManifest: Boolean = false 80 | 81 | override def toBinary(o: AnyRef): Array[Byte] = o match { 82 | case e: EmptyManifestEvent => e.id.getBytes 83 | case _ => throw new IllegalArgumentException(s"Object of type '${o.getClass}' not supported") 84 | } 85 | 86 | override def fromBinary(bytes: Array[Byte], manifest: Option[Class[_]]): AnyRef = 87 | EmptyManifestEvent(new String(bytes)) 88 | } 89 | } 90 | 91 | class EmittedSerializerSpec extends TestKit(ActorSystem("test")) with WordSpecLike with MustMatchers with SpecWords with StopSystemAfterAll { 92 | 93 | import EmittedSerializerSpec._ 94 | 95 | val serialization = SerializationExtension(system) 96 | val emittedSerializer = serialization.serializerFor(classOf[Emitted[_]]) 97 | 98 | def emitted[A](event: A): Emitted[A] = 99 | Emitted(event, "emitter-1") 100 | 101 | def serialize[A](emitted: Emitted[A]): Array[Byte] = 102 | emittedSerializer.toBinary(emitted) 103 | 104 | def deserialize[A](bytes: Array[Byte]): Emitted[A] = 105 | emittedSerializer.fromBinary(bytes, classOf[Emitted[_]]).asInstanceOf[Emitted[A]] 106 | 107 | def emittedSerializations[A](event: A): Unit = { 108 | "serialize and deserialize the Emitted event with the given payload" in { 109 | val original = emitted(event) 110 | 111 | val bytes = serialize(original) 112 | val deserialized = deserialize(bytes) 113 | 114 | deserialized mustBe original 115 | } 116 | } 117 | 118 | "An EmittedSerializer" when { 119 | "serializing an object" that is { 120 | "an Emitted event" which { 121 | "contains an event payload assigned to a serializer" which isA { 122 | "SerializerWithStringManifest" must { 123 | behave like emittedSerializations(StringManifestEvent("ev-1")) 124 | } 125 | "Serializer with class-manifest" must { 126 | behave like emittedSerializations(ClassManifestEvent("ev-1")) 127 | } 128 | "Serializer with an empty manifest" must { 129 | behave like emittedSerializations(EmptyManifestEvent("ev-1")) 130 | } 131 | "JavaSerializer" must { 132 | behave like emittedSerializations(PlainEvent("ev-1")) 133 | } 134 | } 135 | } 136 | "an invalid object" must { 137 | "throw an IllegalArgumentException" in { 138 | intercept[IllegalArgumentException] { 139 | emittedSerializer.toBinary("invalid-object") 140 | } 141 | } 142 | } 143 | } 144 | "deserializing a byte-array" that contains { 145 | "an invalid binary representation" must { 146 | "throw a NotSerializableException" in { 147 | intercept[protobuf.InvalidProtocolBufferException] { 148 | emittedSerializer.fromBinary("invalid-binary-representation".getBytes, classOf[Emitted[_]]) 149 | } 150 | } 151 | } 152 | "a valid binary representation" when invokedWith { 153 | val original = emitted(StringManifestEvent("ev-1")) 154 | 155 | "an empty manifest" must { 156 | "deserialize the Emitted event" in { 157 | val deserialized = emittedSerializer.fromBinary(serialize(original), manifest = None) 158 | 159 | deserialized mustBe original 160 | } 161 | } 162 | "an unsupported manifest" must { 163 | "throw a NotSerializableException" in { 164 | intercept[NotSerializableException] { 165 | emittedSerializer.fromBinary(serialize(original), manifest = Some(classOf[String])) 166 | } 167 | } 168 | } 169 | } 170 | } 171 | } 172 | } 173 | --------------------------------------------------------------------------------