├── .gitignore ├── COPYING ├── LICENSE ├── README.md ├── activator.properties ├── build.sbt ├── example ├── example-location ├── project ├── build.properties └── plugins.sbt ├── src ├── main │ ├── resources │ │ ├── common.conf │ │ ├── location-A.conf │ │ ├── location-B.conf │ │ ├── location-C.conf │ │ ├── location-D.conf │ │ ├── location-E.conf │ │ ├── location-F.conf │ │ └── logback.xml │ └── scala │ │ └── sample │ │ └── eventuate │ │ ├── Order.scala │ │ ├── OrderActor.scala │ │ ├── OrderBot.scala │ │ ├── OrderExample.scala │ │ ├── OrderLocation.scala │ │ ├── OrderLogging.scala │ │ ├── OrderManager.scala │ │ ├── OrderView.scala │ │ └── package.scala └── multi-jvm │ └── scala │ └── sample │ └── eventuate │ └── OrderSpec.scala └── tutorial └── index.html /.gitignore: -------------------------------------------------------------------------------- 1 | *# 2 | *.iml 3 | *.ipr 4 | *.iws 5 | *.pyc 6 | *.tm.epoch 7 | *.vim 8 | */project/boot 9 | */project/build/target 10 | */project/project.target.config-classes 11 | *-shim.sbt 12 | *~ 13 | .#* 14 | .*.swp 15 | .DS_Store 16 | .cache 17 | .cache 18 | .classpath 19 | .codefellow 20 | .ensime* 21 | .eprj 22 | .history 23 | .idea 24 | .manager 25 | .multi-jvm 26 | .project 27 | .sbtserver* 28 | .scala_dependencies 29 | .scalastyle 30 | .settings 31 | .tags 32 | .tags_sorted_by_file 33 | .target 34 | .worksheet 35 | Makefile 36 | TAGS 37 | lib_managed 38 | logs 39 | project/boot/* 40 | project/plugins/project 41 | src_managed 42 | target 43 | tm*.lck 44 | tm*.log 45 | tm.out 46 | worker*.log 47 | /bin 48 | -------------------------------------------------------------------------------- /COPYING: -------------------------------------------------------------------------------- 1 | Creative Commons Legal Code 2 | 3 | CC0 1.0 Universal 4 | 5 | CREATIVE COMMONS CORPORATION IS NOT A LAW FIRM AND DOES NOT PROVIDE 6 | LEGAL SERVICES. DISTRIBUTION OF THIS DOCUMENT DOES NOT CREATE AN 7 | ATTORNEY-CLIENT RELATIONSHIP. CREATIVE COMMONS PROVIDES THIS 8 | INFORMATION ON AN "AS-IS" BASIS. CREATIVE COMMONS MAKES NO WARRANTIES 9 | REGARDING THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS 10 | PROVIDED HEREUNDER, AND DISCLAIMS LIABILITY FOR DAMAGES RESULTING FROM 11 | THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS PROVIDED 12 | HEREUNDER. 13 | 14 | Statement of Purpose 15 | 16 | The laws of most jurisdictions throughout the world automatically confer 17 | exclusive Copyright and Related Rights (defined below) upon the creator 18 | and subsequent owner(s) (each and all, an "owner") of an original work of 19 | authorship and/or a database (each, a "Work"). 20 | 21 | Certain owners wish to permanently relinquish those rights to a Work for 22 | the purpose of contributing to a commons of creative, cultural and 23 | scientific works ("Commons") that the public can reliably and without fear 24 | of later claims of infringement build upon, modify, incorporate in other 25 | works, reuse and redistribute as freely as possible in any form whatsoever 26 | and for any purposes, including without limitation commercial purposes. 27 | These owners may contribute to the Commons to promote the ideal of a free 28 | culture and the further production of creative, cultural and scientific 29 | works, or to gain reputation or greater distribution for their Work in 30 | part through the use and efforts of others. 31 | 32 | For these and/or other purposes and motivations, and without any 33 | expectation of additional consideration or compensation, the person 34 | associating CC0 with a Work (the "Affirmer"), to the extent that he or she 35 | is an owner of Copyright and Related Rights in the Work, voluntarily 36 | elects to apply CC0 to the Work and publicly distribute the Work under its 37 | terms, with knowledge of his or her Copyright and Related Rights in the 38 | Work and the meaning and intended legal effect of CC0 on those rights. 39 | 40 | 1. Copyright and Related Rights. A Work made available under CC0 may be 41 | protected by copyright and related or neighboring rights ("Copyright and 42 | Related Rights"). Copyright and Related Rights include, but are not 43 | limited to, the following: 44 | 45 | i. the right to reproduce, adapt, distribute, perform, display, 46 | communicate, and translate a Work; 47 | ii. moral rights retained by the original author(s) and/or performer(s); 48 | iii. publicity and privacy rights pertaining to a person's image or 49 | likeness depicted in a Work; 50 | iv. rights protecting against unfair competition in regards to a Work, 51 | subject to the limitations in paragraph 4(a), below; 52 | v. rights protecting the extraction, dissemination, use and reuse of data 53 | in a Work; 54 | vi. database rights (such as those arising under Directive 96/9/EC of the 55 | European Parliament and of the Council of 11 March 1996 on the legal 56 | protection of databases, and under any national implementation 57 | thereof, including any amended or successor version of such 58 | directive); and 59 | vii. other similar, equivalent or corresponding rights throughout the 60 | world based on applicable law or treaty, and any national 61 | implementations thereof. 62 | 63 | 2. Waiver. To the greatest extent permitted by, but not in contravention 64 | of, applicable law, Affirmer hereby overtly, fully, permanently, 65 | irrevocably and unconditionally waives, abandons, and surrenders all of 66 | Affirmer's Copyright and Related Rights and associated claims and causes 67 | of action, whether now known or unknown (including existing as well as 68 | future claims and causes of action), in the Work (i) in all territories 69 | worldwide, (ii) for the maximum duration provided by applicable law or 70 | treaty (including future time extensions), (iii) in any current or future 71 | medium and for any number of copies, and (iv) for any purpose whatsoever, 72 | including without limitation commercial, advertising or promotional 73 | purposes (the "Waiver"). Affirmer makes the Waiver for the benefit of each 74 | member of the public at large and to the detriment of Affirmer's heirs and 75 | successors, fully intending that such Waiver shall not be subject to 76 | revocation, rescission, cancellation, termination, or any other legal or 77 | equitable action to disrupt the quiet enjoyment of the Work by the public 78 | as contemplated by Affirmer's express Statement of Purpose. 79 | 80 | 3. Public License Fallback. Should any part of the Waiver for any reason 81 | be judged legally invalid or ineffective under applicable law, then the 82 | Waiver shall be preserved to the maximum extent permitted taking into 83 | account Affirmer's express Statement of Purpose. In addition, to the 84 | extent the Waiver is so judged Affirmer hereby grants to each affected 85 | person a royalty-free, non transferable, non sublicensable, non exclusive, 86 | irrevocable and unconditional license to exercise Affirmer's Copyright and 87 | Related Rights in the Work (i) in all territories worldwide, (ii) for the 88 | maximum duration provided by applicable law or treaty (including future 89 | time extensions), (iii) in any current or future medium and for any number 90 | of copies, and (iv) for any purpose whatsoever, including without 91 | limitation commercial, advertising or promotional purposes (the 92 | "License"). The License shall be deemed effective as of the date CC0 was 93 | applied by Affirmer to the Work. Should any part of the License for any 94 | reason be judged legally invalid or ineffective under applicable law, such 95 | partial invalidity or ineffectiveness shall not invalidate the remainder 96 | of the License, and in such case Affirmer hereby affirms that he or she 97 | will not (i) exercise any of his or her remaining Copyright and Related 98 | Rights in the Work or (ii) assert any associated claims and causes of 99 | action with respect to the Work, in either case contrary to Affirmer's 100 | express Statement of Purpose. 101 | 102 | 4. Limitations and Disclaimers. 103 | 104 | a. No trademark or patent rights held by Affirmer are waived, abandoned, 105 | surrendered, licensed or otherwise affected by this document. 106 | b. Affirmer offers the Work as-is and makes no representations or 107 | warranties of any kind concerning the Work, express, implied, 108 | statutory or otherwise, including without limitation warranties of 109 | title, merchantability, fitness for a particular purpose, non 110 | infringement, or the absence of latent or other defects, accuracy, or 111 | the present or absence of errors, whether or not discoverable, all to 112 | the greatest extent permissible under applicable law. 113 | c. Affirmer disclaims responsibility for clearing rights of other persons 114 | that may apply to the Work or any use thereof, including without 115 | limitation any person's Copyright and Related Rights in the Work. 116 | Further, Affirmer disclaims responsibility for obtaining any necessary 117 | consents, permissions or other rights required for any use of the 118 | Work. 119 | d. Affirmer understands and acknowledges that Creative Commons is not a 120 | party to this document and has no duty or obligation with respect to 121 | this CC0 or use of the Work. 122 | -------------------------------------------------------------------------------- /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 | 203 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | akka-eventuate-scala 2 | ==================== 3 | 4 | [Activator](https://www.typesafe.com/community/core-tools/activator-and-sbt) tutorial-template for 5 | [eventuate](https://github.com/RBMHTechnology/eventuate). 6 | [Submitted](https://www.typesafe.com/activator/template/akka-eventuate-scala) to activator-catalog 7 | so you can open it simply through the activator ui (filter by "eventuate"). -------------------------------------------------------------------------------- /activator.properties: -------------------------------------------------------------------------------- 1 | name=akka-eventuate-scala 2 | title=eventuate with Scala! 3 | description=Illustrates eventsourced distributed application based on eventuate 4 | authorLink=http://volkersyadb.blogspot.de/ 5 | tags=akka,scala,sample,eventuate 6 | authorTwitter=VolkerStampa -------------------------------------------------------------------------------- /build.sbt: -------------------------------------------------------------------------------- 1 | import com.typesafe.sbt.SbtMultiJvm 2 | import com.typesafe.sbt.SbtMultiJvm.MultiJvmKeys.MultiJvm 3 | 4 | val akkaVersion = "2.4.12" 5 | 6 | val project = Project( 7 | id = "akka-eventuate-scala", 8 | base = file("."), 9 | settings = Defaults.coreDefaultSettings ++ SbtMultiJvm.multiJvmSettings ++ Seq( 10 | name := "akka-eventuate-scala", 11 | version := "0.8-SNAPSHOT", 12 | scalaVersion := "2.11.8", 13 | resolvers += "Eventuate Releases" at "https://dl.bintray.com/rbmhtechnology/maven", 14 | libraryDependencies ++= Seq( 15 | "com.rbmhtechnology" %% "eventuate-core" % "0.8", 16 | "com.rbmhtechnology" %% "eventuate-log-leveldb" % "0.8", 17 | "com.typesafe.akka" %% "akka-slf4j" % akkaVersion, 18 | "ch.qos.logback" % "logback-classic" % "1.1.6", 19 | "com.typesafe.akka" %% "akka-multi-node-testkit" % akkaVersion % Test, 20 | "org.scalatest" %% "scalatest" % "2.2.6" % Test), 21 | // make sure that MultiJvm test are compiled by the default test compilation 22 | compile in MultiJvm <<= (compile in MultiJvm) triggeredBy (compile in Test), 23 | // disable parallel tests 24 | parallelExecution in Test := false, 25 | fork in run := true, 26 | Keys.connectInput in run := true, 27 | mainClass in (Compile, run) := Some("sample.eventuate.OrderBot"), 28 | // make sure that MultiJvm tests are executed by the default test target, 29 | // and combine the results from ordinary test and multi-jvm tests 30 | executeTests in Test <<= (executeTests in Test, executeTests in MultiJvm) map { 31 | case (testResults, multiNodeResults) => 32 | val overall = 33 | if (testResults.overall.id < multiNodeResults.overall.id) 34 | multiNodeResults.overall 35 | else 36 | testResults.overall 37 | Tests.Output(overall, 38 | testResults.events ++ multiNodeResults.events, 39 | testResults.summaries ++ multiNodeResults.summaries) 40 | } 41 | ) 42 | ) configs MultiJvm 43 | 44 | 45 | fork in run := true -------------------------------------------------------------------------------- /example: -------------------------------------------------------------------------------- 1 | #!/bin/bash -eu 2 | 3 | locations="${*:-A B C D E F}" 4 | 5 | sbt test:compile 6 | 7 | for location in $locations 8 | do 9 | if command -v osascript >/dev/null 2>&1; then 10 | osascript -e "tell app \"Terminal\" 11 | do script \"cd `pwd`; ./example-location $location\" 12 | end tell" 13 | else 14 | if command -v xterm >/dev/null 2>&1; then 15 | xterm -title $location -e "./example-location $location" & 16 | else 17 | echo "Neiter osascript nor xterm were found"; 18 | fi 19 | fi 20 | sleep 5 21 | done 22 | -------------------------------------------------------------------------------- /example-location: -------------------------------------------------------------------------------- 1 | #!/bin/bash -eu 2 | 3 | EXAMPLE_CONF=location-$1.conf 4 | EXAMPLE_MAIN=sample.eventuate.OrderExample 5 | 6 | sbt "test:runMain $EXAMPLE_MAIN $EXAMPLE_CONF" 7 | -------------------------------------------------------------------------------- /project/build.properties: -------------------------------------------------------------------------------- 1 | sbt.version=0.13.8 2 | -------------------------------------------------------------------------------- /project/plugins.sbt: -------------------------------------------------------------------------------- 1 | addSbtPlugin("com.typesafe.sbt" % "sbt-multi-jvm" % "0.3.11") 2 | -------------------------------------------------------------------------------- /src/main/resources/common.conf: -------------------------------------------------------------------------------- 1 | akka { 2 | loglevel = INFO 3 | stdout-loglevel = OFF 4 | loggers = ["akka.event.slf4j.Slf4jLogger"] 5 | log-dead-letters = 0 6 | actor { 7 | provider = "akka.remote.RemoteActorRefProvider" 8 | enabled-transports = ["akka.remote.netty.tcp"] 9 | } 10 | 11 | remote { 12 | log-remote-lifecycle-events = off 13 | } 14 | } 15 | 16 | eventuate.cli-dispatcher { 17 | executor = "thread-pool-executor" 18 | type = PinnedDispatcher 19 | } 20 | -------------------------------------------------------------------------------- /src/main/resources/location-A.conf: -------------------------------------------------------------------------------- 1 | include "common" 2 | 3 | akka.remote.netty.tcp.hostname = "127.0.0.1" 4 | akka.remote.netty.tcp.port=2552 5 | 6 | eventuate { 7 | endpoint.id = "A" 8 | endpoint.connections = ["127.0.0.1:2554"] 9 | } -------------------------------------------------------------------------------- /src/main/resources/location-B.conf: -------------------------------------------------------------------------------- 1 | include "common" 2 | 3 | akka.remote.netty.tcp.hostname = "127.0.0.1" 4 | akka.remote.netty.tcp.port=2553 5 | 6 | eventuate { 7 | endpoint.id = "B" 8 | endpoint.connections = ["127.0.0.1:2554"] 9 | } -------------------------------------------------------------------------------- /src/main/resources/location-C.conf: -------------------------------------------------------------------------------- 1 | include "common" 2 | 3 | akka.remote.netty.tcp.hostname = "127.0.0.1" 4 | akka.remote.netty.tcp.port=2554 5 | 6 | eventuate { 7 | endpoint.id = "C" 8 | endpoint.connections = ["127.0.0.1:2552", "127.0.0.1:2553", "127.0.0.1:2555"] 9 | } -------------------------------------------------------------------------------- /src/main/resources/location-D.conf: -------------------------------------------------------------------------------- 1 | include "common" 2 | 3 | akka.remote.netty.tcp.hostname = "127.0.0.1" 4 | akka.remote.netty.tcp.port=2555 5 | 6 | eventuate { 7 | endpoint.id = "D" 8 | endpoint.connections = ["127.0.0.1:2554", "127.0.0.1:2556", "127.0.0.1:2557"] 9 | } -------------------------------------------------------------------------------- /src/main/resources/location-E.conf: -------------------------------------------------------------------------------- 1 | include "common" 2 | 3 | akka.remote.netty.tcp.hostname = "127.0.0.1" 4 | akka.remote.netty.tcp.port=2556 5 | 6 | eventuate { 7 | endpoint.id = "E" 8 | endpoint.connections = ["127.0.0.1:2555"] 9 | } -------------------------------------------------------------------------------- /src/main/resources/location-F.conf: -------------------------------------------------------------------------------- 1 | include "common" 2 | 3 | akka.remote.netty.tcp.hostname = "127.0.0.1" 4 | akka.remote.netty.tcp.port=2557 5 | 6 | eventuate { 7 | endpoint.id = "F" 8 | endpoint.connections = ["127.0.0.1:2555"] 9 | } 10 | -------------------------------------------------------------------------------- /src/main/resources/logback.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | %d{HH:mm:ss.SSS} %logger{0}: %msg%n 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | -------------------------------------------------------------------------------- /src/main/scala/sample/eventuate/Order.scala: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2015 - 2016 Red Bull Media House GmbH - all rights reserved. 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 sample.eventuate 18 | 19 | //#order-definition 20 | case class Order(id: String, items: List[String] = Nil, cancelled: Boolean = false) { 21 | def addItem(item: String): Order = 22 | copy(items = item :: items) 23 | 24 | def removeItem(item: String): Order = 25 | copy(items = items.filterNot(_ == item)) 26 | 27 | def cancel: Order = 28 | copy(cancelled = true) 29 | 30 | override def toString() = 31 | s"[${id}] items=${items.reverse.mkString(",")} cancelled=${cancelled}" 32 | } 33 | //# 34 | -------------------------------------------------------------------------------- /src/main/scala/sample/eventuate/OrderActor.scala: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2015 - 2016 Red Bull Media House GmbH - all rights reserved. 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 sample.eventuate 18 | 19 | import akka.actor._ 20 | 21 | import com.rbmhtechnology.eventuate._ 22 | import com.rbmhtechnology.eventuate.VersionedAggregate._ 23 | 24 | import scala.util._ 25 | 26 | object OrderActor { 27 | trait OrderCommand { 28 | def orderId: String 29 | def event: OrderEvent 30 | } 31 | 32 | trait OrderEvent { 33 | def orderId: String 34 | } 35 | 36 | // Order commands 37 | case class CreateOrder(orderId: String) extends OrderCommand { val event = OrderCreated(orderId) } 38 | case class CancelOrder(orderId: String) extends OrderCommand { val event = OrderCancelled(orderId) } 39 | case class AddOrderItem(orderId: String, item: String) extends OrderCommand { val event = OrderItemAdded(orderId, item) } 40 | case class RemoveOrderItem(orderId: String, item: String) extends OrderCommand { val event = OrderItemRemoved(orderId, item) } 41 | 42 | // Order events 43 | case class OrderCreated(orderId: String, creator: String = "") extends OrderEvent 44 | case class OrderItemAdded(orderId: String, item: String) extends OrderEvent 45 | case class OrderItemRemoved(orderId: String, item: String) extends OrderEvent 46 | case class OrderCancelled(orderId: String) extends OrderEvent 47 | 48 | // Order queries + replies 49 | case object GetState 50 | case class GetStateSuccess(state: Map[String, Seq[Versioned[Order]]]) 51 | case class GetStateFailure(cause: Throwable) 52 | 53 | // General replies 54 | case class CommandSuccess(orderId: String) 55 | case class CommandFailure(orderId: String, cause: Throwable) 56 | 57 | // Snapshot command and replies 58 | case class SaveSnapshot(orderId: String) 59 | case class SaveSnapshotSuccess(orderId: String, metadata: SnapshotMetadata) 60 | case class SaveSnapshotFailure(orderId: String, cause: Throwable) 61 | 62 | implicit object OrderDomainCmd extends DomainCmd[OrderCommand] { 63 | override def origin(cmd: OrderCommand): String = "" 64 | } 65 | 66 | implicit object OrderDomainEvt extends DomainEvt[OrderEvent] { 67 | override def origin(evt: OrderEvent): String = evt match { 68 | case OrderCreated(_, creator) => creator 69 | case _ => "" 70 | } 71 | } 72 | } 73 | 74 | /** 75 | * An event-sourced actor that manages a single order aggregate, identified by `orderId`. 76 | */ 77 | class OrderActor(orderId: String, val replicaId: String, val eventLog: ActorRef) extends EventsourcedActor with OrderLogging { 78 | import OrderActor._ 79 | 80 | override val id = s"s-${orderId}-${replicaId}" 81 | override val aggregateId = Some(orderId) 82 | 83 | private var order = VersionedAggregate(orderId, commandValidation, eventProjection) 84 | 85 | override def onCommand = { 86 | case c: CreateOrder => 87 | processValidationResult(c.orderId, order.validateCreate(c)) 88 | case c: OrderCommand => 89 | processValidationResult(c.orderId, order.validateUpdate(c)) 90 | case c: Resolve => 91 | processValidationResult(c.id, order.validateResolve(c.selected, replicaId)) 92 | case GetState => 93 | val reply = order.aggregate match { 94 | case Some(aggregate) => GetStateSuccess(Map(orderId -> aggregate.all)) 95 | case None => GetStateSuccess(Map.empty) 96 | } 97 | sender() ! reply 98 | case c: SaveSnapshot => order.aggregate match { 99 | case None => 100 | sender() ! SaveSnapshotFailure(orderId, new AggregateDoesNotExistException(orderId)) 101 | case Some(aggregate) => 102 | save(aggregate) { 103 | case Success(m) => sender() ! SaveSnapshotSuccess(orderId, m) 104 | case Failure(e) => sender() ! SaveSnapshotFailure(orderId, e) 105 | } 106 | } 107 | } 108 | 109 | override def onEvent = { 110 | case e: OrderCreated => 111 | order = order.handleCreated(e, lastVectorTimestamp, lastSequenceNr) 112 | info(s"${e.getClass.getSimpleName}: ${printOrder(order.versions)}") 113 | case e: OrderEvent => 114 | order = order.handleUpdated(e, lastVectorTimestamp, lastSequenceNr) 115 | info(s"${e.getClass.getSimpleName}: ${printOrder(order.versions)}") 116 | case e: Resolved => 117 | order = order.handleResolved(e, lastVectorTimestamp, lastSequenceNr) 118 | info(s"Resolved Conflict, keep: ${printOrder(order.versions)}") 119 | } 120 | 121 | override def onSnapshot = { 122 | case aggregate: ConcurrentVersionsTree[Order, OrderEvent] => 123 | order = order.withAggregate(aggregate.withProjection(eventProjection)) 124 | println(s"[$orderId] Snapshot loaded:") 125 | printOrder(order.versions) 126 | } 127 | 128 | override def onRecovery() = { 129 | case Success(()) => if (order.versions.nonEmpty) info(s"Initialized from Log: ${printOrder(order.versions)}") 130 | case Failure(ex) => 131 | } 132 | 133 | private def processValidationResult(orderId: String, result: Try[Any]): Unit = result match { 134 | case Failure(err) => 135 | sender() ! CommandFailure(orderId, err) 136 | case Success(evt) => persist(evt) { 137 | case Success(e) => sender() ! CommandSuccess(orderId) 138 | case Failure(e) => sender() ! CommandFailure(orderId, e) 139 | } 140 | } 141 | 142 | private def commandValidation: (Order, OrderCommand) => Try[OrderEvent] = { 143 | case (_, c: CreateOrder) => Success(c.event.copy(creator = replicaId)) 144 | case (_, c: OrderCommand) => Success(c.event) 145 | } 146 | 147 | private def eventProjection: (Order, OrderEvent) => Order = { 148 | case (_ , OrderCreated(`orderId`, _)) => Order(orderId) 149 | case (order, OrderCancelled(`orderId`)) => order.cancel 150 | case (order, OrderItemAdded(`orderId`, item)) => order.addItem(item) 151 | case (order, OrderItemRemoved(`orderId`, item)) => order.removeItem(item) 152 | } 153 | } 154 | -------------------------------------------------------------------------------- /src/main/scala/sample/eventuate/OrderBot.scala: -------------------------------------------------------------------------------- 1 | package sample.eventuate 2 | 3 | import java.util.UUID 4 | 5 | import akka.util.Timeout 6 | import akka.pattern.ask 7 | import OrderActor._ 8 | import org.slf4j.LoggerFactory 9 | 10 | import scala.concurrent.Await 11 | import scala.concurrent.duration.DurationInt 12 | import scala.util.Random 13 | 14 | object OrderBot extends App { 15 | 16 | val locations = List( 17 | new OrderLocation("location-C"), 18 | new OrderLocation("location-D")) 19 | val actions = List( 20 | CreateOrderAction, CreateOrderAction, 21 | AddOrderItemAction, AddOrderItemAction, 22 | CreateOrderAction, AddOrderItemAction, 23 | RemoveOrderItemAction, CancelOrderAction) 24 | 25 | for(i <- 0 to Action.total) { 26 | val currentLocation = locations(i % locations.size) 27 | val action = actions(i % actions.size) 28 | action.execute(currentLocation, i) 29 | Thread.sleep(3000) 30 | } 31 | locations.foreach(loc => Await.result(loc.system.terminate(), 5.seconds)) 32 | } 33 | 34 | trait Action { 35 | val log = LoggerFactory.getLogger(getClass) 36 | val askTimeoutDuration = 3.seconds 37 | implicit val askTimeout = Timeout(askTimeoutDuration) 38 | def execute(location: OrderLocation, i: Int): Unit 39 | 40 | def newOrderId: String = UUID.randomUUID().toString 41 | 42 | def pickOrder(location: OrderLocation, i: Int): Option[Order] = 43 | Await.result(location.manager ? GetState, askTimeoutDuration) match { 44 | case GetStateSuccess(state) => for { 45 | order <- state.values.toSeq.drop((i - 1) % state.size.max(1)).headOption 46 | firstVersion <- order.headOption 47 | } yield firstVersion.value 48 | case GetStateFailure(cause) => 49 | None 50 | } 51 | 52 | def pickItem(order: Order, i: Int): Option[String] = 53 | order.items.drop((i - 1) % order.items.size.max(1)).headOption 54 | 55 | protected def sendCommand(command: OrderCommand, destination: OrderLocation, i: Int): Unit = { 56 | log.info(s"------- Send ${command.getClass.getSimpleName} to ${destination.locationId} ($i/${Action.total}) --------") 57 | destination.manager ! command 58 | } 59 | } 60 | 61 | object Action { 62 | val total = 199 63 | } 64 | 65 | object CreateOrderAction extends Action { 66 | override def execute(location: OrderLocation, i: Int): Unit = 67 | sendCommand(CreateOrder(newOrderId), location, i) 68 | } 69 | 70 | object AddOrderItemAction extends Action { 71 | override def execute(location: OrderLocation, i: Int): Unit = 72 | pickOrder(location, i).foreach { order => 73 | sendCommand(AddOrderItem(order.id, generateItem), location, i) 74 | } 75 | 76 | private def generateItem: String = Random.alphanumeric.take(5).mkString 77 | } 78 | 79 | object CancelOrderAction extends Action { 80 | override def execute(location: OrderLocation, i: Int) = 81 | pickOrder(location, i).foreach { order => 82 | sendCommand(CancelOrder(order.id), location, i) 83 | } 84 | } 85 | 86 | object RemoveOrderItemAction extends Action { 87 | override def execute(location: OrderLocation, i: Int): Unit = for { 88 | order <- pickOrder(location, i) 89 | item <- pickItem(order, i) 90 | } sendCommand(RemoveOrderItem(order.id, item), location, i) 91 | } -------------------------------------------------------------------------------- /src/main/scala/sample/eventuate/OrderExample.scala: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2015 - 2016 Red Bull Media House GmbH - all rights reserved. 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 sample.eventuate 18 | 19 | import akka.actor._ 20 | 21 | import com.rbmhtechnology.eventuate._ 22 | import com.rbmhtechnology.eventuate.VersionedAggregate._ 23 | 24 | import scala.io.Source 25 | 26 | class OrderExample(manager: ActorRef, view: ActorRef) extends Actor { 27 | import OrderActor._ 28 | import OrderView._ 29 | 30 | val lines = Source.stdin.getLines 31 | 32 | def receive = { 33 | case GetStateSuccess(state) => 34 | state.values.foreach(printOrder) 35 | prompt() 36 | case GetStateFailure(cause) => 37 | println(cause.getMessage) 38 | prompt() 39 | case SaveSnapshotSuccess(orderId, metadata) => 40 | println(s"[${orderId}] saved snapshot at sequence number ${metadata.sequenceNr}") 41 | prompt() 42 | case SaveSnapshotFailure(orderId, cause) => 43 | println(s"[${orderId}] save snapshot failed: ${cause}") 44 | cause.printStackTrace() 45 | prompt() 46 | case GetUpdateCountSuccess(orderId, count) => 47 | println(s"[${orderId}] update count = ${count}") 48 | prompt() 49 | case CommandSuccess(_) => 50 | prompt() 51 | case CommandFailure(_, cause: ConflictDetectedException[Order]) => 52 | println(s"${cause.getMessage}, select one of the following versions to resolve conflict") 53 | printOrder(cause.versions) 54 | prompt() 55 | case CommandFailure(_, cause) => 56 | println(cause.getMessage) 57 | prompt() 58 | case line: String => line.split(' ').toList match { 59 | case "state" :: Nil => manager ! GetState 60 | case "count" :: id :: Nil => view ! GetUpdateCount(id) 61 | case "create" :: id :: Nil => manager ! CreateOrder(id) 62 | case "cancel" :: id :: Nil => manager ! CancelOrder(id) 63 | case "save" :: id :: Nil => manager ! SaveSnapshot(id) 64 | case "add" :: id :: item :: Nil => manager ! AddOrderItem(id, item) 65 | case "remove" :: id :: item :: Nil => manager ! RemoveOrderItem(id, item) 66 | case "resolve" :: id :: idx :: Nil => manager ! Resolve(id, idx.toInt) 67 | case Nil => prompt() 68 | case "" :: Nil => prompt() 69 | case na :: nas => println(s"unknown command: ${na}"); prompt() 70 | } 71 | } 72 | 73 | def prompt(): Unit = { 74 | if (lines.hasNext) lines.next() match { 75 | case "exit" => context.system.terminate() 76 | case line => self ! line 77 | } 78 | } 79 | 80 | override def preStart(): Unit = 81 | prompt() 82 | } 83 | 84 | object OrderExample extends App { 85 | val orderLocation = new OrderLocation(args(0)) 86 | val driver = orderLocation.system.actorOf( 87 | Props(new OrderExample(orderLocation.manager, orderLocation.view)) 88 | .withDispatcher("eventuate.cli-dispatcher")) 89 | } 90 | 91 | -------------------------------------------------------------------------------- /src/main/scala/sample/eventuate/OrderLocation.scala: -------------------------------------------------------------------------------- 1 | package sample.eventuate 2 | 3 | import akka.actor.{ActorSystem, Props} 4 | import com.rbmhtechnology.eventuate.ReplicationConnection.DefaultRemoteSystemName 5 | import com.rbmhtechnology.eventuate.ReplicationEndpoint 6 | import com.rbmhtechnology.eventuate.ReplicationEndpoint.DefaultLogName 7 | import com.rbmhtechnology.eventuate.log.leveldb.LeveldbEventLog 8 | import com.typesafe.config.ConfigFactory 9 | 10 | class OrderLocation(val locationId: String) { 11 | val system = ActorSystem(DefaultRemoteSystemName, ConfigFactory.load(locationId)) 12 | val endpoint = ReplicationEndpoint(id => LeveldbEventLog.props(id))(system) 13 | endpoint.activate() 14 | val manager = system.actorOf( 15 | Props(new OrderManager(endpoint.id, endpoint.logs(DefaultLogName)))) 16 | val view = system.actorOf(Props(new OrderView(endpoint.id, endpoint.logs(DefaultLogName)))) 17 | } 18 | -------------------------------------------------------------------------------- /src/main/scala/sample/eventuate/OrderLogging.scala: -------------------------------------------------------------------------------- 1 | package sample.eventuate 2 | 3 | import akka.actor.ActorLogging 4 | import com.rbmhtechnology.eventuate.EventsourcedView 5 | 6 | trait OrderLogging extends ActorLogging { this: EventsourcedView => 7 | 8 | def replicaId: String 9 | 10 | def info(msg: String): Unit = if(!recovering) log.info(s"[$replicaId]: $msg") 11 | } 12 | -------------------------------------------------------------------------------- /src/main/scala/sample/eventuate/OrderManager.scala: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2015 - 2016 Red Bull Media House GmbH - all rights reserved. 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 sample.eventuate 18 | 19 | import akka.actor._ 20 | import akka.pattern.ask 21 | import akka.util.Timeout 22 | import com.rbmhtechnology.eventuate.EventsourcedView 23 | import com.rbmhtechnology.eventuate.VersionedAggregate.Resolve 24 | 25 | import scala.concurrent.Future 26 | import scala.concurrent.duration._ 27 | import scala.util._ 28 | 29 | /** 30 | * Manages event-sourced [[OrderActor]]s of a location where the location identifier is 31 | * `replicaId`. [[OrderActor]]s can be 32 | * 33 | * - instantiated on-demand in the command handler 34 | * - instantiated on-demand in the event handler 35 | * - stopped and removed from the internal map to free memory 36 | * 37 | * This order manager implements [[EventsourcedView]] only for the purpose to eagerly 38 | * instantiate [[OrderActor]]s as soon as an [[OrderActor.OrderCreated]] event has 39 | * been logged. This is usually not necessary but we do it here to see the console 40 | * output of all [[OrderActor]]s at each location immediately. 41 | */ 42 | class OrderManager(val replicaId: String, val eventLog: ActorRef) extends EventsourcedView with OrderLogging { 43 | import OrderActor._ 44 | import context.dispatcher 45 | 46 | private implicit val timeout = Timeout(10.seconds) 47 | private var orderActors: Map[String, ActorRef] = Map.empty 48 | 49 | override val id = s"s-om-$replicaId" 50 | 51 | override def onCommand = { 52 | case c: OrderCommand => 53 | info(s"Process command: ${c.toString}") 54 | orderActor(c.orderId) forward c 55 | case c: SaveSnapshot => orderActor(c.orderId) forward c 56 | case r: Resolve => orderActor(r.id) forward r 57 | case GetState if orderActors.isEmpty => 58 | sender() ! GetStateSuccess(Map.empty) 59 | case GetState => 60 | val sdr = sender() 61 | val statesF = orderActors.values.map(_.ask(GetState).mapTo[GetStateSuccess].map(_.state)) 62 | Future.sequence(statesF).map(_.reduce(_ ++ _)) onComplete { 63 | case Success(states) => sdr ! GetStateSuccess(states) 64 | case Failure(cause) => sdr ! GetStateFailure(cause) 65 | } 66 | } 67 | 68 | override def onEvent = { 69 | // eagerly create order actor so that their console output is immediately visible 70 | case OrderCreated(orderId, _) if !orderActors.contains(orderId) => orderActor(orderId) 71 | } 72 | 73 | private def orderActor(orderId: String): ActorRef = orderActors.get(orderId) match { 74 | case Some(orderActor) => orderActor 75 | case None => 76 | info(s"Create OrderActor for $orderId") 77 | orderActors = orderActors + (orderId -> context.actorOf(Props(new OrderActor(orderId, replicaId, eventLog)))) 78 | orderActors(orderId) 79 | } 80 | } 81 | -------------------------------------------------------------------------------- /src/main/scala/sample/eventuate/OrderView.scala: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2015 - 2016 Red Bull Media House GmbH - all rights reserved. 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 sample.eventuate 18 | 19 | import akka.actor.ActorRef 20 | import com.rbmhtechnology.eventuate.EventsourcedView 21 | 22 | object OrderView { 23 | case class GetUpdateCount(orderId: String) 24 | case class GetUpdateCountSuccess(orderId: String, count: Int) 25 | } 26 | 27 | /** 28 | * Consumes events written by all event-sourced [[OrderActor]]s. 29 | */ 30 | class OrderView(replicaId: String, val eventLog: ActorRef) extends EventsourcedView { 31 | import OrderActor._ 32 | import OrderView._ 33 | 34 | var updateCounts: Map[String, Int] = Map.empty 35 | 36 | override val id = s"s-ov-$replicaId" 37 | 38 | override def onCommand = { 39 | case GetUpdateCount(orderId) => sender() ! GetUpdateCountSuccess(orderId, updateCounts.getOrElse(orderId, 0)) 40 | } 41 | 42 | override def onEvent = { 43 | case oe: OrderEvent => updateCounts.get(oe.orderId) match { 44 | case Some(count) => updateCounts += (oe.orderId -> (count + 1)) 45 | case None => updateCounts += (oe.orderId -> 1) 46 | } 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /src/main/scala/sample/eventuate/package.scala: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2015 - 2016 Red Bull Media House GmbH - all rights reserved. 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 sample 18 | 19 | import com.rbmhtechnology.eventuate.Versioned 20 | 21 | package object eventuate { 22 | def printOrder(versions: Seq[Versioned[Order]]): String = { 23 | if (versions.size > 1) { 24 | versions.zipWithIndex.map { 25 | case (version, idx) => s"- version $idx: ${version.value}" 26 | }.mkString("Conflict:\n", "\n", "") 27 | } else 28 | versions.headOption.map(_.value.toString()).getOrElse("") 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /src/multi-jvm/scala/sample/eventuate/OrderSpec.scala: -------------------------------------------------------------------------------- 1 | package sample.eventuate 2 | 3 | import java.nio.file.{Files, Path} 4 | import java.util.UUID 5 | 6 | import akka.actor.{ActorSystem, ActorRef, Props} 7 | import akka.remote.testconductor.RoleName 8 | import akka.remote.testkit.{MultiNodeConfig, MultiNodeSpec} 9 | import akka.pattern.ask 10 | import akka.remote.transport.ThrottlerTransportAdapter.Direction 11 | import akka.testkit.TestProbe 12 | import com.rbmhtechnology.eventuate.ReplicationEndpoint.DefaultLogName 13 | import com.rbmhtechnology.eventuate.{Versioned, EventsourcedView, ReplicationConnection, ReplicationEndpoint} 14 | import com.rbmhtechnology.eventuate.log.leveldb.LeveldbEventLog 15 | import com.typesafe.config.{Config, ConfigFactory} 16 | import org.apache.commons.io.FileUtils 17 | import org.scalatest.{WordSpec, Matchers} 18 | import OrderActor._ 19 | 20 | import scala.reflect.{classTag, ClassTag} 21 | import scala.collection.JavaConverters.mapAsJavaMapConverter 22 | 23 | class OrderSpecMultiJvmNode1 extends OrderSpec 24 | class OrderSpecMultiJvmNode2 extends OrderSpec 25 | 26 | class TwoNodesReplicationConfig(config: Config) extends MultiNodeConfig { 27 | 28 | val nodeA = role("nodeA") 29 | val nodeB = role("nodeB") 30 | 31 | testTransport(true) 32 | 33 | def otherNode(role: RoleName): RoleName = if(role == nodeA) nodeB else nodeA 34 | 35 | commonConfig(config.withFallback(ConfigFactory.parseString( 36 | s""" 37 | |akka.loglevel = "ERROR" 38 | |akka.stdout-loglevel = "ERROR" 39 | |akka.test.single-expect-default = 10s 40 | |eventuate.log.write-batch-size = 3 41 | |eventuate.log.replication.retry-delay = 1s 42 | |eventuate.log.replication.failure-detection-limit = 60s 43 | """.stripMargin))) 44 | } 45 | 46 | class OrderSpec extends WordSpec with Matchers { 47 | 48 | def newOrderId: String = UUID.randomUUID().toString 49 | 50 | val createdBarrier = "created" 51 | 52 | "An OrderManager with two replicas" when { 53 | "an order is created on each replica" must { 54 | "contain both orders (on each replica)" in withTwoOrderManagers { multiNode => 55 | import multiNode._ 56 | 57 | executeCommand(CreateOrder(newOrderId)) 58 | 59 | val emittedEvents = listener.expectMsgAllClassOf( 60 | List.fill(2)(classOf[OrderCreated]): _*) 61 | awaitCond(getState.size == 2) 62 | 63 | allOrders shouldBe emittedEvents.map(toOrder).toSet 64 | } 65 | } 66 | "an order is created on one replica and a item added on the other" must { 67 | "contain the order with item (on each replica)" in 68 | withTwoOrderManagers { multiNode => 69 | import multiNode._ 70 | 71 | runOn(config.nodeA)(executeCommand(CreateOrder(newOrderId))) 72 | val OrderCreated(orderId, _) = waitFor(orderCreated) 73 | 74 | runOn(config.nodeB)(executeCommand(AddOrderItem(orderId, "item"))) 75 | val OrderItemAdded(_, item) = waitFor(orderItemAdded) 76 | 77 | allOrders shouldBe Set(Order(orderId, List(item))) 78 | } 79 | } 80 | "an item is added on both replica concurrently" must { 81 | "contain two conflicting orders (on each replica)" in 82 | withTwoOrderManagers { multiNode => 83 | import multiNode._ 84 | 85 | runOn(config.nodeA)(executeCommand(CreateOrder(newOrderId))) 86 | val OrderCreated(orderId, _) = waitFor(orderCreated) 87 | 88 | disconnect(config.nodeA, config.nodeB) 89 | 90 | executeCommand(AddOrderItem(orderId, myself.name)) 91 | val OrderItemAdded(_, myItem) = waitFor(orderItemAdded) 92 | 93 | connect(config.nodeA, config.nodeB) 94 | val OrderItemAdded(_, otherItem) = waitFor(orderItemAdded) 95 | 96 | getState.get(orderId).map(allVersions) shouldBe 97 | Some(Set(myItem, otherItem).map(item => Order(orderId, List(item)))) 98 | } 99 | } 100 | } 101 | 102 | private def allVersions(versions: Seq[Versioned[Order]]): Set[Order] = 103 | versions.map(_.value).toSet 104 | 105 | private def orderCreated(event: OrderCreated, 106 | state: Map[String, Seq[Versioned[Order]]]): Boolean = 107 | state.get(event.orderId).isDefined 108 | 109 | private def orderItemAdded(event: OrderItemAdded, 110 | state: Map[String, Seq[Versioned[Order]]]): Boolean = 111 | state.get(event.orderId).exists(_.exists(_.value.items.contains(event.item))) 112 | 113 | private def toOrder(event: OrderCreated) = Order(event.orderId) 114 | 115 | private def withTwoOrderManagers[O] 116 | (block: TwoOrderManagerNode => O): O = { 117 | withMultiReplicationNode( 118 | new TwoNodesReplicationConfig(_), 119 | new TwoOrderManagerNode(_: TwoNodesReplicationConfig))(block) 120 | } 121 | 122 | private def withMultiReplicationNode[C <: MultiNodeConfig, M <: MultiNodeSpec, O] 123 | (multiNodeConfigFactory: Config => C, multiNodeFactory: C => M) 124 | (block: M => O): O = { 125 | withTempDir { tempDir => 126 | val config = multiNodeConfigFactory( 127 | ConfigFactory.parseMap(Map("eventuate.log.leveldb.dir" -> tempDir.toString).asJava)) 128 | withMultiNode(multiNodeFactory(config))(block) 129 | } 130 | } 131 | 132 | private def withTempDir[A](block: Path => A): A = { 133 | val dir = Files.createTempDirectory(getClass.getSimpleName) 134 | try { 135 | block(dir) 136 | } finally { 137 | FileUtils.deleteDirectory(dir.toFile) 138 | } 139 | } 140 | 141 | private def withMultiNode[M <: MultiNodeSpec, O] 142 | (multiNode: M)(block: M => O): O = { 143 | try { 144 | multiNode.multiNodeSpecBeforeAll() 145 | multiNode.enterBarrier("start-test") 146 | block(multiNode) 147 | } finally { 148 | multiNode.enterBarrier("test-finished") 149 | multiNode.multiNodeSpecAfterAll() 150 | // avoid that next test starts before conductor is shut down 151 | Thread.sleep(100 * multiNode.roles.size) 152 | } 153 | } 154 | } 155 | 156 | class TwoOrderManagerNode(config: TwoNodesReplicationConfig) 157 | extends MultiReplicationNode(config) { 158 | 159 | val endpoint: ReplicationEndpoint = 160 | newReplicationEndpointConnectedTo(config.otherNode(myself)) 161 | val listener: TestProbe = newListener(endpoint) 162 | val orderManager: ActorRef = system.actorOf(Props(new OrderManager( 163 | replicaId[OrderManager](myself.name), endpoint.logs(DefaultLogName)))) 164 | 165 | def executeCommand(cmd: Any): Unit = { 166 | (orderManager ? cmd)(testConductor.Settings.QueryTimeout).await match { 167 | case CommandFailure(_, cause) => throw cause 168 | case _ => 169 | } 170 | } 171 | 172 | def waitFor[E : ClassTag](cond: (E, Map[String, Seq[Versioned[Order]]]) => Boolean): E = { 173 | val event = listener.expectMsgClass(classTag[E].runtimeClass).asInstanceOf[E] 174 | awaitCond(cond(event, getState)) 175 | event 176 | } 177 | 178 | def getState: Map[String, Seq[Versioned[Order]]] = 179 | (orderManager ? GetState)(testConductor.Settings.QueryTimeout).await match { 180 | case GetStateSuccess(state) => state 181 | case GetStateFailure(cause) => throw cause 182 | } 183 | 184 | def allOrders: Set[Order] = (for { 185 | versionedOrders <- getState.values 186 | versionedOrder <- versionedOrders 187 | } yield versionedOrder.value).toSet 188 | 189 | private def replicaId[A : ClassTag](nodeId: String) = 190 | s"${classTag[A].runtimeClass.getSimpleName}-$nodeId" 191 | } 192 | 193 | class MultiReplicationNode[C <: MultiNodeConfig](val config: C) 194 | extends MultiNodeSpec(config) { 195 | 196 | override def initialParticipants = roles.size 197 | 198 | def newReplicationEndpointConnectedTo(replicationPartners: RoleName*) = { 199 | val endpoint = new ReplicationEndpoint( 200 | myself.name, 201 | Set(DefaultLogName), 202 | LeveldbEventLog.props(_), 203 | replicationPartners.toSet.map(toReplicationConnection)) 204 | endpoint.activate() 205 | endpoint 206 | } 207 | 208 | def newListener(endpoint: ReplicationEndpoint): TestProbe = 209 | EventListener(endpoint.logs(DefaultLogName)) 210 | 211 | def disconnect(from: RoleName, to: RoleName): Unit = { 212 | enterBarrier("before disconnect") 213 | runOn(from)(testConductor.blackhole(from, to, Direction.Both).await) 214 | enterBarrier("after disconnect") 215 | } 216 | 217 | def connect(from: RoleName, to: RoleName): Unit = { 218 | enterBarrier("before connect") 219 | runOn(from)(testConductor.passThrough(from, to, Direction.Both).await) 220 | enterBarrier("after connect") 221 | } 222 | 223 | private def toReplicationConnection(roleName: RoleName): ReplicationConnection = { 224 | val address = node(roleName).address 225 | ReplicationConnection(address.host.get, address.port.get, address.system) 226 | } 227 | } 228 | 229 | object EventListener { 230 | private class TestEventConsumer(override val id: String, override val eventLog: ActorRef, listener: ActorRef) 231 | extends EventsourcedView { 232 | 233 | override def onCommand = ??? 234 | 235 | override def onEvent = { 236 | case event => listener ! event 237 | } 238 | } 239 | 240 | def apply(eventLog: ActorRef)(implicit system: ActorSystem): TestProbe = { 241 | val listener = TestProbe() 242 | val id = UUID.randomUUID().toString 243 | system.actorOf(Props(new TestEventConsumer(id, eventLog, listener.ref))) 244 | listener 245 | } 246 | } 247 | 248 | -------------------------------------------------------------------------------- /tutorial/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 |
4 |

