{"id":13463719,"url":"https://github.com/eligosource/eventsourced","last_synced_at":"2026-03-12T09:43:45.093Z","repository":{"id":3871637,"uuid":"4957528","full_name":"eligosource/eventsourced","owner":"eligosource","description":"A library for building reliable, scalable and distributed event-sourced applications in Scala","archived":false,"fork":false,"pushed_at":"2014-05-13T13:43:07.000Z","size":7850,"stargazers_count":828,"open_issues_count":22,"forks_count":98,"subscribers_count":106,"default_branch":"master","last_synced_at":"2024-10-29T16:19:41.770Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":"","language":"JavaScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"apache-2.0","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/eligosource.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2012-07-09T12:27:32.000Z","updated_at":"2024-07-17T06:00:31.000Z","dependencies_parsed_at":"2022-09-15T01:02:36.172Z","dependency_job_id":null,"html_url":"https://github.com/eligosource/eventsourced","commit_stats":null,"previous_names":[],"tags_count":11,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/eligosource%2Feventsourced","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/eligosource%2Feventsourced/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/eligosource%2Feventsourced/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/eligosource%2Feventsourced/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/eligosource","download_url":"https://codeload.github.com/eligosource/eventsourced/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":245435071,"owners_count":20614823,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":[],"created_at":"2024-07-31T14:00:27.305Z","updated_at":"2025-12-18T10:06:51.188Z","avatar_url":"https://github.com/eligosource.png","language":"JavaScript","readme":"[![Build Status](https://secure.travis-ci.org/eligosource/eventsourced.png)](http://travis-ci.org/eligosource/eventsourced)\n\nEventsourced\n============\n\n\u003ctable border=\"0\"\u003e\n  \u003ctr\u003e\n    \u003ctd\u003eScala version: \u003c/td\u003e\n    \u003ctd\u003e2.10.2\u003c/td\u003e\n  \u003c/tr\u003e\n  \u003ctr\u003e\n    \u003ctd\u003eAkka version: \u003c/td\u003e\n    \u003ctd\u003e2.2.0\u003c/td\u003e\n  \u003c/tr\u003e\n\u003c/table\u003e\n\n- [Releases](https://github.com/eligosource/eventsourced/wiki#releases)\n- [Installation](https://github.com/eligosource/eventsourced/wiki/Installation)\n\nContents\n--------\n\n- [Overview](#overview)\n    - [Building blocks](#building-blocks)\n        - [Processor](#processor)\n        - [Channel](#channel)\n        - [Journal](#journal)\n    - [Application](#application)\n    - [Journals](#journals)\n- [Terminology](#terminology)\n- [First steps](#first-steps)\n    - [Step 1: EventsourcingExtension initialization](#step-1-eventsourcingextension-initialization)\n    - [Step 2: Event-sourced actor definition](#step-2-event-sourced-actor-definition)\n    - [Step 3: Event-sourced actor creation and recovery](#step-3-event-sourced-actor-creation-and-recovery)\n    - [Step 4: Event-sourced actor usage](#step-4-event-sourced-actor-usage)\n    - [Step 5: Channel usage](#step-5-channel-usage)\n- [Stackable traits](#stackable-traits)\n    - [Eventsourced](#eventsourced-1)\n    - [Receiver](#receiver)\n    - [Emitter](#emitter)\n    - [Confirm](#confirm)\n    - [Modified example](#modified-example)\n- [Sender references](#sender-references)\n- [Channels](#channels)\n    - [DefaultChannel](#defaultchannel)\n    - [ReliableChannel](#reliablechannel)\n    - [Reliable request-reply channel](#reliable-request-reply-channel)\n    - [Usage hints](#usage-hints)\n        - [Eventsourced usage](#eventsourced-usage)\n        - [Standalone usage](#standalone-usage)\n        - [Remote destinations](#remote-destinations)\n    - [Channel alternatives](#channel-alternatives)\n- [Recovery](#recovery)\n    - [Replay parameters](#replay-parameters)\n        - [Recovery without snapshots](#recovery-without-snapshots)\n        - [Recovery with snapshots](#recovery-with-snapshots)\n    - [Await processing](#await-processing)\n    - [Non-blocking recovery](#non-blocking-recovery)\n    - [Channel recovery and usage](#channel-recovery-and-usage)\n    - [State dependencies](#state-dependencies)\n- [Snapshots](#snapshots)\n    - [Configuration](#configuration)\n- [Behavior changes](#behavior-changes)\n- [Event series](#event-series)\n- [Idempotency](#idempotency)\n- [Serialization](#serialization)\n- [Further examples](#further-examples)\n    - [Order management](#order-management)\n    - [State machines](#state-machines)\n    - [Clustering](#clustering)\n- [Miscellaneous](#miscellaneous)\n    - [Multicast processor](#multicast-processor)\n    - [Retroactive changes](#retroactive-changes)\n- [Appendix A: Legend](#appendix-a-legend)\n- [Appendix B: Project](#appendix-b-project)\n- [Appendix C: Articles](#appendix-c-articles)\n- [Appendix D: Support](#appendix-d-support)\n\nOverview\n--------\n\nThe Eventsourced library adds scalable actor state persistence and at-least-once message delivery guarantees to [Akka](http://akka.io/). With Eventsourced, stateful actors\n\n- persist received messages by appending them to a log (journal)\n- project received messages to derive current state\n- usually hold current state in memory (memory image)\n- recover current (or past) state by replaying received messages (during normal application start or after crashes)\n- never persist current state directly (except optional state [snapshots](#snapshots) for recovery time optimization)\n\nIn other words, Eventsourced implements a write-ahead log (WAL) that is used to keep track of messages an actor receives and to recover its state by replaying logged messages. Appending messages to a log instead of persisting actor state directly allows for actor state persistence at very high transaction rates and supports efficient replication. In contrast to other WAL-based systems, Eventsourced usually keeps the whole message history in the log and makes usage of state snapshots optional.\n\nLogged messages represent intended changes to an actor's state. Logging changes instead of updating current state is one of the core concept of [event sourcing](http://martinfowler.com/eaaDev/EventSourcing.html). Eventsourced can be used to implement event sourcing concepts but it is not limited to that. More details about Eventsourced and its relation to event sourcing can be found at [*How does Eventsourced persist actor state and how is this related to event sourcing*](https://github.com/eligosource/eventsourced/wiki/FAQ#wiki-event-sourcing-comparison).\n\nEventsourced can also be used to make message exchanges between actors reliable so that they can be resumed after crashes, for example. For that purpose, channels with at-least-once message delivery guarantees are provided. Channels also prevent that output messages, sent by persistent actors, are redundantly delivered during replays which is relevant for message exchanges between these actors and other services.\n\n### Building blocks\n\nThe core building blocks provided by Eventsourced are processors, channels and journals. These are managed by an Akka extension, the [`EventsourcingExtension`](http://eligosource.github.com/eventsourced/api/snapshot/#org.eligosource.eventsourced.core.EventsourcingExtension).\n\n#### Processor\n\nA processor is a stateful actor that logs (persists) messages it receives. A stateful actor is turned into a processor by modifying it with the stackable [`Eventsourced`](http://eligosource.github.com/eventsourced/api/snapshot/#org.eligosource.eventsourced.core.Eventsourced) trait during construction. A processor can be used like any other actor.\n\nMessages wrapped inside [`Message`](http://eligosource.github.com/eventsourced/api/snapshot/#org.eligosource.eventsourced.core.Message) are logged by a processor, unwrapped messages are not logged. Wrapped messages are often referred to as *events* in this user guide. Wrapped messages can also be *commands*, as explained in section [Application](#application).\n\nLogging behavior is implemented by the `Eventsourced` trait, a processor's `receive` method doesn't need to care about that. Acknowledging a successful write to a sender can be done by sending a reply. A processor can also hot-swap its behavior by still keeping its logging functionality.\n\nProcessors are registered at an `EventsourcingExtension`. This extension provides methods to recover processor state by replaying logged messages. Processors can be registered and recovered at any time during an application run.\n\nEventsourced doesn't impose any restrictions how processors maintain state. A processor can use vars, mutable data structures or STM references, for example.\n\n#### Channel\n\n[Channels](#channels) are used by processors for sending messages to other actors (channel destinations) and receiving replies from them. Channels\n\n- require their destinations to confirm the receipt of messages for providing at-least-once delivery guarantees (explicit ack-retry protocol). Receipt confirmations are written to a log.\n- prevent redundant delivery of messages to destinations during processor recovery (replay of messages). Replayed messages with matching receipt confirmations are dropped by the corresponding channels.\n\nA channel itself is an actor that decorates a destination with the aforementioned functionality. Processors usually create channels as child actors for decorating destination actor references.\n\nA processor may also sent messages directly to another actor without using a channel. In this case that actor will redundantly receive messages during processor recovery.\n\nEventsourced provides three different channel types (more are planned).\n\n- Default channel\n    - Does not store received messages.\n    - Re-delivers uncomfirmed messages only during recovery of the sending processor.\n    - Order of messages as sent by a processor is not preserved in failure cases.\n- Reliable channel\n    - Stores received messages.\n    - Re-delivers unconfirmed messages based on a configurable re-delivery policy.\n    - Order of messages as sent by a processor is preserved, even in failure cases.\n    - Often used to deal with unreliable remote destinations.\n    - Can recover from crashes of the JVM it is running in.\n- Reliable request-reply channel\n    - Same as reliable channel but additionally guarantees at-least-once delivery of replies.\n    - Order of replies not guaranteed to correspond to the order of sent request messages.\n\nEventsourced channels are not meant to replace any existing messaging system but can be used, for example, to reliably connect processors to such a system, if needed. More generally, they are useful to integrate processors with other services, as described in [this article](http://krasserm.blogspot.de/2013/01/event-sourcing-and-external-service.html).\n\n#### Journal\n\nA journal is an actor that is used by processors and channels to log messages and receipt confirmations. The quality of service (availability, scalability, ...) provided by a journal depends on the used storage technology. The [Journals](#journals) section below gives an overview of existing journal implementations and their development status.\n\n### Application\n\nThe Eventsourced library doesn't impose any restrictions on the structure and semantics of [`Message`](http://eligosource.github.com/eventsourced/api/snapshot/#org.eligosource.eventsourced.core.Message) payloads. Hence, persistent messages can therefore be events as well as commands. Both can be seen as *facts* about the interaction of an application with its environment. This is demonstrated in the Eventsourced [reference application](https://github.com/eligosource/eventsourced-example) which persists events as well as commands. This also simplifies the implementation of long-running, persistent business processes (sometimes referred to as *sagas*). These are processors that react on events by sending commands to other services which can be other processors or external services, for example.\n\nEventsourced fits well into applications that implement the [CQRS](http://martinfowler.com/bliki/CQRS.html) pattern and follow a [domain-driven design](http://domaindrivendesign.org/resources/what_is_ddd) (DDD) (see [reference application](https://github.com/eligosource/eventsourced-example)). On the other hand, the library doesn't force applications to do so and allows them to implement event-sourcing (and/or command-sourcing) without CQRS and/or DDD.\n\n### Journals\n\nFor persisting messages, Eventsourced currently provides the following journal implementations:\n\n\u003ctable\u003e\n  \u003ctr\u003e\n    \u003cth align=\"left\"\u003eJournal\u003c/th\u003e\n    \u003cth align=\"left\"\u003eUsage\u003c/th\u003e\n  \u003c/tr\u003e\n  \u003ctr\u003e\n    \u003ctd\u003e\u003ca href=\"http://eligosource.github.com/eventsourced/api/snapshot/#org.eligosource.eventsourced.journal.leveldb.LeveldbJournalProps\"\u003eLevelDB journal\u003c/a\u003e. It can be configured either with a \u003ca href=\"http://code.google.com/p/leveldb/\"\u003enative LevelDB\u003c/a\u003e (accessed via \u003ca href=\"https://github.com/fusesource/leveldbjni\"\u003eleveldbjni\u003c/a\u003e) or a \u003ca href=\"https://github.com/dain/leveldb\"\u003eLevelDB Java port\u003c/a\u003e as storage backend. Running a native LevelDB from sbt requires \u003ca href=\"https://github.com/eligosource/eventsourced/wiki/Installation#native-leveldb\"\u003especial settings\u003c/a\u003e. All examples in this user guide use the LevelDB Java port.\n    \u003ctd\u003eProduction\u003c/td\u003e\n  \u003c/tr\u003e\n  \u003ctr\u003e\n    \u003ctd\u003e\u003ca href=\"http://eligosource.github.com/eventsourced/api/snapshot/#org.eligosource.eventsourced.journal.hbase.HBaseJournalProps\"\u003eHBase journal\u003c/a\u003e. An \u003ca href=\"http://hbase.apache.org/\"\u003eHBase\u003c/a\u003e backed journal supporting high-availability, horizontal read and write scalability, concurrent and non-blocking reads and writes. Details \u003ca href=\"https://github.com/eligosource/eventsourced/blob/master/es-journal/es-journal-hbase/readme.md#hbase-journal\"\u003ehere\u003c/a\u003e.\u003c/td\u003e\n    \u003ctd\u003eExperimental\u003c/td\u003e\n  \u003c/tr\u003e\n  \u003ctr\u003e\n    \u003ctd\u003e\u003ca href=\"http://eligosource.github.com/eventsourced/api/snapshot/#org.eligosource.eventsourced.journal.mongodb.casbah.MongodbCasbahJournalProps\"\u003eMongoDB Casbah based journal\u003c/a\u003e. A \u003ca href=\"http://www.mongodb.org/\"\u003eMongoDB\u003c/a\u003e backed journal. Details \u003ca href=\"https://github.com/eligosource/eventsourced/blob/master/es-journal/es-journal-mongodb-casbah/readme.md#mongodb-casbah-journal\"\u003ehere\u003c/a\u003e. Thanks to \u003ca href=\"https://github.com/ddevore\"\u003eDuncan DeVore\u003c/a\u003e.\u003c/td\u003e\n    \u003ctd\u003eExperimental\u003c/td\u003e\n  \u003c/tr\u003e\n  \u003ctr\u003e\n    \u003ctd\u003e\u003ca href=\"http://eligosource.github.com/eventsourced/api/snapshot/#org.eligosource.eventsourced.journal.mongodb.reactive.MongodbReactiveJournalProps\"\u003eMongoDB Reactive based journal\u003c/a\u003e. A \u003ca href=\"http://www.mongodb.org/\"\u003eMongoDB\u003c/a\u003e backed journal. Details \u003ca href=\"https://github.com/eligosource/eventsourced/blob/master/es-journal/es-journal-mongodb-reactive/readme.md#mongodb-reactive-journal\"\u003ehere\u003c/a\u003e. Thanks to \u003ca href=\"https://github.com/ddevore\"\u003eDuncan DeVore\u003c/a\u003e.\u003c/td\u003e\n    \u003ctd\u003eExperimental\u003c/td\u003e\n  \u003c/tr\u003e\n  \u003ctr\u003e\n    \u003ctd\u003e\u003ca href=\"http://eligosource.github.com/eventsourced/api/snapshot/#org.eligosource.eventsourced.journal.dynamodb.DynamoDBJournalProps\"\u003eDynamoDB journal\u003c/a\u003e. A \u003ca href=\"http://aws.amazon.com/en/dynamodb/\"\u003eDynamoDB \u003c/a\u003e backed journal. Details \u003ca href=\"https://github.com/eligosource/eventsourced/blob/master/es-journal/es-journal-dynamodb/readme.md#dynamodb-journal\"\u003ehere\u003c/a\u003e. Thanks to \u003ca href=\"https://github.com/sclasen\"\u003eScott Clasen\u003c/a\u003e.\u003c/td\u003e\n    \u003ctd\u003eExperimental\u003c/td\u003e\n  \u003c/tr\u003e\n  \u003ctr\u003e\n    \u003ctd\u003e\u003ca href=\"http://eligosource.github.com/eventsourced/api/snapshot/#org.eligosource.eventsourced.journal.journalio.JournalioJournalProps\"\u003eJournal.IO journal\u003c/a\u003e. \u003ca href=\"https://github.com/sbtourist/Journal.IO\"\u003eJournal.IO\u003c/a\u003e backed journal for testing purposes. Messages are persisted.\u003c/td\u003e\n    \u003ctd\u003eTesting\u003c/td\u003e\n  \u003c/tr\u003e\n  \u003ctr\u003e\n    \u003ctd\u003e\u003ca href=\"http://eligosource.github.com/eventsourced/api/snapshot/#org.eligosource.eventsourced.journal.inmem.InmemJournalProps\"\u003eIn memory journal\u003c/a\u003e. An in-memory journal for testing purposes. Messages are not persisted.\u003c/td\u003e\n    \u003ctd\u003eTesting\u003c/td\u003e\n  \u003c/tr\u003e\n\u003c/table\u003e\n\nTerminology\n-----------\n\nIn the following, the terms *persistent actor*, *event-sourced actor*, *event-sourced processor* and *processor* are used interchangeably. Furthermore, a [`Message`](http://eligosource.github.com/eventsourced/api/snapshot/#org.eligosource.eventsourced.core.Message) is often referred to as *event message*.\n\nFirst steps\n-----------\n\nThis section guides through the minimum steps required to create, use and recover an event-sourced actor and demonstrates the usage of channels. Code from this section is contained in [FirstSteps.scala](https://github.com/eligosource/eventsourced/blob/master/es-examples/src/main/scala/org/eligosource/eventsourced/guide/FirstSteps.scala) and [FirstSteps.java](https://github.com/eligosource/eventsourced/blob/master/es-examples/src/main/java/org/eligosource/eventsourced/guide/japi/FirstSteps.java). It can be executed from the sbt prompt with\n\n**Scala:**\n\n    \u003e project eventsourced-examples\n    \u003e run-main org.eligosource.eventsourced.guide.FirstSteps\n\n**Java:**\n\n    \u003e project eventsourced-examples\n    \u003e run-main org.eligosource.eventsourced.guide.japi.FirstSteps\n\nThe example in this section and all further examples use a journal that is backed by a [LevelDB Java port](https://github.com/eligosource/eventsourced/wiki/Installation#leveldb-java-port). For running a [native LevelDB](https://github.com/eligosource/eventsourced/wiki/Installation#native-leveldb) instance from sbt, [additional settings](https://github.com/eligosource/eventsourced/wiki/Installation#native-leveldb) are required. A legend to the figures used in this and other sections is in [Appendix A](#appendix-a-legend).\n\n### Step 1: `EventsourcingExtension` initialization\n\n[`EventsourcingExtension`](http://eligosource.github.com/eventsourced/api/snapshot/#org.eligosource.eventsourced.core.EventsourcingExtension) is an Akka extension provided by the Eventsourced library. It is used by applications to\n\n- create and register event-sourced actors (called *processors* or *event processors*)\n- create and register channels\n- recover registered processors and channels from journaled event messages\n\nAn `EventsourcingExtension` is initialized with an `ActorSystem` and a journal `ActorRef`.\n\n**Scala:**\n\n```scala\nimport java.io.File\nimport akka.actor._\nimport org.eligosource.eventsourced.core._\nimport org.eligosource.eventsourced.journal.leveldb._\n\nval system: ActorSystem = ActorSystem(\"example\")\nval journal: ActorRef = LeveldbJournalProps(new File(\"target/example-1\"), native = false).createJournal\nval extension: EventsourcingExtension = EventsourcingExtension(system, journal)\n```\n\n**Java:**\n\n```java\nimport java.io.File;\nimport akka.actor.*;\nimport org.eligosource.eventsourced.core.*;\nimport org.eligosource.eventsourced.journal.leveldb.*;\n\nfinal ActorSystem system = ActorSystem.create(\"guide\");\nfinal ActorRef journal = LeveldbJournalProps.create(new File(\"target/guide-1-java\")).withNative(false).createJournal(system);\nfinal EventsourcingExtension extension = EventsourcingExtension.create(system, journal);\n```\n\nThis example uses a [LevelDB journal](http://eligosource.github.com/eventsourced/api/snapshot/#org.eligosource.eventsourced.journal.leveldb.LeveldbJournalProps) but any other [journal implementation](#journals) can be used as well.\n\n### Step 2: Event-sourced actor definition\n\nWith the Scala API, event-sourced actors can be defined as 'plain' actors. With the Java API, event-sourced actors need to extend the abstract [`UntypedEventsourcedActor`](http://eligosource.github.com/eventsourced/api/snapshot/#org.eligosource.eventsourced.core.UntypedEventsourcedActor) class. For example,\n\n**Scala:**\n\n```scala\nclass Processor extends Actor {\n  var counter = 0\n\n  def receive = {\n    case msg: Message =\u003e {\n      counter = counter + 1\n      println(\"[processor] event = %s (%d)\" format (msg.event, counter))\n    }\n  }\n}\n```\n\n**Java:**\n\n```java\npublic class Processor extends UntypedEventsourcedActor {\n    private int counter = 0;\n\n    @Override\n    public int id() {\n        return 1;\n    }\n\n    @Override\n    public void onReceive(Object message) throws Exception {\n        if (message instanceof Message) {\n            Message msg = (Message)message;\n            counter = counter + 1;\n            System.out.println(String.format(\"[processor] event = %s (%d)\", msg.event(), counter));\n        }\n    }\n}\n```\n\nis an actor that counts the number of received event [`Message`](http://eligosource.github.com/eventsourced/api/snapshot/#org.eligosource.eventsourced.core.Message)s. In Eventsourced applications, events are always communicated (transported) via event `Message`s.\n\n### Step 3: Event-sourced actor creation and recovery\n\nTo make the Scala `Processor` an event-sourced actor, it must be modified with the stackable [`Eventsourced`](http://eligosource.github.com/eventsourced/api/snapshot/#org.eligosource.eventsourced.core.Eventsourced) trait during instantiation. The Java `Processor` already extends [`UntypedEventsourcedActor`](http://eligosource.github.com/eventsourced/api/snapshot/#org.eligosource.eventsourced.core.UntypedEventsourcedActor) class, so no further modification is needed.\n\n**Scala:**\n\n```scala\n// create and register event-sourced processor\nval processor: ActorRef = extension.processorOf(Props(new Processor with Eventsourced { val id = 1 } ))\n\n// recover registered processors by replaying journaled events\nextension.recover()\n```\n\n**Java:**\n\n```java\n// create and register event-sourced processor\nfinal ActorRef processor = extension.processorOf(Props.create(Processor.class), system);\n\n// recover registered processors by replaying journaled events\nextension.recover();\n```\n\nAn actor that is modified with `Eventsourced` (or extends `UntypedEventsourcedActor`) writes event `Message`s to a journal before its `receive`  method (or `onReceive` method, respectively) is called. The `processorOf` method registers that actor under a unique `id`. The processor `id` is defined by implementing the abstract `Eventsourced.id` member which must be a positive integer and consistently re-used across applications runs. The `recover` method recovers the state of `processor` by replaying all event messages that `processor` received in previous application runs.\n\n### Step 4: Event-sourced actor usage\n\nThe event-sourced `processor` can be used like any other actor. Messages of type [`Message`](http://eligosource.github.com/eventsourced/api/snapshot/#org.eligosource.eventsourced.core.Message) are written to the journal, messages of any other type are directly received by `processor` without being journaled.\n\n![Event-sourced actor](https://raw.github.com/eligosource/eventsourced/master/doc/images/firststeps-1.png)\n\n**Scala:**\n\n```scala\n// send event message to processor (will be journaled)\nprocessor ! Message(\"foo\")\n```\n\n**Java:**\n\n```java\n// send event message to processor (will be journaled)\nprocessor.tell(Message.create(\"foo\"), null);\n```\n\nA first application run will create an empty journal. Hence, no event messages will be replayed and the `processor` writes\n\n    [processor] event = foo (1)\n\nto `stdout`. When the application is restarted, however, the `processor`'s state will be recovered by replaying the previously journaled event message. Then, the application sends another event message. You will therefore see\n\n    [processor] event = foo (1)\n    [processor] event = foo (2)\n\non `stdout` where the first `println` is triggered by a replayed event message.\n\n### Step 5: Channel usage\n\n![Channel](https://raw.github.com/eligosource/eventsourced/master/doc/images/firststeps-2.png)\n\nIn this step, the event-sourced `processor` is extended to send out new event messages to a `destination`. It creates another event message (by making a copy of the received event message) with an updated `event` field and sends the updated message to `destination`.\n\n**Scala:**\n\n```scala\nclass Processor(destination: ActorRef) extends Actor {\n  var counter = 0;\n\n  def receive = {\n    case msg: Message =\u003e {\n      counter = counter + 1\n      // …\n      destination ! msg.copy(event = \"processed %d event messages so far\" format counter)\n    }\n  }\n}\n\nval destination: ActorRef = system.actorOf(Props[Destination])\n// instantiate processor by passing the destination as constructor argument\nval processor: ActorRef = extension.processorOf(Props(new Processor(destination) with Eventsourced { val id = 1 } ))\n\nextension.recover()\n```\n\n**Java:**\n\n```java\npublic class Processor extends UntypedEventsourcedActor {\n    private ActorRef destination;\n    private int counter = 0;\n\n    public Processor(ActorRef destination) {\n        this.destination = destination;\n    }\n\n    @Override\n    public int id() {\n        return 1;\n    }\n\n    @Override\n    public void onReceive(Object message) throws Exception {\n        if (message instanceof Message) {\n            Message msg = (Message)message;\n            counter = counter + 1;\n            // …\n            destination.tell(msg.withEvent(String.format(\"processed %d event messages so far\", counter)), getSelf());\n        }\n    }\n}\n\nfinal ActorRef destination = system.actorOf(Props.create(Destination.class));\n// instantiate processor by passing the destination as constructor argument\nfinal ActorRef processor = extension.processorOf(Props.create(Processor.class, destination), system);\n\nextension.recover();\n```\n\nWithout any further actions, this would also send event messages to `destination` during recovery (i.e. during replay of event messages). With every application restart, `destination` would redundantly receive the whole event message history again and again. This is not acceptable in most cases, such as when `destination` represents an external service, for example.\n\nTo prevent redundant message delivery to `destination` we need something that *remembers* which messages have already been successfully delivered. This is exactly the use case for [channels](#channels). A channel drops all messages that have already been successfully delivered to a destination. We therefore wrap `destination` by a channel and let the processor communicate with the destination via that channel. This can be done without changing the code of `Processor`.\n\n**Scala:**\n\n```scala\nval destination: ActorRef = system.actorOf(Props[Destination])\n// wrap destination by channel\nval channel: ActorRef = extension.channelOf(DefaultChannelProps(1, destination))\n// instantiate processor by passing the channel (i.e. wrapped destination) as constructor argument\nval processor: ActorRef = extension.processorOf(Props(new Processor(channel) with Eventsourced { val id = 1 } ))\n```\n\n**Java:**\n\n```java\nfinal ActorRef destination = system.actorOf(Props.create(Destination.class));\n// wrap destination by channel\nfinal ActorRef channel = extension.channelOf(DefaultChannelProps.create(1, destination), system);\n// instantiate processor by passing the channel (i.e. wrapped destination) as constructor argument\nfinal ActorRef processor = extension.processorOf(Props.create(Processor.class, channel), system);\n```\n\nA channel must have a unique id (`1` in our example), a positive integer that must be consistently defined across application runs. Here, we create a [default channel](#defaultchannel) that is configured with a [`DefaultChannelProps`](http://eligosource.github.com/eventsourced/api/snapshot/#org.eligosource.eventsourced.core.DefaultChannelProps) configuration object. If applications need reliable event message delivery to destinations, they should use a [reliable channel](#reliablechannel) that is configured with a [`ReliableChannelProps`](http://eligosource.github.com/eventsourced/api/snapshot/#org.eligosource.eventsourced.core.ReliableChannelProps) configuration object.\n\nAssuming the following definition of a `Destination` actor\n\n**Scala:**\n\n```scala\nclass Destination extends Actor {\n  def receive = {\n    case msg: Message =\u003e {\n      println(\"[destination] event = '%s'\" format msg.event)\n      // confirm receipt of event message from channel\n      msg.confirm()\n    }\n  }\n}\n```\n\n**Java:**\n\n```java\npublic class Destination extends UntypedActor {\n    @Override\n    public void onReceive(Object message) throws Exception {\n        if (message instanceof Message) {\n            Message msg = (Message)message;\n            System.out.println(String.format(\"[destination] event = %s\", msg.event()));\n            msg.confirm(true);\n        }\n    }\n}\n```\n\nand that we're starting again from an empty journal, you should see\n\n    [processor] event = foo (1)\n    [destination] event = 'processed 1 event messages so far'\n\non `stdout` during a first application run. When running the application again, you'll see that the event-sourced `processor` receives the complete event message history but the `destination` only receives the last event message produced by `processor` (which corresponds the the single event message sent to `processor` during the current application run):\n\n    [processor] event = foo (1)\n    [processor] event = foo (2)\n    [destination] event = 'processed 2 event messages so far'\n\nWhen receiving event messages from a channel, destinations must confirm the receipt of that message by calling `Message.confirm()` which asynchronously writes a confirmation (an *acknowledgement*) to the journal that the message has been successfully delivered. Later, you'll also see how confirmation functionality can be added to destinations with the stackable [`Confirm`](http://eligosource.github.com/eventsourced/api/snapshot/#org.eligosource.eventsourced.core.Confirm) trait.\n\nThis [First steps](#first-steps) guide is a rather low-level introduction to the Eventsourced library. More advanced library features are covered in the following sections.\n\nStackable traits\n----------------\n\n### `Eventsourced`\n\n![Eventsourced](https://raw.github.com/eligosource/eventsourced/master/doc/images/stackabletraits-1.png)\n\nThe [`Eventsourced`](http://eligosource.github.com/eventsourced/api/snapshot/#org.eligosource.eventsourced.core.Eventsourced) trait has already been discussed in section [First steps](#first-steps). It can be combined with the stackable `Receiver`, `Emitter` and/or `Confirm` traits where the `Eventsourced` trait must always be the last modification i.e.\n\n**Scala:**\n\n```scala\nnew MyActor with Receiver with Confirm with Eventsourced\n```\n\n**Java:**\n\n```java\npublic class MyActor extends UntypedEventsourcedConfirmingReceiver\n```\n\nThe Eventsourced Java API provides some predefined combinations of stackable traits as abstract base classes. For example, [`UntypedEventsourcedConfirmingReceiver`](http://eligosource.github.com/eventsourced/api/snapshot/#org.eligosource.eventsourced.core.UntypedEventsourcedConfirmingReceiver) is defined as\n\n```scala\nabstract class UntypedEventsourcedReceiver extends UntypedActor with Receiver with Confirm with Eventsourced\n```\n\nOther predefined combinations of stackable traits in the Java API are described in the following subsections. Refer to the `Untyped*` abstract classes in the [API docs](http://eligosource.github.io/eventsourced/api/snapshot/#org.eligosource.eventsourced.core.package) for all predefined combinations.\n\n### `Receiver`\n\n![Receiver](https://raw.github.com/eligosource/eventsourced/master/doc/images/stackabletraits-2.png)\n\nAn actor that receives event [`Message`](http://eligosource.github.com/eventsourced/api/snapshot/#org.eligosource.eventsourced.core.Message)s often wants to pattern-match against the contained `event` directly instead of the whole event message. This can be achieved by modifying it with the [`Receiver`](http://eligosource.github.com/eventsourced/api/snapshot/#org.eligosource.eventsourced.core.Receiver) trait during instantiation (Scala API) or extending the abstract [`UntypedReceiver`](http://eligosource.github.com/eventsourced/api/snapshot/#org.eligosource.eventsourced.core.UntypedReceiver) class (Java API).\n\n**Scala:**\n\n```scala\nclass MyActor extends Actor {\n  def receive = {\n    case event =\u003e println(\"received event %s\" format event)\n  }\n}\n\nval myActor = system.actorOf(Props(new MyActor with Receiver))\n\nmyActor ! Message(\"foo\")\n```\n\n**Java:**\n\n```java\npublic class MyActor extends UntypedReceiver {\n    @Override\n    public void onReceive(Object event) throws Exception {\n        System.out.println(String.format(\"received event = %s\", event));\n    }\n}\n\nfinal ActorRef myActor = system.actorOf(Props.create(MyActor.class));\n\nmyActor.tell(Message.create(\"foo\"), null);\n```\n\nIn the above example, sending `Message(\"foo\")` to `myActor` will write `received event foo` to `stdout`. The `Receiver` trait stores the received event message as *current* event message in a field, extracts the contained `event` from that message and calls the `receive` (or `onReceive`) method of `MyActor` with `event` as argument. If `MyActor` wants to have access to the current event message it must be defined with a `Receiver` self-type and call the `message` method (Scala API) or just call the `message()` method (Java API).\n\n**Scala:**\n\n```scala\nclass MyActor extends Actor { this: Receiver =\u003e\n  def receive = {\n    case event =\u003e {\n      // obtain current event message\n      val currentMessage = message\n      // …\n      println(\"received event %s\" format event)\n    }\n  }\n}\n```\n\n**Java:**\n\n```java\npublic class MyActor extends UntypedReceiver {\n    @Override\n    public void onReceive(Object event) throws Exception {\n        // obtain current event message\n        Message currentMessage = message();\n        // …\n        System.out.println(String.format(\"received event = %s\", event));\n    }\n}\n```\n\nThe `Receiver` trait can also be combined with the stackable `Eventsourced` and/or `Confirm` traits where `Receiver` must always be the first modification. For example:\n\n**Scala:**\n\n```scala\nnew MyActor with Receiver with Eventsourced\n```\n\n**Java:**\n\n```java\npublic class MyActor extends UntypedEventsourcedReceiver\n```\n\nRefer to the [API docs](http://eligosource.github.com/eventsourced/api/snapshot/#org.eligosource.eventsourced.core.Receiver) for further details.\n\n### `Emitter`\n\n![Emitter](https://raw.github.com/eligosource/eventsourced/master/doc/images/stackabletraits-3.png)\n\nWhere a `Receiver` modification allows actors to pattern-match against incoming events directly instead of whole event `Message`s, an [`Emitter`](http://eligosource.github.com/eventsourced/api/snapshot/#org.eligosource.eventsourced.core.Emitter) introduces a corresponding simplification on the sending (outgoing) side. It allows actors to send (emit) events to channels without having to deal with whole event `Message`s. An emitter can also lookup channels by name (or id, see below).\n\n**Scala:**\n\n```scala\nclass MyActor extends Actor { this: Emitter =\u003e\n    def receive = {\n      case event =\u003e {\n        // emit event to channel \"myChannel\"\n        emitter(\"myChannel\") sendEvent (\"received: %s\" format event)\n      }\n    }\n  }\n\n// create register channel under name \"myChannel\"\nextension.channelOf(DefaultChannelProps(1, destination).withName(\"myChannel\"))\n\nval myActor = system.actorOf(Props(new MyActor with Emitter))\n```\n\n**Java:**\n\n```java\npublic class MyActor extends UntypedEmitter {\n    @Override\n    public void onReceive(Object event) throws Exception {\n        // emit event to channel \"myChannel\"\n        emitter(\"myChannel\").sendEvent(String.format(\"received: %s\", event), getSelf());\n    }\n}\n\n// create register channel under name \"myChannel\"\nextension.channelOf(DefaultChannelProps.create(1, destination).withName(\"myChannel\"), system);\n\nfinal ActorRef myActor = extension.processorOf(Props.create(MyActor.class), system);\n```\n\nEvent messages sent by an emitter to a channel are always derived from (i.e. are a copy of) the current event message (an `Emitter` is also `Receiver` and maintains a *current* event message, see also section [Receiver](#receiver)). A call to the `emitter` method with a channel name as argument creates a [`MessageEmitter`](http://eligosource.github.com/eventsourced/api/snapshot/#org.eligosource.eventsourced.core.MessageEmitter) object that captures the named channel and the current event message. Calling `sendEvent` on that object modifies the captured event message with the specified event argument and sends the updated event message to the channel (see also channel [usage hints](#usage-hints)). A `MessageEmitter` object can also be sent to other actors (or threads) and be used there i.e. a `MessageEmitter` object is thread-safe. Channels can also be referred to by id when creating a `MessageEmitter` i.e. there's no need to define a custom channel name:\n\n**Scala:**\n\n```scala\nclass MyActor extends Actor { this: Emitter =\u003e\n  def receive = {\n    case event =\u003e {\n      // emit event to channel with id 1\n      emitter(1) sendEvent (\"received: %s\" format event)\n    }\n  }\n}\n\n// create register channel\nextension.channelOf(DefaultChannelProps(1, destination))\n```\n\n**Java:**\n\n```java\npublic class MyActor extends UntypedEmitter {\n    @Override\n    public void onReceive(Object event) throws Exception {\n        // emit event to channel with id 1\n        emitter(1).sendEvent(String.format(\"received: %s\", event), getSelf());\n    }\n}\n\n// create register channel\nextension.channelOf(DefaultChannelProps.create(1, destination), system);\n```\n\nThe `Emitter` trait can also be combined with the stackable `Eventsourced` and/or `Confirm` traits where `Emitter` must always be the first modification. For example:\n\n**Scala:**\n\n```scala\nnew MyActor with Emitter with Eventsourced\n```\n\n**Java:**\n\n```java\npublic class MyActor extends UntypedEventsourcedEmitter\n```\n\nRefer to the [API docs](http://eligosource.github.com/eventsourced/api/snapshot/#org.eligosource.eventsourced.core.Emitter) for further details.\n\n### `Confirm`\n\n![Confirm](https://raw.github.com/eligosource/eventsourced/master/doc/images/stackabletraits-4.png)\n\nThe receipt of event messages from channels must be confirmed by calling `confirm()` or `confirm(true)` on the received event `Message`. Applications can also *negatively* confirm an event message receipt by calling `confirm(false)`. This, for example, causes a reliable channel to redeliver the event message.\n\nInstead of calling `confirm(true)` or `confirm(false)` explicitly, actors can also be modified with the stackable [`Confirm`](http://eligosource.github.com/eventsourced/api/snapshot/#org.eligosource.eventsourced.core.Confirm) trait. This trait calls `confirm(true)` on the received event message when the modified actor's `receive` (or `onReceive`) method returns normally and `confirm(false)` when it throws an exception.\n\nThis trait can either be used standalone\n\n**Scala:**\n\n```scala\nnew MyActor with Confirm\n```\n\n**Java:**\n\n```java\npublic class MyActor extends UntypedConfirmingActor\n```\n\nor in combination with the stackable `Receiver`, `Emitter` and/or `Eventsourced` traits where the `Confirm` modification must be made after a `Receiver` or `Emitter` modification but before an `Eventsourced` modification. For example:\n\n**Scala:**\n\n```scala\nnew MyActor with Receiver with Confirm with Eventsourced\n```\n\n**Java:**\n\n```java\npublic class MyActor extends UntypedEventsourcedConfirmingReceiver\n```\n\nRefer to the [API docs](http://eligosource.github.com/eventsourced/api/snapshot/#org.eligosource.eventsourced.core.Confirm) for further details.\n\n### Modified example\n\n![Example](https://raw.github.com/eligosource/eventsourced/master/doc/images/stackabletraits-5.png)\n\nThis section modifies (and simplifies) the example from section [First steps](#first-steps) by making use of the stackable `Receiver`, `Emitter` and `Confirm` traits. In particular, for the Scala API\n\n- `Processor` will be modified with `Emitter` (in addition to `Eventsourced`)\n- `Destination` will be modified with `Receiver` and `Confirm`\n\nFor the Java API\n\n- `Processor` will extend `UntypedEventsourcedEmitter`\n- `Destination` will extend `UntypedConfirmingReceiver`\n\nCode from this section is contained in [StackableTraits.scala](https://github.com/eligosource/eventsourced/blob/master/es-examples/src/main/scala/org/eligosource/eventsourced/guide/StackableTraits.scala) and\n[StackableTraits.java](https://github.com/eligosource/eventsourced/blob/master/es-examples/src/main/java/org/eligosource/eventsourced/guide/japi/StackableTraits.java). It can be executed from the sbt prompt with\n\n**Scala:**\n\n    \u003e project eventsourced-examples\n    \u003e run-main org.eligosource.eventsourced.guide.StackableTraits\n\n**Java:**\n\n    \u003e project eventsourced-examples\n    \u003e run-main org.eligosource.eventsourced.guide.japi.StackableTraits\n\nThe new Scala definition of `Processor` now has a self-type `Emitter` and pattern-matches against events directly. The Java definition of `Processor` extends `UntypedEventsourcedEmitter` and also receives events directly (instead of `Message`s).\n\n**Scala:**\n\n```scala\nclass Processor extends Actor { this: Emitter =\u003e\n  var counter = 0\n\n  def receive = {\n    case event =\u003e {\n      counter = counter + 1\n      println(\"[processor] event = %s (%d)\" format (event, counter))\n      emitter(\"destination\") sendEvent (\"processed %d events so far\" format counter)\n    }\n  }\n}\n```\n\n**Java:**\n\n```java\npublic class Processor extends UntypedEventsourcedEmitter {\n    private int counter = 0;\n\n    @Override\n    public int id() {\n        return 1;\n    }\n\n    @Override\n    public void onReceive(Object event) throws Exception {\n        counter = counter + 1;\n        System.out.println(String.format(\"[processor] event = %s (%d)\", event, counter));\n        emitter(\"destination\").sendEvent(String.format(\"processed %d event messages so far\", counter), getSelf());\n    }\n}\n```\n\nInstead of passing the channel via the constructor it is now looked-up by name (`\"destination\"`). The channel name is specified during channel creation.\n\n**Scala:**\n\n```scala\nextension.channelOf(DefaultChannelProps(1, destination).withName(\"destination\"))\n```\n\n**Java:**\n\n```java\nextension.channelOf(DefaultChannelProps.create(1, destination).withName(\"destination\"), system);\n```\n\nThe Scala `Processor` must be instantiated with an additional `Emitter` modification to conform to the `Processor` self-type. No further modification is needed for the Java `Processor`.\n\n**Scala:**\n\n```scala\nval processor: ActorRef = extension.processorOf(Props(new Processor with Emitter with Eventsourced { val id = 1 } ))\n```\n\n**Java:**\n\n```java\nfinal ActorRef processor = extension.processorOf(Props.create(Processor.class), system);\n```\n\nThe new definition of `Destination`\n\n**Scala:**\n\n```scala\nclass Destination extends Actor {\n  def receive = {\n    case event =\u003e {\n      println(\"[destination] event = '%s'\" format event)\n    }\n  }\n}\n```\n\n**Java:**\n\n```java\npublic class Destination extends UntypedConfirmingReceiver {\n    @Override\n    public void onReceive(Object event) throws Exception {\n        System.out.println(String.format(\"[destination] event = %s\", event));\n    }\n}\n```\n\npattern-matches against events directly and leaves event message receipt confirmation to the `Confirm` trait. The Scala `Destination` must be instantiated with a `Receiver` and a `Confirm` modification and again, no further modification is needed for the Java `Destination`.\n\n**Scala:**\n\n```scala\nval destination: ActorRef = system.actorOf(Props(new Destination with Receiver with Confirm))\n```\n\n**Java:**\n\n```java\nfinal ActorRef destination = system.actorOf(Props.create(Destination.class));\n```\n\nSender references\n-----------------\n\nThe Eventsourced library preserves sender references for all\n\n- message exchanges with actors that are modified with `Eventsourced`, `Receiver`, `Emitter` and/or `Confirm` (or extend any of the abstract `Untyped*` base classes from the Java API) and\n- message exchanges with destination actors via [channels](#channels)\n\ni.e. event-sourced actor applications can make use of sender references in the same way as plain actor applications. If you know how sender references work with Akka [actors](http://doc.akka.io/docs/akka/2.1.0/scala/actors.html), the following will sound familiar to you.\n\n![Processor reply](https://raw.github.com/eligosource/eventsourced/master/doc/images/senderrefs-1.png)\n\nFor example, taking the code from section [First steps](#first-steps) as a starting point, `Processor` can be extended to reply to message senders as follows.\n\n**Scala:**\n\n```scala\nclass Processor(destination: ActorRef) extends Actor {\n  // …\n\n  def receive = {\n    case msg: Message =\u003e {\n      // …\n      // reply to sender\n      sender ! (\"done processing event = %s\" format msg.event)\n    }\n  }\n}\n```\n\n\n**Java:**\n\n```java\npublic class Processor extends UntypedEventsourcedActor {\n    // …\n\n    @Override\n    public void onReceive(Object message) throws Exception {\n        if (message instanceof Message) {\n            // …\n            getSender().tell(String.format(\"done processing event = %s\", msg.event()), getSelf());\n        }\n    }\n}\n```\n\n\nApplications can now *ask* the `processor` and will get a response asynchronously.\n\n**Scala:**\n\n```scala\nprocessor ? Message(\"foo\") onSuccess {\n  case response =\u003e println(response)\n}\n```\n\n**Java:**\n\n```java\nask(processor, Message.create(\"foo\"), 5000L).onSuccess(new OnSuccess\u003cObject\u003e() {\n    @Override\n    public void onSuccess(Object response) throws Throwable {\n        System.out.println(response);\n    }\n}, system.dispatcher());\n```\n\n\nNo surprise here. The sender reference in this example represents the future that is returned from the `?` or `ask` method call. But what happens during a replay? During a replay, the sender reference will be `deadLetters` because `Eventsourced` processors don't store sender references in the journal. The main reason for this is that applications usually do not want to redundantly reply to senders during replays.\n\n![Destination reply](https://raw.github.com/eligosource/eventsourced/master/doc/images/senderrefs-2.png)\n\nInstead of replying to the sender, the processor can also forward the sender reference to a destination and let the destination reply to the sender. This even works if the destination is wrapped by a channel because a channel simply forwards sender references when delivering event messages to destinations. For that reason, a [`ReliableChannel`](http://eligosource.github.com/eventsourced/api/snapshot/#org.eligosource.eventsourced.core.ReliableChannel) needs to store sender references (in contrast to processors), so that sender references are even available after a reliable channel has been restarted. If a stored sender reference is a remote reference, it remains valid even after recovery from a JVM crash (i.e. a crash of the JVM the reliable channel is running in) provided the remote sender is still available.\n\n**Scala:**\n\n```scala\nclass Processor(destination: ActorRef) extends Actor {\n  var counter = 0\n\n  def receive = {\n    case msg: Message =\u003e {\n      // …\n      // forward modified event message to destination (together with sender reference)\n      destination forward msg.copy(event = \"processed %d event messages so far\" format counter)\n    }\n  }\n}\n\nclass Destination extends Actor {\n  def receive = {\n    case msg: Message =\u003e {\n      // …\n      // reply to sender\n      sender ! (\"done processing event = %s (%d)\" format msg.event)\n    }\n  }\n}\n\nval destination: ActorRef = system.actorOf(Props[Destination])\nval channel: ActorRef = extension.channelOf(DefaultChannelProps(1, destination))\nval processor: ActorRef = extension.processorOf(Props(new Processor(channel) with Eventsourced { val id = 1 } ))\n```\n\n**Java:**\n\n```java\npublic class Processor extends UntypedEventsourcedActor {\n    private ActorRef destination;\n    private int counter = 0;\n\n    public Processor(ActorRef destination) {\n        this.destination = destination;\n    }\n\n    @Override\n    public int id() {\n        return 1;\n    }\n\n    @Override\n    public void onReceive(Object message) throws Exception {\n        if (message instanceof Message) {\n            Message msg = (Message)message;\n            // forward modified event message to destination (together with sender reference)\n            destination.forward(msg.withEvent(String.format(\"processed %d event messages so far\", counter)), getContext());\n        }\n    }\n}\n\npublic class Destination extends UntypedActor {\n    @Override\n    public void onReceive(Object message) throws Exception {\n        if (message instanceof Message) {\n            Message msg = (Message)message;\n            // …\n            // reply to sender\n            getSender().tell(String.format(\"done processing event = %s\", msg.event()), getSelf());\n        }\n    }\n}\n\nfinal ActorRef destination = system.actorOf(Props.create(Destination.class));\nfinal ActorRef channel = extension.channelOf(DefaultChannelProps.create(1, destination), system);\nfinal ActorRef processor = extension.processorOf(Props.create(Processor.class, channel), system);\n```\n\nWhen using a [`MessageEmitter`](http://eligosource.github.com/eventsourced/api/snapshot/#org.eligosource.eventsourced.core.MessageEmitter) (see also section [Emitter](#emitter)) applications can choose between methods `sendEvent` and `forwardEvent` where `sendEvent` takes an (implicit) sender reference as parameter and `forwardEvent` forwards the current sender reference. They work in the same way as the `tell` (`!`) and `forward` methods on `ActorRef`, respectively.\n\nCode from this section is contained in [SenderReferences.scala](https://github.com/eligosource/eventsourced/blob/master/es-examples/src/main/scala/org/eligosource/eventsourced/guide/SenderReferences.scala) and [SenderReferences.java](https://github.com/eligosource/eventsourced/blob/master/es-examples/src/main/java/org/eligosource/eventsourced/guide/japi/SenderReferences.java). It can be executed from the sbt prompt with\n\n**Scala:**\n\n    \u003e project eventsourced-examples\n    \u003e run-main org.eligosource.eventsourced.guide.SenderReferences\n\n**Java:**\n\n    \u003e project eventsourced-examples\n    \u003e run-main org.eligosource.eventsourced.guide.japi.SenderReferences\n\nChannels\n--------\n\nA [channel](#channel) is an actor that keeps track of successfully delivered event messages. Channels are used by event-sourced actors (processors) to prevent redundant message delivery to destinations during event message replay. Some channels can also be used [standalone](#standalone-usage) i.e. independent of event-sourced actors.\n\nA use case for channels is described in section [External Updates](http://martinfowler.com/eaaDev/EventSourcing.html#ExternalUpdates) of Martin Fowler's [Event Sourcing](http://martinfowler.com/eaaDev/EventSourcing.html) article. A getting-started example is given in section [Channel usage](#step-5-channel-usage) of the [First steps](#first-steps) guide\n\nCurrently, the library provides two different channel implementations, [`DefaultChannel`](http://eligosource.github.com/eventsourced/api/snapshot/#org.eligosource.eventsourced.core.DefaultChannel) and [`ReliableChannel`](http://eligosource.github.com/eventsourced/api/snapshot/#org.eligosource.eventsourced.core.ReliableChannel), and a pattern on top of `ReliableChannel`, a [reliable request-reply channel](#reliable-request-reply-channel). These are explained in the following subsections.\n\n### `DefaultChannel`\n\n![Default channel](https://raw.github.com/eligosource/eventsourced/master/doc/images/channels-1.png)\n\nA default channel is a transient channel that delivers event messages to a destination actor. When the destination confirms the delivery of an event message by calling either `confirm()` or `confirm(true)` on the received `Message` object, a confirmation (an *acknowledgement*) is asynchronously written to the journal. During a replay, event messages for which a confirmation exists won't be delivered again to the destination.\n\nEvent messages that are negatively confirmed by the destination (via a call to `confirm(false)` on the received event message) will be re-delivered during the next event message replay. This is also the case for event messages for which no confirmation has been made. Therefore, in cases of negative or missing confirmations, the order of event messages received by a destination from a default channel may differ from the order of event messages produced by an event-sourced processor.\n\nA `DefaultChannel` is created and registered at an `EventsourcingExtension` as follows.\n\n```scala\nval extension: EventsourcingExtension = …\nval destination: ActorRef = …\nval channelId: Int = …\n\nval channel: ActorRef = extension.channelOf(DefaultChannelProps(channelId, destination))\n```\n\nThe `channelId` must be a positive integer and consistently defined across application runs. The map of registered channels can be obtained via the `channels` method of `EventsourcingExtension` which returns a map of type `Map[Int, ActorRef]` where the mapping key is the channel id. Channels can optionally be registered under a custom name (see also section [Emitter](#emitter)).\n\n```scala\n// …\nval channelId: Int = …\nval channelName: String = …\n\nval channel: ActorRef = extension.channelOf(DefaultChannelProps(channelId, destination).withName(channelName))\n```\n\nThe map of registered named channels can be obtained via the `namedChannels` method which returns a map of type `Map[String, ActorRef]` where the mapping key is the channel name.\n\nA default channel preserves [sender references](#sender-references). Applications can therefore use `?` and `forward` as well to communicate with channel destinations via channel actor refs. However, special care must be taken when using `?`: replayed messages that have already been confirmed by a channel destination will be ignored by the corresponding channel and the destination cannot reply. Hence, the sender will see a reply timeout. This can be avoided by finding out in advance if the channel will ignore a message or not. Applications do that by investigating the `Message.acks` list. If the channel's id is contained in that list, the message will be ignored and should not be used for asking.\n\n```scala\nval channelId: Int = …\nval channel: ActorRef = …\n\nif (!message.acks.contains(channelId)) channel ? message.copy(…) onComplete {\n  case result =\u003e …\n}\n```\n\nSee also [usage-hints](#usage-hints) regarding `message.copy(…)`.\n\n### `ReliableChannel`\n\n![Reliable channel](https://raw.github.com/eligosource/eventsourced/master/doc/images/channels-2.png)\n\nA reliable channel is a persistent channel that writes event messages to a journal before delivering them to a destination actor. In contrast to a default channel, a reliable channel preserves the order of messages as produced by an event-sourced processor and attempts to re-deliver event messages on destination failures. Therefore, a reliable channel enables applications to recover from temporary destination failures without having to run an event message replay. Furthermore, a reliable channel can also recover from crashes of the JVM it is running in. This allows applications to guarantee at-least-once message delivery in case of both, destination failures and sender failures.\n\nIf a destination positively confirms the receipt of an event message, the stored message is removed from the channel and the next one is delivered. If a destination negatively confirms the receipt of an event message or if no confirmation is made (i.e. a timeout occurs), a re-delivery attempt is made after a certain *redelivery delay*. If the maximum number of re-delivery attempts have been made, the channel restarts itself after a certain *restart delay* and starts again with re-deliveries. If the maximum number of restarts has been reached, the channel stops message delivery and publishes a [`DeliveryStopped`](http://eligosource.github.com/eventsourced/api/snapshot/#org.eligosource.eventsourced.core.Channel$$DeliveryStopped) event to the event stream of the actor system this channel belongs to. Applications can then re-activate the channel by calling the `deliver(Int)` method of `EventsourcingExtension` with the channel id as argument. Refer to the [`ReliableChannel`](http://eligosource.github.com/eventsourced/api/snapshot/#org.eligosource.eventsourced.core.ReliableChannel) API docs for details.\n\nA `ReliableChannel` is created and registered in the same way as a default channel except that a [`ReliableChannelProps`](http://eligosource.github.com/eventsourced/api/snapshot/#org.eligosource.eventsourced.core.ReliableChannelProps) configuration object is used.\n\n```scala\n// …\nval channel: ActorRef = extension.channelOf(ReliableChannelProps(channelId, destination))\n```\n\nThis configuration object additionally allows applications to configure a [`RedeliveryPolicy`](http://eligosource.github.com/eventsourced/api/snapshot/#org.eligosource.eventsourced.core.RedeliveryPolicy) for the channel.\n\nA reliable channel preserves [sender references](#sender-references). Applications can therefore use `?` and `forward` as well to communicate with channel destinations via channel actor refs. Details have already been described in the [default channel](#defaultchannel) section. A reliable channel also stores sender references along with event messages so that they can be forwarded to destinations even after the channel has been restarted. If a stored sender reference is a remote reference, it remains valid even after recovery from a JVM crash (i.e. a crash of the JVM the reliable channel is running in) provided the remote sender is still available.\n\nFor those familiar with Akka, a reliable channel is similar to an [Akka reliable proxy](http://doc.akka.io/docs/akka/snapshot/contrib/reliable-proxy.html) except that it additionally can recover from sender JVM crashes (see also section [Remote destinations](#remote-destinations)).\n\n### Reliable request-reply channel\n\n![Reliable request-reply channel](https://raw.github.com/eligosource/eventsourced/master/doc/images/channels-3.png)\n\nA reliable request-reply channel is a pattern implemented on top of a [reliable channel](#reliablechannel). It mediates reliable request-reply interactions between a request sender (usually an `Eventsourced` processor) and a destination. This channel has the following properties in addition to a plain reliable channel. It\n\n- extracts requests from received [`Message`](http://eligosource.github.com/eventsourced/api/snapshot/#org.eligosource.eventsourced.core.Message)s before sending them to the destination.\n- wraps replies from the destination into a `Message` before sending them back to the request sender.\n- sends a special [`DestinationNotResponding`](http://eligosource.github.com/eventsourced/api/snapshot/#org.eligosource.eventsourced.patterns.reliable.requestreply.DestinationNotResponding) reply to the request sender if the destination doesn't reply within a configurable reply timeout.\n- sends a special [`DestinationFailure`](http://eligosource.github.com/eventsourced/api/snapshot/#org.eligosource.eventsourced.patterns.reliable.requestreply.DestinationFailure) reply to the request sender if destination responds with `Status.Failure`.\n- guarantees at-least-once delivery of replies to the request sender (in addition to at-least-once delivery of requests to the destination).\n- requires a positive receipt confirmation for a reply to mark a request-reply interaction as successfully completed.\n- redelivers requests, and subsequently replies, on missing or negative receipt confirmations.\n\nA reliable request-reply channel is created and registered in the same way as a reliable channel except that a [`ReliableRequestReplyChannelProps`](http://eligosource.github.com/eventsourced/api/snapshot/#org.eligosource.eventsourced.patterns.reliable.requestreply.ReliableRequestReply$ReliableRequestReplyChannelProps) configuration object is used.\n\n```scala\n// …\nimport org.eligosource.eventsourced.patterns.reliable.requestreply._\n\nval channel: ActorRef = extension.channelOf(ReliableRequestReplyChannelProps(channelId, destination))\n```\n\nThis configuration object additionally allows applications to configure a `replyTimeout` for replies from the destination. A detailed usage example of a reliable request-reply channel is given in [this article](http://krasserm.blogspot.com/2013/01/event-sourcing-and-external-service.html).\n\n### Usage hints\n\n#### General\n\nChannels must be activated before usage, see extension.deliver().\n\n#### Eventsourced usage\n\nFor channels to work properly, event-sourced processors must copy the `processorId` and `sequenceNr` values from a received (and journaled) input event message to output event messages. This is usually done by calling `copy()` on the received input event message and updating only those fields that are relevant for the application such as `event` or `ack`, for example:\n\n```scala\nclass Processor(channel: ActorRef) extends Actor {\n  def receive = {\n    case msg: Message =\u003e {\n      // …\n      channel ! msg.copy(event = …, ack = …)\n    }\n  }\n}\n```\n\nWhen using a [message emitter](#emitter), this is done automatically.\n\n#### Standalone usage\n\n[Reliable channels](#reliablechannel) and [reliable request-reply channels](#reliable-request-reply-channel) can also be used independently of `Eventsourced` processors (i.e. standalone). For standalone channel usage, senders must set the `Message.processorId` of the sent `Message` to `0` (which is the default value):\n\n```scala\nval channel = extension.channelOf(ReliableChannelProps(…))\n\nchannel ! Message(\"my event\") // processorId == 0\n```\n\nThis is equivalent to directly sending the `Message.event`:\n\n```scala\nchannel ! \"my event\"\n```\n\nA reliable channel internally wraps a received event into a `Message` with `processorId` set to `0`. Setting the `processorId` to `0` causes a reliable channel to skip writing an acknowledgement. An acknowledgement always refers to an event message received by an `Eventsourced` processor, so there's no need to write one in this case. Another (unrelated) use case for turning off writing acknowledgements is the emission of [event message series](#event-series) in context of [event-sourced channel usage](#eventsourced-usage).\n\n#### Remote destinations\n\nApplications should consider using reliable channels whenever a sender processor should deliver messages to a **remote** destination at-least-once and in sending order, even in cases of\n\n1. network errors between sender and destination (remote actor ref remains valid but remote actor is temporarily unavailable)\n2. destination JVM crashes (remote actor ref becomes invalid) and\n3. sender JVM crashes (messages already received by a sender processor but not yet delivered to the remote destination must be automatically delivered when the sender [recovers](#recovery) from a crash)\n\nUsing a remote actor ref as channel destination would work in case 1 but not in case 2. One possible way to deal with case 2, is to use a local actor (a destination proxy) that communicates with the remote destination via an `ActorSelection`. An `ActorSelection` can be created from an actor path and is not bound to the remote destination's life-cycle.\n\n```scala\nclass DestinationProxy(destinationPath: String) extends Actor {\n  val destinationSelection: ActorSelection = context.actorSelection(destinationPath)\n\n  def receive = {\n    case msg =\u003e destinationSelection tell (msg, sender) // forward\n  }\n}\n\nval destinationPath: String = …\nval proxy = system.actorOf(Props(new DestinationProxy(destinationPath)))\nval channel = extension.channelOf(ReliableChannelProps(1, proxy))\n```\n\nUsing an `ActorSelection` also covers case 1, of course. Case 3 is automatically covered by the fact that a sender processor uses a reliable channel for sending messages to a destination. Here's an example:\n\n```scala\nclass Sender extends Actor {\n  val id = 1\n  val ext = EventsourcingExtension(context.system)\n  val proxy = context.actorOf(Props(new DestinationProxy(\"akka.tcp://example@127.0.0.1:2852/user/destination\")))\n  val channel = ext.channelOf(ReliableChannelProps(1, proxy))\n\n  def receive = {\n    case msg: Message =\u003e channel forward msg\n  }\n}\n\n// create and recover sender and its channel\nval sender = extension.processorOf(Props(new Sender with Eventsourced))\n\nsender ! Message(\"hello\")\n```\n\nSpecial care must be taken if the remote destination actor is an `Eventsourced` actor. In this case, the application must ensure that the destination actor can only be accessed remotely **after** it has been successfully recovered. This can be achieved, for example, by using an additional *endpoint* actor that simply forwards to the destination actor. The endpoint actor is registered under the destination path after the destination actor has been successfully recovered.\n\n```scala\nclass DestinationEndpoint(destination: ActorRef) extends Actor {\n  def receive = {\n    case msg =\u003e destination forward msg\n  }\n}\n\nclass Destination extends Actor {\n  val id = 2\n\n  def receive = {\n    case msg: Message =\u003e {\n      println(s\"received ${msg.event}\")\n      msg.confirm()\n    }\n  }\n}\n\nval destination = extension.processorOf(Props(new Destination with Eventsourced))\n\n// wait for destination recovery to complete\nextension.recover()\n\n// make destination remotely accessible after recovery\nsystem.actorOf(Props(new DestinationEndpoint(destination)), \"destination\")\n```\n\nThis ensures that new remote messages never interleave with messages that are replayed to the destination actor during recovery.\n\nCode from this section is contained in [ReliableChannelExample.scala](https://github.com/eligosource/eventsourced/blob/master/es-examples/src/main/scala/org/eligosource/eventsourced/example/ReliableChannelExample.scala). The sender application can be started from sbt with\n\n    \u003e project eventsourced-examples\n    \u003e run-main org.eligosource.eventsourced.example.Sender\n\nThe (remote) destination can be started with\n\n    \u003e project eventsourced-examples\n    \u003e run-main org.eligosource.eventsourced.example.Destination\n\nThe sender application prompts the user to enter messages on `stdin` which are then reliably sent to the remote destination.\n\n### Channel alternatives\n\nA less reliable alternative to channels is communication via sender references. This means producing event messages to destinations that have been passed to a processor via sender references (along with an input event message). These sender references will be `deadLetters` during a replay which also prevents redundant delivery. The main difference, however, is that the delivery guarantee changes from *at-least-once* to *at-most-once*.\n\nRecovery\n--------\n\nRecovery is a procedure that re-creates the state of event-sourced applications consisting of [`Eventsourced`](http://eligosource.github.com/eventsourced/api/snapshot/#org.eligosource.eventsourced.core.Eventsourced) actors (processors) and [channels](#channels). Recovery is usually done at application start, either after normal termination or after a crash (but can also be done any time later, even for individual processors and channels).\n\n```scala\nval system: ActorSystem = …\nval journal: ActorRef = …\n\nval extension = EventsourcingExtension(system, journal)\n\n// create and register event-sourced processors\nextension.processorOf(…)\n// …\n\n// create and register channels\nextension.channelOf(…)\n// …\n\n// recover state of registered processors and activate channels\nextension.recover()\n\n// processors and channels are now ready to use\n// …\n```\n\nThe `recover()` method first replays journaled event messages to all registered processors. By replaying the event message history, processors can recover state. Processors that emit event messages to one or more channels will also do so during replay. These channels will either ignore (discard) event messages that have already been successfully delivered (i.e. *acknowledged*) in previous application runs or buffer them for later delivery. After replay, the `recover()` method triggers the delivery of buffered messages by activating channels.\n\nIf channels delivered event messages immediately instead of buffering them, delivered event messages could wrongly interleave with replayed event messages. This could lead to inconsistencies in event message ordering across application runs and therefore to inconsistencies in application state. Therefore, recovery must ensure that buffered event messages are only delivered after all replayed event messages have been added to their corresponding processors' mailboxes. This is especially important for the recovery of processors and channels that are connected to cyclic, directed graphs.\n\n### Replay parameters\n\nRecovery can be parameterized with [replay parameters](http://eligosource.github.com/eventsourced/api/snapshot/#org.eligosource.eventsourced.core.ReplayParams) using the `EventsourcingExtension.recover(Seq[ReplayParams])` method (or one of its overloaded definitions). `ReplayParams` allow fine-grained control over state recovery of individual processors. For each processor to be recovered, an application must create a `ReplayParams` instance. `ReplayParams` specify\n\n- whether replay should start from scratch, from a [snapshot](#snapshots) or from a given sequence number (lower sequence number bound).\n- whether replay should end at current state or any state in the past (using an upper sequence number bound)\n\nThe following two subsections demonstrate some `ReplayParams` usage examples. For more details, refer to the API docs of [`ReplayParams`](http://eligosource.github.com/eventsourced/api/snapshot/#org.eligosource.eventsourced.core.ReplayParams) and its [companion object](http://eligosource.github.com/eventsourced/api/snapshot/#org.eligosource.eventsourced.core.ReplayParams$). For details about snapshot creation refer to the [Snapshots](#snapshots) section.\n\n#### Recovery without snapshots\n\nAs already explained above\n\n```scala\nval extension: EventsourcingExtension = …\n\nimport extension._\n\nrecover()\n```\n\nrecovers all processors with no lower and upper sequence number bound i.e. all event messages are replayed. This is equivalent to\n\n```scala\nrecover(replayParams.allFromScratch)\n```\n\nor\n\n```scala\nrecover(processors.keys.map(pid =\u003e ReplayParams(pid)).toSeq)\n```\n\nIf an application only wants to recover specific processors it should create `ReplayParams` only for these processors. For example\n\n```scala\nrecover(Seq(ReplayParams(1), ReplayParams(2)))\n```\n\nonly recovers processors with ids `1` and `2`. Upper and lower sequence number bounds can be specified as well.\n\n```scala\nrecover(Seq(ReplayParams(1, toSequenceNr = 12651L), ReplayParams(2, fromSequenceNr = 10L)))\n```\n\nHere processor `1` will receive replayed event messages with sequence numbers within range `0` and `12651` (inclusive), processor `2` with receive event messages with sequence numbers starting from `10` with no upper sequence number bound.\n\n#### Recovery with snapshots\n\nDuring snapshot based recovery, a processor receives a [`SnapshotOffer`](http://eligosource.github.com/eventsourced/api/snapshot/#org.eligosource.eventsourced.core.SnapshotOffer) message before receiving the remaining event messages (if there are any). A processor uses a `SnapshotOffer` message to restore its state.\n\n**Scala:**\n\n```scala\nclass Processor extends Actor {\n  var state = // …\n\n  def receive = {\n    case so: SnapshotOffer =\u003e state = so.snapshot.state\n    // …\n  }\n}\n```\n\n**Java:**\n\n```java\npublic class Processor extends UntypedEventsourcedActor {\n    private Object state = // …\n\n    @Override\n    public void onReceive(Object message) throws Exception {\n        if (message instanceof SnapshotOffer) {\n            SnapshotOffer so = (SnapshotOffer)message;\n            state = so.snapshot().state();\n        }\n        // …\n    }\n}\n```\n\nSnapshot based recovery will only send a `SnapshotOffer` message to a processor if one or more snapshots have been created for that processor before and these snapshots match the criteria in the corresponding `ReplayParams`. Relevant criteria are `toSequenceNr` and `snapshotFilter`. If there are no snapshots for a processor or existing snapshots do not match `ReplayParams` criteria, event messages will be replayed from scratch i.e. from sequence number `0`.\n\nTo recover all processors from their latest snapshot\n\n```scala\nrecover(replayParams.allWithSnapshot)\n```\n\ncan be used. This is equivalent to\n\n```scala\nrecover(processors.keys.map(pid =\u003e ReplayParams(pid, snapshot = true)).toSeq)\n```\n\nSnapshot based recovery can also be made with upper sequence number bound.\n\n```scala\nrecover(Seq(ReplayParams(1, snapshot = true, toSequenceNr = 12651L)))\n```\n\nThis recovers processor `1` with the latest snapshot that has a sequence number `\u003c= 12651`. Remaining event messages (if there are any) are replayed up to sequence number `12651` (inclusive). Applications may also define further constraints on snapshots. For example\n\n```scala\nimport scala.concurrent.duration._\n\nval limit = System.currentTimeMillis - 24.hours.toMillis\n\nrecover(Seq(ReplayParams(1, snapshotFilter = snapshotMetadata =\u003e snapshotMetadata.timestamp \u003c limit)))\n```\n\nuses the latest snapshot of processor `1` that is older than 24 hours. This is done with a `snapshotFilter` that filters snapshots based on their timestamp. Snapshot filters operate on [`SnapshotMetadata`](http://eligosource.github.com/eventsourced/api/snapshot/#org.eligosource.eventsourced.core.SnapshotMetadata).\n\n### Await processing\n\nThe `recover` method waits for replayed messages being sent to all processors (via `!`) but does not wait for replayed event messages being processed by these processors. However, any new message sent to any registered processor, after `recover` successfully returned, will be processed after the replayed event messages. Applications that want to wait for processors to complete processing of replayed event messages, should use the `awaitProcessing()` method of [`EventsourcingExtension`](http://eligosource.github.com/eventsourced/api/snapshot/#org.eligosource.eventsourced.core.EventsourcingExtension).\n\n```scala\nval extension: EventsourcingExtension = …\n\nextension.recover()\nextension.awaitProcessing()\n```\n\nThis can be useful in situations where event-sourced processors maintain state via STM references and the application wants to ensure that the (externally visible) state is fully recovered before accepting new read requests from client applications. By default, the `awaitProcessing()` method waits for all registered processors to complete processing but applications can also specify a subset of registered processors.\n\n### Non-blocking recovery\n\nThe `recover` and `awaitProcessing` methods block the calling thread. This may be convenient in scenarios where a main thread wants to recover the state of an event-sourced application before taking any further actions. In other scenarios, for example, where recovery is done for individual child processors (and channels) inside an actor (see [OrderExampleReliable.scala](https://github.com/eligosource/eventsourced/blob/master/es-examples/src/main/scala/org/eligosource/eventsourced/example/OrderExampleReliable.scala)), the non-blocking recovery API should be used:\n\n```scala\nval extension: EventsourcingExtension = …\n\nval future = for {\n  _ \u003c- extension.replay(…)\n  _ \u003c- extension.deliver(…)            // optional\n  _ \u003c- extension.completeProcessing(…) // optional\n} yield ()\n\nfuture onSuccess {\n  case _ =\u003e // event-sourced processors now ready to use …\n}\n```\n\nHere, the futures returned by `replay`, `deliver` and `completeProcessing` are monadically composed with a for-comprehension which ensures a sequential execution of the corresponding asynchronous operations. When the composite `future` completes, the recovered processors and channels are ready to use. More details in the [API docs](http://eligosource.github.com/eventsourced/api/snapshot/#org.eligosource.eventsourced.core.EventsourcingExtension). The `replay` method can also be parameterized with a `ReplayParams` sequence (see section [Replay parameters](#replay-parameters)).\n\n### Channel recovery and usage\n\nChannels can even be used by applications immediately after creation i.e. before activating them. This is especially important when event-sourced (parent) processors create new event-sourced child processors during handling of an event:\n\n```scala\nclass Parent extends Actor { this: Receiver with Eventsourced =\u003e\n  import context.dispatcher\n\n  var child: Option[ActorRef] = None\n\n  def receive = {\n    case event =\u003e {\n        // create child processor wrapped by channel\n        if (child.isEmpty) { child = Some(createChildProcessor(2, 2)) }\n        // channel can be used immediately\n        child.foreach(_ ! message.copy(…))\n    }\n  }\n\n  def createChildProcessor(pid: Int, cid: Int): ActorRef = {\n    implicit val recoveryTimeout = Timeout(10 seconds)\n\n    val childProcessor = extension.processorOf(Props(new Child with Receiver with Eventsourced { val id = pid } ))\n    val childChannel = extension.channelOf(DefaultChannelProps(cid, childProcessor))\n\n    for { // asynchronous, non-blocking recovery\n      _ \u003c- extension.replay(Seq(ReplayParams(pid)))\n      _ \u003c- extension.deliver(cid)\n    } yield ()\n\n    childChannel\n  }\n}\n\nclass Child extends Actor { this: Receiver =\u003e\n  def receive = {\n    case event =\u003e {\n      …\n      confirm()\n    }\n  }\n}\n```\n\n\nHere, `Parent` lazily creates a new `childProcessor` (wrapped by a default channel) on receiving an `event`. The `childChannel` is used by `Parent` immediately after creation i.e. concurrently to `childProcessor` message replay and `childChannel` activation. This is possible because a channel internally buffers new messages before its activation and delivers them to its destination after activation. This ensures that new messages will only be delivered to `childProcessor` after `childChannel` has been activated. During `Parent` recovery, `childChannel` will ignore messages that have already been successfully delivered to `childActor` (i.e. confirmed by `childActor`).\n\n### State dependencies\n\nThe behavior of [`Eventsourced`](http://eligosource.github.com/eventsourced/api/snapshot/#org.eligosource.eventsourced.core.Eventsourced) processors may depend on the state of other `Eventsourced` processors. For example, processor A sends a message to processor B and processor B replies with a message that includes (part of) processor B's state. Depending on the state value included in the reply, processor A may take different actions. To ensure a proper recovery of such a setup, any state-conveying or state-dependent messages exchanged between processors A and B must be of type [`Message`](http://eligosource.github.com/eventsourced/api/snapshot/#org.eligosource.eventsourced.core.Message) (see also [DependentStateRecoverySpec.scala](https://github.com/eligosource/eventsourced/blob/master/es-core/src/test/scala/org/eligosource/eventsourced/core/DependentStateRecoverySpec.scala)). Exchanging state via non-journaled messages (i.e. messages of type other than `Message`) can break consistent recovery. This is also the case if an `Eventsourced` processor maintains state via an externally visible STM reference and another `Eventsourced` processor directly reads from that reference. Communication between `Eventsourced` processors is closely related to [external queries](http://martinfowler.com/eaaDev/EventSourcing.html#ExternalQueries) and [external updates](http://martinfowler.com/eaaDev/EventSourcing.html#ExternalUpdates).\n\nSnapshots\n---------\n\nSnapshots represent processor state at a certain point in time and can dramatically reduce [recovery](#recovery) times. Snapshot capturing and saving is triggered by applications and does not delete entries from the event message history unless explicitly requested by an application.\n\nApplications can create snapshots by sending an `Eventsourced` processor a [`SnapshotRequest`](http://eligosource.github.com/eventsourced/api/snapshot/#org.eligosource.eventsourced.core.SnapshotRequest$) message (Scala API) or `SnapshotRequest.get()` message (Java API).\n\n**Scala:**\n\n```scala\nimport org.eligosource.eventsourced.core._\n// …\n\nval processor: ActorRef = …\n\nprocessor ! SnapshotRequest\n```\n\n**Java:**\n\n```java\nimport org.eligosource.eventsourced.core.*;\n// …\n\nfinal ActorRef processor = …\n\nprocessor.tell(SnapshotRequest.get(), …)\n```\n\nThis will asynchronously capture and save a snapshot of `processor`'s state. The sender will be notified when the snapshot has been successfully saved.\n\n**Scala:**\n\n```scala\n(processor ? SnapshotRequest).mapTo[SnapshotSaved].onComplete {\n  case Success(SnapshotSaved(processorId, sequenceNr, timestamp)) =\u003e …\n  case Failure(e)                                                 =\u003e …\n}\n```\n\n**Java:**\n\n```java\nask(processor, SnapshotRequest.get(), 5000L).mapTo(Util.classTag(SnapshotSaved.class)).onComplete(new OnComplete\u003cSnapshotSaved\u003e() {\n    public void onComplete(Throwable failure, SnapshotSaved result) {\n        if (failure != null) { … } else { … }\n    }\n}, system.dispatcher());\n```\n\nAlternatively, applications may also use the `EventsourcingExtension.snapshot` method to trigger snapshot creation. For example,\n\n**Scala:**\n\n```scala\nval extension: EventsourcingExtension = …\n\nextension.snapshot(Set(1, 2)) onComplete {\n  case Success(snapshotSavedSet: Set[SnapshotSaved]) =\u003e …\n  case Failure(_)                                    =\u003e …\n}\n```\n\n**Java:**\n\n```java\nSet\u003cInteger\u003e processorIds = new HashSet\u003cInteger\u003e();\n\nprocessorIds.add(1);\nprocessorIds.add(2);\n\nextension.snapshot(processorIds, new Timeout(5000L)).onComplete(new OnComplete\u003cSet\u003cSnapshotSaved\u003e\u003e() {\n    public void onComplete(Throwable failure, Set\u003cSnapshotSaved\u003e snapshotSavedSet) {\n        if (failure != null) { … } else { … }\n    }\n}, system.dispatcher());\n```\n\n\ncreates snapshots of processors with ids `1` and `2`. The returned future (of type `Future[scala.immutable.Set[SnapshotSaved]]` (Scala API) or `Future\u003cjava.util.Set\u003cSnapshotSaved\u003e\u003e` (Java API)) successfully completes when the snapshots of both processors have been successfully saved.\n\nTo participate in snapshot capturing, a processor must process [`SnapshotRequest`](http://eligosource.github.com/eventsourced/api/snapshot/#org.eligosource.eventsourced.core.SnapshotRequest) messages by calling their `process` method with its current `state` as argument:\n\n**Scala:**\n\n```scala\nclass Processor extends Actor {\n  var state = …\n\n  def receive = {\n    case sr: SnapshotRequest =\u003e sr.process(state)\n    // …\n  }\n}\n```\n\n**Java:**\n\n```java\npublic class Processor extends UntypedEventsourcedActor {\n    private Object state = …\n\n    @Override\n    public void onReceive(Object message) throws Exception {\n        if (message instanceof SnapshotRequest) {\n            SnapshotRequest sr = (SnapshotRequest)message;\n            sr.process(state, getContext());\n        }\n        // …\n    }\n}\n```\n\nCalling `process` will asynchronously save the `state` argument together with (generated) snapshot metadata. Creating a new snapshot does not delete older snapshots unless explicitly requested by an application. Hence, there can be n snapshots per processor.\n\nAn example that demonstrates snapshot creation and [snapshot based recovery](#recovery-with-snapshots) is contained in [SnapshotExample.scala](https://github.com/eligosource/eventsourced/blob/master/es-examples/src/main/scala/org/eligosource/eventsourced/example/SnapshotExample.scala) and [SnapshotExample.java](https://github.com/eligosource/eventsourced/blob/master/es-examples/src/main/java/org/eligosource/eventsourced/example/japi/SnapshotExample.java). It can be executed from the sbt prompt with\n\n**Scala:**\n\n    \u003e project eventsourced-examples\n    \u003e run-main org.eligosource.eventsourced.example.SnapshotExample\n\n**Java:**\n\n    \u003e project eventsourced-examples\n    \u003e run-main org.eligosource.eventsourced.example.japi.SnapshotExample\n\n### Configuration\n\nSnapshotting is supported by all journals via the Hadoop [`FileSystem`](http://hadoop.apache.org/docs/r1.1.2/api/org/apache/hadoop/fs/FileSystem.html) abstraction. The default `FileSystem` instance is the local filesystem i.e. snapshots are by default written locally unless configured otherwise by the application. Please refer to the Hadoop documentation how to create `FileSystem` instances for HDFS, FTP, S3 etc. Application-defined `FileSystem` instances can be configured in the following way:\n\n**Scala:**\n\n```scala\n// …\nimport org.apache.hadoop.fs.FileSystem\n\n// …\nval hdfs: FileSystem = FileSystem.get(...)\nval journal: ActorRef = LeveldbJournalProps(..., snapshotFilesystem = hdfs).createJournal\n```\n\n**Java:**\n\n```java\n// …\nimport org.apache.hadoop.fs.FileSystem;\n\n// …\nfinal FileSystem hdfs = FileSystem.get(…);\nfinal ActorRef journal = LeveldbJournalProps.create(...).withSnapshotFilesystem(hdfs).createJournal(system);\n```\n\n\nFind out more in the [HadoopFilesystemSnapshottingProps](http://eligosource.github.com/eventsourced/api/snapshot/#org.eligosource.eventsourced.journal.common.snapshot.HadoopFilesystemSnapshottingProps) API docs.\n\nBehavior changes\n----------------\n\nActors that are modified with a stackable `Receiver`, `Emitter` and/or `Eventsourced` trait (Scala API) or extend any of the abstract `Untyped*` base classes (Java API) can change their behavior with the methods `become()` and `unbecome()`. These are defined on the [`Behavior`](http://eligosource.github.com/eventsourced/api/snapshot/#org.eligosource.eventsourced.core.Behavior) trait from which `Receiver`, `Emitter` and `Eventsourced` inherit.\n\nActors that change their behavior with `become()` and `unbecome()` will keep the functionality introduced by a stackable `Receiver`, `Emitter` and/or `Eventsourced` trait. For example, an actor that is modified with the `Eventsourced` trait (Scala API) or extends `UntypedEventsourcedActor` (Java API) will continue to journal event messages after having changed its behavior with `become()`.\n\nOn the other hand, actors that change their behavior with `context.become()` (Scala API) or `getContext().become()` (Java API) will loose the functionality introduced by the stackable `Receiver`, `Emitter` and/or `Eventsourced` traits (although the lost behavior can be recovered with `context.unbecome()` or `getContext().unbecome()`).\n\nEvent series\n------------\n\nWhen a processor derives more than one output event message from a single input event message and emits those output messages to a single channel, it generates a series of event messages. For an event message series, the event processor should set the `ack` field for all but the last emitted message to `false`.\n\n```scala\nclass Processor(channel: ActorRef) extends Actor {\n  def receive = {\n    case msg: Message =\u003e {\n      // …\n      channel ! msg.copy(event = \"event 1\", ack = false) // 1st message of series\n      channel ! msg.copy(event = \"event 2\", ack = false) // 2nd message of series\n      // …\n      channel ! msg.copy(event = \"event n\") // last message of series\n    }\n  }\n}\n```\n\nProcessors that use an emitter do that in the following way.\n\n```scala\nclass Processor extends Actor { this: Emitter =\u003e\n  def receive = {\n    case event =\u003e {\n      // …\n      emitter(\"channelName\") send (msg =\u003e msg.copy(event = \"event 1\", ack = false)) // 1st message of series\n      emitter(\"channelName\") send (msg =\u003e msg.copy(event = \"event 2\", ack = false)) // 2nd message of series\n      // …\n      emitter(\"channelName\") sendEvent \"event n\"\n    }\n  }\n}\n```\n\nThis ensures that an acknowledgement is only written to the journal after the last message of a series has been successfully\n\n- delivered by a [default channel](#defaultchannel) or\n- stored by a [reliable channel](#reliablechannel)\n\nDestinations, however, should confirm the receipt of every event message, regardless whether it belongs to a series or not.\n\nIdempotency\n-----------\n\nUnder certain failure conditions, [channels](#channels) may deliver event messages to destinations more than once. A typical example is that a destination positively confirms a message receipt but the application crashes shortly before that confirmation can be written to the journal. In this case, the destination will receive the event message again during recovery.\n\nFor these (but also other) reasons, channel destinations must be idempotent event message consumers which is an application-level concern. For example, an event message consumer that stores received purchase orders in a map (where the map key is the order id) is likely to be an idempotent consumer because receiving a purchase order only once or several times will lead to the same result: the purchase order is contained in the map only once. An event message consumer that counts the number of received purchase orders is not an idempotent consumer: a re-delivery will lead to a wrong counter value from a business logic perspective. In this case the event message consumer must implement some extra means to detect event message *duplicates*.\n\nFor detecting duplicates, applications should use identifiers with their events. Identifier values should be set by an event-sourced processor before an event is emitted via a channel. Channel destinations (or other downstream consumers) should keep track of identifiers of successfully processed events and compare them to identifiers of newly received events. A newly received event with an already known identifier can be considered as a duplicate (assuming that the emitting processor generates unique identifiers). For generating unique identifiers, processors can use the sequence number of received event messages:\n\n```scala\ncase class MyEvent(details: Any, eventId: Long)\n\nclass Processor extends Actor { this: Emitter with Eventsourced =\u003e\n  def receive = {\n    case event =\u003e {\n      // get sequence number of current event message\n      val snr: Long = sequenceNr\n      val details: Any = …\n      // …\n      emitter(\"channelName\") sendEvent MyEvent(details, snr)\n    }\n  }\n}\n```\n\nUsing the sequence number has the advantage that consumers of emitted events only need to remember the identifier of the last successfully consumed event. If the identifier of a newly received event is less than or equal to that of the last consumed event then it is a duplicate and can therefore be ignored.\n\n```scala\nclass Consumer extends Actor {\n  var lastEventId = 0L\n\n  def receive = {\n    case MyEvent(details, eventId) =\u003e\n      if (eventId \u003c= lastEventId) {\n        // duplicate\n      } else {\n        // …\n        lastEventId = eventId\n      }\n  }\n}\n```\n\nConsumers that are event-sourced processors can store the event identifier as part of their state which will be recovered during an event message replay. Other consumers must store the identifier somewhere else.\n\nProcessors that emit [event message series](#event-series) should use an event message index in addition to the sequence number to uniquely identify an emitted event:\n\n```scala\ncase class MyEvent(details: Any, eventId: (Long, Int))\n\nclass Processor extends Actor { this: Emitter with Eventsourced =\u003e\n  def receive = {\n    case event =\u003e {\n      // get sequence number of current event message\n      val snr: Long = sequenceNr\n      val details: Seq[Any] = …\n      // …\n      emitter(\"channelName\") send (msg =\u003e msg.copy(event = MyEvent(details(0), (snr, 0)), ack = false))\n      emitter(\"channelName\") send (msg =\u003e msg.copy(event = MyEvent(details(1), (snr, 1)), ack = false))\n      // …\n    }\n  }\n}\n```\n\nConsumers should then compare the sequence number - index pairs for detecting duplicates.\n\nSerialization\n-------------\n\nApplications can configure custom serializers for events of event `Message`s. Custom serializers are used for both, writing the event to a journal and for remote communication. They can be configured like any other [Akka serializer](http://doc.akka.io/docs/akka/2.1.0/scala/serialization.html). For example:\n\n    akka {\n      actor {\n        serializers {\n          custom = \"example.MyEventSerializer\"\n        }\n        serialization-bindings {\n          \"example.MyEvent\" = custom\n        }\n      }\n    }\n\nHere, `example.MyEvent` is an application-specific event type and `example.MyEventSerializer` is an application-specific serializer that extends `akka.serialization.Serializer`\n\n```scala\nimport akka.serialization.Serializer\n\nclass CustomEventSerializer extends Serializer {\n  def identifier = …\n  def includeManifest = true\n\n  def toBinary(o: AnyRef) = …\n  def fromBinary(bytes: Array[Byte], manifest: Option[Class[_]]) = …\n}\n```\n\nEvent [Message](http://eligosource.github.com/eventsourced/api/snapshot/#org.eligosource.eventsourced.core.Message)s themselves are serialized with a [pre-configured](https://github.com/eligosource/eventsourced/blob/master/es-journal/es-journal-common/src/main/resources/reference.conf#L4), library-specific serializer. This serializer is automatically used for event `Message`s when the `eventsourced-journal-common-*.jar` is on the classpath of an Akka application.\n\nFurther examples\n----------------\n\n### Order management\n\nThe order management example in this section is taken from [Martin Fowler](http://www.martinfowler.com/)'s great [LMAX article](http://martinfowler.com/articles/lmax.html):\n\n\u003e Imagine you are making an order for jelly beans by credit card. A simple retailing system would take your order information, use a credit card validation service to check your credit card number, and then confirm your order - all within a single operation. The thread processing your order would block while waiting for the credit card to be checked, but that block wouldn't be very long for the user, and the server can always run another thread on the processor while it's waiting.\n\u003e\n\u003e In the LMAX architecture, you would split this operation into two. The first operation would capture the order information and finish by outputting an event (credit card validation requested) to the credit card company. The Business Logic Processor would then carry on processing events for other customers until it received a credit-card-validated event in its input event stream. On processing that event it would carry out the confirmation tasks for that order.\n\nThis can be implemented with the Eventsourced library as shown in the following diagram (legend is in [Appendix A](#appendix-a-legend)).\n\n![Order management](https://raw.github.com/eligosource/eventsourced/master/doc/images/ordermgnt-1.png)\n\n- We implement the mentioned *Business Logic Processor* processor as event-sourced actor (`OrderProcessor`). It processes `OrderSubmitted` events by assigning submitted orders an id and storing them in a map (= state of `OrderProcessor`). For every submitted order it emits a `CreditCardValidationRequested` event.\n- `CreditCardValidationRequested` events are processed by a `CreditCardValidator` actor. It contacts an external credit card validation service and sends `CreditCardValidated` events back to the `OrderProcessor` for every order with a valid credit card number. In the example implementation below, we won't actually use an external service to keep the implementation simple, but for real-world implementations, [akka-camel](http://doc.akka.io/docs/akka/2.1.0/scala/camel.html) would be a perfect fit here.\n- On receiving a `CreditCardValidated` event, the event-sourced `OrderProcessor` updates the status of corresponding order to `validated = true` and sends an `OrderAccepted` event, containing the updated order, to `Destination`. It also replies the updated order to the initial sender.\n\nThe `Order` domain object, the domain events and the `OrderProcessor` are defined as follows:\n\n```scala\n// domain object\ncase class Order(id: Int = -1, details: String, validated: Boolean = false, creditCardNumber: String)\n\n// domain events\ncase class OrderSubmitted(order: Order)\ncase class OrderAccepted(order: Order)\ncase class CreditCardValidationRequested(order: Order)\ncase class CreditCardValidated(orderId: Int)\n\n// event-sourced order processor\nclass OrderProcessor extends Actor { this: Emitter =\u003e\n  var orders = Map.empty[Int, Order] // processor state\n\n  def receive = {\n    case OrderSubmitted(order) =\u003e {\n      val id = orders.size\n      val upd = order.copy(id = id)\n      orders = orders + (id -\u003e upd)\n      emitter(\"validation_requests\") forwardEvent CreditCardValidationRequested(upd)\n    }\n    case CreditCardValidated(orderId) =\u003e {\n      orders.get(orderId).foreach { order =\u003e\n        val upd = order.copy(validated = true)\n        orders = orders + (orderId -\u003e upd)\n        sender ! upd\n        emitter(\"accepted_orders\") sendEvent OrderAccepted(upd)\n      }\n    }\n  }\n}\n```\n\nThe `OrderProcessor` uses a message `emitter` to send `CreditCardValidationRequested` events to `CreditCardValidator` via the named `\"validation_requests\"` channel. The `forwardEvent` method not only sends the event but also forwards the initial [sender reference](#sender-references). Upon receiving a `CreditCardValidationRequested` event, the `CreditCardValidator` runs a credit card validation in the background and sends a `CreditCardValidated` event back to the `OrderProcessor`\n\n```scala\nclass CreditCardValidator(orderProcessor: ActorRef) extends Actor { this: Receiver =\u003e\n  def receive = {\n    case CreditCardValidationRequested(order) =\u003e {\n      val sdr = sender  // initial sender\n      val msg = message // current event message\n      Future {\n        // do some credit card validation\n        // …\n\n        // and send back a successful validation result (preserving the initial sender)\n        orderProcessor tell (msg.copy(event = CreditCardValidated(order.id)), sdr)\n      }\n    }\n  }\n}\n```\n\n\nThe `CreditCardValidator` again forwards the initial sender reference which finally enables the `OrderProcessor` to reply to the initial sender when it receives the `CreditCardValidated` event. The `OrderProcessor` also sends an `OrderAccepted` event to `Destination` via the named `\"accepted_orders\"` channel.\n\n```scala\nclass Destination extends Actor {\n  def receive = {\n    case event =\u003e println(\"received event %s\" format event)\n  }\n}\n```\n\nNext step is to wire the collaborators and to recover them:\n\n```scala\nval extension: EventsourcingExtension = …\n\nval processor = extension.processorOf(Props(new OrderProcessor with Emitter with Confirm with Eventsourced { val id = 1 }))\nval validator = system.actorOf(Props(new CreditCardValidator(processor) with Receiver))\nval destination = system.actorOf(Props(new Destination with Receiver with Confirm))\n\nextension.channelOf(ReliableChannelProps(1, validator).withName(\"validation_requests\"))\nextension.channelOf(DefaultChannelProps(2, destination).withName(\"accepted_orders\"))\n\nextension.recover()\n```\n\nThe named `\"validation requests\"` channel is a reliable channel that re-delivers `CreditCardValidationRequested` events in case of `CreditCardValidator` failures (for example, when the external credit card validation service is temporarily unavailable). Furthermore, it should be noted that the `CreditCardValidator` does not confirm event message deliveries (it neither calls `confirm()` explicitly nor is it modified with the `Confirm` trait during instantiation). Delivery confirmation will take place when the `OrderProcessor` successfully processed the `CreditCardValidated` event.\n\nThe `Order processor` is now ready to receive `OrderSubmitted` events.\n\n```scala\nprocessor ? Message(OrderSubmitted(Order(details = \"jelly beans\", creditCardNumber = \"1234-5678-1234-5678\"))) onSuccess {\n  case order: Order =\u003e println(\"received response %s\" format order)\n}\n```\n\nRunning this example with an empty journal will write\n\n    received response Order(0,jelly beans,true,1234-5678-1234-5678)\n    received event OrderAccepted(Order(0,jelly beans,true,1234-5678-1234-5678))\n\nto `stdout`. You may observe a different line ordering when running the example. The submitted order was assigned an `id` of `0` which corresponds to the initial size of the `OrderProcessor`'s `orders` map. A second application run will first recover the previous application state, so that another order submission will generate an order `id` of `1`.\n\n    received response Order(1,jelly beans,true,1234-5678-1234-5678)\n    received event OrderAccepted(Order(1,jelly beans,true,1234-5678-1234-5678))\n\nThe example code is contained in [OrderExample.scala](https://github.com/eligosource/eventsourced/blob/master/es-examples/src/main/scala/org/eligosource/eventsourced/example/OrderExample.scala) and can be executed from the sbt prompt with\n\n    \u003e project eventsourced-examples\n    \u003e run-main org.eligosource.eventsourced.example.OrderExample\n\nAn advanced version of this example, using a [reliable request-reply channel](#reliable-request-reply-channel), is discussed in [Event sourcing and external service integration](http://krasserm.blogspot.com/2013/01/event-sourcing-and-external-service.html).\n\n### State machines\n\n![State machines](https://raw.github.com/eligosource/eventsourced/master/doc/images/statemachines-1.png)\n\nWith a [change](https://www.assembla.com/spaces/akka/tickets/2680) since Akka 2.1, event-sourcing Akka [FSM](http://doc.akka.io/docs/akka/2.1.0/scala/fsm.html)s is now pretty easy. The following state machine example is a `Door` which can be in one of two states: `Open` and `Closed`.\n\n```scala\nsealed trait DoorState\n\ncase object Open extends DoorState\ncase object Closed extends DoorState\n\ncase class DoorMoved(state: DoorState, times: Int)\ncase class DoorNotMoved(state: DoorState, cmd: String)\ncase class NotSupported(cmd: Any)\n\nclass Door extends Actor with FSM[DoorState, Int] { this: Emitter =\u003e\n  startWith(Closed, 0)\n\n  when(Closed) {\n    case Event(\"open\", counter) =\u003e {\n      emit(DoorMoved(Open, counter + 1))\n      goto(Open) using(counter + 1)\n    }\n  }\n\n  when(Open) {\n    case Event(\"close\", counter) =\u003e {\n      emit(DoorMoved(Closed, counter + 1))\n      goto(Closed) using(counter + 1)\n    }\n  }\n\n  whenUnhandled {\n    case Event(cmd @ (\"open\" | \"close\"), counter) =\u003e {\n      emit(DoorNotMoved(stateName, \"cannot %s door\" format cmd))\n      stay\n    }\n    case Event(cmd, counter) =\u003e {\n      emit(NotSupported(cmd))\n      stay\n    }\n  }\n\n  def emit(event: Any) = emitter(\"destination\") forwardEvent event\n}\n```\n\nOn state changes, a door emits `DoorMoved` events to the named `\"destination\"` channel. `DoorMoved` events contain the door's current state and the number of moves so far. On invalid attempts to move a door e.g. trying to open an opened door, a `DoorNotMoved` event is emitted. The channel destination is an actor that simply prints received events to `stdout`.\n\n```scala\nclass Destination extends Actor {\n  def receive = { case event =\u003e println(\"received event %s\" format event) }\n}\n```\n\nAfter configuring the application\n\n```scala\nval system: ActorSystem = …\nval extension: EventsourcingExtension = …\n\nval destination = system.actorOf(Props(new Destination with Receiver with Confirm))\n\nextension.channelOf(DefaultChannelProps(1, destination).withName(\"destination\"))\nextension.processorOf(Props(new Door with Emitter with Eventsourced { val id = 1 } ))\nextension.recover()\n\nval door = extension.processors(1)\n```\n\nwe can start sending event messages to `door`:\n\n```scala\ndoor ! Message(\"open\")\ndoor ! Message(\"close\")\n```\n\nThis will write\n\n    received event DoorMoved(Open,1)\n    received event DoorMoved(Closed,2)\n\nto `stdout`. When trying to attempt an invalid state change with\n\n```scala\ndoor ! Message(\"close\")\n```\n\nthe `destination` will receive a `DoorNotMoved` event:\n\n    received event DoorNotMoved(Closed,cannot close door)\n\nRestarting the example application will recover the door's state so that\n\n```scala\ndoor ! Message(\"open\")\ndoor ! Message(\"close\")\n```\n\nwill produce\n\n    received event DoorMoved(Open,3)\n    received event DoorMoved(Closed,4)\n\nThe code from this section is contained in slightly modified form in [FsmExample.scala](https://github.com/eligosource/eventsourced/blob/master/es-core-test/src/test/scala/org/eligosource/eventsourced/core/FsmSpec.scala).\n\n### Clustering\n\nThis section makes the `Door` state machine from the [previous example](#state-machines) highly-available in an Akka [cluster](http://doc.akka.io/docs/akka/2.1.0/cluster/index.html). The `Door` state machine is a cluster-wide singleton that is managed by `NodeActor`s. There's one `NodeActor` per cluster node listening to cluster events. If a `NodeActor` becomes the master (= leader) it creates and recovers a `Door` instance. The other `NodeActor`s obtain a remote reference to the `Door` instance on master.\n\n![Clustering](https://raw.github.com/eligosource/eventsourced/master/doc/images/clustering-1.png)\n\nClients interact with the `Door` singleton via `NodeActor`s by sending them door commands (`\"open\"` or `\"close\"`). `NodeActor`s accept commands on any cluster node, not only on master. A `NodeActor` forwards these commands to the `Door` as command [`Message`](http://eligosource.github.com/eventsourced/api/snapshot/#org.eligosource.eventsourced.core.Message)s. Event `Message`s emitted by the `Door` are sent to a remote `Destination` actor via the named `\"destination\"` channel. The `Destination` creates a response from the received events and sends that response back to the initial sender. The application that runs the `Destination` actor is not part of the cluster but a standalone remote application. It also hosts the journal that is used by the cluster nodes (which is a SPOF in this example but later versions will use a distributed journal).\n\nWhen the master crashes, another node in the cluster becomes the master and recovers the `Door` state machine. The remaining slave node renews its remote reference to the `Door` instance on the new master.\n\n![Clustering](https://raw.github.com/eligosource/eventsourced/master/doc/images/clustering-2.png)\n\nCode from this section is contained in [ClusterExample.scala](https://github.com/eligosource/eventsourced/blob/master/es-examples/src/main/scala/org/eligosource/eventsourced/example/ClusterExample.scala), the configuration files used are [journal.conf](https://github.com/eligosource/eventsourced/blob/master/es-examples/src/main/resources/journal.conf) and [cluster.conf](https://github.com/eligosource/eventsourced/blob/master/es-examples/src/main/resources/cluster.conf). For a more detailed description of the example code, refer to the code comments. To run the distributed example application from sbt, first start the application that hosts the `Destination` actor and the journal:\n\n    \u003e run-main org.eligosource.eventsourced.example.DestinationApp\n\nThen start the first seed node of the cluster\n\n    \u003e run-main org.eligosource.eventsourced.example.NodeApp 2561\n\nthen the second seed node\n\n    \u003e run-main org.eligosource.eventsourced.example.NodeApp 2562\n\nand finally a third cluster node\n\n    \u003e run-main org.eligosource.eventsourced.example.NodeApp\n\nThe above commands require that you're in the `eventsourced-examples` project. You can switch to it via\n\n    \u003e project eventsourced-examples\n\nMost likely the first seed node will become the master which writes\n\n    MASTER: recovered door at akka://node@127.0.0.1:2561\n\nto `stdout`. The other nodes become slaves that write\n\n    SLAVE: referenced door at akka://node@127.0.0.1:2561\n\nto `stdout`. All nodes prompt the user to enter a door command:\n\n    command (open|close):\n\nWe will now enter commands on the last started cluster node (a slave node).\n\nThe `Door` singleton is initially in closed state. Entering `open` will open it:\n\n    command (open|close): open\n    moved 1 times: door now open\n\nThen close it again:\n\n    command (open|close): close\n    moved 2 times: door now closed\n\nTrying to close a closed door will result in an error:\n\n    command (open|close): close\n    cannot close door: door is closed\n\nNow kill the master node with `ctrl^c`. This will also destroy the `Door` singleton. After 1-2 seconds, a new master has been determined by the cluster. The new master is going to recover the event-sourced `Door` singleton. The slave will renew its remote reference to the `Door`. To verify that the `Door` has been properly recovered, open the door again:\n\n    command (open|close): open\n    moved 3 times: door now open\n\nYou can see that the `Door` state (which contains the number of past moves) has been properly failed-over.\n\nMiscellaneous\n-------------\n\n### Multicast processor\n\n![Multicast](https://raw.github.com/eligosource/eventsourced/master/doc/images/multicast-1.png)\n\nThe [`Multicast`](http://eligosource.github.com/eventsourced/api/snapshot/#org.eligosource.eventsourced.core.Multicast) processor is a predefined `Eventsourced` processor that forwards received event messages to multiple targets. Using a `Multicast` processor with n targets is an optimization of having n `Eventsourced` processors that receive the same event `Message`s. Using a multicast processor, a received event message is journaled only once whereas with n `Eventsourced` processors that message would be journaled n times (once for each processor). Using a `Multicast` processor for a large number of targets can therefore significantly save disk space and increase throughput.\n\nApplications can create a `Multicast` processor with the `multicast` factory method which is defined in package [`core`](http://eligosource.github.com/eventsourced/api/snapshot/#org.eligosource.eventsourced.core.package).\n\n```scala\n// …\nimport org.eligosource.eventsourced.core._\n\nval extension: EventsourcingExtension = …\n\nval processorId: Int = …\nval target1: ActorRef = …\nval target2: ActorRef = …\n\nval multicast = extension.processorOf(Props(multicast(processorId, List(target1, target2))))\n```\n\nThis is equivalent to\n\n```scala\nval multicast = extension.processorOf(Props(new Multicast(List(target1, target2), identity) with Eventsourced { val id = processorId } ))\n```\n\nApplications that want to modify received event `Message`s, before they are forwarded to targets, can specify a `transformer` function.\n\n```scala\nval transformer: Message =\u003e Any = msg =\u003e msg.event\nval multicast = extension.processorOf(Props(multicast(1, List(target1, target2), transformer)))\n```\n\nIn the above example, the `transformer` function extracts the `event` from a received event `Message`. If the `transformer` function is not specified, it defaults to the `identity` function. Another `Multicast` factory method is the `decorator` method for creating a multicast processor with a single target.\n\n### Retroactive changes\n\nTODO\n\nAppendix A: Legend\n------------------\n\n![Legend](https://raw.github.com/eligosource/eventsourced/master/doc/images/legend.png)\n\nAppendix B: Project\n-------------------\n\n- [Eventsourced API](http://eligosource.github.com/eventsourced/api/snapshot/#org.eligosource.eventsourced.core.package)\n- [Eventsourced reference application](https://github.com/eligosource/eventsourced-example)\n- [Developer guidelines](https://github.com/eligosource/eventsourced/wiki/Developer-guidelines)\n- [Installation](https://github.com/eligosource/eventsourced/wiki/Installation)\n- [FAQ](https://github.com/eligosource/eventsourced/wiki/FAQ)\n\nAppendix C: Articles\n--------------------\n\n- [Event sourcing and external service integration](http://krasserm.blogspot.com/2013/01/event-sourcing-and-external-service.html)\n\nAppendix D: Support\n--------------------\n\n- [Eventsourced user forum](http://groups.google.com/group/eventsourced)\n- [Eventsourced developer forum](http://groups.google.com/group/eventsourced-dev)\n- Commercial support by [Eligotech B.V.](http://www.eligotech.com/)\n","funding_links":[],"categories":["General Programming"],"sub_categories":["Angular"],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Feligosource%2Feventsourced","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Feligosource%2Feventsourced","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Feligosource%2Feventsourced/lists"}