/// The outbox delivery: a listener on `event_store_events` wakes the /// drainer, which applies unpublished outbox rows to the projection in /// one transaction. A failed drain leaves rows unpublished: the next /// notification retries. import std/actor.{Continue} import std/net.{type net} import std/process.{type proc} import std/random.{type random} import std/result import postgres as pg import postgres.{type sql, sql} /// The drainer actor and the listener feeding it. Keep (and supervise) /// the returned listener. pub fn deliver :: config: pg.Config pool: pg.Pool -> Result / { let drainer = actor.start () fn state n: pg.Notification { on_notification pool state n } pg.listen config "event_store_events" drainer } fn on_notification :: pool: pg.Pool state: () _n: pg.Notification -> actor.Next<()> / { drain pool Continue(state) } /// Every unpublished outbox row, applied to the projection in one /// transaction (100 at a time: a notification per batch). fn drain :: pool: pg.Pool -> () / { let _ = pg.transaction pool fn { use found <- result.try ( pg.query_statement sql`select id, stream from outbox where not published order by id limit 100` ) apply_each found.rows } () } fn apply_each :: rows: List -> Result<(), pg.Error> / { match rows { [] -> Ok(()) , [row, ..rest] -> { use id <- result.try (need (pg.row_int row "id") "id") use stream <- result.try (need (pg.row_text row "stream") "stream") use _ <- result.try ( pg.execute_statement sql`insert into stream_counts (stream, count) values ({stream}, 1) on conflict (stream) do update set count = stream_counts.count + 1` ) use _ <- result.try ( pg.execute_statement sql`update outbox set published = true where id = {id}` ) apply_each rest } } } fn need :: r: Result, String> what: String -> Result { match r { Ok(Some(v)) -> Ok(v) , Ok(None) -> Error(pg.driver "no {what}") , Error(e) -> Error(pg.driver e) } }