eventuate tutorial

5 |

6 | This tutorial guides you through a distributed order management application 7 | based on eventuate by 8 | using distributed and 9 | event-sourced 10 | order-actors. It 11 | demonstrates the most important parts of such an application and how to build 12 | one yourself. The 13 | example 14 | is actually taken from the eventuate project itself 15 | and only modified slightly to allow better integration into an activator template. 16 |

17 | The application 18 | runs an OrderManager on several nodes. Each one is able to accept 19 |

20 |
    21 |
  • new orders
  • 22 |
  • new order items for an existing order
  • 23 |
  • cancellation of orders
  • 24 |
  • removal of items from an existing order
  • 25 |
26 |

27 | The changes are replicated to all connected nodes. Changing the same order on 28 | multiple nodes concurrently is considered a conflict. In that case 29 | multiple versions of this order are maintained until one is picked interactively 30 | to resolve the conflict. 31 |

32 |
33 |
34 |

The application: OrderLocation

35 | 36 |

37 | The entry into the application is 38 | OrderLocation. 39 | It starts the actor-system and the actors 40 | OrderManager as well as OrderView in the 41 | akka-typical manner. What makes it an eventuate-based application that supports distributed 42 | deployment is the 43 | ReplicationEndpoint. 44 | This takes care of replicating changes to all connected ReplicationEndpoints. 45 | A ReplicationEndpoint can either be setup programmatically or (as in this case) by 46 | configuration. For this on each node 47 | akka-remoting 48 | host and port (under which this RelicationEndpoint is available) needs to be defined: 49 |

