/// An event store (issue #145 §4, the DDD discussion): aggregates are /// `decide`/`evolve` functions; where events live is the `event_store` /// effect — PostgreSQL in production (`with_postgres`), memory in tests /// (`with_memory`). Writes are one transaction: the events, the outbox /// rows, and the `pg_notify` that wakes the projections. /// /// Optimistic concurrency: appending at a version the stream has passed /// is `Error(Conflict)` (the `(stream, version)` unique index's 23505, /// or a moved head caught by the insert's `where`). import std/dict.{type Dict} import std/list import std/option import std/process.{type proc} import std/ref import std/result import postgres as pg import postgres.{sql} import postgres.{type sql} /// An event, before it has its version. pub type NewEvent { NewEvent(kind: String, data: Bytes) } /// An event stored: its stream and version. @derive Eq Debug pub type Event { Event(stream: String, version: Int, kind: String, data: Bytes) } /// Why a store call failed. @derive Eq Debug pub type StoreError { /// The stream's version moved on (someone else wrote first). Conflict /// Anything else, with its message. , Store(String) } /// The event store port: handlers decide where events live. pub effect event_store { /// The events of a stream, in order. fn load :: stream: String -> Result, StoreError> /// Append events with the stream at `expected` version: `Conflict` /// when it has moved on. The result is the new version. fn append :: stream: String expected: Int events: List -> Result } // ---- the in-memory handler (tests) ------------------------------------------- /// The store in memory: `with_memory(fn() { ... })` in tests. pub fn with_memory :: action: fn() -> a / -> a / { region { // stream -> its events, newest first. let store = ref.new (dict.empty ()) handle { action () } with { load stream -> Ok(list.reverse (current (ref.get store) stream)) , append stream expected events -> { let current = current (ref.get store) stream if list.length current != expected { Error(Conflict) } else { let stored = store_events stream expected events current ref.set store (dict.insert (ref.get store) stream stored) Ok(list.length stored) } } } } } /// The stream's events, newest first. fn current :: store: Dict> stream: String -> List { option.unwrap_or (dict.get store stream) [] } fn store_events :: stream: String at: Int events: List acc: List -> List { match events { [] -> acc , [e, ..rest] -> store_events stream (at + 1) rest [Event(stream, at + 1, e.kind, e.data), ..acc] } } // ---- the PostgreSQL handler (production) -------------------------------------- /// The tables: `events` (the log, unique on `(stream, version)`) and /// `outbox` (what projections haven't seen), plus `stream_counts` (the /// example projection). Event payloads are `bytea` (binary on the wire, /// ADR 0043's codecs): opaque to the store. pub fn migrate :: pool: pg.Pool -> Result<(), pg.Error> / { match pg.with_connection pool fn { use _ <- result.try ( pg.execute_statement sql`create table if not exists events (stream text not null, version int not null, kind text not null, data bytea not null, primary key (stream, version))` ) use _ <- result.try ( pg.execute_statement sql`create table if not exists outbox (id bigint generated always as identity primary key, stream text not null, version int not null, kind text not null, data bytea not null, published boolean not null default false)` ) pg.execute_statement sql`create table if not exists stream_counts (stream text primary key, count int not null)` } { Ok(Ok(_)) -> Ok(()), Ok(Error(e)) -> Error(e), Error(e) -> Error(e) } } /// The store on PostgreSQL: each operation is its own transaction; the /// pool serves them. pub fn with_postgres :: pool: pg.Pool action: fn() -> a / -> a / { handle { action () } with { load stream -> pg_load pool stream , append stream expected events -> pg_append pool stream expected events } } fn pg_load :: pool: pg.Pool stream: String -> Result, StoreError> / { match pg.with_connection pool fn { pg.query_statement sql`select version, kind, data from events where stream = {stream} order by version` } { Ok(Ok(res)) -> rows_to_events res.rows stream [] , Ok(Error(e)) -> Error(Store(pg.error_message e)) , Error(e) -> Error(Store(pg.error_message e)) } } fn rows_to_events :: rows: List stream: String acc: List -> Result, StoreError> { match rows { [] -> Ok(list.reverse acc) , [row, ..rest] -> { use version <- result.try (need_int row "version") use kind <- result.try (need_text row "kind") use data <- result.try (need_bytes row "data") rows_to_events rest stream [Event(stream, version, kind, data), ..acc] } } } fn need_int :: row: pg.Row name: String -> Result { match pg.row_int row name { Ok(Some(v)) -> Ok(v), _ -> Error(Store("no column {name}")) } } fn need_text :: row: pg.Row name: String -> Result { match pg.row_text row name { Ok(Some(v)) -> Ok(v), _ -> Error(Store("no column {name}")) } } fn need_bytes :: row: pg.Row name: String -> Result { match pg.row_bytea row name { Ok(Some(v)) -> Ok(v), _ -> Error(Store("no column {name}")) } } /// The outcome of an append inside its transaction. type AppendOutcome { Stored(Int), MovedOn } fn pg_append :: pool: pg.Pool stream: String expected: Int events: List -> Result / { match pg.transaction pool fn { use outcome <- result.try (append_each stream expected events) match outcome { MovedOn -> Ok(MovedOn) , Stored(at) -> { use _ <- result.try (outbox_each stream expected events) use _ <- result.try ( pg.execute_statement sql`select pg_notify('event_store_events', {stream})` ) Ok(Stored(at)) } } } { Ok(Stored(at)) -> Ok(at) , Ok(MovedOn) -> Error(Conflict) , Error(e) -> if pg.sqlstate e == Some("23505") { Error(Conflict) } else { Error(Store(pg.error_message e)) } } } /// Insert the events, each at its version: the `where` checks the /// stream's head, and inserts nothing when it moved on (a race's loser /// also meets the primary key, a 23505, mapped by the caller). fn append_each :: stream: String at: Int events: List -> Result / { match events { [] -> Ok(Stored(at)) , [event, ..rest] -> { let version = at + 1 // Parameters, not a template: the `bytea` binds in binary, where a // template hole would be its `\x…` text form (issue #311). match pg.execute "insert into events (stream, version, kind, data) select $1, $2, $3, $4 where (select coalesce(max(version), 0) from events where stream = $1) = $5" [ pg.text stream , pg.int version , pg.text event.kind , pg.bytea event.data , pg.int at ] { Error(e) -> Error(e) , Ok(0) -> Ok(MovedOn) , Ok(_) -> append_each stream version rest } } } } /// The outbox rows for the events (same transaction). fn outbox_each :: stream: String at: Int events: List -> Result<(), pg.Error> / { match events { [] -> Ok(()) , [event, ..rest] -> { use _ <- result.try ( pg.execute "insert into outbox (stream, version, kind, data) values ($1, $2, $3, $4)" [ pg.text stream , pg.int (at + 1) , pg.text event.kind , pg.bytea event.data ] ) outbox_each stream (at + 1) rest } } }