Skip to main content

giong_postgres/
pool.rs

1//! A pool of connections for one worker thread.
2
3use std::cell::RefCell;
4use std::future::poll_fn;
5use std::ops::{Deref, DerefMut};
6use std::rc::Rc;
7use std::task::{Poll, Waker};
8use std::time::Duration;
9
10use giong::time::Instant;
11
12use crate::client::{Client, Transaction};
13use crate::config::Config;
14use crate::error::{Error, ErrorKind};
15use crate::row::Row;
16use crate::types::ToSql;
17
18/// How long a connection's oldest statement may have been running before
19/// shared statements avoid that connection.
20const STALLED: Duration = Duration::from_millis(5);
21
22/// Connections to one server, for the tasks of one worker thread.
23///
24/// Make one pool per worker, inside [`giong::Runtime::run`]: nothing is
25/// shared between threads, so nothing is locked.
26///
27/// ```no_run
28/// use giong_postgres::{Config, Pool};
29///
30/// fn main() -> std::io::Result<()> {
31///     let config = Config::from_url("postgres://app:secret@db.internal/shop")?;
32///     giong::Builder::new().build()?.run(move |_worker| {
33///         let pool = Pool::new(config.clone(), 4);
34///         async move {
35///             let row = pool.query_one("SELECT count(*) FROM orders", &[]).await.unwrap();
36///             let n: i64 = row.get(0).unwrap();
37///             println!("{n} orders");
38///         }
39///     })
40/// }
41/// ```
42///
43/// [`query`](Self::query) and the other statement methods do not take a
44/// connection for themselves: they run on the least busy connection, beside
45/// statements from other tasks (pipelining), and the pool opens another
46/// connection, up to its maximum, when every open one is busy. That is the
47/// fast path for statements that stand alone. On one connection the server
48/// answers in order, so a statement waits for those sent before it; the pool
49/// steers new statements away from a connection whose oldest statement has
50/// been running for more than 5 ms. Run statements known to be slow (reports,
51/// migrations) on a connection of their own, from [`get`](Self::get).
52///
53/// **How many connections.** Because statements pipeline, a few connections
54/// keep the server busy: start with the server's cores, shared among the
55/// workers' pools. More than that adds no throughput and raises tail latency,
56/// since a backend waiting for a core holds up every statement queued on its
57/// connection. Statements that wait on disk or on locks need more.
58///
59/// [`get`](Self::get) takes a connection for one task alone, for a
60/// transaction or for session settings. While it is out, no shared statement
61/// runs on it. It comes back when the [`PooledClient`] is dropped; if a
62/// transaction was left open, or a statement is still on its way, a
63/// `ROLLBACK` is queued first.
64///
65/// **Transactions never run on the shared connections**, since the
66/// statements of other tasks would run inside them. `query`, `query_one`,
67/// `query_opt` and `execute` refuse `BEGIN`, `COMMIT`, `ROLLBACK` and the
68/// other transaction statements before sending anything
69/// ([`ErrorKind::Statement`]). [`batch_execute`](Self::batch_execute) may
70/// carry a whole transaction (`BEGIN; ...; COMMIT`); if a batch leaves one
71/// open, its connection is closed, which rolls it back, and the batch and
72/// every statement sent on that connection after it fail with
73/// [`ErrorKind::Closed`].
74///
75/// Connections the server closed, or that broke, are left behind as soon as
76/// that is noticed, which is when it happens: each connection is read
77/// continuously.
78#[derive(Clone)]
79pub struct Pool {
80    inner: Rc<Inner>,
81}
82
83struct Inner {
84    config: Config,
85    max_size: usize,
86    wait_timeout: Duration,
87    state: Rc<RefCell<State>>,
88    /// The pool as `giong::observe` sees it; registered by a weak reference,
89    /// so it leaves snapshots when the pool is dropped.
90    _observed: Rc<Observed>,
91}
92
93/// Reports the pool's state in `giong::observe` snapshots (and so to
94/// giong-mcp).
95struct Observed {
96    name: String,
97    max_size: usize,
98    state: Rc<RefCell<State>>,
99}
100
101impl giong::observe::Source for Observed {
102    fn kind(&self) -> &'static str {
103        "postgres pool"
104    }
105
106    fn name(&self) -> String {
107        self.name.clone()
108    }
109
110    fn stats(&self) -> Vec<(&'static str, u64)> {
111        let s = stats_of(&self.state.borrow());
112        let n = |v: usize| v as u64;
113        vec![
114            ("max_size", n(self.max_size)),
115            ("connections", n(s.connections)),
116            ("taken", n(s.taken)),
117            ("connecting", n(s.connecting)),
118            ("in_flight", n(s.in_flight)),
119            ("waiting", n(s.waiting)),
120            ("opened", s.opened),
121            ("connect_errors", s.connect_errors),
122            ("timeouts", s.timeouts),
123        ]
124    }
125}
126
127fn stats_of(st: &State) -> PoolStats {
128    PoolStats {
129        connections: st.shared.len() + st.taken,
130        taken: st.taken,
131        connecting: st.connecting,
132        in_flight: st.shared.iter().map(|c| c.in_flight()).sum(),
133        waiting: st.waiting,
134        opened: st.opened,
135        connect_errors: st.connect_errors,
136        timeouts: st.timeouts,
137    }
138}
139
140#[derive(Default)]
141struct State {
142    /// Open connections that are not taken.
143    shared: Vec<Rc<Client>>,
144    taken: usize,
145    connecting: usize,
146    waiting: usize,
147    waiters: Vec<Waker>,
148    opened: u64,
149    connect_errors: u64,
150    timeouts: u64,
151}
152
153/// What a pool is doing, from [`Pool::stats`].
154#[derive(Clone, Copy, Debug, PartialEq, Eq)]
155#[non_exhaustive]
156pub struct PoolStats {
157    /// Open connections, taken or not.
158    pub connections: usize,
159    /// Connections taken with [`Pool::get`].
160    pub taken: usize,
161    /// Connections being opened.
162    pub connecting: usize,
163    /// Requests sent on the shared connections and not answered yet.
164    pub in_flight: usize,
165    /// Tasks waiting for a connection.
166    pub waiting: usize,
167    /// Connections opened since the pool was made.
168    pub opened: u64,
169    /// Attempts to open a connection that failed.
170    pub connect_errors: u64,
171    /// Waits that ended with [`ErrorKind::PoolTimeout`].
172    pub timeouts: u64,
173}
174
175enum Decision<T> {
176    Ready(T),
177    Connect,
178    Wait,
179}
180
181/// Undoes the `connecting` count however the attempt ends.
182struct Connecting<'a>(&'a Pool);
183
184impl Drop for Connecting<'_> {
185    fn drop(&mut self) {
186        self.0.inner.state.borrow_mut().connecting -= 1;
187        self.0.notify();
188    }
189}
190
191/// Undoes the `waiting` count however the wait ends.
192struct Waiting<'a>(&'a Pool);
193
194impl Drop for Waiting<'_> {
195    fn drop(&mut self) {
196        self.0.inner.state.borrow_mut().waiting -= 1;
197    }
198}
199
200impl Pool {
201    /// A pool of at most `max_size` connections to the server in `config`.
202    /// Connections are opened when needed, not here.
203    ///
204    /// Size it from the server's `max_connections`: the pools of all workers
205    /// of all processes together must stay below it.
206    ///
207    /// # Panics
208    ///
209    /// Panics if `max_size` is 0.
210    pub fn new(config: Config, max_size: usize) -> Self {
211        assert!(
212            max_size > 0,
213            "a pool needs room for at least one connection"
214        );
215        let state = Rc::new(RefCell::default());
216        let observed = Rc::new(Observed {
217            name: config.describe(),
218            max_size,
219            state: Rc::clone(&state),
220        });
221        giong::observe::register_rc(&observed);
222        Self {
223            inner: Rc::new(Inner {
224                config,
225                max_size,
226                wait_timeout: Duration::from_secs(5),
227                state,
228                _observed: observed,
229            }),
230        }
231    }
232
233    /// The longest a task waits for a connection when all `max_size` are
234    /// taken: 5 seconds by default. A longer wait fails with
235    /// [`ErrorKind::PoolTimeout`].
236    ///
237    /// # Panics
238    ///
239    /// Panics if other clones of this pool exist; set it right after
240    /// [`new`](Self::new).
241    pub fn wait_timeout(mut self, timeout: Duration) -> Self {
242        Rc::get_mut(&mut self.inner)
243            .expect("set the wait timeout before cloning the pool")
244            .wait_timeout = timeout;
245        self
246    }
247
248    /// Runs a statement on a shared connection and returns its rows; see
249    /// [`Client::query`]. Transaction statements are refused
250    /// ([`ErrorKind::Statement`]): run them on a connection from
251    /// [`get`](Self::get).
252    pub async fn query(&self, sql: &str, params: &[&dyn ToSql]) -> Result<Vec<Row>, Error> {
253        refuse_transaction(sql)?;
254        let client = self.shared().await?;
255        client.query(sql, params).await
256    }
257
258    /// Runs a statement that returns exactly one row; see
259    /// [`Client::query_one`]. Transaction statements are refused.
260    pub async fn query_one(&self, sql: &str, params: &[&dyn ToSql]) -> Result<Row, Error> {
261        refuse_transaction(sql)?;
262        let client = self.shared().await?;
263        client.query_one(sql, params).await
264    }
265
266    /// Runs a statement that returns at most one row; see
267    /// [`Client::query_opt`]. Transaction statements are refused.
268    pub async fn query_opt(&self, sql: &str, params: &[&dyn ToSql]) -> Result<Option<Row>, Error> {
269        refuse_transaction(sql)?;
270        let client = self.shared().await?;
271        client.query_opt(sql, params).await
272    }
273
274    /// Runs a statement and returns the number of rows it changed; see
275    /// [`Client::execute`]. Transaction statements are refused.
276    pub async fn execute(&self, sql: &str, params: &[&dyn ToSql]) -> Result<u64, Error> {
277        refuse_transaction(sql)?;
278        let client = self.shared().await?;
279        client.execute(sql, params).await
280    }
281
282    /// Runs several statements without parameters; see
283    /// [`Client::batch_execute`].
284    ///
285    /// The batch may hold a whole transaction, `BEGIN; ...; COMMIT`. If it
286    /// leaves one open, the connection is closed, which rolls the
287    /// transaction back, and the batch fails with [`ErrorKind::Closed`], as
288    /// do the statements other tasks sent on that connection after it: they
289    /// would otherwise have run inside the transaction.
290    pub async fn batch_execute(&self, sql: &str) -> Result<(), Error> {
291        let client = self.shared().await?;
292        client.batch_execute(sql).await
293    }
294
295    /// Takes a connection for this task alone, for a transaction or session
296    /// settings:
297    ///
298    /// ```no_run
299    /// # async fn f(pool: &giong_postgres::Pool) -> Result<(), giong_postgres::Error> {
300    /// let mut conn = pool.get().await?;
301    /// let tx = conn.transaction().await?;
302    /// tx.execute("INSERT INTO audit (what) VALUES ($1)", &[&"signup"]).await?;
303    /// tx.commit().await?;
304    /// # Ok(()) }
305    /// ```
306    ///
307    /// Waits up to the [wait timeout](Self::wait_timeout) when every
308    /// connection is taken or busy and the pool is full.
309    pub async fn get(&self) -> Result<PooledClient, Error> {
310        let client = self
311            .acquire(|st, max| {
312                let idle = st
313                    .shared
314                    .iter()
315                    .position(|c| Rc::strong_count(c) == 1 && c.in_flight() == 0);
316                if let Some(i) = idle {
317                    let c = st.shared.swap_remove(i);
318                    st.taken += 1;
319                    return match Rc::try_unwrap(c) {
320                        Ok(client) => {
321                            client.set_shared(false);
322                            Decision::Ready(client)
323                        }
324                        Err(_) => unreachable!("checked: nobody else holds it"),
325                    };
326                }
327                if st.shared.len() + st.taken + st.connecting < max {
328                    st.connecting += 1;
329                    Decision::Connect
330                } else {
331                    Decision::Wait
332                }
333            })
334            .await?;
335        let client = match client {
336            Ok(c) => c,
337            Err(new) => {
338                self.inner.state.borrow_mut().taken += 1;
339                new
340            }
341        };
342        Ok(PooledClient {
343            client: Some(client),
344            pool: self.clone(),
345        })
346    }
347
348    /// The pool's current state and counters.
349    pub fn stats(&self) -> PoolStats {
350        stats_of(&self.inner.state.borrow())
351    }
352
353    /// The least busy shared connection, or a new one if every open one is
354    /// busy and there is room.
355    ///
356    /// A connection whose oldest statement has been running for more than
357    /// [`STALLED`] is passed over while another will do: statements queue
358    /// behind it in order, so a slow one would hold up everything sent after
359    /// it on that connection.
360    async fn shared(&self) -> Result<Lent<'_>, Error> {
361        let client = self
362            .acquire(|st, max| {
363                let now = Instant::now();
364                let room = st.shared.len() + st.taken + st.connecting < max;
365                // Busy means used by other tasks right now.
366                let best = st
367                    .shared
368                    .iter()
369                    .filter(|c| c.waiting_for(now) <= STALLED)
370                    .min_by_key(|c| Rc::strong_count(c))
371                    .cloned();
372                match best {
373                    Some(c) if Rc::strong_count(&c) == 2 || !room => Decision::Ready(c),
374                    _ if room => {
375                        st.connecting += 1;
376                        Decision::Connect
377                    }
378                    // Every connection is stalled and the pool is full: the
379                    // one whose oldest statement has waited least, which is
380                    // the one most likely to be moving.
381                    _ => match st.shared.iter().min_by_key(|c| c.waiting_for(now)) {
382                        Some(c) => Decision::Ready(c.clone()),
383                        None => Decision::Wait,
384                    },
385                }
386            })
387            .await?;
388        let client = match client {
389            Ok(c) => c,
390            Err(new) => {
391                new.set_shared(true);
392                let c = Rc::new(new);
393                self.inner.state.borrow_mut().shared.push(c.clone());
394                c
395            }
396        };
397        Ok(Lent {
398            pool: self,
399            client: Some(client),
400        })
401    }
402
403    /// Wakes every task waiting for a connection, to look again.
404    fn notify(&self) {
405        let waiters = std::mem::take(&mut self.inner.state.borrow_mut().waiters);
406        for w in waiters {
407            w.wake();
408        }
409    }
410
411    /// Runs `decide` until it hands out a connection (`Ok`), or a new one is
412    /// opened for the caller (`Err(client)`), or the wait times out.
413    async fn acquire<T>(
414        &self,
415        mut decide: impl FnMut(&mut State, usize) -> Decision<T>,
416    ) -> Result<Result<T, Client>, Error> {
417        let deadline = Instant::now() + self.inner.wait_timeout;
418        loop {
419            let decision = {
420                let mut st = self.inner.state.borrow_mut();
421                st.shared.retain(|c| !c.is_closed());
422                decide(&mut st, self.inner.max_size)
423            };
424            match decision {
425                Decision::Ready(c) => return Ok(Ok(c)),
426                Decision::Connect => {
427                    let _connecting = Connecting(self);
428                    let result = Client::connect(&self.inner.config).await;
429                    let mut st = self.inner.state.borrow_mut();
430                    return match result {
431                        Ok(client) => {
432                            st.opened += 1;
433                            Ok(Err(client))
434                        }
435                        Err(e) => {
436                            st.connect_errors += 1;
437                            Err(e)
438                        }
439                    };
440                }
441                Decision::Wait => {
442                    self.inner.state.borrow_mut().waiting += 1;
443                    let _waiting = Waiting(self);
444                    let mut registered = false;
445                    let woken = poll_fn(|cx| {
446                        if registered {
447                            return Poll::Ready(());
448                        }
449                        registered = true;
450                        let mut st = self.inner.state.borrow_mut();
451                        st.waiters.push(cx.waker().clone());
452                        // A connection kept busy only by statements whose
453                        // tasks stopped waiting (a timeout dropped them) is
454                        // free once they are answered, which nothing else
455                        // would announce.
456                        for c in &st.shared {
457                            if Rc::strong_count(c) == 1 && c.in_flight() > 0 {
458                                c.wake_when_idle(cx.waker());
459                            }
460                        }
461                        Poll::Pending
462                    });
463                    let left = deadline.saturating_duration_since(Instant::now());
464                    if giong::time::timeout(left, woken).await.is_err() {
465                        let mut st = self.inner.state.borrow_mut();
466                        st.timeouts += 1;
467                        return Err(Error::new(
468                            ErrorKind::PoolTimeout,
469                            format!(
470                                "no connection to {} became free within {:?}: all {} are taken or \
471                                 busy. Raise the pool's max_size (the server's max_connections \
472                                 allowing), look for transactions held open too long, or raise \
473                                 Pool::wait_timeout",
474                                self.inner.config.target(),
475                                self.inner.wait_timeout,
476                                self.inner.max_size
477                            ),
478                        ));
479                    }
480                }
481            }
482        }
483    }
484}
485
486/// A shared connection lent to one statement. Dropping it, when the
487/// statement is answered or its future is dropped, tells waiting tasks to
488/// look again: the connection may have become free.
489struct Lent<'a> {
490    pool: &'a Pool,
491    client: Option<Rc<Client>>,
492}
493
494impl Deref for Lent<'_> {
495    type Target = Client;
496
497    fn deref(&self) -> &Client {
498        self.client.as_ref().expect("present until dropped")
499    }
500}
501
502impl Drop for Lent<'_> {
503    fn drop(&mut self) {
504        self.client = None;
505        self.pool.notify();
506    }
507}
508
509/// Refuses a statement that controls a transaction, which must not run on a
510/// connection that other tasks share.
511fn refuse_transaction(sql: &str) -> Result<(), Error> {
512    let words = leading_words(sql);
513    let word = |i: usize| words.get(i).map_or("", String::as_str);
514    let refused = match word(0) {
515        "BEGIN" | "START" | "END" | "ABORT" | "SAVEPOINT" | "RELEASE" => true,
516        // Two-phase commit's second phase may run on any connection.
517        "COMMIT" | "ROLLBACK" => word(1) != "PREPARED",
518        "PREPARE" => word(1) == "TRANSACTION",
519        _ => false,
520    };
521    if !refused {
522        return Ok(());
523    }
524    Err(Error::new(
525        ErrorKind::Statement,
526        format!(
527            "{} controls a transaction, and the pool's own methods run statements on \
528             connections that other tasks share, whose statements would run inside it; \
529             nothing was sent. Run the transaction on a connection of this task's own: \
530             let mut conn = pool.get().await?; let tx = conn.transaction().await?; ...; \
531             tx.commit().await?",
532            word(0)
533        ),
534    ))
535}
536
537/// The first two words of `sql`, upper-cased, after blanks and comments.
538fn leading_words(sql: &str) -> Vec<String> {
539    let b = sql.as_bytes();
540    let mut i = 0;
541    let mut words = Vec::new();
542    while words.len() < 2 && i < b.len() {
543        match b[i] {
544            c if c.is_ascii_whitespace() => i += 1,
545            b'-' if b.get(i + 1) == Some(&b'-') => {
546                while i < b.len() && b[i] != b'\n' {
547                    i += 1;
548                }
549            }
550            b'/' if b.get(i + 1) == Some(&b'*') => {
551                // PostgreSQL's block comments nest.
552                let mut depth = 0;
553                while i < b.len() {
554                    if b[i..].starts_with(b"/*") {
555                        depth += 1;
556                        i += 2;
557                    } else if b[i..].starts_with(b"*/") {
558                        depth -= 1;
559                        i += 2;
560                        if depth == 0 {
561                            break;
562                        }
563                    } else {
564                        i += 1;
565                    }
566                }
567            }
568            c if c.is_ascii_alphabetic() || c == b'_' => {
569                let start = i;
570                while i < b.len() && (b[i].is_ascii_alphanumeric() || b[i] == b'_') {
571                    i += 1;
572                }
573                words.push(sql[start..i].to_ascii_uppercase());
574            }
575            _ => break,
576        }
577    }
578    words
579}
580
581impl std::fmt::Debug for Pool {
582    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
583        f.debug_struct("Pool")
584            .field("server", &self.inner.config.target())
585            .field("max_size", &self.inner.max_size)
586            .field("stats", &self.stats())
587            .finish()
588    }
589}
590
591/// A connection taken from a [`Pool`] with [`Pool::get`]. It dereferences to
592/// the [`Client`], and goes back to the pool when dropped.
593pub struct PooledClient {
594    client: Option<Client>,
595    pool: Pool,
596}
597
598impl PooledClient {
599    /// Starts a transaction; see [`Client::transaction`].
600    pub async fn transaction(&mut self) -> Result<Transaction<'_>, Error> {
601        self.deref_mut().transaction().await
602    }
603}
604
605impl Deref for PooledClient {
606    type Target = Client;
607
608    fn deref(&self) -> &Client {
609        self.client.as_ref().expect("present until dropped")
610    }
611}
612
613impl DerefMut for PooledClient {
614    fn deref_mut(&mut self) -> &mut Client {
615        self.client.as_mut().expect("present until dropped")
616    }
617}
618
619impl Drop for PooledClient {
620    fn drop(&mut self) {
621        let client = self.client.take().expect("present until dropped");
622        {
623            let mut st = self.pool.inner.state.borrow_mut();
624            st.taken -= 1;
625            if !client.is_closed() {
626                // A statement still on its way (its future was dropped, by a
627                // timeout say) may be a BEGIN: the last answer cannot tell.
628                // Queued ahead of anything a shared statement sends next.
629                if client.in_flight() > 0 || client.in_transaction() {
630                    client.send_and_forget("ROLLBACK");
631                }
632                client.set_shared(true);
633                st.shared.push(Rc::new(client));
634            }
635        }
636        self.pool.notify();
637    }
638}
639
640impl std::fmt::Debug for PooledClient {
641    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
642        f.debug_tuple("PooledClient").field(&**self).finish()
643    }
644}