50 |

 51 | akka.remote.netty.tcp.hostname = "127.0.0.1"
 52 | akka.remote.netty.tcp.port=2554
 53 |     
54 |

55 | as well as an endpoint-id and the replication-partners on the other nodes: 56 |

57 |

 58 | eventuate {
 59 |   endpoint.id = "C"
 60 |   endpoint.connections = ["127.0.0.1:2552", "127.0.0.1:2553", "127.0.0.1:2555"]
 61 | }
 62 |     
63 |

64 | So in this case ReplicationEndpoint C listens on 127.0.0.1:2554 and connects to 65 | ReplicationEndpoints on other nodes listening on 66 | 127.0.0.1:2552, 127.0.0.1:2553 and 127.0.0.1:2555. 67 |

68 |
69 |
70 |

The order manager

71 | 72 |

73 | At the heart of the application is the 74 | OrderManager. 75 | It is implemented as 76 | EventsourcedView 77 | to better illustrate how orders are created in the distributed system. For the moment 78 | it is enough to assume that it is a plain actor and its onCommand method is actually the 79 | receive method of an actor. 80 |

81 | Its main purpose is to maintain a Map of 82 | OrderActors 83 | by id each one representing a specific 84 | order and dispatch OrderCommands or a Resolve-command to them 85 | (to modify the order) or a SaveSnapshot-command for taking a 86 | snapshot 87 | of the internal state of an order. 88 | Additionally it allows to retrieve the current state of all orders (currently in memory). 89 |

