/// A pool of connections (issue gabla108/louise#145 §3): the pool actor hands out /// connections, one borrower at a time, and watches everyone it talks to /// — a dead borrower frees its connection (closed, not reused: its /// transaction state is unknown), a dead connection frees its slot. /// /// Waiting callers queue; the acquire timeout is the caller's /// (`acquire`'s), and a `CancelAcquire` best-effort message drops a /// request whose waiter gave up. /// /// The knobs (`PoolSettings`): `min_idle` keeps a floor of connections /// warm, `idle_timeout` closes connections that sit idle (down to the /// floor), `max_lifetime` recycles old connections when they come back, /// and a connection that sat idle past `check_after` is pinged (a bare /// `Sync`, the cheapest round trip the protocol has) before it is handed /// out, so a stale connection never reaches a borrower. Durations are in /// milliseconds, evaluated with `tick` granularity: the pool wakes every /// `tick` to maintain itself. Durations are approximate by a tick, and /// ticks only fire while the pool is quiet — which is when reaping /// matters; handouts and returns are checked per message. import std/actor.{Continue, Stop} import std/list import std/process.{type Down, type Pid, type Subject, type proc, Down} import std/random.{type random} import std/result import client import config.{type Config} /// A pool of connections. pub opaque type Pool { Pool(Subject) } /// The pool's knobs. `pool.defaults(size)` is a good start; adjust with /// a record update. A `0` duration disables its check. pub type PoolSettings { PoolSettings( /// The most connections the pool holds, idle or out. size: Int /// The floor of idle connections the tick keeps warm (clamped to /// `size`). , min_idle: Int /// Close a connection idle this long, down to `min_idle` (0: never). , idle_timeout: Int /// Close a connection this old when it comes back, instead of /// reusing it (0: never). , max_lifetime: Int /// Ping a connection that sat idle this long before handing it out /// (0: never). On by default: a stale connection fails the ping and /// is replaced, instead of failing a borrower's first query. , check_after: Int /// The maintenance period, in milliseconds. , tick: Int ) } /// `size` connections, no reaping, a liveness check past 30 s idle, a /// one-second tick. pub fn defaults :: size: Int -> PoolSettings { PoolSettings( size: size , min_idle: 0 , idle_timeout: 0 , max_lifetime: 0 , check_after: 30000 , tick: 1000 ) } /// The pool's messages. pub type Msg { /// Check a connection out; the answer is the connection's subject (or /// why not — connecting one failed). Acquire( borrower: Pid , reply: Subject, client.Error>> ) /// A waiter that gave up; drop its queued request. , CancelAcquire(borrower: Pid) /// Return a connection. , Release(conn: Subject) /// Relinquish a connection whose state cannot be trusted; close, never /// reuse it. , Discard(conn: Subject) } /// What the pool's mailbox carries: its messages, monitor reports, and /// ping answers. type Event { Ev(Msg) , DownEv(Down) , PongEv(conn: Subject, result: Result<(), client.Error>) } /// A connection the pool tracks: its subject and its age in ticks. type ConnInfo { ConnInfo(conn: Subject, age: Int) } /// A handout waiting on a ping: the borrower, its answer subject, the /// connection, the ping's reply subject, and ticks since the ping. type Checking { Checking( borrower: Pid , reply: Subject, client.Error>> , info: ConnInfo , pong: Subject> , ticks: Int ) } type PoolState { PoolState( config: Config , settings: PoolSettings /// The pool's own subject. , inbox: Subject /// Connections ready to hand out, with their idle time in ticks. , idle: List<(ConnInfo, Int)> /// (borrower, connection) pairs. , checked_out: List<(Pid, ConnInfo)> /// Handouts waiting on a ping. , checking: List /// Waiting borrowers, in order: (pid, its reply subject). , waiting: List<(Pid, Subject, client.Error>>)> /// Everyone watched: connection actors and borrowers. , monitored: List<(Pid, Subject)> ) } /// A pool of `size` connections, made now, with the default settings. /// The pool replaces dead connections as they're needed. pub fn start :: cfg: Config size: Int -> Result / { start_with cfg (defaults size) } /// A pool with explicit settings, its connections made now. pub fn start_with :: cfg: Config settings: PoolSettings -> Result / { let settings = sane settings use conns <- result.try (connect_all cfg settings.size []) let ready = process.subject () { use <- process.spawn let inbox = process.subject () process.send ready inbox serve PoolState( cfg , settings , inbox , list.map conns fn c { (ConnInfo(c, 0), 0) } , [] , [] , [] , monitor_all conns [] ) } Ok(Pool(process.receive_forever ready)) } /// Settings with the clamps applied: a positive tick, `min_idle` within /// `size`. fn sane :: settings: PoolSettings -> PoolSettings { let tick = if settings.tick <= 0 { 1000 } else { settings.tick } let min_idle = if settings.min_idle < 0 { 0 } else if settings.min_idle > settings.size { settings.size } else { settings.min_idle } PoolSettings(..settings, tick: tick, min_idle: min_idle) } /// `size` connections, or the first failure. fn connect_all :: cfg: Config size: Int acc: List> -> Result>, client.Error> / { if size <= 0 { Ok(list.reverse acc) } else { use conn <- result.try (client.connect cfg) connect_all cfg (size - 1) [conn, ..acc] } } // ---- the protocol (used by lib.lse) ------------------------------------------- /// A connection from the pool, or why not (nothing within the timeout). /// A grant that races a cancel is returned at once, never leaked. pub fn acquire :: pool: Pool timeout: Int -> Result, client.Error> / { let Pool(subject) = pool let me = process.self () let reply = process.subject () process.send subject Acquire(me, reply) match process.receive reply timeout { Some(answer) -> answer , None -> { actor.cast subject CancelAcquire(me) match process.receive reply 0 { Some(Ok(conn)) -> { actor.cast subject Release(conn) Error(client.Driver("no connection within the timeout")) } , _ -> Error(client.Driver("no connection within the timeout")) } } } } /// Return a connection to the pool. pub fn release :: pool: Pool conn: Subject -> () / { let Pool(subject) = pool actor.cast subject Release(conn) } /// Relinquish a checked-out connection whose state cannot be trusted. The /// pool closes it and frees its slot instead of handing it to another caller. pub fn discard :: pool: Pool conn: Subject -> () / { let Pool(subject) = pool actor.cast subject Discard(conn) } // ---- the actor ------------------------------------------------------------------ fn serve :: state: PoolState -> () / { match process.select (selector_of state) state.settings.tick { Some(event) -> match handle_event state event { Continue(next) -> serve next, Stop -> () } // A quiet pool: the tick fires, and maintenance runs. , None -> serve (maintain state) } } /// A selector over the pool's messages, every monitor report, and every /// outstanding ping. fn selector_of :: state: PoolState -> process.Selector { let base = process.new_selector () |> process.selecting state.inbox Ev let with_downs = list.fold state.monitored base fn sel entry { process.selecting sel entry.1 DownEv } list.fold state.checking with_downs fn sel entry { let Checking(_, _, info, pong, _) = entry process.selecting sel pong fn res { PongEv(info.conn, res) } } } fn handle_event :: state: PoolState event: Event -> actor.Next / { match event { Ev(Acquire(borrower, reply)) -> Continue(grant_or_queue state borrower reply) , Ev(CancelAcquire(borrower)) -> Continue(drop_waiter state borrower) , Ev(Release(conn)) -> Continue(returned state conn) , Ev(Discard(conn)) -> Continue(discarded state conn) , DownEv(down) -> Continue(stopped state down) , PongEv(conn, res) -> Continue(ponged state conn res) } } /// Answer an acquire: from the idle list (pinging first when the /// connection sat long enough), from a new connection (while under /// size), else queue the waiter. fn grant_or_queue :: state: PoolState borrower: Pid reply: Subject, client.Error>> -> PoolState / { match state.idle { [(info, idle_ticks), ..rest] -> grant_idle PoolState(..state, idle: rest) borrower reply info idle_ticks , [] -> if live state < state.settings.size { match client.connect state.config { Ok(conn) -> grant state borrower reply ConnInfo(conn, 0) , Error(e) -> { process.send reply Error(e) state } } } else { PoolState( ..state , waiting: [..state.waiting, (borrower, reply)] , monitored: watch borrower state.monitored ) } } } /// Hand an idle connection to a borrower: straight away, or after a /// ping when it sat past `check_after`. fn grant_idle :: state: PoolState borrower: Pid reply: Subject, client.Error>> info: ConnInfo idle_ticks: Int -> PoolState / { if state.settings.check_after > 0 && idle_ticks * state.settings.tick >= state.settings.check_after { let pong = process.subject () actor.cast info.conn client.Ping(pong) PoolState( ..state , checking: [Checking(borrower, reply, info, pong, 0), ..state.checking] , monitored: watch borrower state.monitored ) } else { grant state borrower reply info } } /// Hand `info` to `borrower`: watch the borrower, record the checkout, /// answer. fn grant :: state: PoolState borrower: Pid reply: Subject, client.Error>> info: ConnInfo -> PoolState / { process.send reply Ok(info.conn) PoolState( ..state , checked_out: [(borrower, info), ..state.checked_out] , monitored: watch (process.owner info.conn) (watch borrower state.monitored) ) } /// A returned connection answers the oldest waiter, or idles — unless /// it reached `max_lifetime`, in which case it is closed and a waiter /// gets a fresh one. fn returned :: state: PoolState conn: Subject -> PoolState / { let previous = owner_of state.checked_out conn let info = info_of state.checked_out conn let state = PoolState( ..state , checked_out: drop_conn state.checked_out conn , monitored: unwatch previous state.monitored ) match info { Some ( info ) if state.settings.max_lifetime > 0 && info.age * state.settings.tick >= state.settings.max_lifetime -> { actor.cast conn client.Close(process.subject ()) drain PoolState( ..state , monitored: unwatch Some(process.owner conn) state.monitored ) } , _ -> match state.waiting { [(borrower, reply), ..rest] -> match info { Some(info) -> grant PoolState(..state, waiting: rest) borrower reply info , None -> PoolState(..state, waiting: rest) } , [] -> match info { Some(info) -> PoolState(..state, idle: [(info, 0), ..state.idle]) , None -> state } } } } /// A connection with an unknown outcome leaves the pool instead of becoming /// idle. Removing its checkout before closing it also lets a waiter reconnect. fn discarded :: state: PoolState conn: Subject -> PoolState / { let previous = owner_of state.checked_out conn match info_of state.checked_out conn { None -> state , Some(_) -> { let state = PoolState( ..state , checked_out: drop_conn state.checked_out conn , monitored: unwatch previous state.monitored ) actor.cast conn client.Close(process.subject ()) drain PoolState( ..state , monitored: unwatch Some(process.owner conn) state.monitored ) } } } /// A ping's answer: hand the connection over, or — it failed, and the /// connection actor is stopping — forget it and find the borrower /// another one. An answer for a connection no longer being checked (its /// borrower gave up) returns it to the idle list; an answer for a /// connection the pool no longer tracks at all closes it. fn ponged :: state: PoolState conn: Subject res: Result<(), client.Error> -> PoolState / { match find_checking state.checking conn { Some(entry) -> { let Checking(borrower, reply, info, _, _) = entry let state = PoolState(..state, checking: drop_checking state.checking conn) match res { Ok(()) -> grant state borrower reply info , Error(_) -> grant_or_queue PoolState( ..state , monitored: unwatch Some(process.owner conn) state.monitored ) borrower reply } } , None -> if is_idle state.idle conn { state } else { actor.cast conn client.Close(process.subject ()) PoolState( ..state , monitored: unwatch Some(process.owner conn) state.monitored ) } } } /// A monitor report: a stopped connection actor frees its slot; a stopped /// borrower frees its connection (closed, not reused) or its queue entry. fn stopped :: state: PoolState down: Down -> PoolState / { let Down(pid, _) = down let state = PoolState(..state, monitored: drop_pid state.monitored pid) match find_conn state.checked_out pid { Some(entry) -> { // The borrower died holding it: its state is unknown, so close it. let (_, info) = entry actor.cast info.conn client.Close(process.subject ()) drain PoolState(..state, checked_out: drop_pid state.checked_out pid) } , None -> match find_checking_by_borrower state.checking pid { Some(entry) -> { // The borrower died waiting on a ping: the connection is // clean (a bare Sync changes nothing), so it idles; its late // answer is a no-op then. let Checking(_, _, info, _, _) = entry PoolState( ..state , checking: drop_checking state.checking info.conn , idle: [(info, 0), ..state.idle] ) } , None -> match find_checking_by_owner state.checking pid { Some(entry) -> { // The connection died mid-ping: the borrower gets another. let Checking(borrower, reply, info, _, _) = entry grant_or_queue PoolState(..state, checking: drop_checking state.checking info.conn) borrower reply } , None -> match find_owner state.idle pid { Some(_) -> drain PoolState(..state, idle: drop_owner state.idle pid) , None -> // A waiter's death only empties its queue entry. drain PoolState(..state, waiting: drop_pid state.waiting pid) } } } } } /// A waiter gave up: drop its entry, queued or checking (a checking /// connection is clean; it idles, and its late answer is a no-op). fn drop_waiter :: state: PoolState borrower: Pid -> PoolState { match find_checking_by_borrower state.checking borrower { Some(entry) -> { let Checking(_, _, info, _, _) = entry PoolState( ..state , checking: drop_checking state.checking info.conn , idle: [(info, 0), ..state.idle] , monitored: unwatch Some(borrower) state.monitored ) } , None -> PoolState( ..state , waiting: drop_pid state.waiting borrower , monitored: unwatch Some(borrower) state.monitored ) } } /// Answer waiting callers while there is something to hand out. fn drain :: state: PoolState -> PoolState / { match state.waiting { [] -> state , [(borrower, reply), ..rest] -> match state.idle { [(info, idle_ticks), ..idle] -> drain ( grant_idle PoolState(..state, idle: idle, waiting: rest) borrower reply info idle_ticks ) , [] -> if live state < state.settings.size { match client.connect state.config { Ok(conn) -> drain ( grant PoolState(..state, waiting: rest) borrower reply ConnInfo(conn, 0) ) , Error(e) -> { process.send reply Error(e) drain PoolState(..state, waiting: rest) } } } else { state } } } } // ---- the tick ------------------------------------------------------------------- /// Maintenance, every tick while the pool is quiet: age everything, /// expire pings that take too long, close connections past /// `max_lifetime`, close connections idle past `idle_timeout` down to /// the `min_idle` floor, and warm the floor back up. fn maintain :: state: PoolState -> PoolState / { let state = age state let state = expire_checks state let state = reap state replenish state } /// Everything ages a tick. fn age :: state: PoolState -> PoolState { PoolState( ..state , idle: list.map state.idle fn entry { let (info, ticks) = entry (ConnInfo(..info, age: info.age + 1), ticks + 1) } , checked_out: list.map state.checked_out fn entry { let (borrower, info) = entry (borrower, ConnInfo(..info, age: info.age + 1)) } , checking: list.map state.checking fn entry { let Checking(borrower, reply, info, pong, ticks) = entry Checking( borrower , reply , ConnInfo(..info, age: info.age + 1) , pong , ticks + 1 ) } ) } /// A ping is answered within a round trip; two ticks without an answer /// means the connection is hung: close it and find the borrower another. fn expire_checks :: state: PoolState -> PoolState / { match state.checking { [] -> state , [entry, ..rest] -> { let Checking(borrower, reply, info, _, ticks) = entry let state = PoolState(..state, checking: rest) if ticks >= 2 { actor.cast info.conn client.Close(process.subject ()) let state = PoolState( ..state , monitored: unwatch Some(process.owner info.conn) state.monitored ) expire_checks (grant_or_queue state borrower reply) } else { expire_checks PoolState(..state, checking: [entry, ..state.checking]) } } } } /// Close idle connections past `max_lifetime` (always) or past /// `idle_timeout` (down to the `min_idle` floor). fn reap :: state: PoolState -> PoolState / { let tick = state.settings.tick let floor = state.settings.min_idle let count = list.length state.idle let (closing, keeping) = partition_indexed state.idle [] [] fn entry i { let (info, idle_ticks) = entry let too_old = state.settings.max_lifetime > 0 && info.age * tick >= state.settings.max_lifetime let too_idle = state.settings.idle_timeout > 0 && idle_ticks * tick >= state.settings.idle_timeout && count - i > floor too_old || too_idle } close_all closing match closing { [] -> state , _ -> PoolState( ..state , idle: keeping , monitored: list.fold closing state.monitored fn m entry { let (info, _) = entry unwatch Some(process.owner info.conn) m } ) } } /// Warm the `min_idle` floor with fresh connections. fn replenish :: state: PoolState -> PoolState / { let missing = state.settings.min_idle - list.length state.idle if missing <= 0 || live state >= state.settings.size { state } else { match client.connect state.config { Ok(conn) -> replenish PoolState(..state, idle: [(ConnInfo(conn, 0), 0), ..state.idle]) // The database is down; the next tick tries again. , Error(_) -> state } } } /// Close every connection in the list (best effort, fire and forget). fn close_all :: entries: List<(ConnInfo, Int)> -> () / { match entries { [] -> () , [(info, _), ..rest] -> { actor.cast info.conn client.Close(process.subject ()) close_all rest } } } // ---- small helpers -------------------------------------------------------------- /// The connections out, idle, or being checked (those are the live /// ones: a stopped connection actor's subject is removed on its Down). fn live :: state: PoolState -> Int { list.length state.idle + list.length state.checked_out + list.length state.checking } /// Watch `pid` (once). fn watch :: pid: Pid monitored: List<(Pid, Subject)> -> List<(Pid, Subject)> / { if has_pid monitored pid { monitored } else { [(pid, process.monitor pid), ..monitored] } } /// Stop watching `pid` (its subject stays in the mailbox; read no more). fn unwatch :: pid: Option monitored: List<(Pid, Subject)> -> List<(Pid, Subject)> { match pid { Some(pid) -> drop_pid monitored pid, None -> monitored } } /// The entry whose borrower is `pid`. fn find_conn :: list_: List<(Pid, ConnInfo)> pid: Pid -> Option<(Pid, ConnInfo)> { match list_ { [] -> None , [entry, ..rest] -> if entry.0 == pid { Some(entry) } else { find_conn rest pid } } } /// The pid a connection is checked out to, by its owner pid. fn owner_of :: entries: List<(Pid, ConnInfo)> conn: Subject -> Option { match entries { [] -> None , [ (pid, info) , ..rest ] -> if process.owner info.conn == process.owner conn { Some(pid) } else { owner_of rest conn } } } /// The connection info checked out under `conn`'s owner pid. fn info_of :: entries: List<(Pid, ConnInfo)> conn: Subject -> Option { match entries { [] -> None , [ (_, info) , ..rest ] -> if process.owner info.conn == process.owner conn { Some(info) } else { info_of rest conn } } } /// Drop the pair whose connection is `conn` (by its owner's pid). fn drop_conn :: entries: List<(Pid, ConnInfo)> conn: Subject -> List<(Pid, ConnInfo)> { match entries { [] -> [] , [ (p, info) , ..rest ] -> if process.owner info.conn == process.owner conn { drop_conn rest conn } else { [(p, info), ..drop_conn rest conn] } } } /// The checking entry for `conn`. fn find_checking :: entries: List conn: Subject -> Option { match entries { [] -> None , [ entry , ..rest ] -> if process.owner entry.info.conn == process.owner conn { Some(entry) } else { find_checking rest conn } } } /// The checking entry whose borrower is `pid`. fn find_checking_by_borrower :: entries: List pid: Pid -> Option { match entries { [] -> None , [entry, ..rest] -> if entry.borrower == pid { Some(entry) } else { find_checking_by_borrower rest pid } } } /// The checking entry whose connection's owner is `pid`. fn find_checking_by_owner :: entries: List pid: Pid -> Option { match entries { [] -> None , [entry, ..rest] -> if process.owner entry.info.conn == pid { Some(entry) } else { find_checking_by_owner rest pid } } } /// Drop the checking entry for `conn`. fn drop_checking :: entries: List conn: Subject -> List { match entries { [] -> [] , [ entry , ..rest ] -> if process.owner entry.info.conn == process.owner conn { drop_checking rest conn } else { [entry, ..drop_checking rest conn] } } } /// Is `conn` in the idle list? fn is_idle :: entries: List<(ConnInfo, Int)> conn: Subject -> Bool { match entries { [] -> False , [(info, _), ..rest] -> process.owner info.conn == process.owner conn || is_idle rest conn } } /// The idle entry whose connection's owner is `pid`. fn find_owner :: list_: List<(ConnInfo, Int)> pid: Pid -> Option<(ConnInfo, Int)> { match list_ { [] -> None , [entry, ..rest] -> if process.owner entry.0.conn == pid { Some(entry) } else { find_owner rest pid } } } fn drop_owner :: list_: List<(ConnInfo, Int)> pid: Pid -> List<(ConnInfo, Int)> { match list_ { [] -> [] , [ entry , ..rest ] -> if process.owner entry.0.conn == pid { drop_owner rest pid } else { [entry, ..drop_owner rest pid] } } } fn drop_pid :: entries: List<(Pid, a)> pid: Pid -> List<(Pid, a)> { match entries { [] -> [] , [(p, v), ..rest] -> if p == pid { drop_pid rest pid } else { [(p, v), ..drop_pid rest pid] } } } fn has_pid :: entries: List<(Pid, a)> pid: Pid -> Bool { match entries { [] -> False, [(p, _), ..rest] -> p == pid || has_pid rest pid } } /// `list.partition`, with each element's index: the idle-timeout floor /// counts from the end of the list. `(closing, keeping)`. fn partition_indexed :: entries: List yes: List no: List close: fn(a, Int) -> Bool -> (List, List) { partition_from entries yes no 0 close } fn partition_from :: entries: List yes: List no: List i: Int close: fn(a, Int) -> Bool -> (List, List) { match entries { [] -> (list.reverse yes, list.reverse no) , [entry, ..rest] -> if close entry i { partition_from rest [entry, ..yes] no (i + 1) close } else { partition_from rest yes [entry, ..no] (i + 1) close } } } /// Watch every connection's owner. fn monitor_all :: conns: List> acc: List<(Pid, Subject)> -> List<(Pid, Subject)> / { match conns { [] -> acc , [conn, ..rest] -> monitor_all rest (watch (process.owner conn) acc) } }