/// The example aggregate: a counter. `decide` and `evolve` are pure; the /// store is the `event_store` effect, so the same code runs against /// memory in tests and PostgreSQL in production. import std/bytes import std/list import std/result import std/string import event_store.{type Event, type NewEvent, type event_store, NewEvent} /// The counter's commands. pub type Command { Increment(by: Int) } /// The command handler's flow: load the stream, evolve the state, decide, /// append at the version we read. pub fn increment :: stream: String by: Int -> Result / { use events <- result.try (event_store.load stream) let state = list.fold events 0 fn s e { evolve s e } use decided <- result.try (decide Increment(by) state |> result.map_error event_store.Store) event_store.append stream (list.length events) decided } /// What a command decides, given the state. Payloads are bytes (the /// column is `bytea`); the counter's are the text of the increment. pub fn decide :: command: Command state: Int -> Result, String> { match command { Increment(by) -> if by <= 0 { Error("increments are positive") } else { Ok([NewEvent("incremented", bytes.from_string "{by}")]) } } } /// The state after an event. pub fn evolve :: state: Int event: Event -> Int { match bytes.to_string event.data { Ok(s) -> match string.to_int s { Ok(n) -> state + n, Error(_) -> state } , Error(_) -> state } }