90 |
91 |
92 |

The order-actor

93 | 94 |

95 | A single order is represented by an 96 | OrderActor. 97 | It is implemented as an 98 | EventsourcedActor. 99 | It represents a special case of an 100 | aggregate root 101 | and that is why it defines 102 | the member aggregateId. This has to be an application wide unique id. 103 | Even eventsourced aggregate roots of different type must not share the same ids. 104 | In addition to this it defines the members id and eventLog. 105 | id must be a globally unique id, so all other EventsourcedActors or even 106 | EventsourcedViews in the entire distributed setup must not share this id. Here it 107 | is built as combination of replicaId that 108 | identifies a node or location and orderId. The idea is that there are several OrderActor-instances 109 | with the same orderId (respectively aggregateId) 110 | at different nodes (and thus with different replicaId) and state-changes to one of them are replicated to the 111 | others so that they are eventually all in the same state. 112 | For this an 113 | EventsourcedActor defines the two methods: 114 |

115 |
    116 |
  • onCommand
  • 117 |
  • onEvent
  • 118 |
119 |

120 | The purpose of onCommand is to process commands (of type 121 | OrderCommand) that sre sent to change 122 | the state of the order (like AddOrderItem) by 123 |

124 |
    125 |
  • verifying that the command is valid and can be accepted and in case it is
  • 126 |
  • emitting an event (or multiple) that describes the state-change (by calling persist(event))
  • 127 |
