| @@ -0,0 +1,210 @@ |
| 1 | +/// An event store (issue #145 §4, the DDD discussion): aggregates are |
| 2 | +/// `decide`/`evolve` functions; where events live is the `event_store` |
| 3 | +/// effect — PostgreSQL in production (`with_postgres`), memory in tests |
| 4 | +/// (`with_memory`). Writes are one transaction: the events, the outbox |
| 5 | +/// rows, and the `pg_notify` that wakes the projections. |
| 6 | +/// |
| 7 | +/// Optimistic concurrency: appending at a version the stream has passed |
| 8 | +/// is `Error(Conflict)` (the `(stream, version)` unique index's 23505, |
| 9 | +/// or a moved head caught by the insert's `where`). |
| 10 | + |
| 11 | +import std/dict.{type Dict} |
| 12 | +import std/list |
| 13 | +import std/option |
| 14 | +import std/random.{type random} |
| 15 | +import std/ref |
| 16 | +import std/result |
| 17 | +import std/string |
| 18 | +import std/process.{type proc} |
| 19 | + |
| 20 | +import postgres as pg |
| 21 | +import postgres.{type sql} |
| 22 | + |
| 23 | +/// An event, before it has its version. |
| 24 | +pub type NewEvent { |
| 25 | + NewEvent(kind: String, data: String) |
| 26 | +} |
| 27 | + |
| 28 | +/// An event stored: its stream and version. |
| 29 | +@derive(Eq, Debug) |
| 30 | +pub type Event { |
| 31 | + Event(stream: String, version: Int, kind: String, data: String) |
| 32 | +} |
| 33 | + |
| 34 | +/// Why a store call failed. |
| 35 | +@derive(Eq, Debug) |
| 36 | +pub type StoreError { |
| 37 | + /// The stream's version moved on (someone else wrote first). |
| 38 | + Conflict |
| 39 | + /// Anything else, with its message. |
| 40 | + Store(String) |
| 41 | +} |
| 42 | + |
| 43 | +/// The event store port: handlers decide where events live. |
| 44 | +pub effect event_store { |
| 45 | + /// The events of a stream, in order. |
| 46 | + fn load(stream: String) -> Result<List<Event>, StoreError> |
| 47 | + /// Append events with the stream at `expected` version: `Conflict` |
| 48 | + /// when it has moved on. The result is the new version. |
| 49 | + fn append(stream: String, expected: Int, events: List<NewEvent>) -> Result<Int, StoreError> |
| 50 | +} |
| 51 | + |
| 52 | +// ---- the in-memory handler (tests) ------------------------------------------- |
| 53 | + |
| 54 | +/// The store in memory: `with_memory(fn() { ... })` in tests. |
| 55 | +pub fn with_memory(action: fn() -> a / <event_store | e>) -> a / <e> { |
| 56 | + region { |
| 57 | + // stream -> its events, newest first. |
| 58 | + let store = ref.new(dict.empty()) |
| 59 | + handle { action() } with { |
| 60 | + load(stream) -> Ok(list.reverse(current(ref.get(store), stream))), |
| 61 | + append(stream, expected, events) -> { |
| 62 | + let current = current(ref.get(store), stream) |
| 63 | + if list.length(current) != expected { |
| 64 | + Error(Conflict) |
| 65 | + } else { |
| 66 | + let stored = store_events(stream, expected, events, current) |
| 67 | + ref.set(store, dict.insert(ref.get(store), stream, stored)) |
| 68 | + Ok(list.length(stored)) |
| 69 | + } |
| 70 | + }, |
| 71 | + } |
| 72 | + } |
| 73 | +} |
| 74 | + |
| 75 | +/// The stream's events, newest first. |
| 76 | +fn current(store: Dict<String, List<Event>>, stream: String) -> List<Event> { |
| 77 | + option.unwrap_or(dict.get(store, stream), []) |
| 78 | +} |
| 79 | + |
| 80 | +fn store_events(stream: String, at: Int, events: List<NewEvent>, acc: List<Event>) -> List<Event> { |
| 81 | + match events { |
| 82 | + [] -> acc, |
| 83 | + [e, ..rest] -> store_events(stream, at + 1, rest, [Event(stream, at + 1, e.kind, e.data), ..acc]), |
| 84 | + } |
| 85 | +} |
| 86 | + |
| 87 | +// ---- the PostgreSQL handler (production) -------------------------------------- |
| 88 | + |
| 89 | +/// The tables: `events` (the log, unique on `(stream, version)`) and |
| 90 | +/// `outbox` (what projections haven't seen), plus `stream_counts` (the |
| 91 | +/// example projection). |
| 92 | +pub fn migrate(pool: pg.Pool) -> Result<(), pg.Error> / <proc> { |
| 93 | + match pg.with_connection(pool, fn() { |
| 94 | + use _ <- result.try(pg.execute("create table if not exists events (stream text not null, version int not null, kind text not null, data text not null, primary key (stream, version))", [])) |
| 95 | + use _ <- result.try(pg.execute("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 text not null, published boolean not null default false)", [])) |
| 96 | + pg.execute("create table if not exists stream_counts (stream text primary key, count int not null)", []) |
| 97 | + }) { |
| 98 | + Ok(Ok(_)) -> Ok(()), |
| 99 | + Ok(Error(e)) -> Error(e), |
| 100 | + Error(e) -> Error(e), |
| 101 | + } |
| 102 | +} |
| 103 | + |
| 104 | +/// The store on PostgreSQL: each operation is its own transaction; the |
| 105 | +/// pool serves them. |
| 106 | +pub fn with_postgres(pool: pg.Pool, action: fn() -> a / <event_store, proc | e>) -> a / <proc | e> { |
| 107 | + handle { action() } with { |
| 108 | + load(stream) -> pg_load(pool, stream), |
| 109 | + append(stream, expected, events) -> pg_append(pool, stream, expected, events), |
| 110 | + } |
| 111 | +} |
| 112 | + |
| 113 | +fn pg_load(pool: pg.Pool, stream: String) -> Result<List<Event>, StoreError> / <proc> { |
| 114 | + match pg.with_connection(pool, fn() { |
| 115 | + pg.query("select version, kind, data from events where stream = $1 order by version", [pg.text(stream)]) |
| 116 | + }) { |
| 117 | + Ok(Ok(result)) -> rows_to_events(result.rows, stream, []), |
| 118 | + Ok(Error(e)) -> Error(Store(pg.error_message(e))), |
| 119 | + Error(e) -> Error(Store(pg.error_message(e))), |
| 120 | + } |
| 121 | +} |
| 122 | + |
| 123 | +fn rows_to_events(rows: List<pg.Row>, stream: String, acc: List<Event>) -> Result<List<Event>, StoreError> { |
| 124 | + match rows { |
| 125 | + [] -> Ok(list.reverse(acc)), |
| 126 | + [row, ..rest] -> { |
| 127 | + use version <- result.try(need_int(row, "version")) |
| 128 | + use kind <- result.try(need_text(row, "kind")) |
| 129 | + use data <- result.try(need_text(row, "data")) |
| 130 | + rows_to_events(rest, stream, [Event(stream, version, kind, data), ..acc]) |
| 131 | + } |
| 132 | + } |
| 133 | +} |
| 134 | + |
| 135 | +fn need_int(row: pg.Row, name: String) -> Result<Int, StoreError> { |
| 136 | + match pg.row_int(row, name) { |
| 137 | + Ok(Some(v)) -> Ok(v), |
| 138 | + _ -> Error(Store("no column {name}")), |
| 139 | + } |
| 140 | +} |
| 141 | + |
| 142 | +fn need_text(row: pg.Row, name: String) -> Result<String, StoreError> { |
| 143 | + match pg.row_text(row, name) { |
| 144 | + Ok(Some(v)) -> Ok(v), |
| 145 | + _ -> Error(Store("no column {name}")), |
| 146 | + } |
| 147 | +} |
| 148 | + |
| 149 | +/// The outcome of an append inside its transaction. |
| 150 | +type AppendOutcome { |
| 151 | + Stored(Int) |
| 152 | + MovedOn |
| 153 | +} |
| 154 | + |
| 155 | +fn pg_append(pool: pg.Pool, stream: String, expected: Int, events: List<NewEvent>) -> Result<Int, StoreError> / <proc> { |
| 156 | + match pg.transaction(pool, fn() { |
| 157 | + use outcome <- result.try(append_each(stream, expected, events)) |
| 158 | + match outcome { |
| 159 | + MovedOn -> Ok(MovedOn), |
| 160 | + Stored(at) -> { |
| 161 | + use _ <- result.try(outbox_each(stream, expected, events)) |
| 162 | + use _ <- result.try(pg.execute("select pg_notify('event_store_events', $1)", [pg.text(stream)])) |
| 163 | + Ok(Stored(at)) |
| 164 | + }, |
| 165 | + } |
| 166 | + }) { |
| 167 | + Ok(Stored(at)) -> Ok(at), |
| 168 | + Ok(MovedOn) -> Error(Conflict), |
| 169 | + Error(e) -> |
| 170 | + if pg.sqlstate(e) == Some("23505") { |
| 171 | + Error(Conflict) |
| 172 | + } else { |
| 173 | + Error(Store(pg.error_message(e))) |
| 174 | + }, |
| 175 | + } |
| 176 | +} |
| 177 | + |
| 178 | +/// Insert the events, each at its version: the `where` checks the |
| 179 | +/// stream's head, and inserts nothing when it moved on (a race's loser |
| 180 | +/// also meets the primary key, a 23505, mapped by the caller). |
| 181 | +fn append_each(stream: String, at: Int, events: List<NewEvent>) -> Result<AppendOutcome, pg.Error> / <sql, proc> { |
| 182 | + match events { |
| 183 | + [] -> Ok(Stored(at)), |
| 184 | + [event, ..rest] -> { |
| 185 | + let version = at + 1 |
| 186 | + match pg.execute( |
| 187 | + "insert into events (stream, version, kind, data) select $1, $2, $3, $4 where (select coalesce(max(version), 0) from events where stream = $1) = $5", |
| 188 | + [pg.text(stream), pg.int(version), pg.text(event.kind), pg.text(event.data), pg.int(at)], |
| 189 | + ) { |
| 190 | + Error(e) -> Error(e), |
| 191 | + Ok(0) -> Ok(MovedOn), |
| 192 | + Ok(_) -> append_each(stream, version, rest), |
| 193 | + } |
| 194 | + } |
| 195 | + } |
| 196 | +} |
| 197 | + |
| 198 | +/// The outbox rows for the events (same transaction). |
| 199 | +fn outbox_each(stream: String, at: Int, events: List<NewEvent>) -> Result<(), pg.Error> / <sql, proc> { |
| 200 | + match events { |
| 201 | + [] -> Ok(()), |
| 202 | + [event, ..rest] -> { |
| 203 | + use _ <- result.try(pg.execute( |
| 204 | + "insert into outbox (stream, version, kind, data) values ($1, $2, $3, $4)", |
| 205 | + [pg.text(stream), pg.int(at + 1), pg.text(event.kind), pg.text(event.data)], |
| 206 | + )) |
| 207 | + outbox_each(stream, at + 1, rest) |
| 208 | + } |
| 209 | + } |
| 210 | +} |