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.

85 lignes · 2232 octetsBrut · Historique
1/// The outbox delivery: a listener on `event_store_events` wakes the
2/// drainer, which applies unpublished outbox rows to the projection in
3/// one transaction. A failed drain leaves rows unpublished: the next
4/// notification retries.
5
6import std/actor.{Continue}
7import std/process.{type proc}
8import std/random.{type random}
9import std/result
10
11import postgres as pg
12import postgres.{type sql, sql}
13
14/// The drainer actor and the listener feeding it. Keep (and supervise)
15/// the returned listener.
16pub fn deliver ::
17 config: pg.Config
18 pool: pg.Pool
19 -> Result<pg.Listener, pg.Error> / <io, proc, random>
20{
21 let drainer =
22 actor.start () fn state n: pg.Notification { on_notification pool state n }
23 pg.listen config "event_store_events" drainer
24}
25
26fn on_notification ::
27 pool: pg.Pool
28 state: ()
29 _n: pg.Notification
30 -> actor.Next<()> / <proc>
31{
32 drain pool
33 Continue(state)
34}
35
36/// Every unpublished outbox row, applied to the projection in one
37/// transaction (100 at a time: a notification per batch).
38fn drain :: pool: pg.Pool -> () / <proc>
39{
40 let _ =
41 pg.transaction
42 pool
43 fn
44 {
45 use found <-
46 result.try
47 ( pg.query_statement
48 sql`select id, stream from outbox where not published order by id limit 100`
49 )
50 apply_each found.rows
51 }
52 ()
53}
54
55fn apply_each :: rows: List<pg.Row> -> Result<(), pg.Error> / <sql, proc>
56{
57 match rows
58 { [] -> Ok(())
59 , [row, ..rest] ->
60 {
61 use id <- result.try (need (pg.row_int row "id") "id")
62 use stream <- result.try (need (pg.row_text row "stream") "stream")
63 use _ <-
64 result.try
65 ( pg.execute_statement
66 sql`insert into stream_counts (stream, count) values ({stream}, 1) on conflict (stream) do update set count = stream_counts.count + 1`
67 )
68 use _ <-
69 result.try
70 ( pg.execute_statement
71 sql`update outbox set published = true where id = {id}`
72 )
73 apply_each rest
74 }
75 }
76}
77
78fn need :: r: Result<Option<a>, String> what: String -> Result<a, pg.Error>
79{
80 match r
81 { Ok(Some(v)) -> Ok(v)
82 , Ok(None) -> Error(pg.driver "no {what}")
83 , Error(e) -> Error(pg.driver e)
84 }
85}