128 |

129 | So for example if an AddOrderItem-command can be accepted the 130 | onCommand-handler emits an OrderItemAdded-event. 131 | Before this event is processed by the onEvent-handler to 132 | perform the requested state-change, it is persisted by eventuate to the 133 | event-log (represented by the member eventLog). 134 |

135 |

136 | This reflects the core principle of eventsourced applications. Instead of 137 | persisting the current state, state-changes are persisted. When the application (or just the actor) 138 | is restarted all persisted events are replayed (i.e. the onEvent-handler 139 | is called for each of them) to reconstruct the state as before. 140 |

141 |

142 | Note that onCommand and onEvent are both called during normal 143 | actor message dispatch so they can safely access and modify an actor's mutable state, 144 | however as persisting is done asynchronously they are not invoked through a single message. 145 | Nonetheless eventuate guarantees by default that no new command slips between an 146 | onCommand-call and the onEvent-calls for each emitted/persisted 147 | event by stashing commands that arrive in the meantime. This guarantee can be 148 | relaxed 149 | for performance reasons. 150 |

151 |

152 | eventuate provides two additional important features: 153 |

154 |
    155 |
  1. Once persisted it replicates the event to all connected nodes and calls 156 | the onEvent-handler of all affected eventsourced-actors on all nodes. In this 157 | case the affected eventsourced actor is an (already active) OrderActor with the same aggregate-id.
  2. 158 |
  3. It tracks causality of events, i.e. it ensures that an event that 159 | is known 160 | to has 161 | happened before another event is consumed by all affected actors' onEvent-handler 162 | before the other event
  4. 163 |
