tobogganSe connecter

louise

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

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