├── .gitignore ├── .travis.yml ├── LICENSE ├── README.md ├── build.sbt ├── project ├── Common.scala ├── build.properties └── plugins.sbt └── src ├── main ├── resources │ └── reference.conf └── scala │ └── akka │ └── persistence │ └── mongo │ ├── CasbahCommon.scala │ ├── CasbahRoot.scala │ ├── journal │ ├── CasbahJournal.scala │ ├── CasbahJournalRoot.scala │ └── CasbahRecovery.scala │ └── snapshot │ ├── CasbahSnapshot.scala │ └── CasbahSnapshotRoot.scala └── test └── scala └── akka └── persistence └── mongo ├── CasbahRootSpec.scala ├── EmbeddedMongoSupport.scala ├── journal ├── CasbahJournalRootSpec.scala ├── CasbahJournalSpec.scala └── CasbahLJournalLoadSpec.scala └── snapshot └── CasbahSnapshotSpec.scala /.gitignore: -------------------------------------------------------------------------------- 1 | *.class 2 | *.log 3 | 4 | # sbt specific 5 | dist/* 6 | target/ 7 | lib_managed/ 8 | src_managed/ 9 | project/boot/ 10 | project/plugins/project/ 11 | 12 | # Scala-IDE specific 13 | .scala_dependencies 14 | .target 15 | .cache 16 | .classpath 17 | .project 18 | .settings/ 19 | 20 | # Intellij specific 21 | *.iml 22 | *.idea/ 23 | *.idea_modules/ 24 | 25 | # Sublime specific 26 | *.sublime-project 27 | *.sublime-workspace 28 | 29 | # OS specific 30 | .DS_Store 31 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: scala 2 | scala: 3 | - "2.11.7" 4 | jdk: 5 | - oraclejdk8 6 | branches: 7 | except: 8 | - /^wip-.*$/ 9 | -------------------------------------------------------------------------------- /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 | # An Akka Persistence Plugin for Mongo 2 | 3 | [![Build Status](https://travis-ci.org/ironfish/akka-persistence-mongo.png?branch=master)](https://travis-ci.org/ironfish/akka-persistence-mongo) 4 | 5 | A replicated [Akka Persistence](http://doc.akka.io/docs/akka/current/scala/persistence.html) journal backed by [MongoDB Casbah](http://mongodb.github.io/casbah/). 6 | 7 | ## Prerequisites 8 | 9 | ### Release 10 | 11 | | Technology | Version | 12 | | :--------: | -------------------------------- | 13 | | Plugin | [](http://search.maven.org/#search%7cga%7c1%7cg%3a%22com.github.ironfish%22a%3a%22akka-persistence-mongo-casbah_2.11%22)
[](http://search.maven.org/#search%7cga%7c1%7cg%3a%22com.github.ironfish%22a%3a%22akka-persistence-mongo-casbah_2.10%22)| 14 | | Scala | 2.10.5, 2.11.7 - Cross Compiled | 15 | | Akka | 2.3.12 or higher | 16 | | Mongo | 2.6.x or higher | 17 | 18 | ### Snapshot 19 | 20 | | Technology | Version | 21 | | :--------: | -------------------------------- | 22 | | Plugin | [](https://oss.sonatype.org/content/repositories/snapshots/com/github/ironfish/akka-persistence-mongo-casbah_2.11/1.0.0-SNAPSHOT/) 23 | | Scala | 2.11.7 | 24 | | Akka | 2.4.1 or higher | 25 | | Mongo | 3.1.x or higher | 26 | 27 | ## Installation 28 | 29 | ### SBT 30 | 31 | #### Release 32 | 33 | ```scala 34 | resolvers += "Sonatype OSS Snapshots" at "https://oss.sonatype.org/content/repositories/releases" 35 | 36 | libraryDependencies ++= Seq( 37 | "com.github.ironfish" %% "akka-persistence-mongo-casbah" % "0.7.6" % "compile") 38 | ``` 39 | 40 | #### Snapshot 41 | 42 | ```scala 43 | resolvers += "Sonatype OSS Snapshots" at "https://oss.sonatype.org/content/repositories/snapshots" 44 | 45 | libraryDependencies ++= Seq( 46 | "com.github.ironfish" %% "akka-persistence-mongo" % "1.0.0-SNAPSHOT" % "compile") 47 | ``` 48 | 49 | ### Maven 50 | 51 | #### Release 52 | 53 | ```XML 54 | // Scala 2.10.5 55 | 56 | com.github.ironfish 57 | akka-persistence-mongo-casbah_2.10 58 | 0.7.6 59 | 60 | 61 | // Scala 2.11.7 62 | 63 | com.github.ironfish 64 | akka-persistence-mongo-casbah_2.11 65 | 0.7.6 66 | 67 | ``` 68 | 69 | #### Snapshot 70 | 71 | ```XML 72 | // Scala 2.11.7 73 | 74 | com.github.ironfish 75 | akka-persistence-mongo_2.11 76 | 1.0.0-SNAPSHOT 77 | 78 | ``` 79 | 80 | ### Build Locally 81 | 82 | You can build and install the plugin to your local Ivy cache. This requires sbt 0.13.8 or above. 83 | 84 | ```scala 85 | sbt publishLocal 86 | ``` 87 | 88 |
It can then be included as dependency: 89 | 90 | ```scala 91 | libraryDependencies += "com.github.ironfish" %% "akka-persistence-mongo" % "1.0.0-SNAPSHOT" 92 | ``` 93 | 94 | ## Mongo Specific Details 95 | 96 | Both the [Journal](#journal-configuration) and [Snapshot](#snapshot-configuration) configurations use the following Mongo components for connection management and write guarantees. 97 | 98 | ### Mongo Connection String URI 99 | 100 | The [Mongo Connection String URI Format](http://docs.mongodb.org/manual/reference/connection-string/) is used for establishing a connection to Mongo. Please **note** that while some of the components of the connection string are **[optional]** from a Mongo perspective, they are **[required]** for the Journal and Snapshot to function properly. Below are the required and optional components. 101 | 102 | #### Standard URI connection scheme 103 | 104 | ```scala 105 | mongodb://[username:password@]host1[:port1][,host2[:port2],...[,hostN[:portN]]][/[database][.collection][?options]] 106 | ``` 107 | 108 | #### Required 109 | 110 | | Component | Description | 111 | | :------------ | ------------------------------------------------------------------------------------------- | 112 | | `mongodb:// ` | The prefix to identify that this is a string in the standard connection format. | 113 | | `host1` | A server address to connect to. It is either a hostname, IP address, or UNIX domain socket. | 114 | | `/database ` | The name of the database to use. | 115 | | `.collection` | The name of the collection to use. | 116 | 117 | #### Optional 118 | 119 | | Component | Description | 120 | | :-------- | ----------- | 121 | | `username:password@` | If specified, the client will attempt to log in to the specific database using these credentials after connecting to the mongod instance. | 122 | | `:port1` | The default value is :27017 if not specified. | 123 | | `hostN` | You can specify as many hosts as necessary. You would specify multiple hosts, for example, for connections to replica sets. | 124 | | `:portN` | The default value is :27017 if not specified. | 125 | | `?options` | Connection specific options. See [Connection String Options](http://docs.mongodb.org/manual/reference/connection-string/#connections-connection-options) for a full description of these options. | 126 | 127 | ### Mongo Write Concern 128 | 129 | The [Write Concern Specification](https://docs.mongodb.org/manual/reference/write-concern/) describes the guarantee that MongoDB provides when reporting on the success of a write operation. The strength of the write concern determine the level of guarantee. When a `PersistentActor's` `persist` or `persistAsync` method completes successfully, a plugin must ensure the `message` or `snapshot` has persisted to the store. As a result, this plugin implementation enforces Mongo [Journaling](https://docs.mongodb.org/manual/core/journaling/) on all write concerns and requires all mongo instance(s) to enable journaling. 130 | 131 | | Options | Description | 132 | | :------------ | ----------- | 133 | | `woption` | The `woption` requests acknowledgment that the write operation has propagated to a specified number of mongod instances or to mongod instances with specified tags. Mongo's `wOption` can be either an `Integer` or `String`, and this plugin implementation supports both with `woption`.

If `woption` is an `Integer`, then the write concern requests acknowledgment that the write operation has propagated to the specified number of mongod instances. Note: The `woption` cannot be set to zero.

If `woption` is a `String`, then the value can be either `"majority"` or a `tag set name`. If the value is `"majority"` then the write concern requests acknowledgment that write operations have propagated to the majority of voting nodes. If the value is a `tag set name`, the write concern requests acknowledgment that the write operations have propagated to a replica set member with the specified tag. The default value is an `Integer` value of `1`. | 134 | | `wtimeout` | This option specifies a time limit, in `milliseconds`, for the write concern. If you do not specify the `wtimeout` option, and the level of write concern is unachievable, the write operation will **block** indefinitely. Specifying a `wtimeout` value of `0` is equivalent to a write concern without the `wTimeout` option. The default value is `10000` (10 seconds). | 135 | 136 | ## Journal Configuration 137 | 138 | ### Activation 139 | 140 | To activate the journal feature of the plugin, add the following line to your Akka `application.conf`. This will run the journal with its default settings. 141 | 142 | ```scala 143 | akka.persistence.journal.plugin = "casbah-journal" 144 | ``` 145 | 146 | ### Connection 147 | 148 | The default `mongo-url` is a `string` with a value of: 149 | 150 | ```scala 151 | casbah-journal.mongo-url = "mongodb://localhost:27017/store.messages" 152 | ``` 153 | 154 |
This value can be changed in the `application.conf` with the following key: 155 | 156 | ```scala 157 | casbah-journal.mongo-url 158 | 159 | # Example 160 | casbah-journal.mongo-url = "mongodb://localhost:27017/employee.events" 161 | ``` 162 | 163 |
See the [Mongo Connection String URI](#mongo-connection-string-uri) section of this document for more information. 164 | 165 | ### Write Concern 166 | 167 | The default `woption` is an `Integer` with a value of: 168 | 169 | ```scala 170 | casbah-journal.woption = 1 171 | ``` 172 | 173 |
This value can be changed in the `application.conf` with the following key: 174 | 175 | ```scala 176 | casbah-journal.woption 177 | 178 | # Example 179 | casbah-journal.woption = "majority" 180 | ``` 181 | 182 | ### Write Concern Timeout 183 | 184 | The default `wtimeout` is an `Long` in milliseconds with a value of: 185 | 186 | ```scala 187 | casbah-journal.wtimeout = 10000 188 | ``` 189 | 190 |
This value can be changed in the `application.conf` with the following key: 191 | 192 | ```scala 193 | casbah-journal.wtimeout 194 | 195 | # Example 196 | casbah-journal.wtimeout = 5000 197 | ``` 198 | 199 |
See the [Mongo Write Concern](#mongo-write-concern) section of this document for more information. 200 | 201 | ### Reject Non-Serializable Objects 202 | 203 | This plugin supports the rejection of `non-serializable` journal messages. If `reject-non-serializable-objects` is set to `true` and a message is received who's payload cannot be `serialized` then it is rejected. 204 | 205 | If set to `false` (the default value) then the `non-serializable` payload of the message becomes `Array.empty[Byte]` and is persisted. 206 | 207 | the default `reject-non-serializable-objects` is a `Boolean` with the value of: 208 | 209 | ```scala 210 | casbah-journal.reject-non-serializable-objects = false 211 | ``` 212 | 213 |
This value can be changed in the `application.conf` with the following key: 214 | 215 | ```scala 216 | casbah-journal.reject-non-serializable-objects 217 | 218 | # Example 219 | casbah-journal.reject-non-serializable-objects = true 220 | ``` 221 | 222 | ## Snapshot Configuration 223 | 224 | ### Activation 225 | 226 | To activate the snapshot feature of the plugin, add the following line to your Akka `application.conf`. This will run the snapshot-store with its default settings. 227 | 228 | ```scala 229 | akka.persistence.snapshot-store.plugin = "casbah-snapshot" 230 | ``` 231 | 232 | ### Connection 233 | 234 | The default `mongo-url` is a `string` with a value of: 235 | 236 | ```scala 237 | casbah-snapshot.mongo-url = "mongodb://localhost:27017/store.snapshots" 238 | ``` 239 | 240 |
This value can be changed in the `application.conf` with the following key: 241 | 242 | ```scala 243 | casbah-snapshot.mongo-url 244 | 245 | # Example 246 | casbah-snapshot.mongo-url = "mongodb://localhost:27017/employee.snapshots" 247 | ``` 248 | 249 |
See the [Mongo Connection String URI](#mongo-connection-string-uri) section of this document for more information. 250 | 251 | ### Write Concern 252 | 253 | The default `woption` is an `Integer` with a value of: 254 | 255 | ```scala 256 | casbah-snapshot.woption = 1 257 | ``` 258 | 259 |
This value can be changed in the `application.conf` with the following key: 260 | 261 | ```scala 262 | casbah-snapshot.woption 263 | 264 | # Example 265 | casbah-snapshot.woption = "majority" 266 | ``` 267 | 268 | ### Write Concern Timeout 269 | 270 | The default `wtimeout` is an `Long` in milliseconds with a value of: 271 | 272 | ```scala 273 | casbah-snapshot.wtimeout = 10000 274 | ``` 275 | 276 |
This value can be changed in the `application.conf` with the following key: 277 | 278 | ```scala 279 | casbah-snapshot.wtimeout 280 | 281 | # Example 282 | casbah-snapshot.wtimeout = 5000 283 | ``` 284 | 285 |
See the [Mongo Write Concern](#mongo-write-concern) section of this document for more information. 286 | 287 | ### Snapshot Load Attempts 288 | 289 | The snapshot feature of the plugin allows for the selection of the youngest of `{n}` snapshots that match an upper bound specified by configuration. This helps where a snapshot may not have persisted correctly because of a JVM crash. As a result an attempt to load the snapshot may fail but an older may succeed. 290 | 291 | The default `load-attempts` is an `Integer` with a value of: 292 | 293 | ```scala 294 | casbah-snapshot.load-attempts = 3 295 | ``` 296 | 297 |
This value can be changed in the `application.conf` with the following key: 298 | 299 | ```scala 300 | casbah-snapshot.load-attempts 301 | 302 | # Example 303 | casbah-snapshot.load-attempts = 5 304 | ``` 305 | 306 | ## Status 307 | 308 | * All operations required by the Akka Persistence [journal plugin API](http://doc.akka.io/docs/akka/current/scala/persistence.html#Journal_plugin_API) are supported. 309 | * All operations required by the Akka Persistence [Snapshot store plugin API](http://doc.akka.io/docs/akka/current/scala/persistence.html#Snapshot_store_plugin_API) are supported. 310 | * Tested against [Plugin TCK](http://doc.akka.io/docs/akka/current/scala/persistence.html#Plugin_TCK). 311 | * Plugin uses [Asynchronous Casbah Driver](http://mongodb.github.io/casbah/3.1/) 312 | * Message writes are batched to optimize throughput. 313 | 314 | ## Performance 315 | 316 | Minimal performance testing is included against a **native** instance. In general the journal will persist around 8,000 to 10,000 messages per second. 317 | 318 | ## Sample Applications 319 | 320 | The [sample applications](https://github.com/ironfish/akka-persistence-mongo-samples) are now located in their own repository. 321 | 322 | ## Change Log 323 | 324 | ### 1.0.0-SNAPSHOT 325 | 326 | * Upgrade `Akka` 2.4.1. 327 | * Upgrade `Casbah` to `Async` driver 3.1. 328 | * Supports latest [Plugin TCK](http://doc.akka.io/docs/akka/current/scala/persistence.html#Plugin_TCK). 329 | 330 | ### 0.7.6 331 | 332 | * Upgrade `sbt` to 0.13.8. 333 | * Upgrade `Scala` cross-compilation to 2.10.5 & 2.11.7. 334 | * Upgrade `Akka` to 2.3.12. 335 | 336 | ### 0.7.5 337 | 338 | * Upgrade `sbt` to 0.13.7. 339 | * Upgrade `Scala` cross-compilation to 2.10.4 & 2.11.4. 340 | * Upgrade `Akka` to 2.3.7. 341 | * Examples moved to their own [repository](https://github.com/ironfish/akka-persistence-mongo-samples). 342 | * Removed `logback.xml` in `akka-persistence-mongo-casbah` as it was not needed. 343 | * Added `pomOnly()` resolution to `casbah` dependency, fixes #63. 344 | 345 | ### 0.7.4 346 | 347 | * First release version to Maven Central Releases. 348 | * Upgrade `Sbt` to 0.13.5. 349 | * Upgrade `Scala` cross-compilation to 2.10.4 & 2.11.2. 350 | * Upgrade `Akka` to 2.3.5. 351 | * Added exception if `/database` or `.collection` are not accessible upon boot. Thanks @Fristi. 352 | * Modified snapshot feature for custom serialization support. Thanks @remcobeckers. 353 | 354 | ### 0.7.3-SNAPSHOT 355 | 356 | * Upgrade `Sbt` to 0.13.4. 357 | * Upgrade `Scala` cross-compilation to 2.10.4 & 2.11.2. 358 | * Upgrade `Akka` to 2.3.4. 359 | * `@deprecated` write confirmations, `CasbahJournal.writeConfirmations`, in favor of `AtLeastOnceDelivery`. 360 | * `@deprecated` delete messages, `CasbahJournal.deleteMessages`, per akka-persistence documentation. 361 | 362 | ## Author / Maintainer 363 | 364 | * [Duncan DeVore (@ironfish)](https://github.com/ironfish/) 365 | 366 | ## Contributors 367 | 368 | * [Heiko Seeberger (@hseeberger)](https://github.com/hseeberger) 369 | * [Sean Walsh (@SeanWalshEsq)](https://github.com/sean-walsh/) 370 | * [Al Iacovella](https://github.com/aiacovella/) 371 | * [Remco Beckers](https://github.com/remcobeckers) 372 | * [Mark Fristi](https://github.com/Fristi) 373 | -------------------------------------------------------------------------------- /build.sbt: -------------------------------------------------------------------------------- 1 | val akkaVer = "2.4.1" 2 | val casbahVer = "3.1.0" 3 | val commonsIoVer = "2.4" 4 | val embeddedMongoVer = "1.50.1" 5 | val logbackVer = "1.1.3" 6 | val scalaVer = "2.11.7" 7 | val scalatestVer = "2.2.4" 8 | 9 | organization := "com.github.ironfish" 10 | name := "akka-persistence-mongo" 11 | version := "1.0.0-SNAPSHOT" 12 | 13 | scalaVersion := scalaVer 14 | scalacOptions ++= Seq( 15 | "-encoding", "UTF-8", 16 | "-deprecation", 17 | "-unchecked", 18 | "-feature", 19 | "-language:postfixOps", 20 | "-target:jvm-1.8") 21 | 22 | parallelExecution in ThisBuild := false 23 | 24 | parallelExecution in Test := false 25 | logBuffered in Test := false 26 | 27 | libraryDependencies ++= Seq( 28 | "ch.qos.logback" % "logback-classic" % logbackVer % "test", 29 | "commons-io" % "commons-io" % commonsIoVer % "test", 30 | "com.typesafe.akka" %% "akka-testkit" % akkaVer % "test", 31 | "com.typesafe.akka" %% "akka-persistence" % akkaVer % "compile", 32 | "com.typesafe.akka" %% "akka-persistence-tck" % akkaVer % "test", 33 | "de.flapdoodle.embed" % "de.flapdoodle.embed.mongo" % embeddedMongoVer % "test", 34 | "org.mongodb" %% "casbah" % casbahVer % "compile" pomOnly(), 35 | "org.scalatest" %% "scalatest" % scalatestVer % "test" 36 | ) 37 | 38 | pomExtra := { 39 | https://github.com/ironfish/akka-persistence-mongo 40 | 41 | 42 | Apache 2 43 | http://www.apache.org/licenses/LICENSE-2.0.txt 44 | 45 | 46 | 47 | scm:git:github.com/ironfish/akka-persistence-mongo.git 48 | scm:git:git@github.com:ironfish/akka-persistence-mongo.git 49 | github.com/ironfish/akka-persistence-mongo.git 50 | 51 | 52 | 53 | ironfish 54 | Duncan DeVore 55 | https://github.com/ironfish/ 56 | 57 | 58 | sean-walsh 59 | Sean Walsh 60 | https://github.com/sean-walsh/ 61 | 62 | 63 | aiacovella 64 | Al Iacovella 65 | https://github.com/aiacovella/ 66 | 67 | 68 | } 69 | -------------------------------------------------------------------------------- /project/Common.scala: -------------------------------------------------------------------------------- 1 | ///** 2 | // * Copyright (C) 2013-2014 Duncan DeVore. 3 | // */ 4 | // 5 | //object Common { 6 | // def Organization = "com.github.ironfish" 7 | // def Name = "akka-persistence-mongo" 8 | // def NameCommon = Name + "-common" 9 | // def NameCasbah = Name + "-casbah" 10 | // def AkkaVersion = "2.4.1" 11 | // def CrossScalaVersions = Seq("2.10.5", "2.11.7") 12 | // def EmbeddedMongoVersion = "1.50.1" 13 | // def ScalaVersion = "2.11.7" 14 | // def ScalatestVersion = "2.2.4" 15 | // def Version = "1.0.0-SNAPSHOT" 16 | // def ParallelExecutionInTest = false 17 | // def ScalaCOptions = Seq( "-deprecation", "-unchecked", "-feature", "-language:postfixOps" ) 18 | // def TestCompile = "test->test;compile->compile" 19 | // val PomXtra = { 20 | // https://github.com/ironfish/akka-persistence-mongo 21 | // 22 | // 23 | // Apache 2 24 | // http://www.apache.org/licenses/LICENSE-2.0.txt 25 | // 26 | // 27 | // 28 | // scm:git:github.com/ironfish/akka-persistence-mongo.git 29 | // scm:git:git@github.com:ironfish/akka-persistence-mongo.git 30 | // github.com/ironfish/akka-persistence-mongo.git 31 | // 32 | // 33 | // 34 | // ironfish 35 | // Duncan DeVore 36 | // https://github.com/ironfish/ 37 | // 38 | // 39 | // sean-walsh 40 | // Sean Walsh 41 | // https://github.com/sean-walsh/ 42 | // 43 | // 44 | // aiacovella 45 | // Al Iacovella 46 | // https://github.com/aiacovella/ 47 | // 48 | // 49 | // } 50 | //} 51 | -------------------------------------------------------------------------------- /project/build.properties: -------------------------------------------------------------------------------- 1 | sbt.version=0.13.8 2 | -------------------------------------------------------------------------------- /project/plugins.sbt: -------------------------------------------------------------------------------- 1 | addSbtPlugin("org.xerial.sbt" % "sbt-sonatype" % "0.5.0") 2 | addSbtPlugin("com.jsuereth" % "sbt-pgp" % "1.0.0") 3 | -------------------------------------------------------------------------------- /src/main/resources/reference.conf: -------------------------------------------------------------------------------- 1 | ################################################# 2 | # Akka Persistence Casbah Reference Config File # 3 | ################################################# 4 | 5 | # casbah journal plugin 6 | # 7 | # A journal must support the following akka-persistence rule: 8 | # 9 | # When a PersistentActor's persist/persistAsync method completes successfully, we can safely assume the message has 10 | # persisted to the store. As a result, this journal implementation enforces journaled on all write concerns and 11 | # requires all mongo instance(s) to enable journaling. 12 | casbah-journal { 13 | 14 | # Class name of the plugin 15 | class = "akka.persistence.mongo.journal.CasbahJournal" 16 | 17 | # Default plugin dispatcher 18 | plugin-dispatcher = "casbah-journal.default-dispatcher" 19 | 20 | # Dispatcher for fetching and replaying messages 21 | replay-dispatcher = "akka.persistence.dispatchers.default-replay-dispatcher" 22 | 23 | # Option for rejecting non-serializable objects. 24 | reject-non-serializable-objects = false 25 | 26 | # Mongo URL including database and collection 27 | mongo-url = "mongodb://localhost:27017/store.messages" 28 | 29 | # woption: 30 | # The w option requests acknowledgment that the write operation has propagated to a specified number of mongod 31 | # instances or to mongod instances with specified tags. Mongo's wOption can be either an Int or String and this 32 | # journal implementation supports both with woption. 33 | # 34 | # If woption is an Int, then the write concern requests acknowledgment that the write operation has propagated to the 35 | # specified number of mongod instances. Note: The woption cannot be set to zero. 36 | # 37 | # If woption is a String, then the value can be either "majority" or a "tag set" name. If the value is "majority" 38 | # then the write concern requests acknowledgment that write operations have propagated to the majority of voting 39 | # nodes. If the value is a "tag set" name, the write concern requests acknowledgment that the write operations have 40 | # propagated to a replica set member with the specified tag. The default value is an integer value of 1. 41 | woption = 1 42 | 43 | # wtimeout: 44 | # This option specifies a time limit, in milliseconds, for the write concern. If you do not specify the wtimeout 45 | # option, and the level of write concern is unachievable, the write operation will block indefinitely. Specifying 46 | # a wtimeout value of 0 is equivalent to a write concern without the wTimeout option. The default value is 10000 47 | wtimeout = 10000 48 | 49 | # Default dispatcher for plugin actor. 50 | default-dispatcher { 51 | type = Dispatcher 52 | executor = "fork-join-executor" 53 | fork-join-executor { 54 | parallelism-min = 2 55 | parallelism-max = 8 56 | } 57 | } 58 | } 59 | 60 | # casbah snapshot plugin 61 | casbah-snapshot { 62 | 63 | # Class name of the plugin 64 | class = "akka.persistence.mongo.snapshot.CasbahSnapshot" 65 | 66 | # Default plugin dispatcher 67 | plugin-dispatcher = "casbah-snapshot.default-dispatcher" 68 | 69 | # Mongo URL including database and collection 70 | mongo-url = "mongodb://localhost:27017/store.snapshots" 71 | 72 | # woption: 73 | # The w option requests acknowledgment that the write operation has propagated to a specified number of mongod 74 | # instances or to mongod instances with specified tags. Mongo's wOption can be either an Int or String and this 75 | # journal implementation supports both with woption. 76 | # 77 | # If woption is an Int, then the write concern requests acknowledgment that the write operation has propagated to the 78 | # specified number of mongod instances. Note: The woption cannot be set to zero. 79 | # 80 | # If woption is a String, then the value can be either "majority" or a "tag set name". If the value is "majority" 81 | # then the write concern requests acknowledgment that write operations have propagated to the majority of voting 82 | # nodes. If the value is a "tag set name", the write concern requests acknowledgment that the write operations have 83 | # propagated to a replica set member with the specified tag. The default value is an integer value of 1. 84 | woption = 1 85 | 86 | # wtimeout: 87 | # This option specifies a time limit, in milliseconds, for the write concern. If you do not specify the wtimeout 88 | # option, and the level of write concern is unachievable, the write operation will block indefinitely. Specifying 89 | # a wtimeout value of 0 is equivalent to a write concern without the wTimeout option. The default value is 10000 90 | wtimeout = 10000 91 | 92 | # load-attempts 93 | # Select the youngest of {n} snapshots that match the upper bound. This helps where a snapshot may not have persisted 94 | # correctly because of a JVM crash. As a result an attempt to load the snapshot may fail but an older may succeed. 95 | load-attempts = 3 96 | 97 | # Default dispatcher for plugin actor. 98 | default-dispatcher { 99 | type = Dispatcher 100 | executor = "fork-join-executor" 101 | fork-join-executor { 102 | parallelism-min = 2 103 | parallelism-max = 8 104 | } 105 | } 106 | } 107 | -------------------------------------------------------------------------------- /src/main/scala/akka/persistence/mongo/CasbahCommon.scala: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright (C) 2015-2016 Duncan DeVore. 3 | */ 4 | package akka.persistence.mongo 5 | 6 | import com.mongodb.casbah 7 | import com.mongodb.casbah.Imports._ 8 | import com.typesafe.config.Config 9 | 10 | object CasbahCommon { 11 | val persistenceIdKey = "persistenceId" 12 | val sequenceNrKey = "sequenceNr" 13 | val messageKey: String = "message" 14 | val markerKey: String = "marker" 15 | val lteKey = "$lte" 16 | val gteKey: String = "$gte" 17 | } 18 | 19 | trait CasbahCommon { 20 | protected val initError: String = "Cannot get %s, out of the mongodb URI %s, probably invalid format." 21 | protected def mongoUrlKey: String = "mongo-url" 22 | protected val databaseMsg: String = "database" 23 | protected val collectionMsg: String = "collection" 24 | 25 | protected val configRootKey: String 26 | 27 | protected val config: Config 28 | 29 | private lazy val mongolUrl: String = config.getString(mongoUrlKey) 30 | 31 | private lazy val clientURI: casbah.MongoClientURI = MongoClientURI(mongolUrl) 32 | 33 | lazy val client: MongoClient = MongoClient(clientURI) 34 | 35 | lazy val mongoDB: MongoDB = 36 | client(clientURI.database.getOrElse( 37 | throw new IllegalArgumentException(initError.format(databaseMsg, clientURI.toString())))) 38 | 39 | lazy val mongoCollection: MongoCollection = 40 | mongoDB(clientURI.collection.getOrElse( 41 | throw new IllegalArgumentException(initError.format(collectionMsg, clientURI.toString())))) 42 | } 43 | 44 | trait CasbahJournalCommon extends CasbahCommon { 45 | override protected val configRootKey: String = "casbah-journal" 46 | protected def rejectNonSerializableObjectsKey: String = "reject-non-serializable-objects" 47 | lazy val rejectNonSerializableObjectId: Boolean = config.getBoolean(rejectNonSerializableObjectsKey) 48 | } 49 | 50 | trait CasbahSnapshotCommon extends CasbahCommon { 51 | override protected val configRootKey: String = "casbah-snapshot" 52 | val snapshotKey: String = "snapshot" 53 | val timestampKey = "timestamp" 54 | } 55 | -------------------------------------------------------------------------------- /src/main/scala/akka/persistence/mongo/CasbahRoot.scala: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright (C) 2015-2016 Duncan DeVore. 3 | */ 4 | package akka.persistence.mongo 5 | 6 | import java.util.concurrent.TimeUnit 7 | 8 | import akka.actor.{ActorSystem, ActorLogging} 9 | import akka.serialization.{Serialization, SerializationExtension} 10 | import com.mongodb.casbah.Imports._ 11 | import com.typesafe.config.{Config, ConfigException} 12 | 13 | import scala.reflect.ClassTag 14 | import scala.reflect.classTag 15 | import scala.util.{Failure, Try} 16 | 17 | object CasbahRoot { 18 | val wOptionKey: String = "woption" 19 | val wTimeoutKey: String = "wtimeout" 20 | val wOptionWrongTypeSuffix: String = s"$wOptionKey has type INVALID rather than Integer or String." 21 | val wOptionBadValueSuffix: String = s"must be greater than zero." 22 | 23 | def writeConcern(config: Config): WriteConcern = { 24 | val wOption = config.getAnyRef(wOptionKey) 25 | val wTimeout = config.getLong(wTimeoutKey) 26 | wOption match { 27 | case i: Integer if i == 0 => 28 | throw new ConfigException.BadValue(config.origin, s"$wOptionKey", s"$wOptionBadValueSuffix") 29 | case i: Integer => 30 | WriteConcern.Journaled.withW(i).withWTimeout(wTimeout, TimeUnit.MILLISECONDS) 31 | case s: String => 32 | WriteConcern.Journaled.withW(s).withWTimeout(wTimeout, TimeUnit.MILLISECONDS) 33 | case _ => 34 | throw new ConfigException.WrongType(config.origin, s"$wOptionWrongTypeSuffix") 35 | } 36 | } 37 | } 38 | 39 | trait CasbahRoot extends CasbahCommon { mixin : ActorLogging => 40 | private val uniqueKey = "unique" 41 | 42 | val actorSystem: ActorSystem 43 | 44 | protected lazy val serialization: Serialization = SerializationExtension(actorSystem) 45 | 46 | protected lazy val indexOptions: MongoDBObject = MongoDBObject(uniqueKey -> true) 47 | 48 | implicit def writeConcern: WriteConcern = CasbahRoot.writeConcern(config) 49 | 50 | protected def initialize(): Unit 51 | 52 | protected def fromBytes[T: ClassTag](dbObject: DBObject, key: String): Try[T] = { 53 | try { 54 | val byteArray: Array[Byte] = dbObject.as[Array[Byte]](key) 55 | serialization.deserialize(byteArray, classTag[T].runtimeClass.asInstanceOf[Class[T]]) 56 | } catch { 57 | case e: Exception => 58 | Failure(e) 59 | } 60 | } 61 | 62 | protected def toBytes(data: AnyRef): Try[Array[Byte]] = serialization.serialize(data) 63 | 64 | private val errorHandler: PartialFunction[Throwable, Unit] = { 65 | case ex: Exception => log.info("Index creation error: {}", ex.getMessage) 66 | } 67 | 68 | def ensure(ind0: DBObject, ind1: DBObject): (MongoCollection) => Unit = 69 | collection => 70 | Try(collection.createIndex(ind0, ind1)).recover(errorHandler) 71 | 72 | 73 | def ensure(ind: DBObject): (MongoCollection) => Unit = 74 | collection => 75 | Try (collection.createIndex(ind)).recover(errorHandler) 76 | 77 | protected def shutdown(): Unit = { 78 | client.close() 79 | } 80 | } 81 | -------------------------------------------------------------------------------- /src/main/scala/akka/persistence/mongo/journal/CasbahJournal.scala: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright (C) 2015-2016 Duncan DeVore. 3 | */ 4 | package akka.persistence.mongo.journal 5 | 6 | import akka.actor.{ActorSystem, ActorLogging} 7 | import akka.persistence._ 8 | import akka.persistence.journal.AsyncWriteJournal 9 | 10 | import com.mongodb.casbah.Imports._ 11 | import com.typesafe.config.Config 12 | 13 | import scala.collection.immutable 14 | import scala.concurrent.{Promise, Future} 15 | import scala.util.{Failure, Success, Try} 16 | 17 | private[journal] class CasbahJournal extends AsyncWriteJournal 18 | with CasbahJournalRoot 19 | with CasbahRecovery 20 | with ActorLogging { 21 | 22 | import CasbahJournalRoot._ 23 | 24 | override val actorSystem: ActorSystem = context.system 25 | 26 | override val config: Config = context.system.settings.config.getConfig(configRootKey) 27 | 28 | implicit val concern: WriteConcern = writeConcern 29 | 30 | implicit val rejectNonSerializableObjects: Boolean = rejectNonSerializableObjectId 31 | 32 | initialize() 33 | 34 | def asyncWriteMessages(messages: immutable.Seq[AtomicWrite]): Future[immutable.Seq[Try[Unit]]] = { 35 | 36 | val messagesToTryAndPersist: immutable.Seq[Try[DBObject]] = messages.flatMap(message => 37 | message.payload.map(persistentReprToDBObject)) 38 | 39 | val persistedMessages: Future[WriteResult] = 40 | Future(persistExecute(mongoCollection, messagesToTryAndPersist.flatMap(_.toOption))) 41 | 42 | val promise = Promise[immutable.Seq[Try[Unit]]]() 43 | 44 | persistedMessages.onComplete { 45 | case Success(_) if messagesToTryAndPersist.exists(_.isFailure) => 46 | promise.success(messagesToTryAndPersist.map(_ match { 47 | case Success(_) => Success((): Unit) 48 | case Failure(error) => Failure(error) 49 | })) 50 | case Success(_) => 51 | promise.complete(Success(Nil)) 52 | case Failure(e) => promise.failure(e) 53 | } 54 | promise.future 55 | } 56 | 57 | def asyncDeleteMessagesTo(persistenceId: String, toSequenceNr: Long): Future[Unit] = { 58 | Future(deleteTo(mongoCollection, concern, persistenceId, toSequenceNr)) 59 | } 60 | 61 | override def postStop(): Unit = { 62 | shutdown() 63 | } 64 | } 65 | -------------------------------------------------------------------------------- /src/main/scala/akka/persistence/mongo/journal/CasbahJournalRoot.scala: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright (C) 2015-2016 Duncan DeVore. 3 | */ 4 | package akka.persistence.mongo.journal 5 | 6 | import akka.actor.ActorLogging 7 | import akka.persistence.PersistentRepr 8 | import akka.persistence.mongo.{CasbahCommon, CasbahRoot, CasbahJournalCommon} 9 | import com.mongodb.casbah.Imports._ 10 | 11 | import scala.collection.immutable 12 | import scala.util.{Try, Failure, Success} 13 | 14 | object CasbahJournalRoot { 15 | 16 | import CasbahCommon._ 17 | 18 | def dbObjectToPersistentRepr(dbObject: DBObject, f: (DBObject, String) => 19 | Try[PersistentRepr]): Option[PersistentRepr] = { 20 | 21 | if (dbObject.as[String](markerKey) == "D") return None 22 | f(dbObject, messageKey) match { 23 | case Success(pr) => 24 | Some(pr) 25 | case Failure(error) => 26 | None 27 | } 28 | } 29 | 30 | def persistentReprToDBObjectExecute(persistentRepr: PersistentRepr, f: PersistentRepr => Try[Array[Byte]]) 31 | (implicit rejectNonSerializableObjects: Boolean): Try[DBObject] = { 32 | 33 | val errorMsg: String = "Unable to serialize payload for" 34 | val pidMsg: String = s"$persistenceIdKey: ${persistentRepr.persistenceId}" 35 | val snrMsg: String = s"$sequenceNrKey: ${persistentRepr.sequenceNr}" 36 | 37 | def marker(): String = if (persistentRepr.deleted) "D" else "" 38 | def toDBObject(data: Array[Byte]): DBObject = { 39 | val builder = MongoDBObject.newBuilder 40 | builder += persistenceIdKey -> persistentRepr.persistenceId 41 | builder += sequenceNrKey -> persistentRepr.sequenceNr 42 | builder += markerKey -> marker() 43 | builder += messageKey -> data 44 | builder.result() 45 | } 46 | 47 | f(persistentRepr) match { 48 | case Failure(error) if rejectNonSerializableObjects => 49 | Failure(new Exception(s"$errorMsg $pidMsg, $snrMsg", error)) 50 | case Failure(error) => 51 | Success(toDBObject(Array.empty[Byte])) 52 | case Success(value) => 53 | Success(toDBObject(value)) 54 | } 55 | } 56 | 57 | def deleteToExecute(collection: MongoCollection, concern: WriteConcern, persistenceId: String, 58 | toSequenceNr: Long, f: PersistentRepr => Try[Array[Byte]]): Unit = { 59 | 60 | val sequenceNbr = highestSequenceNrExecute(collection, persistenceId) 61 | collection.remove(MongoDBObject( 62 | persistenceIdKey -> persistenceId, 63 | sequenceNrKey -> MongoDBObject(lteKey -> toSequenceNr)), concern) 64 | if (toSequenceNr >= sequenceNbr) { 65 | val retainHighestSequenceNbr = PersistentRepr("D", sequenceNbr, persistenceId, deleted = true) 66 | val dbObject: DBObject = 67 | persistentReprToDBObjectExecute(retainHighestSequenceNbr, f)(rejectNonSerializableObjects = false).get 68 | persistExecute(collection, immutable.Seq(dbObject)) 69 | } 70 | } 71 | 72 | def highestSequenceNrExecute(collection: MongoCollection, persistenceId: String): Long = { 73 | val cursor: MongoCursor = collection 74 | .find(MongoDBObject(persistenceIdKey -> persistenceId)) 75 | .sort(MongoDBObject(sequenceNrKey -> -1)).limit(1) 76 | if (cursor.hasNext) cursor.next().getAs[Long](sequenceNrKey).get else 0L 77 | } 78 | 79 | 80 | def persistExecute(collection: MongoCollection, objects: immutable.Seq[DBObject]): WriteResult = { 81 | collection.insert(objects:_ *) 82 | } 83 | 84 | def replayCursorExecute(collection: MongoCollection, persistenceId: String, fromSequenceNr: Long, 85 | toSequenceNr: Long, maxNumberOfMessages: Int, f: (DBObject, String) => 86 | Try[PersistentRepr]): Iterator[PersistentRepr] = { 87 | 88 | val cursor: MongoCursor = collection.find(MongoDBObject( 89 | persistenceIdKey -> persistenceId, 90 | sequenceNrKey -> MongoDBObject(gteKey -> fromSequenceNr, lteKey -> toSequenceNr))) 91 | .sort(MongoDBObject( 92 | persistenceIdKey -> 1, 93 | sequenceNrKey -> 1)) 94 | .limit(maxNumberOfMessages) 95 | 96 | cursor.flatMap(dbObject => dbObjectToPersistentRepr(dbObject, f)) 97 | } 98 | } 99 | 100 | trait CasbahJournalRoot extends CasbahRoot 101 | with CasbahJournalCommon { mixin : ActorLogging => 102 | 103 | import CasbahJournalRoot._ 104 | import CasbahCommon._ 105 | 106 | private val replayDispatcherKey: String = "replay-dispatcher" 107 | protected lazy val replayDispatcherId: String = config.getString(replayDispatcherKey) 108 | 109 | override protected def initialize(): Unit = { 110 | val indexOne: MongoDBObject = MongoDBObject(persistenceIdKey -> 1, sequenceNrKey -> 1) 111 | val indexTwo: MongoDBObject = MongoDBObject(sequenceNrKey -> 1) 112 | ensure(indexOne, indexOptions)(mongoCollection) 113 | ensure(indexTwo)(mongoCollection) 114 | } 115 | 116 | protected def persistentReprToDBObject(persistentRepr: PersistentRepr) 117 | (implicit rejectNonSerializableObjects: Boolean): Try[DBObject] = 118 | persistentReprToDBObjectExecute(persistentRepr, toBytes) 119 | 120 | protected def deleteTo(collection: MongoCollection,concern: WriteConcern, persistenceId: String, 121 | toSequenceNr: Long): Unit = 122 | deleteToExecute(collection, concern, persistenceId, toSequenceNr, toBytes) 123 | 124 | def replayCursor(collection: MongoCollection, persistenceId: String, fromSequenceNr: Long, 125 | toSequenceNr: Long, maxNumberOfMessages: Int): Iterator[PersistentRepr] = 126 | replayCursorExecute(collection, persistenceId, fromSequenceNr, toSequenceNr, maxNumberOfMessages, 127 | fromBytes[PersistentRepr]) 128 | } 129 | -------------------------------------------------------------------------------- /src/main/scala/akka/persistence/mongo/journal/CasbahRecovery.scala: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright (C) 2015-2016 Duncan DeVore. 3 | */ 4 | package akka.persistence.mongo.journal 5 | 6 | import akka.persistence._ 7 | import akka.persistence.journal.AsyncRecovery 8 | 9 | import scala.concurrent._ 10 | 11 | trait CasbahRecovery extends AsyncRecovery { this: CasbahJournal ⇒ 12 | 13 | import CasbahJournalRoot._ 14 | 15 | implicit lazy val replayDispatcher = context.system.dispatchers.lookup(replayDispatcherId) 16 | 17 | override def asyncReadHighestSequenceNr(persistenceId: String, fromSequenceNr: Long): Future[Long] = 18 | Future (highestSequenceNrExecute(mongoCollection, persistenceId)) 19 | 20 | def asyncReplayMessages(persistenceId: String, fromSequenceNr: Long, toSequenceNr: Long, max: Long) 21 | (recoveryCallback: PersistentRepr ⇒ Unit): Future[Unit] = Future { 22 | 23 | val maxNbrOfMessages: Int = 24 | if (max <= Int.MaxValue) max.toInt 25 | else Int.MaxValue 26 | 27 | if (maxNbrOfMessages > 0) 28 | replayCursor(mongoCollection, persistenceId, fromSequenceNr, toSequenceNr, maxNbrOfMessages).foreach(recoveryCallback) 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /src/main/scala/akka/persistence/mongo/snapshot/CasbahSnapshot.scala: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright (C) 2015-2016 Duncan DeVore. 3 | */ 4 | package akka.persistence.mongo.snapshot 5 | 6 | import akka.actor.{ActorSystem, ActorLogging} 7 | import akka.persistence.snapshot.SnapshotStore 8 | import akka.persistence.{SnapshotMetadata, SelectedSnapshot, SnapshotSelectionCriteria} 9 | 10 | import com.mongodb.casbah.Imports._ 11 | 12 | import com.typesafe.config.Config 13 | 14 | import scala.collection.immutable 15 | import scala.concurrent._ 16 | 17 | private[snapshot] class CasbahSnapshot extends SnapshotStore 18 | with CasbahSnapshotRoot 19 | with ActorLogging { 20 | 21 | import context.dispatcher 22 | 23 | override val actorSystem: ActorSystem = context.system 24 | 25 | override val config: Config = context.system.settings.config.getConfig(configRootKey) 26 | 27 | implicit val concern: WriteConcern = writeConcern 28 | 29 | initialize() 30 | 31 | def deleteAsync(metadata: SnapshotMetadata): Future[Unit] = 32 | Future( mongoCollection.remove(deleteStatement(metadata))) 33 | 34 | override def deleteAsync(persistenceId: String, criteria: SnapshotSelectionCriteria): Future[Unit] = 35 | Future(mongoCollection.remove(deleteStatement(persistenceId, criteria))) 36 | 37 | // Select the youngest of {n} snapshots that match the upper bound. This helps where a snapshot may not have 38 | // persisted correctly because of a JVM crash. As a result an attempt to load the snapshot may fail but an older 39 | // may succeed. 40 | override def loadAsync(persistenceId: String, 41 | criteria: SnapshotSelectionCriteria): Future[Option[SelectedSnapshot]] = Future { 42 | 43 | val snapshots: MongoCursor = 44 | mongoCollection.find(loadStatement(persistenceId, criteria)).sort(sortStatement).limit(loadAttempts) 45 | 46 | snapshots.flatMap(dbObjectToSelectedSnapshot).to[immutable.Seq].headOption 47 | } 48 | 49 | override def saveAsync(metadata: SnapshotMetadata, snapshot: Any): Future[Unit] = 50 | Future(mongoCollection.insert(snapshotToDbObject(metadata, snapshot))) 51 | 52 | override def postStop(): Unit = { 53 | shutdown() 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /src/main/scala/akka/persistence/mongo/snapshot/CasbahSnapshotRoot.scala: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright (C) 2015-2016 Duncan DeVore. 3 | */ 4 | package akka.persistence.mongo.snapshot 5 | 6 | import akka.actor.ActorLogging 7 | import akka.persistence.serialization.Snapshot 8 | import akka.persistence.{SelectedSnapshot, SnapshotSelectionCriteria, SnapshotMetadata} 9 | import akka.persistence.mongo.{CasbahRoot, CasbahCommon, CasbahSnapshotCommon} 10 | import com.mongodb.casbah.Imports._ 11 | 12 | import scala.util.{Failure, Success} 13 | 14 | trait CasbahSnapshotRoot extends CasbahRoot 15 | with CasbahSnapshotCommon { mixin : ActorLogging => 16 | 17 | import CasbahCommon._ 18 | 19 | private val loadAttemptsKey: String = "load-attempts" 20 | 21 | protected lazy val loadAttempts: Int = config.getInt(loadAttemptsKey) 22 | 23 | override protected def initialize(): Unit = { 24 | val indexOne: MongoDBObject = MongoDBObject( 25 | persistenceIdKey -> 1, 26 | sequenceNrKey -> 1, 27 | timestampKey -> 1) 28 | ensure(indexOne, indexOptions)(mongoCollection) 29 | } 30 | 31 | protected def deleteStatement(meta: SnapshotMetadata): MongoDBObject = 32 | MongoDBObject( 33 | persistenceIdKey -> meta.persistenceId, 34 | sequenceNrKey -> meta.sequenceNr) 35 | 36 | protected def deleteStatement(persistenceId: String, criteria: SnapshotSelectionCriteria): MongoDBObject = 37 | maxSequenceNrMaxTimeStatement(persistenceId, criteria) 38 | 39 | protected def loadStatement(persistenceId: String, criteria: SnapshotSelectionCriteria): MongoDBObject = 40 | maxSequenceNrMaxTimeStatement(persistenceId, criteria) 41 | 42 | 43 | protected def snapshotToDbObject(metadata: SnapshotMetadata, snapshot: Any): DBObject = { 44 | val builder = MongoDBObject.newBuilder 45 | builder += persistenceIdKey -> metadata.persistenceId 46 | builder += sequenceNrKey -> metadata.sequenceNr 47 | builder += snapshotKey -> toBytes(Snapshot(snapshot)).get // okay, will not be stored if serialization failed. 48 | builder += timestampKey -> metadata.timestamp 49 | builder.result() 50 | } 51 | 52 | protected def sortStatement: MongoDBObject = 53 | MongoDBObject( 54 | sequenceNrKey -> -1, 55 | timestampKey -> -1) 56 | 57 | def dbObjectToSelectedSnapshot(dbObject: DBObject): Option[SelectedSnapshot] = { 58 | 59 | def toSelectedSnapshot(dBObject: DBObject, snapshot: Snapshot): SelectedSnapshot = { 60 | val snapshotMetadata = SnapshotMetadata( 61 | dbObject.as[String](persistenceIdKey), 62 | dbObject.as[Long](sequenceNrKey), 63 | dbObject.as[Long](timestampKey)) 64 | SelectedSnapshot(snapshotMetadata, snapshot.data) 65 | } 66 | 67 | fromBytes[Snapshot](dbObject,snapshotKey) match { 68 | case Success(snapshot) => 69 | Some(toSelectedSnapshot(dbObject, snapshot)) 70 | case Failure(error) => 71 | log.error(error, s"error replaying snapshot: ${dbObject.toString}") 72 | None 73 | } 74 | } 75 | 76 | private def maxSequenceNrMaxTimeStatement(persistenceId: String, criteria: SnapshotSelectionCriteria): MongoDBObject = 77 | MongoDBObject( 78 | persistenceIdKey -> persistenceId, 79 | sequenceNrKey -> MongoDBObject(lteKey -> criteria.maxSequenceNr), 80 | timestampKey -> MongoDBObject(lteKey -> criteria.maxTimestamp)) 81 | } 82 | -------------------------------------------------------------------------------- /src/test/scala/akka/persistence/mongo/CasbahRootSpec.scala: -------------------------------------------------------------------------------- 1 | package akka.persistence.mongo 2 | 3 | import java.util.concurrent.TimeUnit 4 | 5 | import com.mongodb.casbah.Imports._ 6 | import com.typesafe.config.{Config, ConfigException, ConfigFactory} 7 | import org.scalatest.{Matchers, WordSpecLike} 8 | 9 | object CasbahRootSpec { 10 | 11 | val wOptionZero = 0 12 | val wOptionOne = 1 13 | val wOptionMajority = "majority" 14 | val wOptionFalse = false 15 | 16 | val wTimeoutOneThousand = 10000 17 | val wTimeoutString = "timeout" 18 | } 19 | 20 | class CasbahRootSpec extends WordSpecLike with Matchers { 21 | 22 | import CasbahRoot._ 23 | import CasbahRootSpec._ 24 | 25 | "A CasbahRoot" should { 26 | "Return a valid WriteConcern with a valid Integer woption and wtimeout" in { 27 | val config = ConfigFactory.parseString( 28 | s""" 29 | |$wOptionKey = $wOptionOne 30 | |$wTimeoutKey = $wTimeoutOneThousand 31 | """.stripMargin 32 | ) 33 | val writeConcern: WriteConcern = CasbahRoot.writeConcern(config) 34 | writeConcern.getW shouldBe wOptionOne 35 | writeConcern.getWTimeout(TimeUnit.MILLISECONDS) shouldBe wTimeoutOneThousand 36 | } 37 | "throw ConfigException.BadValue when woption is zero" in { 38 | val config = ConfigFactory.parseString( 39 | s""" 40 | |$wOptionKey = $wOptionZero 41 | |$wTimeoutKey = $wTimeoutOneThousand 42 | """.stripMargin 43 | ) 44 | val thrown: ConfigException.BadValue = the [ConfigException.BadValue] thrownBy CasbahRoot.writeConcern(config) 45 | thrown.getMessage should include (s"$wOptionBadValueSuffix") 46 | } 47 | "Return a valid WriteConcern with a valid String woption and wtimeout" in { 48 | val config = ConfigFactory.parseString( 49 | s""" 50 | |$wOptionKey = $wOptionMajority 51 | |$wTimeoutKey = $wTimeoutOneThousand 52 | """.stripMargin 53 | ) 54 | val writeConcern: WriteConcern = CasbahRoot.writeConcern(config) 55 | writeConcern.getWString shouldBe wOptionMajority 56 | writeConcern.getWTimeout(TimeUnit.MILLISECONDS) shouldBe wTimeoutOneThousand 57 | } 58 | "throw ConfigException.WrongType when woption not of type Integer or String" in { 59 | val config = ConfigFactory.parseString( 60 | s""" 61 | |$wOptionKey = $wOptionFalse 62 | |$wTimeoutKey = $wTimeoutOneThousand 63 | """.stripMargin 64 | ) 65 | val thrown: ConfigException.WrongType = the [ConfigException.WrongType] thrownBy CasbahRoot.writeConcern(config) 66 | thrown.getMessage should include (s"$wOptionWrongTypeSuffix") 67 | } 68 | "throw ConfigException.WrongType when wtimeout not of type Long" in { 69 | val config = ConfigFactory.parseString( 70 | s""" 71 | |$wOptionKey = $wOptionOne 72 | |$wTimeoutKey = $wTimeoutString 73 | """.stripMargin 74 | ) 75 | val thrown: ConfigException.WrongType = the [ConfigException.WrongType] thrownBy CasbahRoot.writeConcern(config) 76 | thrown.getMessage should include (s"$wTimeoutKey has type STRING rather than NUMBER") 77 | } 78 | } 79 | } 80 | -------------------------------------------------------------------------------- /src/test/scala/akka/persistence/mongo/EmbeddedMongoSupport.scala: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright (C) 2015-2016 Duncan DeVore. 3 | */ 4 | package akka.persistence.mongo 5 | 6 | import de.flapdoodle.embed.mongo.{ Command, MongodStarter } 7 | import de.flapdoodle.embed.mongo.config._ 8 | import de.flapdoodle.embed.mongo.distribution.Version 9 | import de.flapdoodle.embed.process.config.IRuntimeConfig 10 | import de.flapdoodle.embed.process.config.io.ProcessOutput 11 | import de.flapdoodle.embed.process.extract.UUIDTempNaming 12 | import de.flapdoodle.embed.process.io.{ NullProcessor, Processors } 13 | import de.flapdoodle.embed.process.io.directories.PlatformTempDir 14 | import de.flapdoodle.embed.process.runtime.Network 15 | 16 | object PortServer { 17 | lazy val freePort = Network.getFreeServerPort 18 | } 19 | 20 | import PortServer._ 21 | 22 | trait EmbeddedMongoSupport { 23 | 24 | lazy val host = "localhost" 25 | lazy val port = freePort 26 | lazy val localHostIPV6 = Network.localhostIsIPv6() 27 | 28 | val artifactStorePath = new PlatformTempDir() 29 | val executableNaming = new UUIDTempNaming() 30 | val command = Command.MongoD 31 | val version = Version.Main.PRODUCTION 32 | 33 | // Used to filter out console output messages. 34 | val processOutput = new ProcessOutput( 35 | Processors.named("[mongod>]", new NullProcessor), 36 | Processors.named("[MONGOD>]", new NullProcessor), 37 | Processors.named("[console>]", new NullProcessor)) 38 | 39 | val runtimeConfig: IRuntimeConfig = 40 | new RuntimeConfigBuilder() 41 | .defaults(command) 42 | .processOutput(processOutput) 43 | .artifactStore(new ExtractedArtifactStoreBuilder() 44 | .defaults(command) 45 | .download(new DownloadConfigBuilder() 46 | .defaultsForCommand(command) 47 | .artifactStorePath(artifactStorePath).build()) 48 | .executableNaming(executableNaming)) 49 | .build() 50 | 51 | val mongodConfig = 52 | new MongodConfigBuilder() 53 | .version(version) 54 | .net(new Net(port, localHostIPV6)) 55 | .cmdOptions(new MongoCmdOptionsBuilder() 56 | .syncDelay(1) 57 | .useNoPrealloc(false) 58 | .useSmallFiles(false) 59 | .useNoJournal(false) 60 | .enableTextSearch(true) 61 | .build()) 62 | .build() 63 | 64 | lazy val mongodStarter = MongodStarter.getInstance(runtimeConfig) 65 | lazy val mongod = mongodStarter.prepare(mongodConfig) 66 | lazy val mongodExe = mongod.start() 67 | 68 | def embeddedMongoStartup() { 69 | mongodExe 70 | } 71 | 72 | def embeddedMongoShutdown() { 73 | mongod.stop() 74 | mongodExe.stop() 75 | } 76 | } 77 | -------------------------------------------------------------------------------- /src/test/scala/akka/persistence/mongo/journal/CasbahJournalRootSpec.scala: -------------------------------------------------------------------------------- 1 | package akka.persistence.mongo.journal 2 | 3 | import akka.actor._ 4 | import akka.persistence.PersistentRepr 5 | import akka.persistence.mongo.CasbahCommon 6 | import akka.persistence.mongo.EmbeddedMongoSupport 7 | import akka.persistence.mongo.PortServer._ 8 | import com.mongodb.casbah.Imports._ 9 | import com.typesafe.config.{Config, ConfigFactory} 10 | import org.scalatest.{BeforeAndAfterAll, Matchers, WordSpecLike} 11 | 12 | import scala.collection.immutable 13 | import scala.concurrent.Await 14 | import scala.concurrent.duration.Duration 15 | 16 | object CasbahJournalRootSpec extends CasbahCommon { 17 | override protected val configRootKey: String = "casbah-journal" 18 | override protected val mongoUrlKey: String = s"$configRootKey.mongo-url" 19 | 20 | val pidOne: String = "p-1" 21 | val pidTwo: String = "p-2" 22 | val minSnr: Long = 1L 23 | val maxSnr: Long = 10L 24 | 25 | val config = ConfigFactory.parseString( 26 | s""" 27 | |akka.persistence.snapshot-store.plugin = "$configRootKey" 28 | |$mongoUrlKey = "mongodb://localhost:$freePort/store.snapshots" 29 | """.stripMargin) 30 | } 31 | 32 | class CasbahJournalRootSpec extends EmbeddedMongoSupport 33 | with CasbahJournalRoot 34 | with WordSpecLike 35 | with Matchers 36 | with BeforeAndAfterAll { mixin : ActorLogging => 37 | 38 | override val actorSystem: ActorSystem = ActorSystem("test", CasbahJournalRootSpec.config) 39 | override protected val config: Config = actorSystem.settings.config.getConfig(configRootKey) 40 | 41 | implicit val concern: WriteConcern = writeConcern 42 | 43 | import CasbahJournalRoot._ 44 | import CasbahJournalRootSpec._ 45 | 46 | override def beforeAll(): Unit = { 47 | embeddedMongoStartup() 48 | super.beforeAll() 49 | } 50 | 51 | override def afterAll(): Unit = { 52 | super.afterAll() 53 | mongoDB.dropDatabase() 54 | client.close() 55 | actorSystem.terminate() 56 | Await.result(actorSystem.whenTerminated, Duration.Inf) 57 | embeddedMongoShutdown() 58 | } 59 | 60 | def persistentRepr(persistenceId: String, sequenceNr: Long) = 61 | PersistentRepr(payload = s"a-$sequenceNr", sequenceNr = sequenceNr, persistenceId = persistenceId) 62 | 63 | def messages(persistenceId: String): immutable.Seq[PersistentRepr] = { 64 | var msgs: immutable.Seq[PersistentRepr] = List.empty[PersistentRepr] 65 | minSnr to maxSnr foreach(snr => msgs = msgs :+ persistentRepr(persistenceId, snr)) 66 | msgs 67 | } 68 | 69 | "A CasbahJournalRoot" should { 70 | "return 0L for highest sequenceNr if none exist" in { 71 | val pid: String = "none" 72 | highestSequenceNrExecute(mongoCollection, pid) shouldBe 0L 73 | } 74 | "persist valid messages" in { 75 | persistExecute(mongoCollection, messages(pidOne).flatMap { 76 | message => persistentReprToDBObjectExecute(message, toBytes)(rejectNonSerializableObjects = false).toOption 77 | }) 78 | } 79 | "return the highest sequenceNr for a given persistenceId" in { 80 | highestSequenceNrExecute(mongoCollection, pidOne) shouldBe maxSnr 81 | } 82 | "return all persisted messages for a given pid on replay" in { 83 | val iter: Iterator[PersistentRepr] = 84 | replayCursorExecute(mongoCollection, pidOne, minSnr, maxSnr, maxSnr.toInt, fromBytes[PersistentRepr]) 85 | iter.size shouldBe 10 86 | var snrCntr: Long = 1 87 | iter.foreach { pr => 88 | pr.persistenceId shouldBe pidOne 89 | pr.sequenceNr shouldBe snrCntr 90 | snrCntr += 1 91 | } 92 | } 93 | "deleteTo the provided sequenceNr" in { 94 | var msgs: immutable.Seq[PersistentRepr] = List.empty[PersistentRepr] 95 | minSnr to maxSnr foreach(snr => msgs = msgs :+ persistentRepr(pidTwo, snr)) 96 | persistExecute(mongoCollection, messages(pidTwo).flatMap { 97 | message => persistentReprToDBObjectExecute(message, toBytes)(rejectNonSerializableObjects = false).toOption 98 | }) 99 | deleteToExecute(mongoCollection, concern, pidTwo, 5L, toBytes) 100 | val iter: Iterator[PersistentRepr] = 101 | replayCursorExecute(mongoCollection, pidTwo, minSnr, maxSnr, maxSnr.toInt, fromBytes[PersistentRepr]) 102 | iter.size shouldBe 5 103 | var snrCntr: Long = 6 104 | iter.foreach { pr => 105 | pr.persistenceId shouldBe pidTwo 106 | pr.sequenceNr shouldBe snrCntr 107 | snrCntr += 1 108 | } 109 | } 110 | "not replay when all entries for a given pid have been deleted" in { 111 | deleteToExecute(mongoCollection, concern, pidTwo, maxSnr, toBytes) 112 | val iter: Iterator[PersistentRepr] = 113 | replayCursorExecute(mongoCollection, pidTwo, minSnr, maxSnr, maxSnr.toInt, fromBytes[PersistentRepr]) 114 | iter.size shouldBe 0 115 | } 116 | "should retain highest sequence number when all entries for a given pid have been deleted" in { 117 | highestSequenceNrExecute(mongoCollection, pidTwo) shouldBe maxSnr 118 | } 119 | } 120 | } 121 | -------------------------------------------------------------------------------- /src/test/scala/akka/persistence/mongo/journal/CasbahJournalSpec.scala: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright (C) 2015-2016 Duncan DeVore. 3 | */ 4 | package akka.persistence.mongo.journal 5 | 6 | import akka.persistence.CapabilityFlag 7 | import akka.persistence.journal.JournalSpec 8 | import akka.persistence.mongo.{CasbahJournalCommon, EmbeddedMongoSupport} 9 | import akka.persistence.mongo.PortServer._ 10 | 11 | import com.typesafe.config.ConfigFactory 12 | 13 | import scala.concurrent.Await 14 | import scala.concurrent.duration.Duration 15 | 16 | object CasbahJournalSpec extends CasbahJournalCommon { 17 | override protected val rejectNonSerializableObjectsKey: String = s"$configRootKey.reject-non-serializable-objects" 18 | override protected val mongoUrlKey: String = s"$configRootKey.mongo-url" 19 | 20 | val config = ConfigFactory.parseString( 21 | s""" 22 | |akka.persistence.journal.plugin = "$configRootKey" 23 | |$mongoUrlKey = "mongodb://localhost:$freePort/store.messages" 24 | |$rejectNonSerializableObjectsKey = true 25 | """.stripMargin) 26 | } 27 | 28 | class CasbahJournalSpec extends JournalSpec(CasbahJournalSpec.config) 29 | with EmbeddedMongoSupport { 30 | 31 | import CasbahJournalSpec._ 32 | 33 | override def supportsRejectingNonSerializableObjects: CapabilityFlag = rejectNonSerializableObjectId 34 | 35 | override def beforeAll(): Unit = { 36 | embeddedMongoStartup() 37 | super.beforeAll() 38 | } 39 | 40 | override def afterAll(): Unit = { 41 | super.afterAll() 42 | mongoDB.dropDatabase() 43 | client.close() 44 | system.terminate() 45 | Await.result(system.whenTerminated, Duration.Inf) 46 | embeddedMongoShutdown() 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /src/test/scala/akka/persistence/mongo/journal/CasbahLJournalLoadSpec.scala: -------------------------------------------------------------------------------- 1 | package akka.persistence.mongo.journal 2 | 3 | import akka.actor.{ActorRef, Props, ActorSystem, Actor} 4 | import akka.persistence.PersistentActor 5 | import akka.persistence.mongo.{EmbeddedMongoSupport, CasbahJournalCommon} 6 | import akka.persistence.mongo.PortServer._ 7 | import akka.testkit.{ImplicitSender, TestKit} 8 | 9 | import com.typesafe.config.ConfigFactory 10 | 11 | import org.scalatest.{BeforeAndAfterAll, Matchers, WordSpecLike} 12 | 13 | import scala.concurrent.Await 14 | import scala.concurrent.duration._ 15 | 16 | object CasbahLJournalLoadSpec extends CasbahJournalCommon { 17 | override protected val rejectNonSerializableObjectsKey: String = s"$configRootKey.reject-non-serializable-objects" 18 | override protected val mongoUrlKey: String = s"$configRootKey.mongo-url" 19 | 20 | val config = ConfigFactory.parseString( 21 | s""" 22 | |akka.persistence.journal.plugin = "$configRootKey" 23 | |$mongoUrlKey = "mongodb://localhost:$freePort/store.messages" 24 | |$rejectNonSerializableObjectsKey = false 25 | """.stripMargin) 26 | 27 | trait Measure extends { this: Actor ⇒ 28 | val NanoToSecond = 1000.0 * 1000 * 1000 29 | 30 | var startTime: Long = 0L 31 | var stopTime: Long = 0L 32 | 33 | var startSequenceNr = 0L 34 | var stopSequenceNr = 0L 35 | 36 | def startMeasure(): Unit = { 37 | startSequenceNr = lastSequenceNr 38 | startTime = System.nanoTime 39 | } 40 | 41 | def stopMeasure(): Unit = { 42 | stopSequenceNr = lastSequenceNr 43 | stopTime = System.nanoTime 44 | sender ! (NanoToSecond * (stopSequenceNr - startSequenceNr) / (stopTime - startTime)) 45 | } 46 | 47 | def lastSequenceNr: Long 48 | } 49 | 50 | class ProcessorA(val persistenceId: String) extends PersistentActor with Measure { 51 | def receiveRecover: Receive = handle 52 | 53 | def receiveCommand: Receive = { 54 | case c@"start" => 55 | deferAsync(c) { 56 | _ => startMeasure() 57 | sender ! "started" 58 | } 59 | case c@"stop" => 60 | deferAsync(c)(_ => stopMeasure()) 61 | case payload: String => 62 | persistAsync(payload)(handle) 63 | } 64 | 65 | def handle: Receive = { 66 | case payload: String => 67 | } 68 | } 69 | 70 | class ProcessorB(val persistenceId: String, failAt: Option[Long], receiver: ActorRef) extends PersistentActor { 71 | def receiveRecover: Receive = handle 72 | 73 | def receiveCommand: Receive = { 74 | case payload: String => persistAsync(payload)(handle) 75 | } 76 | 77 | def handle: Receive = { 78 | case payload: String => 79 | receiver ! s"$payload-$lastSequenceNr" 80 | } 81 | } 82 | } 83 | 84 | class CasbahLJournalLoadSpec extends TestKit(ActorSystem("test", CasbahLJournalLoadSpec.config)) 85 | with EmbeddedMongoSupport 86 | with ImplicitSender 87 | with WordSpecLike 88 | with Matchers 89 | with BeforeAndAfterAll{ 90 | 91 | import CasbahLJournalLoadSpec._ 92 | 93 | override def beforeAll(): Unit = { 94 | embeddedMongoStartup() 95 | super.beforeAll() 96 | } 97 | 98 | override def afterAll(): Unit = { 99 | super.afterAll() 100 | mongoDB.dropDatabase() 101 | client.close() 102 | system.terminate() 103 | Await.result(system.whenTerminated, Duration.Inf) 104 | embeddedMongoShutdown() 105 | } 106 | 107 | "A Casbah journal" should { 108 | "have some reasonable write throughput" in { 109 | val warmCycles = 100L 110 | val loadCycles = 1000L 111 | 112 | val processor1 = system.actorOf(Props(classOf[ProcessorA], "p1a")) 113 | 1L to warmCycles foreach { i => processor1 ! "a" } 114 | processor1 ! "start" 115 | expectMsg("started") 116 | 1L to loadCycles foreach { i => processor1 ! "a" } 117 | processor1 ! "stop" 118 | expectMsgPF(100 seconds) { 119 | case throughput: Double ⇒ println(f"\nthroughput = $throughput%.2f persistent commands per second") } 120 | } 121 | "work properly under load" in { 122 | val cycles = 1000L 123 | 124 | val processor1 = system.actorOf(Props(classOf[ProcessorB], "p1b", None, self)) 125 | 1L to cycles foreach { i => processor1 ! "a" } 126 | 1L to cycles foreach { i => expectMsg(s"a-$i") } 127 | 128 | val processor2 = system.actorOf(Props(classOf[ProcessorB], "p1b", None, self)) 129 | 1L to cycles foreach { i => expectMsg(s"a-$i") } 130 | 131 | processor2 ! "b" 132 | expectMsg(s"b-${cycles + 1L}") 133 | } 134 | } 135 | } -------------------------------------------------------------------------------- /src/test/scala/akka/persistence/mongo/snapshot/CasbahSnapshotSpec.scala: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright (C) 2015-2016 Duncan DeVore. 3 | */ 4 | package akka.persistence.mongo.snapshot 5 | 6 | import akka.persistence.SnapshotProtocol.{LoadSnapshotResult, LoadSnapshot} 7 | import akka.persistence.SnapshotSelectionCriteria 8 | import akka.persistence.mongo.{CasbahCommon, CasbahSnapshotCommon, EmbeddedMongoSupport} 9 | import akka.persistence.mongo.PortServer._ 10 | import akka.persistence.snapshot.SnapshotStoreSpec 11 | import akka.testkit.TestProbe 12 | import com.mongodb.casbah.Imports._ 13 | import com.typesafe.config.ConfigFactory 14 | 15 | import scala.compat.Platform 16 | import scala.concurrent.Await 17 | import scala.concurrent.duration.Duration 18 | 19 | object CasbahSnapshotSpec extends CasbahSnapshotCommon { 20 | override protected val mongoUrlKey: String = s"$configRootKey.mongo-url" 21 | 22 | val config = ConfigFactory.parseString( 23 | s""" 24 | |akka.persistence.snapshot-store.plugin = "$configRootKey" 25 | |$mongoUrlKey = "mongodb://localhost:$freePort/store.snapshots" 26 | """.stripMargin) 27 | } 28 | 29 | class CasbahSnapshotSpec extends SnapshotStoreSpec(CasbahSnapshotSpec.config) 30 | with EmbeddedMongoSupport { 31 | 32 | implicit val concern: WriteConcern = WriteConcern.Journaled 33 | 34 | import CasbahCommon._ 35 | import CasbahSnapshotSpec._ 36 | 37 | override def beforeAll(): Unit = { 38 | embeddedMongoStartup() 39 | super.beforeAll() 40 | } 41 | 42 | override def afterAll(): Unit = { 43 | super.afterAll() 44 | mongoDB.dropDatabase() 45 | client.close() 46 | system.terminate() 47 | Await.result(system.whenTerminated, Duration.Inf) 48 | embeddedMongoShutdown() 49 | } 50 | 51 | private def badSnapshot(persistenceId: String, sequenceNr: Long): DBObject = { 52 | val builder = MongoDBObject.newBuilder 53 | builder += persistenceIdKey -> persistenceId 54 | builder += sequenceNrKey -> sequenceNr 55 | builder += snapshotKey -> s"BAD SNAPSHOT $persistenceId" 56 | builder += timestampKey -> Platform.currentTime 57 | builder.result() 58 | } 59 | 60 | "A Casbah snapshot store" must { 61 | "make up to 3 snapshot loading attempts" in { 62 | val probe = TestProbe() 63 | 64 | // load most recent snapshot 65 | snapshotStore.tell(LoadSnapshot(pid, SnapshotSelectionCriteria.Latest, Long.MaxValue), probe.ref) 66 | 67 | // get most recent snapshot 68 | val expected = probe.expectMsgPF() { case LoadSnapshotResult(Some(snapshot), _) => snapshot } 69 | 70 | mongoCollection.insert(badSnapshot(pid, 123L))(identity, concern) 71 | mongoCollection.insert(badSnapshot(pid, 124L))(identity, concern) 72 | 73 | // load most recent snapshot, first two attempts will fail ... 74 | snapshotStore.tell(LoadSnapshot(pid, SnapshotSelectionCriteria.Latest, Long.MaxValue), probe.ref) 75 | 76 | // third attempt succeeds 77 | probe.expectMsg(LoadSnapshotResult(Some(expected), Long.MaxValue)) 78 | } 79 | "give up after 3 snapshot loading attempts" in { 80 | val probe = TestProbe() 81 | 82 | // load most recent snapshot 83 | snapshotStore.tell(LoadSnapshot(pid, SnapshotSelectionCriteria.Latest, Long.MaxValue), probe.ref) 84 | 85 | // wait for most recent snapshot 86 | probe.expectMsgPF() { case LoadSnapshotResult(Some(snapshot), _) => snapshot } 87 | 88 | // write three more snapshots that cannot be de-serialized. 89 | mongoCollection.insert(badSnapshot(pid, 123L))(identity, concern) 90 | mongoCollection.insert(badSnapshot(pid, 124L))(identity, concern) 91 | mongoCollection.insert(badSnapshot(pid, 125L))(identity, concern) 92 | 93 | // load most recent snapshot, first three attempts will fail ... 94 | snapshotStore.tell(LoadSnapshot(pid, SnapshotSelectionCriteria.Latest, Long.MaxValue), probe.ref) 95 | 96 | // no 4th attempt has been made 97 | probe.expectMsg(LoadSnapshotResult(None, Long.MaxValue)) 98 | } 99 | } 100 | } --------------------------------------------------------------------------------