164 |
165 |
166 |

The order-view

167 |

168 | Another typical element of eventsourced application are so called 169 | eventsourced views. 170 | These are actors that consume events (to build up internal state) but cannot emit any. They 171 | can be used to implement the query-side of 172 | a CQRS based application. 173 |

174 |

175 | The 176 | OrderView 177 | implements a simple example of such an 178 | EventsourcedView. 179 | As it does not define aggregateId it consumes all events that are written to its 180 | eventLog either directly by eventsourced actors on the same node or through replication. 181 |

182 |

183 | Here the OrderView simply counts for each order its updates 184 | (i.e. the emitted OrderEvents) and allows to query for this number by order-id. 185 |

186 |
187 |
188 |

Running the example

189 |

190 | On the Run-tab you can start an example-setup 191 | with two locations (C and D) 192 | running in a single JVM in action (main file: sample.eventuate.OrderBot). 193 | A bot will send commands 194 | alternating to the OrderManagers of both locations. 195 |

196 |

197 | When you start it the first time you will see something like this in the log-output: 198 |

199 |

200 | ( 1) 15:40:16.965 CreateOrderAction$: ------- Send CreateOrder to location-D (1/9) -------
201 | ( 1) 15:40:16.966 OrderManager: [D]: Process command: CreateOrder(0762ee15-c570-4c57-8b03-bf757418df9f)
202 | ( 2) 15:40:16.966 OrderManager: [D]: Create OrderActor for 0762ee15-c570-4c57-8b03-bf757418df9f
203 | ( 3) 15:40:16.971 OrderActor: [D]: OrderCreated: [0762ee15-c570-4c57-8b03-bf757418df9f] items= cancelled=false
204 | ( 5) 15:40:16.978 OrderManager: [C]: Create OrderActor for 0762ee15-c570-4c57-8b03-bf757418df9f
205 | ( 6) 15:40:16.981 OrderActor: [C]: Initialized from Log: [0762ee15-c570-4c57-8b03-bf757418df9f] items= cancelled=false
206 | ( 7) 15:40:19.978 AddOrderItemAction$: ------- Send AddOrderItem to location-C (2/9) --------
207 | ( 8) 15:40:19.978 OrderManager: [C]: Process command: AddOrderItem(0762ee15-c570-4c57-8b03-bf757418df9f,Fqmtv)
208 | ( 9) 15:40:19.984 OrderActor: [C]: OrderItemAdded: [0762ee15-c570-4c57-8b03-bf757418df9f] items=Fqmtv cancelled=false
209 | (10) 15:40:19.990 OrderActor: [D]: OrderItemAdded: [0762ee15-c570-4c57-8b03-bf757418df9f] items=Fqmtv cancelled=false
210 |         
211 |

