tobogganSe connecter

louise

The Louise language: compiler, runtime, std, tooling

Clone avec HTTPS, un jeton personnel en mot de passe, ou avec SSH, une clé ajoutée dans vos paramètres.

309 lignes · 8425 octetsBrut · Historique
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
11import std/dict.{type Dict}
12import std/list
13import std/option
14import std/process.{type proc}
15import std/ref
16import std/result
17
18import postgres as pg
19import postgres.{sql}
20import postgres.{type sql}
21
22/// An event, before it has its version.
23pub type NewEvent { NewEvent(kind: String, data: Bytes) }
24
25/// An event stored: its stream and version.
26@derive Eq Debug
27pub type Event
28{ Event(stream: String, version: Int, kind: String, data: Bytes) }
29
30/// Why a store call failed.
31@derive Eq Debug
32pub type StoreError
33{ /// The stream's version moved on (someone else wrote first).
34 Conflict
35 /// Anything else, with its message.
36, Store(String)
37}
38
39/// The event store port: handlers decide where events live.
40pub effect event_store
41{
42 /// The events of a stream, in order.
43 fn load :: stream: String -> Result<List<Event>, StoreError>
44 /// Append events with the stream at `expected` version: `Conflict`
45 /// when it has moved on. The result is the new version.
46 fn append ::
47 stream: String
48 expected: Int
49 events: List<NewEvent>
50 -> Result<Int, StoreError>
51}
52
53// ---- the in-memory handler (tests) -------------------------------------------
54
55/// The store in memory: `with_memory(fn() { ... })` in tests.
56pub fn with_memory :: action: fn() -> a / <event_store | e> -> a / <e>
57{
58 region
59 {
60 // stream -> its events, newest first.
61 let store = ref.new (dict.empty ())
62 handle
63 {
64 action ()
65 }
66 with
67 { load stream -> Ok(list.reverse (current (ref.get store) stream))
68 , append stream
69 expected
70 events ->
71 {
72 let current = current (ref.get store) stream
73 if list.length current != expected
74 {
75 Error(Conflict)
76 }
77 else
78 {
79 let stored = store_events stream expected events current
80 ref.set store (dict.insert (ref.get store) stream stored)
81 Ok(list.length stored)
82 }
83 }
84 }
85 }
86}
87
88/// The stream's events, newest first.
89fn current :: store: Dict<String, List<Event>> stream: String -> List<Event>
90{
91 option.unwrap_or (dict.get store stream) []
92}
93
94fn store_events ::
95 stream: String
96 at: Int
97 events: List<NewEvent>
98 acc: List<Event>
99 -> List<Event>
100{
101 match events
102 { [] -> acc
103 , [e, ..rest] ->
104 store_events
105 stream
106 (at + 1)
107 rest
108 [Event(stream, at + 1, e.kind, e.data), ..acc]
109 }
110}
111
112// ---- the PostgreSQL handler (production) --------------------------------------
113
114/// The tables: `events` (the log, unique on `(stream, version)`) and
115/// `outbox` (what projections haven't seen), plus `stream_counts` (the
116/// example projection). Event payloads are `bytea` (binary on the wire,
117/// ADR 0043's codecs): opaque to the store.
118pub fn migrate :: pool: pg.Pool -> Result<(), pg.Error> / <proc>
119{
120 match pg.with_connection
121 pool
122 fn
123 {
124 use _ <-
125 result.try
126 ( pg.execute_statement
127 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))`
128 )
129 use _ <-
130 result.try
131 ( pg.execute_statement
132 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)`
133 )
134 pg.execute_statement
135 sql`create table if not exists stream_counts (stream text primary key, count int not null)`
136 }
137 { Ok(Ok(_)) -> Ok(()), Ok(Error(e)) -> Error(e), Error(e) -> Error(e) }
138}
139
140/// The store on PostgreSQL: each operation is its own transaction; the
141/// pool serves them.
142pub fn with_postgres ::
143 pool: pg.Pool
144 action: fn() -> a / <event_store, proc | e>
145 -> a / <proc | e>
146{
147 handle
148 {
149 action ()
150 }
151 with
152 { load stream -> pg_load pool stream
153 , append stream expected events -> pg_append pool stream expected events
154 }
155}
156
157fn pg_load ::
158 pool: pg.Pool
159 stream: String
160 -> Result<List<Event>, StoreError> / <proc>
161{
162 match pg.with_connection
163 pool
164 fn
165 {
166 pg.query_statement
167 sql`select version, kind, data from events where stream = {stream} order by version`
168 }
169 { Ok(Ok(res)) -> rows_to_events res.rows stream []
170 , Ok(Error(e)) -> Error(Store(pg.error_message e))
171 , Error(e) -> Error(Store(pg.error_message e))
172 }
173}
174
175fn rows_to_events ::
176 rows: List<pg.Row>
177 stream: String
178 acc: List<Event>
179 -> Result<List<Event>, StoreError>
180{
181 match rows
182 { [] -> Ok(list.reverse acc)
183 , [row, ..rest] ->
184 {
185 use version <- result.try (need_int row "version")
186 use kind <- result.try (need_text row "kind")
187 use data <- result.try (need_bytes row "data")
188 rows_to_events rest stream [Event(stream, version, kind, data), ..acc]
189 }
190 }
191}
192
193fn need_int :: row: pg.Row name: String -> Result<Int, StoreError>
194{
195 match pg.row_int row name
196 { Ok(Some(v)) -> Ok(v), _ -> Error(Store("no column {name}")) }
197}
198
199fn need_text :: row: pg.Row name: String -> Result<String, StoreError>
200{
201 match pg.row_text row name
202 { Ok(Some(v)) -> Ok(v), _ -> Error(Store("no column {name}")) }
203}
204
205fn need_bytes :: row: pg.Row name: String -> Result<Bytes, StoreError>
206{
207 match pg.row_bytea row name
208 { Ok(Some(v)) -> Ok(v), _ -> Error(Store("no column {name}")) }
209}
210
211/// The outcome of an append inside its transaction.
212type AppendOutcome { Stored(Int), MovedOn }
213
214fn pg_append ::
215 pool: pg.Pool
216 stream: String
217 expected: Int
218 events: List<NewEvent>
219 -> Result<Int, StoreError> / <proc>
220{
221 match pg.transaction
222 pool
223 fn
224 {
225 use outcome <- result.try (append_each stream expected events)
226 match outcome
227 { MovedOn -> Ok(MovedOn)
228 , Stored(at) ->
229 {
230 use _ <- result.try (outbox_each stream expected events)
231 use _ <-
232 result.try
233 ( pg.execute_statement
234 sql`select pg_notify('event_store_events', {stream})`
235 )
236 Ok(Stored(at))
237 }
238 }
239 }
240 { Ok(Stored(at)) -> Ok(at)
241 , Ok(MovedOn) -> Error(Conflict)
242 , Error(e) -> if pg.sqlstate e == Some("23505")
243 {
244 Error(Conflict)
245 }
246 else
247 {
248 Error(Store(pg.error_message e))
249 }
250 }
251}
252
253/// Insert the events, each at its version: the `where` checks the
254/// stream's head, and inserts nothing when it moved on (a race's loser
255/// also meets the primary key, a 23505, mapped by the caller).
256fn append_each ::
257 stream: String
258 at: Int
259 events: List<NewEvent>
260 -> Result<AppendOutcome, pg.Error> / <sql, proc>
261{
262 match events
263 { [] -> Ok(Stored(at))
264 , [event, ..rest] ->
265 {
266 let version = at + 1
267 // Parameters, not a template: the `bytea` binds in binary, where a
268 // template hole would be its `\x…` text form (issue #311).
269 match pg.execute
270 "insert into events (stream, version, kind, data) select $1, $2, $3, $4 where (select coalesce(max(version), 0) from events where stream = $1) = $5"
271 [ pg.text stream
272 , pg.int version
273 , pg.text event.kind
274 , pg.bytea event.data
275 , pg.int at
276 ]
277 { Error(e) -> Error(e)
278 , Ok(0) -> Ok(MovedOn)
279 , Ok(_) -> append_each stream version rest
280 }
281 }
282 }
283}
284
285/// The outbox rows for the events (same transaction).
286fn outbox_each ::
287 stream: String
288 at: Int
289 events: List<NewEvent>
290 -> Result<(), pg.Error> / <sql, proc>
291{
292 match events
293 { [] -> Ok(())
294 , [event, ..rest] ->
295 {
296 use _ <-
297 result.try
298 ( pg.execute
299 "insert into outbox (stream, version, kind, data) values ($1, $2, $3, $4)"
300 [ pg.text stream
301 , pg.int (at + 1)
302 , pg.text event.kind
303 , pg.bytea event.data
304 ]
305 )
306 outbox_each stream (at + 1) rest
307 }
308 }
309}