esource
A generic event sourcing library for Haxe. Requires Haxe 4.3.0+.
Event sourcing stores every state change as an immutable event. Instead of persisting current state, you persist the full history of events that produced it. This gives you undo, replay, time travel debugging, and full audit trails for free.
Install
haxelib install hx-event-sourcing
Or use as a local dev dependency:
-cp path/to/esource/src
Quick Start
1. Define your events
Events are classes implementing a shared marker interface. Each event is a fact — something that happened.
interface TodoEvent {}
class ItemAdded implements TodoEvent {
public final text:String;
public function new(text:String) { this.text = text; }
}
class ItemCompleted implements TodoEvent {
public final index:Int;
public function new(index:Int) { this.index = index; }
}
class ItemRemoved implements TodoEvent {
public final index:Int;
public function new(index:Int) { this.index = index; }
}
2. Create your aggregate
Extend Aggregate and define applyXxx methods — one per event type. They are auto-discovered by naming convention. No switch statements, no manual dispatch.
class TodoList extends Aggregate<TodoEvent> {
public var items:Array<{text:String, done:Bool}> = [];
function applyItemAdded(event:ItemAdded):Void {
items.push({text: event.text, done: false});
}
function applyItemCompleted(event:ItemCompleted):Void {
items[event.index].done = true;
}
function applyItemRemoved(event:ItemRemoved):Void {
items.splice(event.index, 1);
}
}
3. Use it
Record events with recordThat, then persist with pullEvents.
final store = new InMemoryEventStore<TodoEvent>();
final list = new TodoList("my-list");
// Record events — state updates immediately
list.recordThat(new ItemAdded("Buy milk"));
list.recordThat(new ItemAdded("Write code"));
list.recordThat(new ItemCompleted(0));
trace(list.items); // [{text: "Buy milk", done: true}, {text: "Write code", done: false}]
trace(list.version); // 3
// Persist to store
list.persist(store);
Undo
Truncate events from the store and rebuild.
// Undo the last action
store.truncate("my-list", list.version - 1);
// Rebuild from remaining events
final restored = new TodoList("my-list");
restored.replay(store.getEvents("my-list"));
trace(restored.items[0].done); // false — completion was undone
Replay to a specific version
Reconstruct state at any point in history without modifying the store.
final atV1 = new TodoList("my-list");
atV1.replay(store.getEvents("my-list").filter(e -> e.sequenceNumber <= 1));
trace(atV1.items.length); // 1 — only "Buy milk" existed at version 1
Game Example
A full example showing aggregates, sub-aggregates, interceptors, and reactors working together. Each player is an Aggregate with its own interceptor/reactor chain, so handlers are naturally scoped — no target checks needed.
interface GameEvent {}
class DamageDealt implements GameEvent {
public final amount:Int;
public function new(amount:Int) { this.amount = amount; }
}
class PlayerHealed implements GameEvent {
public final amount:Int;
public function new(amount:Int) { this.amount = amount; }
}
class ShieldCast implements GameEvent {
public function new() {}
}
// Player is an Aggregate — has its own interceptors and reactors
class Player extends Aggregate<GameEvent> {
public var health:Int;
public function new(id:String, health:Int) {
this.health = health;
super(id);
}
function applyDamageDealt(event:DamageDealt):Void {
health -= event.amount;
}
function applyPlayerHealed(event:PlayerHealed):Void {
health += event.amount;
}
function applyShieldCast(event:ShieldCast):Void {
registerInterceptor(new ShieldInterceptor());
}
}
// Game coordinates two players
class Game {
public final player1:Player;
public final player2:Player;
public function new(player1:Player, player2:Player) {
this.player1 = player1;
this.player2 = player2;
}
}
Interceptors
Interceptors fire before an event is applied. They can replace the event, suppress it entirely, or let it pass through. Since they're registered on a specific player's aggregate, they only affect that player's events.
Extend Interceptor and define interceptXxx methods — same reflection-based dispatch as aggregates.
import handlers.Interceptor;
import handlers.InterceptResult;
// Suppress all damage — scoped to whichever player it's registered on
class ShieldInterceptor extends Interceptor<GameEvent> {
public function new() { super(); }
function interceptDamageDealt(event:DamageDealt):InterceptResult<GameEvent> {
return Suppress;
}
}
// Reverse healing into damage
class CurseInterceptor extends Interceptor<GameEvent> {
public function new() { super(); }
function interceptPlayerHealed(event:PlayerHealed):InterceptResult<GameEvent> {
return Replace(new DamageDealt(event.amount));
}
}
Reactors
Reactors fire after an event is applied. They produce follow-up events that go through the full recordThat pipeline (including interceptors and other reactors).
Extend Reactor and define reactToXxx methods.
import handlers.Reactor;
// Lifesteal: when this player takes damage, heal for 1
class LifestealReactor extends Reactor<GameEvent> {
public function new() { super(); }
function reactToDamageDealt(event:DamageDealt):Array<GameEvent> {
return ([new PlayerHealed(1)] : Array<GameEvent>);
}
}
Usage
final p1 = new Player("p1", 20);
final p2 = new Player("p2", 20);
final game = new Game(p1, p2);
// p1 casts shield — interceptor registered on p1's chain
p1.recordThat(new ShieldCast());
p1.recordThat(new DamageDealt(10));
trace(p1.health); // 20 — damage blocked by shield
p2.recordThat(new DamageDealt(5));
trace(p2.health); // 15 — p2 has no shield, unaffected
// p2 gains lifesteal
p2.registerReactor(new LifestealReactor());
p2.recordThat(new DamageDealt(4));
trace(p2.health); // 12 — took 4 damage, healed 1 from lifesteal
Interceptors and reactors only run during recordThat — they are skipped during replay. Because interceptors are registered inside applyXxx handlers (like applyShieldCast), they are automatically re-registered when replaying events.
Multiple interceptors chain in registration order. Reactor follow-up events go through the full pipeline, so interceptors can suppress or replace them. To prevent infinite reactor chains, there is a maxReactorDepth limit (default 10).
Save and Load
Export events to JSON for persistence and import them back later.
Create a codec
class TodoEventCodec implements Codec<TodoEvent> {
public function new() {}
public function encode(value:TodoEvent):Dynamic {
final cls = Type.getClass(value);
final name = Type.getClassName(cls).split(".").pop();
final obj:Dynamic = {type: name};
for (field in Type.getInstanceFields(cls)) {
Reflect.setField(obj, field, Reflect.getProperty(value, field));
}
return obj;
}
public function decode(data:Dynamic):TodoEvent {
final type:String = data.type;
switch (type) {
case "ItemAdded": return new ItemAdded(data.text);
case "ItemCompleted": return new ItemCompleted(data.index);
case "ItemRemoved": return new ItemRemoved(data.index);
default: throw 'Unknown event type: $type';
}
}
}
Export and import
final codec = new TodoEventCodec();
// Export
final events = store.getEvents("my-list");
final json = haxe.Json.stringify([for (e in events) e.toJson(codec)]);
// Import into a fresh store
final parsed:Array<Dynamic> = haxe.Json.parse(json);
final imported = [for (data in parsed) Event.fromJson(data, codec)];
final newStore = new InMemoryEventStore<TodoEvent>();
newStore.append("my-list", imported);
// Rebuild
final restored = new TodoList("my-list");
restored.replay(newStore.getEvents("my-list"));
Snapshots
For aggregates with long event histories, snapshots avoid replaying from event 0.
// Save a snapshot
final snapshot = new Snapshot("my-list", list.version, {items: list.items});
store.saveSnapshot(snapshot);
// Load from snapshot + replay only newer events
final snap = store.getLatestSnapshot("my-list");
final restored = new TodoList("my-list");
restored.items = snap.state.items;
restored.replay(store.getEvents("my-list", snap.version));
Custom Event Store
EventStore is an interface. Implement it to persist events to files, SQLite, or anywhere else.
import store.EventStore;
class FileEventStore<TEvent> implements EventStore<TEvent> {
public function append(aggregateId:String, events:Array<Event<TEvent>>):Void { /* ... */ }
public function getEvents(aggregateId:String, ?afterVersion:Int):Array<Event<TEvent>> { /* ... */ }
public function getEventCount(aggregateId:String):Int { /* ... */ }
public function truncate(aggregateId:String, toVersion:Int):Void { /* ... */ }
public function saveSnapshot(snapshot:Snapshot):Void { /* ... */ }
public function getLatestSnapshot(aggregateId:String):Null<Snapshot> { /* ... */ }
public function getAllAggregateIds():Array<String> { /* ... */ }
}
API Reference
Aggregate<TEvent> (abstract class)
| Member | Description |
|---|---|
id:String | Aggregate identity. |
version:Int | Sequence number of the last applied event. |
maxReactorDepth:Int | Maximum depth for reactor chains (default 10). |
recordThat(event) | Run interceptors, apply event, persist to pending, run reactors. |
replay(events) | Replay events to rebuild state. Skips interceptors and reactors. |
pullEvents() | Return pending events and clear the list. |
registerInterceptor(interceptor) | Add an interceptor to the before-event chain. |
unregisterInterceptor(interceptor) | Remove a specific interceptor instance. |
registerReactor(reactor) | Add a reactor to the after-event chain. |
unregisterReactor(reactor) | Remove a specific reactor instance. |
applyXxx(event:Xxx) | Convention. Define these methods — they are auto-discovered. |
Event<TEvent>
| Member | Description |
|---|---|
aggregateId:String | Which aggregate this event belongs to. |
sequenceNumber:Int | Position in the aggregate's event stream. |
timestamp:Float | When the event was created. |
data:TEvent | The domain event. |
toJson(codec) | Serialize to a JSON-compatible Dynamic. |
fromJson(json, codec) | Static. Deserialize from JSON. |
EventStore<TEvent> (interface, store package)
| Method | Description |
|---|---|
append(id, events) | Append events to an aggregate's stream. |
getEvents(id, ?afterVersion) | Get events, optionally only those after a version. |
getEventCount(id) | Number of events for an aggregate. |
truncate(id, toVersion) | Remove events after a version (for undo). Also removes snapshots beyond that version. |
saveSnapshot(snapshot) | Persist a snapshot. |
getLatestSnapshot(id) | Get the most recent snapshot. |
getAllAggregateIds() | List all aggregate IDs in the store. |
Interceptor<TEvent> (abstract class, handlers package)
| Member | Description |
|---|---|
intercept(event) | Dispatches to interceptXxx handler. Returns PassThrough if no handler matches. |
interceptXxx(event:Xxx) | Convention. Define these methods — they are auto-discovered. Return InterceptResult. |
InterceptResult<TEvent> (enum, handlers package)
| Variant | Description |
|---|---|
Replace(event) | Swap the event for a different one. |
Suppress | Drop the event entirely — it is not applied or persisted. |
PassThrough | Let the event through unchanged. |
Reactor<TEvent> (abstract class, handlers package)
| Member | Description |
|---|---|
reactTo(event) | Dispatches to reactToXxx handler. Returns [] if no handler matches. |
reactToXxx(event:Xxx) | Convention. Define these methods — they are auto-discovered. Return Array<TEvent>. |
Codec<T> (interface)
| Method | Description |
|---|---|
encode(value) | Convert a value to JSON-compatible Dynamic. |
decode(data) | Convert JSON-compatible Dynamic back to a value. |
Snapshot
| Member | Description |
|---|---|
aggregateId:String | Which aggregate this snapshot is for. |
version:Int | The event version at snapshot time. |
state:Dynamic | Serialized aggregate state. |
toJson() / fromJson(json) | JSON serialization. |
License
MIT