212 | This shows that: 213 |

214 |
    215 |
  1. A CreateOrder-command is sent to D.
  2. 216 |
  3. D's OrderManager starts the OrderActor-accordingly.
  4. 217 |
  5. The OrderActor emits the OrderCreated event.
  6. 218 |
  7. This event gets replicated to location C.
  8. 219 |
  9. C's OrderManager sees it and eagerly starts a corresponding OrderActor.
  10. 220 |
  11. This OrderActor gets initialized from C's event log 221 | that already contains the replicated event and thus ends up in the 222 | same state as D's order.
  12. 223 |
  13. After a short pause an AddOrderItem-command for this order is sent to C.
  14. 224 |
  15. C's OrderManager dispatches the command to the OrderActor,
  16. 225 |
  17. which emits a corresponding OrderItemAdded-event
  18. 226 |
  19. The event gets replicated to D und the (already existing) OrderActor 227 | can consume the same event to bring itself into the same state as C's order.
  20. 228 |
229 |
230 |
231 |

Concurrent events and conflicts

232 | 233 |

234 | Now that you have seen the example application you may wonder what happens if 235 | an item is added to the same order on both locations C and D simultaneously. 236 | By tracking causality of events eventuate can detect concurrent events 237 | and thus potentially conflicting updates. 238 |

239 |

240 | You can actually try this out by commenting the sleep-statement in 241 | OrderBot 242 | and running the example again. As the activator UI gives access to a 243 | limited number of log-lines only, it makes sense to test this using 244 | sbt started from a terminal. For this execute: 245 |

246 |
sbt "runMain sample.eventuate.OrderBot"
247 |

248 | Depending on your hardware you may need a couple of tries or it might even make sense 249 | to increase the total number of commands sent to the application (sample.eventuate.Action#total), 250 | but eventually you should find something like this in the output: 251 |

252 |

253 | 16:25:59.248 OrderActor: [C]: OrderItemAdded: Conflict:
254 | - version 0: [5f789bc3-9a20-4741-a6c6-dd87cfe36042] items=XN7iM,3hZQO cancelled=false
255 | - version 1: [5f789bc3-9a20-4741-a6c6-dd87cfe36042] items=XN7iM,T6dEy cancelled=false
256 | ...
257 | 16:25:59.252 OrderActor: [D]: OrderItemAdded: Conflict:
258 | - version 0: [5f789bc3-9a20-4741-a6c6-dd87cfe36042] items=XN7iM,T6dEy cancelled=false
259 | - version 1: [5f789bc3-9a20-4741-a6c6-dd87cfe36042] items=XN7iM,3hZQO cancelled=false
260 |     
261 |

262 | In this case the bot added to the order with id 5f789bc3... (which already 263 | contained item XN7iM) simultaneously the items 3hZQO and T6dEy. 264 | As the bot actually runs purely sequential, simultaneously in this case means 265 | the items were added on nodes C and D before the corresponding event was replicated 266 | to the other location. 267 |

268 |

269 | By using 270 | ConcurrentVersions 271 | an actor is able to maintain a 272 | tree of conflicting versions. 273 | These conflicts can be resolved by a selecting a winner-version either 274 | automatically 275 | or 276 | interactively. 277 | See the section on resolving conflicts in the example application for an 278 | interactive example. 279 |

280 |
281 |
282 |

Testing the application

283 | 284 |

285 | While seeing the replication and conflict detection in a log-file is nice, you 286 | would typically want to write automated tests to check correct behaviour of 287 | the application in these circumstances. 288 |

289 |

290 | For this akka comes with the amazing 291 | multi-node-testing-toolkit 292 | and 293 | OrderSpec 294 | uses exactly this to verify that the application behaves as expected 295 | when distributed to two JVMs. 296 |

297 |

298 | A multi-jvm test basically consists out of two parts: 299 |

300 |
    301 |
  • A MultiNodeConfig 302 | defining the common configuration and the nodes that take part in the test
  • 303 |
  • A (or several) MultiNodeSpec(s) 304 | defining the actual test-logic.
  • 305 |
306 |

307 | The MultiNodeConfig TwoNodesReplicationConfig defines two roles 308 | nodeA and nodeB which are equivalent 309 | to nodes in the test. Additionally it configures replication properties that 310 | ensure better timing for testing than the default ones. 311 |

312 |

313 | The actual test-code can be found in OrderSpec. Each test uses the method 314 | withTwoOrderManagers (implementing the 315 | loan-fixture-pattern) 316 | to get a MultiNodeSpec-reference that sets up the replication for the two nodes 317 | (running in two JVMs!) and starts an 318 | OrderManager (on each node). In addition this reference comes with some convenience methods that ease 319 | testing the OrderManager. The actual test-code comes in the withTwoOrderManagers-block and is 320 | executed on both JVMs simultaneously. 321 |

322 |

Create Orders on both nodes

323 |

324 | The first test simply sends the CreateOder-command to the local OrderManager (on each node) 325 |

326 |

327 | executeCommand(CreateOrder(newOrderId))
328 |     
329 |

330 | waits for both OrderCreated-events (on each node) 331 |

332 |

333 | val emittedEvents = listener.expectMsgAllClassOf(
334 |   List.fill(2)(classOf[OrderCreated]): _*)
335 |     
336 |

337 | and verifies (on each node) that the OrderManagers contain both orders 338 |

339 |

340 | allOrders shouldBe emittedEvents.map(toOrder).toSet
341 |     
342 |

Create Order on one node, add item on the other

343 |

344 | The second test creates the order only on node A 345 |

346 |

347 | runOn(config.nodeA)(executeCommand(CreateOrder(newOrderId)))
348 |     
349 |

350 | waits for the order to be created (on each node) 351 |

352 |

353 | val OrderCreated(orderId, _) = waitFor(orderCreated)
354 |     
355 |

356 | and adds an item to the order only on node B 357 |

358 |

359 | runOn(config.nodeB)(executeCommand(AddOrderItem(orderId, "item")))
360 |     
361 |

362 | At the end the OrderManager (on each node) must contain the 363 | same order. 364 |

365 |

Add item on both nodes simultaneously

366 |

367 | The third test finally provokes a conflict by 368 |

369 |
    370 |
  1. creating an order on nodeA (and waiting for replication)
  2. 371 |
  3. disconnecting both nodes (i.e. simulating a network partition)
  4. 372 |
  5. adding an order on each node (which creates the conflict)
  6. 373 |
  7. connecting the nodes again
  8. 374 |
375 |

376 | Once the connection is reestablished the added items are replicated to the other node 377 | and (since they took place concurrently) result in a conflict on each node. At the end the 378 | test verifies (on each node) that the OrderManager contain both versions 379 | of the order. 380 |

381 |
382 |
383 |

Resolving conflicts

384 | 385 |

386 | To demonstrate interactive conflict resolution one can use the 387 | OrderExample 388 | started from a terminal. For this execute in the root-directory of the project (Linux and Mac only): 389 |

390 |

391 | ./example A B C
392 |     
393 |

394 | to start three nodes in three terminal windows on your machine. With 395 |

396 |

397 | create Order1
398 |     
399 |

400 | in any of the windows you can create an order and see that it gets replicated to all nodes. 401 | Once that is done you can add an item in another window: 402 |

403 |

404 | add Order1 Item1
405 |     
406 |

407 | Now lets create a partition by stopping node C (Ctrl-C) and add different item in A's and B's 408 | window: 409 |

410 |

411 | (in A:) add Order1 ItemA
412 | (in B:) add Order1 ItemB
413 |     
414 |

415 | Restart C (Cursor Up + Enter) to re-enable replication and you should see something as 416 | follows in all windows: 417 |

418 |

419 | 14:17:46.863 OrderActor: [?]: OrderItemAdded: Conflict:
420 | - version 0: [Order1] items=Item1,ItemA cancelled=false
421 | - version 1: [Order1] items=Item1,ItemB cancelled=false
422 |     
423 |

424 | The conflict can be resolved with the following command: 425 |

426 |

427 | resolve Order1 0
428 |     
429 |

430 | To avoid conflicting resolutions the example application implements the rule that a conflict can 431 | only be resolved on the node that initially created the order. This command sends an 432 | Resolve(Order1, 0) (defined in the eventuate-library) to the 433 | OrderManager 434 | which in turn forwards it to the corresponding 435 | OrderActor. 436 | When the command can be accepted a corresponding Resolved(Order1, vector-timestamp) 437 | event is emitted and consumed and processed by all nodes. 438 |

439 |
440 | 441 | 442 | --------------------------------------------------------------------------------