Skip to main content

giong_postgres/
pool.rs

1//! A pool of connections for one worker thread.
2
3use std::cell::{Cell, RefCell};
4use std::collections::VecDeque;
5use std::future::{poll_fn, Future};
6use std::ops::{Deref, DerefMut};
7use std::pin::pin;
8use std::rc::{Rc, Weak};
9use std::task::{Poll, Waker};
10use std::time::Duration;
11
12use giong::time::Instant;
13
14use crate::client::{Client, Transaction};
15use crate::config::Config;
16use crate::error::{Error, ErrorKind};
17use crate::row::Row;
18use crate::types::ToSql;
19
20/// How long a connection's oldest statement may have been running before
21/// shared statements avoid that connection.
22const STALLED: Duration = Duration::from_millis(5);
23
24/// The most statements the pool's statement methods keep on one connection
25/// at a time; past it they use another connection, or wait.
26const MAX_PIPELINE: usize = 1024;
27
28/// Connections to one server, for the tasks of one worker thread.
29///
30/// Make one pool per worker, inside [`giong::Runtime::run`]: nothing is
31/// shared between threads, so nothing is locked.
32///
33/// ```no_run
34/// use giong_postgres::{Config, Pool};
35///
36/// fn main() -> std::io::Result<()> {
37///     let config = Config::from_url("postgres://app:secret@db.internal/shop")?;
38///     giong::Builder::new().build()?.run(move |_worker| {
39///         let pool = Pool::new(config.clone(), 4);
40///         async move {
41///             let row = pool.query_one("SELECT count(*) FROM orders", &[]).await.unwrap();
42///             let n: i64 = row.get(0).unwrap();
43///             println!("{n} orders");
44///         }
45///     })
46/// }
47/// ```
48///
49/// [`query`](Self::query) and the other statement methods do not take a
50/// connection for themselves: they run on the least busy connection, beside
51/// statements from other tasks (pipelining), and the pool opens another
52/// connection, up to its maximum, when every open one is busy. That is the
53/// fast path for statements that stand alone. On one connection the server
54/// answers in order, so a statement waits for those sent before it; the pool
55/// steers new statements away from a connection whose oldest statement has
56/// been running for more than 5 ms. Run statements known to be slow (reports,
57/// migrations) on a connection of their own, from [`get`](Self::get). At most
58/// 1024 statements run on one connection at a time; past that, statements
59/// use another connection or wait for room.
60///
61/// **How many connections.** Because statements pipeline, a few connections
62/// keep the server busy: start with the server's cores, shared among the
63/// workers' pools. More than that adds no throughput and raises tail latency,
64/// since a backend waiting for a core holds up every statement queued on its
65/// connection. Statements that wait on disk or on locks need more.
66///
67/// [`get`](Self::get) takes a connection for one task alone: for a
68/// transaction, for session settings (`SET`, `SET ROLE`, temporary tables,
69/// advisory locks, `LISTEN`), or for a slow statement. While it is out, no
70/// shared statement runs on it. Tasks waiting in `get` are served in the
71/// order they came, and shared statements stop using a connection while a
72/// `get` waits for it, so `get` is served even when shared statements keep
73/// every connection busy; shared statements always keep at least one
74/// connection when the pool has room for two. The connection comes back when
75/// the [`PooledClient`] is dropped, and its session is reset before anything
76/// else runs on it: a transaction left open is rolled back, and if anything
77/// was sent on it, `SET SESSION AUTHORIZATION DEFAULT; RESET ALL; CLOSE ALL;
78/// UNLISTEN *; SELECT pg_advisory_unlock_all(); DISCARD TEMP; DISCARD
79/// SEQUENCES` follows (plus `DEALLOCATE ALL` after an SQL-level `PREPARE`).
80/// Settings given to [`Config`] survive the reset; settings made with `SET`
81/// do not. These requests are pipelined in front of the next statement, so
82/// nobody waits a round trip for them; if they fail, the connection is closed
83/// instead of reused.
84///
85/// **Transactions and session changes never run on the shared
86/// connections**, since the statements of other tasks would run inside them
87/// or under them. `query`, `query_one`, `query_opt` and `execute` refuse
88/// `BEGIN`, `COMMIT`, `ROLLBACK` and the other transaction statements, and
89/// all the statement methods refuse statements that change the session
90/// (`SET` without `LOCAL`, `RESET`, `DISCARD`, `LISTEN`, `UNLISTEN`,
91/// `PREPARE`, `DEALLOCATE`, `DECLARE`, `LOAD`, `CREATE TEMP ...`) and
92/// `COPY ... FROM STDIN`, before sending anything ([`ErrorKind::Statement`]).
93/// Functions that change the session (`set_config(.., false)`,
94/// `pg_advisory_lock`) cannot be recognised this way: call them on a
95/// connection from `get`. [`batch_execute`](Self::batch_execute) may carry a
96/// whole transaction (`BEGIN; ...; COMMIT`); if a batch leaves one open, its
97/// connection is closed, which rolls it back, and the batch and every
98/// statement sent on that connection after it fail with
99/// [`ErrorKind::Closed`].
100///
101/// Connections the server closed, or that broke, are left behind as soon as
102/// that is noticed, which is when it happens: each connection is read
103/// continuously. A connection unused for the [idle
104/// timeout](Self::idle_timeout) is closed, and so is one older than the
105/// [maximum lifetime](Self::max_lifetime) or whose server refused a write
106/// because it is a standby (after a failover), once no statement uses it.
107#[derive(Clone)]
108pub struct Pool {
109    inner: Rc<Inner>,
110}
111
112struct Inner {
113    config: Config,
114    max_size: usize,
115    wait_timeout: Duration,
116    idle_timeout: Duration,
117    max_lifetime: Duration,
118    state: Rc<RefCell<State>>,
119    /// The pool as `giong::observe` sees it; registered by a weak reference,
120    /// so it leaves snapshots when the pool is dropped.
121    _observed: Rc<Observed>,
122}
123
124impl Drop for Inner {
125    fn drop(&mut self) {
126        // The task that closes idle connections ends with the pool.
127        let reaper = {
128            let mut st = self.state.borrow_mut();
129            st.stopped = true;
130            st.reaper_waker.take()
131        };
132        if let Some(w) = reaper {
133            w.wake();
134        }
135    }
136}
137
138/// Reports the pool's state in `giong::observe` snapshots (and so to
139/// giong-mcp).
140struct Observed {
141    name: String,
142    max_size: usize,
143    state: Rc<RefCell<State>>,
144}
145
146impl giong::observe::Source for Observed {
147    fn kind(&self) -> &'static str {
148        "postgres pool"
149    }
150
151    fn name(&self) -> String {
152        self.name.clone()
153    }
154
155    fn stats(&self) -> Vec<(&'static str, u64)> {
156        let s = stats_of(&self.state.borrow());
157        let n = |v: usize| v as u64;
158        vec![
159            ("max_size", n(self.max_size)),
160            ("connections", n(s.connections)),
161            ("taken", n(s.taken)),
162            ("connecting", n(s.connecting)),
163            ("in_flight", n(s.in_flight)),
164            ("waiting", n(s.waiting)),
165            ("opened", s.opened),
166            ("connect_errors", s.connect_errors),
167            ("timeouts", s.timeouts),
168            ("recycled", s.recycled),
169        ]
170    }
171}
172
173fn stats_of(st: &State) -> PoolStats {
174    PoolStats {
175        connections: st.shared.len() + st.taken,
176        taken: st.taken,
177        connecting: st.connecting,
178        in_flight: st.shared.iter().map(|m| m.client.in_flight()).sum(),
179        waiting: st.waiting,
180        opened: st.opened,
181        connect_errors: st.connect_errors,
182        timeouts: st.timeouts,
183        recycled: st.recycled,
184    }
185}
186
187#[derive(Default)]
188struct State {
189    /// Open connections that are not taken.
190    shared: Vec<Member>,
191    taken: usize,
192    connecting: usize,
193    waiting: usize,
194    /// Tasks of the statement methods waiting for room, woken one at a time:
195    /// a statement that finishes frees room for one more.
196    shared_waiters: VecDeque<Waker>,
197    /// Tasks waiting in `get`, all woken when a connection may have become
198    /// free (there are few of them).
199    get_waiters: Vec<Waker>,
200    /// The tickets of the `get` calls waiting, oldest first: only the oldest
201    /// may take a connection.
202    queue: VecDeque<u64>,
203    next_ticket: u64,
204    /// Wakers to wake once the state is no longer borrowed.
205    to_wake: Vec<Waker>,
206    /// The task that closes idle and old connections is running.
207    reaper: bool,
208    reaper_waker: Option<Waker>,
209    /// The pool was dropped.
210    stopped: bool,
211    /// The last attempt to open a connection failed, and none has opened
212    /// since: the error. Meanwhile one attempt runs at a time, and the tasks
213    /// that waited through it get its error.
214    failing: Option<Error>,
215    /// Attempts to open a connection that failed in a row.
216    failures_in_row: u32,
217    /// While opening connections fails and none is open, calls fail at once
218    /// with `failing` until then, rather than try again (see
219    /// [`connect_backoff`]).
220    retry_at: Option<Instant>,
221    opened: u64,
222    /// Attempts to open a connection that failed.
223    connect_errors: u64,
224    timeouts: u64,
225    recycled: u64,
226}
227
228/// A connection among the shared ones.
229struct Member {
230    client: Rc<Client>,
231    /// Kept free for a task waiting in `get`: shared statements do not use it.
232    draining: bool,
233    /// When it was last lent or came back.
234    used: Instant,
235    /// When it is to be closed, however busy it is.
236    expires: Instant,
237}
238
239impl Member {
240    /// No statement method is using it: nobody else holds it.
241    fn is_free(&self) -> bool {
242        Rc::strong_count(&self.client) == 1
243    }
244
245    /// To be closed once free: too old, or its server is a standby.
246    fn is_retiring(&self, now: Instant) -> bool {
247        now >= self.expires || self.client.should_retire()
248    }
249}
250
251/// How long calls fail at once after `failures` attempts to open a
252/// connection failed in a row with none open: 10 ms doubling to 1 s, less a
253/// random part of up to half, so that the pools of many workers and
254/// processes do not try again together.
255fn connect_backoff(failures: u32) -> Duration {
256    use std::hash::{BuildHasher, Hasher};
257    let full = Duration::from_millis(10)
258        .saturating_mul(1 << failures.saturating_sub(1).min(7))
259        .min(Duration::from_secs(1));
260    // Not for secrets: only spreads the attempts. The standard library
261    // seeds each RandomState differently.
262    let seed = std::collections::hash_map::RandomState::new()
263        .build_hasher()
264        .finish();
265    full - (full / 2).mul_f64((seed % 1024) as f64 / 1024.0)
266}
267
268impl State {
269    /// Room for one more connection: below the maximum, and, while opening
270    /// connections fails, no attempt under way.
271    fn room(&self, max: usize) -> bool {
272        self.shared.len() + self.taken + self.connecting < max
273            && (self.failing.is_none() || self.connecting == 0)
274    }
275
276    /// Wakes every waiting task (later, see `to_wake`), to look again.
277    fn wake_all(&mut self) {
278        let shared = std::mem::take(&mut self.shared_waiters);
279        self.to_wake.extend(shared);
280        self.to_wake.append(&mut self.get_waiters);
281    }
282
283    /// Wakes the tasks waiting in `get`.
284    fn wake_gets(&mut self) {
285        let gets = std::mem::take(&mut self.get_waiters);
286        self.to_wake.extend(gets);
287    }
288
289    /// Wakes one task of the statement methods.
290    fn wake_one_shared(&mut self) {
291        if let Some(w) = self.shared_waiters.pop_front() {
292            self.to_wake.push(w);
293        }
294    }
295
296    /// Closes the shared connections that broke, and the free ones that are
297    /// idle, too old, or on a standby.
298    fn sweep(&mut self, now: Instant, idle_timeout: Duration) {
299        let before = self.shared.len();
300        let mut recycled = 0;
301        self.shared.retain(|m| {
302            if m.client.is_closed() {
303                return false;
304            }
305            let stale = m.is_free()
306                && (m.is_retiring(now)
307                    || (m.client.in_flight() == 0
308                        && now.saturating_duration_since(m.used) >= idle_timeout));
309            recycled += u64::from(stale);
310            !stale
311        });
312        self.recycled += recycled;
313        if self.shared.len() != before {
314            // Room for a new connection, or fewer to drain.
315            self.wake_all();
316        }
317    }
318
319    /// Marks as many shared connections draining as tasks wait in `get`,
320    /// leaving at least one to the statement methods when the pool has room
321    /// for two.
322    fn rebalance(&mut self, max: usize) {
323        let target = match self.queue.len() {
324            0 => 0,
325            n if max == 1 => n.min(self.shared.len()),
326            n => n.min(self.shared.len().saturating_sub(1)),
327        };
328        let mut draining = self.shared.iter().filter(|m| m.draining).count();
329        while draining < target {
330            // The least used one, so that it drains soonest.
331            let next = self
332                .shared
333                .iter_mut()
334                .filter(|m| !m.draining)
335                .min_by_key(|m| (Rc::strong_count(&m.client), m.client.in_flight()));
336            let Some(m) = next else { break };
337            m.draining = true;
338            draining += 1;
339        }
340        if draining > target {
341            for m in self.shared.iter_mut().filter(|m| m.draining) {
342                if draining == target {
343                    break;
344                }
345                m.draining = false;
346                draining -= 1;
347            }
348            self.wake_all();
349        }
350    }
351
352    fn remove_ticket(&mut self, ticket: u64) {
353        if let Some(i) = self.queue.iter().position(|&t| t == ticket) {
354            self.queue.remove(i);
355        }
356    }
357}
358
359/// What a pool is doing, from [`Pool::stats`].
360#[derive(Clone, Copy, Debug, PartialEq, Eq)]
361#[non_exhaustive]
362pub struct PoolStats {
363    /// Open connections, taken or not.
364    pub connections: usize,
365    /// Connections taken with [`Pool::get`].
366    pub taken: usize,
367    /// Connections being opened.
368    pub connecting: usize,
369    /// Requests sent on the shared connections and not answered yet.
370    pub in_flight: usize,
371    /// Tasks waiting for a connection.
372    pub waiting: usize,
373    /// Connections opened since the pool was made.
374    pub opened: u64,
375    /// Attempts to open a connection that failed.
376    pub connect_errors: u64,
377    /// Waits that ended with [`ErrorKind::PoolTimeout`].
378    pub timeouts: u64,
379    /// Connections the pool closed although they worked: idle longer than
380    /// the [idle timeout](Pool::idle_timeout), older than the [maximum
381    /// lifetime](Pool::max_lifetime), or on a server that turned out to be a
382    /// standby.
383    pub recycled: u64,
384}
385
386enum Decision<T> {
387    Ready(T),
388    Connect,
389    Wait,
390}
391
392/// Which list a waiting task is in.
393#[derive(Clone, Copy, PartialEq, Eq)]
394enum Waiter {
395    Shared,
396    Get,
397}
398
399/// Undoes the `connecting` count however the attempt ends.
400struct Connecting<'a>(&'a Pool);
401
402impl Drop for Connecting<'_> {
403    fn drop(&mut self) {
404        let mut st = self.0.inner.state.borrow_mut();
405        st.connecting -= 1;
406        st.wake_all();
407        drop(st);
408        self.0.flush_wakes();
409    }
410}
411
412/// Counts a task as waiting from its first wait until it gets a connection
413/// or gives up. A task of the statement methods that gives up passes its
414/// turn on: it may have been woken for room it will not use.
415struct Waiting<'a> {
416    pool: &'a Pool,
417    kind: Waiter,
418    served: bool,
419}
420
421impl Drop for Waiting<'_> {
422    fn drop(&mut self) {
423        let mut st = self.pool.inner.state.borrow_mut();
424        st.waiting -= 1;
425        if !self.served && self.kind == Waiter::Shared {
426            st.wake_one_shared();
427        }
428        drop(st);
429        self.pool.flush_wakes();
430    }
431}
432
433/// A `get` call's place in the queue, given up however the call ends.
434struct Ticket<'a> {
435    pool: &'a Pool,
436    id: Cell<Option<u64>>,
437}
438
439impl Drop for Ticket<'_> {
440    fn drop(&mut self) {
441        if let Some(id) = self.id.take() {
442            let mut st = self.pool.inner.state.borrow_mut();
443            st.remove_ticket(id);
444            st.rebalance(self.pool.inner.max_size);
445            // The next one in the queue may go now.
446            st.wake_gets();
447            drop(st);
448            self.pool.flush_wakes();
449        }
450    }
451}
452
453impl Pool {
454    /// A pool of at most `max_size` connections to the server in `config`.
455    /// Connections are opened when needed, not here.
456    ///
457    /// When opening one fails, the pool opens one at a time until one
458    /// succeeds, and tasks that waited through a failed attempt, with no
459    /// connection open to wait for, get its error at once: while the server
460    /// is down, a burst of calls makes one attempt, not one each. With no
461    /// connection open, calls after a failed attempt also get its error at
462    /// once for a pause that starts at 10 ms and doubles with each failure
463    /// in a row up to 1 s (less a random part of up to half, so that many
464    /// pools do not try together); the first call after the pause tries
465    /// again, and the first success ends it.
466    ///
467    /// Size it from the server's `max_connections`: the pools of all workers
468    /// of all processes together must stay below it.
469    ///
470    /// # Panics
471    ///
472    /// Panics if `max_size` is 0.
473    pub fn new(config: Config, max_size: usize) -> Self {
474        assert!(
475            max_size > 0,
476            "a pool needs room for at least one connection"
477        );
478        let state = Rc::new(RefCell::default());
479        let observed = Rc::new(Observed {
480            name: config.describe(),
481            max_size,
482            state: Rc::clone(&state),
483        });
484        let source: Weak<dyn giong::observe::Source> = Rc::downgrade(&observed) as _;
485        giong::observe::register(source);
486        Self {
487            inner: Rc::new(Inner {
488                config,
489                max_size,
490                wait_timeout: Duration::from_secs(5),
491                idle_timeout: Duration::from_secs(10 * 60),
492                max_lifetime: Duration::from_secs(30 * 60),
493                state,
494                _observed: observed,
495            }),
496        }
497    }
498
499    fn settings(&mut self, what: &str) -> &mut Inner {
500        Rc::get_mut(&mut self.inner)
501            .unwrap_or_else(|| panic!("set the {what} before cloning the pool"))
502    }
503
504    /// The longest a task waits for a connection when all `max_size` are
505    /// taken or busy: 5 seconds by default. A longer wait fails with
506    /// [`ErrorKind::PoolTimeout`]. A task that opens a new connection waits
507    /// for it up to [`Config::connect_timeout`] instead.
508    ///
509    /// A wait longer than a century (`Duration::MAX`) counts as a
510    /// century: no limit.
511    ///
512    /// # Panics
513    ///
514    /// Panics if other clones of this pool exist; set it right after
515    /// [`new`](Self::new).
516    pub fn wait_timeout(mut self, timeout: Duration) -> Self {
517        self.settings("wait timeout").wait_timeout =
518            timeout.min(Duration::from_secs(100 * 365 * 24 * 3600));
519        self
520    }
521
522    /// How long a connection may sit unused before the pool closes it: 10
523    /// minutes by default. The pool opens connections again when it needs
524    /// them, so a burst does not hold the server's connections forever.
525    ///
526    /// # Panics
527    ///
528    /// Panics if other clones of this pool exist; set it right after
529    /// [`new`](Self::new).
530    pub fn idle_timeout(mut self, timeout: Duration) -> Self {
531        self.settings("idle timeout").idle_timeout = timeout;
532        self
533    }
534
535    /// How long a connection may live: 30 minutes by default, less up to a
536    /// tenth at random so that the connections of a pool do not all close at
537    /// once. An older connection is closed as soon as no statement uses it,
538    /// and replaced when needed, so that connections follow DNS changes and
539    /// failovers, and the server's per-connection memory is given back.
540    ///
541    /// # Panics
542    ///
543    /// Panics if other clones of this pool exist; set it right after
544    /// [`new`](Self::new).
545    pub fn max_lifetime(mut self, lifetime: Duration) -> Self {
546        self.settings("maximum lifetime").max_lifetime = lifetime;
547        self
548    }
549
550    /// Runs a statement on a shared connection and returns its rows; see
551    /// [`Client::query`]. Statements that control a transaction or change
552    /// the session are refused ([`ErrorKind::Statement`]): run them on a
553    /// connection from [`get`](Self::get).
554    ///
555    /// Not cancel safe: if the future is dropped, the statement may still run
556    /// on the server, and what it changes stays; the pool and its connections
557    /// stay usable.
558    pub async fn query(&self, sql: &str, params: &[&dyn ToSql]) -> Result<Vec<Row>, Error> {
559        refuse_on_shared(sql, false)?;
560        let client = self.shared().await?;
561        let batch = self.inner.config.batch_reads && is_select(sql);
562        client.query_shared(sql, params, batch).await
563    }
564
565    /// Runs a statement that returns exactly one row; see
566    /// [`Client::query_one`]. Refuses the statements [`query`](Self::query)
567    /// refuses.
568    ///
569    /// Not cancel safe, like [`query`](Self::query).
570    pub async fn query_one(&self, sql: &str, params: &[&dyn ToSql]) -> Result<Row, Error> {
571        refuse_on_shared(sql, false)?;
572        let client = self.shared().await?;
573        let batch = self.inner.config.batch_reads && is_select(sql);
574        crate::client::one_row(client.query_shared(sql, params, batch).await?)
575    }
576
577    /// Runs a statement that returns at most one row; see
578    /// [`Client::query_opt`]. Refuses the statements [`query`](Self::query)
579    /// refuses.
580    ///
581    /// Not cancel safe, like [`query`](Self::query).
582    pub async fn query_opt(&self, sql: &str, params: &[&dyn ToSql]) -> Result<Option<Row>, Error> {
583        refuse_on_shared(sql, false)?;
584        let client = self.shared().await?;
585        let batch = self.inner.config.batch_reads && is_select(sql);
586        crate::client::at_most_one_row(client.query_shared(sql, params, batch).await?)
587    }
588
589    /// Runs a statement and returns the number of rows it changed; see
590    /// [`Client::execute`]. Refuses the statements [`query`](Self::query)
591    /// refuses.
592    ///
593    /// Not cancel safe, like [`query`](Self::query).
594    pub async fn execute(&self, sql: &str, params: &[&dyn ToSql]) -> Result<u64, Error> {
595        refuse_on_shared(sql, false)?;
596        let client = self.shared().await?;
597        client.execute(sql, params).await
598    }
599
600    /// Runs several statements without parameters; see
601    /// [`Client::batch_execute`].
602    ///
603    /// The batch may hold a whole transaction, `BEGIN; ...; COMMIT`. If it
604    /// leaves one open, the connection is closed, which rolls the
605    /// transaction back, and the batch fails with [`ErrorKind::Closed`], as
606    /// do the statements other tasks sent on that connection after it: they
607    /// would otherwise have run inside the transaction. Statements that
608    /// change the session (`SET` without `LOCAL`, `LISTEN`,
609    /// `COPY ... FROM STDIN` and the others listed on [`Pool`]) are refused
610    /// before anything is sent ([`ErrorKind::Statement`]).
611    ///
612    /// Not cancel safe, like [`query`](Self::query).
613    pub async fn batch_execute(&self, sql: &str) -> Result<(), Error> {
614        refuse_on_shared(sql, true)?;
615        let client = self.shared().await?;
616        client.batch_execute(sql).await
617    }
618
619    /// Takes a connection for this task alone, for a transaction, session
620    /// settings or a slow statement:
621    ///
622    /// ```no_run
623    /// # async fn f(pool: &giong_postgres::Pool) -> Result<(), giong_postgres::Error> {
624    /// let mut conn = pool.get().await?;
625    /// let tx = conn.transaction().await?;
626    /// tx.execute("INSERT INTO audit (what) VALUES ($1)", &[&"signup"]).await?;
627    /// tx.commit().await?;
628    /// # Ok(()) }
629    /// ```
630    ///
631    /// Waits up to the [wait timeout](Self::wait_timeout) when every
632    /// connection is taken or busy and the pool is full. Tasks waiting here
633    /// are served in the order they came. The session is reset when the
634    /// connection comes back (see [`Pool`]).
635    ///
636    /// Cancel safe: if the future is dropped, no connection is taken, and the
637    /// place in line goes to the next task.
638    pub async fn get(&self) -> Result<PooledClient, Error> {
639        let ticket = Ticket {
640            pool: self,
641            id: Cell::new(None),
642        };
643        let max = self.inner.max_size;
644        let taken = self
645            .acquire(Waiter::Get, |st, now| {
646                let mine = ticket.id.get();
647                let turn = st.queue.front().map_or(true, |&t| Some(t) == mine);
648                if turn {
649                    // A connection nobody else holds, busy at most with
650                    // requests whose tasks stopped waiting (and only
651                    // briefly), draining ones first.
652                    let free = st
653                        .shared
654                        .iter()
655                        .enumerate()
656                        .filter(|(_, m)| {
657                            m.is_free()
658                                && !m.is_retiring(now)
659                                && (m.client.in_flight() == 0
660                                    || m.client.waiting_for(now) <= STALLED)
661                        })
662                        .min_by_key(|(_, m)| (m.client.in_flight() > 0, !m.draining))
663                        .map(|(i, _)| i);
664                    let decision = if let Some(i) = free {
665                        let m = st.shared.swap_remove(i);
666                        st.taken += 1;
667                        let Ok(client) = Rc::try_unwrap(m.client) else {
668                            unreachable!("checked: nobody else holds it")
669                        };
670                        Some(Decision::Ready((client, m.expires)))
671                    } else if st.room(max) {
672                        st.connecting += 1;
673                        Some(Decision::Connect)
674                    } else {
675                        None
676                    };
677                    if let Some(decision) = decision {
678                        if let Some(id) = ticket.id.take() {
679                            st.remove_ticket(id);
680                        }
681                        st.rebalance(max);
682                        // The next in the queue may find a connection too.
683                        st.wake_gets();
684                        return decision;
685                    }
686                }
687                if mine.is_none() {
688                    let id = st.next_ticket;
689                    st.next_ticket += 1;
690                    st.queue.push_back(id);
691                    ticket.id.set(Some(id));
692                }
693                st.rebalance(max);
694                Decision::Wait
695            })
696            .await?;
697        let (client, expires) = match taken {
698            Ok(taken) => taken,
699            Err(new) => {
700                self.inner.state.borrow_mut().taken += 1;
701                (new, self.expiry())
702            }
703        };
704        client.set_shared(false);
705        client.begin_lease();
706        Ok(PooledClient {
707            requests: client.requests(),
708            client: Some(client),
709            expires,
710            pool: self.clone(),
711        })
712    }
713
714    /// The pool's current state and counters.
715    pub fn stats(&self) -> PoolStats {
716        stats_of(&self.inner.state.borrow())
717    }
718
719    /// When a connection opened now is to be closed: the maximum lifetime,
720    /// less up to a tenth of it.
721    fn expiry(&self) -> Instant {
722        use std::hash::{BuildHasher, Hasher};
723        let life = self.inner.max_lifetime;
724        // Not for secrets: only spreads the closing times. The standard
725        // library seeds each RandomState differently.
726        let seed = std::collections::hash_map::RandomState::new()
727            .build_hasher()
728            .finish();
729        let jitter = life / 10_000 * u32::try_from(seed % 1000).unwrap_or(0);
730        // A lifetime too long for the clock (`Duration::MAX`) means none.
731        Instant::now()
732            .checked_add(life - jitter)
733            .unwrap_or_else(|| Instant::now() + Duration::from_secs(100 * 365 * 24 * 3600))
734    }
735
736    /// The least busy shared connection, or a new one if every open one is
737    /// busy and there is room.
738    ///
739    /// A connection whose oldest statement has been running for more than
740    /// [`STALLED`] is passed over while another will do: statements queue
741    /// behind it in order, so a slow one would hold up everything sent after
742    /// it on that connection. Connections kept for a task waiting in `get`
743    /// and connections about to be closed are not used.
744    async fn shared(&self) -> Result<Lent<'_>, Error> {
745        let max = self.inner.max_size;
746        let client = self
747            .acquire(Waiter::Shared, |st, now| {
748                let room = st.room(max);
749                // The tasks holding the connection count, not only the
750                // requests sent: tasks waiting for a statement to be
751                // prepared have sent nothing yet. Abandoned requests count
752                // too, though nobody holds them.
753                let usable = |m: &Member| {
754                    let users = Rc::strong_count(&m.client) - 1;
755                    !m.draining
756                        && !m.is_retiring(now)
757                        && users.max(m.client.in_flight()) < MAX_PIPELINE
758                };
759                // Busy means used by other tasks right now.
760                let best = st
761                    .shared
762                    .iter()
763                    .enumerate()
764                    .filter(|(_, m)| usable(m) && m.client.waiting_for(now) <= STALLED)
765                    .min_by_key(|(_, m)| Rc::strong_count(&m.client))
766                    .map(|(i, m)| (i, m.is_free()));
767                let pick = match best {
768                    Some((i, free)) if free || !room => Some(i),
769                    _ if room => {
770                        st.connecting += 1;
771                        return Decision::Connect;
772                    }
773                    // Every usable connection is stalled and the pool is
774                    // full: the one whose oldest statement has waited least,
775                    // which is the one most likely to be moving.
776                    _ => st
777                        .shared
778                        .iter()
779                        .enumerate()
780                        .filter(|(_, m)| usable(m))
781                        .min_by_key(|(_, m)| m.client.waiting_for(now))
782                        .map(|(i, _)| i),
783                };
784                match pick {
785                    Some(i) => {
786                        let m = &mut st.shared[i];
787                        m.used = now;
788                        Decision::Ready(m.client.clone())
789                    }
790                    None => Decision::Wait,
791                }
792            })
793            .await?;
794        let client = match client {
795            Ok(c) => c,
796            Err(new) => {
797                new.set_shared(true);
798                let c = Rc::new(new);
799                let member = Member {
800                    client: c.clone(),
801                    draining: false,
802                    used: Instant::now(),
803                    expires: self.expiry(),
804                };
805                let mut st = self.inner.state.borrow_mut();
806                st.shared.push(member);
807                // Room for other waiting statements too.
808                st.wake_all();
809                drop(st);
810                self.flush_wakes();
811                c
812            }
813        };
814        Ok(Lent {
815            pool: self,
816            client: Some(client),
817        })
818    }
819
820    /// Wakes the tasks the state says to wake. Called with the state not
821    /// borrowed.
822    fn flush_wakes(&self) {
823        let wakers = std::mem::take(&mut self.inner.state.borrow_mut().to_wake);
824        for w in wakers {
825            w.wake();
826        }
827    }
828
829    /// Starts the task that closes idle and old connections, once.
830    fn start_reaper(&self, st: &mut State) {
831        if st.reaper {
832            return;
833        }
834        st.reaper = true;
835        let state = Rc::downgrade(&self.inner.state);
836        let idle_timeout = self.inner.idle_timeout;
837        let period = (self.inner.idle_timeout.min(self.inner.max_lifetime) / 4)
838            .clamp(Duration::from_millis(50), Duration::from_secs(30));
839        giong::spawn(reap(state, idle_timeout, period));
840    }
841
842    /// Runs `decide` until it hands out a connection (`Ok`), or a new one is
843    /// opened for the caller (`Err(client)`), or the wait times out.
844    async fn acquire<T>(
845        &self,
846        kind: Waiter,
847        mut decide: impl FnMut(&mut State, Instant) -> Decision<T>,
848    ) -> Result<Result<T, Client>, Error> {
849        let _wait = giong::observe::wait(giong::observe::Wait::Pool, "postgres");
850        let deadline = Instant::now() + self.inner.wait_timeout;
851        let mut waiting: Option<Waiting<'_>> = None;
852        // Failed attempts to open a connection so far: when one fails while
853        // this task waits, and the pool has no connection open to wait for,
854        // the task fails with its error rather than try again at once.
855        let failed_before = self.inner.state.borrow().connect_errors;
856        loop {
857            let decision = {
858                let mut st = self.inner.state.borrow_mut();
859                let none_open = st.shared.is_empty() && st.taken == 0;
860                if waiting.is_some() && none_open && st.connect_errors != failed_before {
861                    if let Some(e) = st.failing.clone() {
862                        drop(st);
863                        return Err(e);
864                    }
865                }
866                if none_open && st.connecting == 0 {
867                    if let (Some(e), Some(at)) = (&st.failing, st.retry_at) {
868                        if Instant::now() < at {
869                            let e = e.clone();
870                            drop(st);
871                            return Err(e);
872                        }
873                    }
874                }
875                let now = Instant::now();
876                st.sweep(now, self.inner.idle_timeout);
877                let d = decide(&mut st, now);
878                if matches!(d, Decision::Wait) && waiting.is_none() {
879                    st.waiting += 1;
880                }
881                d
882            };
883            self.flush_wakes();
884            match decision {
885                Decision::Ready(c) => {
886                    if let Some(w) = &mut waiting {
887                        w.served = true;
888                    }
889                    return Ok(Ok(c));
890                }
891                Decision::Connect => {
892                    if let Some(w) = &mut waiting {
893                        w.served = true;
894                    }
895                    drop(waiting);
896                    let _connecting = Connecting(self);
897                    let result = Client::connect(&self.inner.config).await;
898                    let mut st = self.inner.state.borrow_mut();
899                    return match result {
900                        Ok(client) => {
901                            st.opened += 1;
902                            st.failing = None;
903                            st.failures_in_row = 0;
904                            st.retry_at = None;
905                            self.start_reaper(&mut st);
906                            Ok(Err(client))
907                        }
908                        Err(e) => {
909                            st.connect_errors += 1;
910                            st.failing = Some(e.clone());
911                            st.failures_in_row = st.failures_in_row.saturating_add(1);
912                            st.retry_at =
913                                Some(Instant::now() + connect_backoff(st.failures_in_row));
914                            Err(e)
915                        }
916                    };
917                }
918                Decision::Wait => {
919                    if waiting.is_none() {
920                        waiting = Some(Waiting {
921                            pool: self,
922                            kind,
923                            served: false,
924                        });
925                    }
926                    let mut registered = false;
927                    let woken = poll_fn(|cx| {
928                        if registered {
929                            return Poll::Ready(());
930                        }
931                        registered = true;
932                        let mut st = self.inner.state.borrow_mut();
933                        match kind {
934                            Waiter::Shared => st.shared_waiters.push_back(cx.waker().clone()),
935                            Waiter::Get => st.get_waiters.push(cx.waker().clone()),
936                        }
937                        // A connection kept busy only by requests whose tasks
938                        // stopped waiting (a timeout dropped them) frees up
939                        // once they are answered, which nothing else would
940                        // announce.
941                        for m in &st.shared {
942                            if m.is_free() && m.client.in_flight() > 0 {
943                                m.client.wake_when_idle(cx.waker());
944                            }
945                        }
946                        Poll::Pending
947                    });
948                    let left = deadline.saturating_duration_since(Instant::now());
949                    if giong::time::timeout(left, woken).await.is_err() {
950                        let mut st = self.inner.state.borrow_mut();
951                        st.timeouts += 1;
952                        let (taken, max) = (st.taken, self.inner.max_size);
953                        drop(st);
954                        let why = if taken == max {
955                            format!("all {max} are taken with Pool::get")
956                        } else {
957                            format!("all {max} are taken or busy ({taken} taken with Pool::get)")
958                        };
959                        return Err(Error::new(
960                            ErrorKind::PoolTimeout,
961                            format!(
962                                "no connection to {} became free within {:?}: {why}. Raise the \
963                                 pool's max_size (the server's max_connections allowing), look \
964                                 for transactions or connections from Pool::get held too long, \
965                                 or raise Pool::wait_timeout",
966                                self.inner.config.target(),
967                                self.inner.wait_timeout,
968                            ),
969                        ));
970                    }
971                }
972            }
973        }
974    }
975}
976
977/// Closes idle and old connections now and then, until the pool is dropped.
978async fn reap(state: Weak<RefCell<State>>, idle_timeout: Duration, period: Duration) {
979    loop {
980        let mut sleep = pin!(giong::time::sleep(period));
981        let stopped = poll_fn(|cx| {
982            let Some(state) = state.upgrade() else {
983                return Poll::Ready(true);
984            };
985            let mut st = state.borrow_mut();
986            if st.stopped {
987                return Poll::Ready(true);
988            }
989            st.reaper_waker = Some(cx.waker().clone());
990            drop(st);
991            sleep.as_mut().poll(cx).map(|()| false)
992        })
993        .await;
994        if stopped {
995            return;
996        }
997        let Some(state) = state.upgrade() else { return };
998        let wakers = {
999            let mut st = state.borrow_mut();
1000            st.sweep(Instant::now(), idle_timeout);
1001            std::mem::take(&mut st.to_wake)
1002        };
1003        for w in wakers {
1004            w.wake();
1005        }
1006    }
1007}
1008
1009/// A shared connection lent to one statement. Dropping it, when the
1010/// statement is answered or its future is dropped, tells waiting tasks to
1011/// look again: there is room for one more statement, and the connection may
1012/// have become free.
1013struct Lent<'a> {
1014    pool: &'a Pool,
1015    client: Option<Rc<Client>>,
1016}
1017
1018impl Deref for Lent<'_> {
1019    type Target = Client;
1020
1021    fn deref(&self) -> &Client {
1022        self.client.as_ref().expect("present until dropped")
1023    }
1024}
1025
1026impl Drop for Lent<'_> {
1027    fn drop(&mut self) {
1028        let client = self.client.take().expect("present until dropped");
1029        // The pool's reference and this one.
1030        let free = Rc::strong_count(&client) == 2;
1031        drop(client);
1032        let mut st = self.pool.inner.state.borrow_mut();
1033        st.wake_one_shared();
1034        if free {
1035            if st
1036                .shared
1037                .iter()
1038                .any(|m| m.is_free() && m.client.should_retire())
1039            {
1040                st.sweep(Instant::now(), self.pool.inner.idle_timeout);
1041            }
1042            st.wake_gets();
1043        }
1044        drop(st);
1045        self.pool.flush_wakes();
1046    }
1047}
1048
1049/// Whether `sql` starts with the word `SELECT`, the statements a batch may
1050/// take ([`Config::batch_reads`]), and does not contain `set_config`: a
1051/// transaction-local setting made that way (`set_config(..., true)`, as
1052/// row-level security policies read) would reach the rest of its batch.
1053/// Matched anywhere in the text, quoted or commented too, since a false
1054/// match only runs a statement alone. A call hidden inside a function is
1055/// not seen; [`Config::batch_reads`] says so.
1056fn is_select(sql: &str) -> bool {
1057    let sql = sql.trim_start();
1058    sql.get(..6)
1059        .is_some_and(|w| w.eq_ignore_ascii_case("select"))
1060        && !sql[6..].starts_with(|c: char| c.is_ascii_alphanumeric() || c == '_')
1061        && !sql
1062            .as_bytes()
1063            .windows(10)
1064            .any(|w| w.eq_ignore_ascii_case(b"set_config"))
1065}
1066
1067/// Refuses, before anything is sent, a statement that must not run on a
1068/// shared connection: one that controls a transaction (unless in a `batch`),
1069/// changes the session, or starts `COPY ... FROM STDIN`. It is on the path of
1070/// every shared statement, so it reads no further than the first word or
1071/// three that decide.
1072fn refuse_on_shared(sql: &str, batch: bool) -> Result<(), Error> {
1073    // Through the extended protocol the server refuses more than one
1074    // statement, so only a batch needs looking at past its first.
1075    let mut statements = Statements {
1076        sql,
1077        i: 0,
1078        first_only: !batch,
1079    };
1080    while let Some(words) = statements.next() {
1081        let word = |i: usize| words.get(i);
1082        let is = |i: usize, any: &[&str]| any.iter().any(|w| word(i).eq_ignore_ascii_case(w));
1083        let transaction = match words.lead {
1084            Lead::Transaction => true,
1085            // Two-phase commit's second phase may run on any connection.
1086            Lead::CommitOrRollback => !is(1, &["PREPARED"]),
1087            Lead::Prepare => is(1, &["TRANSACTION"]),
1088            _ => false,
1089        };
1090        if transaction && !batch {
1091            return Err(Error::new(
1092                ErrorKind::Statement,
1093                format!(
1094                    "{} controls a transaction, and the pool's own methods run statements on \
1095                     connections that other tasks share, whose statements would run inside it; \
1096                     nothing was sent. Run the transaction on a connection of this task's own: \
1097                     let mut conn = pool.get().await?; let tx = conn.transaction().await?; ...; \
1098                     tx.commit().await?",
1099                    word(0).to_ascii_uppercase()
1100                ),
1101            ));
1102        }
1103        if transaction {
1104            continue;
1105        }
1106        let session = match words.lead {
1107            // SET LOCAL and the transaction's own settings end with it.
1108            Lead::Set => !is(1, &["LOCAL", "TRANSACTION", "CONSTRAINTS"]),
1109            Lead::Create => {
1110                is(1, &["TEMP", "TEMPORARY"])
1111                    || (is(1, &["LOCAL", "GLOBAL"]) && is(2, &["TEMP", "TEMPORARY"]))
1112            }
1113            Lead::Prepare | Lead::Session => true,
1114            _ => false,
1115        };
1116        if session {
1117            let what = match words.lead {
1118                Lead::Create => "CREATE TEMP".to_owned(),
1119                Lead::Set => format!("SET {}", word(1).to_ascii_uppercase()),
1120                _ => word(0).to_ascii_uppercase(),
1121            };
1122            return Err(Error::new(
1123                ErrorKind::Statement,
1124                format!(
1125                    "{what} changes the session, and the pool's own methods run statements on \
1126                     connections that other tasks share, which would then run under it; nothing \
1127                     was sent. Run it on a connection of this task's own, from pool.get(): its \
1128                     session is reset when it goes back to the pool. For a setting that every \
1129                     connection needs, use Config::param"
1130                ),
1131            ));
1132        }
1133        if words.lead == Lead::Copy && words.from_stdin {
1134            return Err(Error::new(
1135                ErrorKind::Statement,
1136                "COPY ... FROM STDIN is not supported by giong-postgres yet, and on a connection \
1137                 that other tasks share it would fail their statements too; nothing was sent. \
1138                 Insert the rows with INSERT, several per statement",
1139            ));
1140        }
1141    }
1142    Ok(())
1143}
1144
1145/// What the first word of a statement says about it, for
1146/// [`refuse_on_shared`].
1147#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
1148enum Lead {
1149    /// Anything else (`SELECT`, `INSERT`, `WITH`...): the rest of the
1150    /// statement does not matter.
1151    #[default]
1152    Other,
1153    /// `BEGIN`, `START`, `END`, `ABORT`, `SAVEPOINT`, `RELEASE`.
1154    Transaction,
1155    /// `COMMIT` or `ROLLBACK`, unless `PREPARED` follows.
1156    CommitOrRollback,
1157    /// `PREPARE`, or `PREPARE TRANSACTION`.
1158    Prepare,
1159    /// `SET`, unless `LOCAL`, `TRANSACTION` or `CONSTRAINTS` follows.
1160    Set,
1161    /// `CREATE`, which matters when a temporary object follows.
1162    Create,
1163    /// `RESET`, `DISCARD`, `LISTEN`, `UNLISTEN`, `DEALLOCATE`, `DECLARE`,
1164    /// `LOAD`.
1165    Session,
1166    /// `COPY`, which matters when `FROM STDIN` appears in it.
1167    Copy,
1168}
1169
1170impl Lead {
1171    fn of(word: &str) -> Lead {
1172        let mut upper = [0u8; 10];
1173        let Some(upper) = upper.get_mut(..word.len()) else {
1174            return Lead::Other;
1175        };
1176        for (u, b) in upper.iter_mut().zip(word.bytes()) {
1177            *u = b.to_ascii_uppercase();
1178        }
1179        match &*upper {
1180            b"BEGIN" | b"START" | b"END" | b"ABORT" | b"SAVEPOINT" | b"RELEASE" => {
1181                Lead::Transaction
1182            }
1183            b"COMMIT" | b"ROLLBACK" => Lead::CommitOrRollback,
1184            b"PREPARE" => Lead::Prepare,
1185            b"SET" => Lead::Set,
1186            b"CREATE" => Lead::Create,
1187            b"RESET" | b"DISCARD" | b"LISTEN" | b"UNLISTEN" | b"DEALLOCATE" | b"DECLARE"
1188            | b"LOAD" => Lead::Session,
1189            b"COPY" => Lead::Copy,
1190            _ => Lead::Other,
1191        }
1192    }
1193
1194    /// How many words decide the statement (the whole of it for `COPY`).
1195    fn words(self) -> usize {
1196        match self {
1197            Lead::Other | Lead::Transaction | Lead::Session => 1,
1198            Lead::CommitOrRollback | Lead::Prepare | Lead::Set => 2,
1199            Lead::Create => 3,
1200            Lead::Copy => usize::MAX,
1201        }
1202    }
1203}
1204
1205/// The first words of one statement, as they are written, and whether
1206/// `FROM STDIN` appears in it. A quoted identifier counts as the word `"`.
1207#[derive(Default)]
1208struct Words<'a> {
1209    lead: Lead,
1210    first: [&'a str; 3],
1211    len: usize,
1212    from_stdin: bool,
1213    after_from: bool,
1214}
1215
1216impl<'a> Words<'a> {
1217    /// Word `i`, or `""` past the last one kept.
1218    fn get(&self, i: usize) -> &'a str {
1219        if i < self.len {
1220            self.first[i]
1221        } else {
1222            ""
1223        }
1224    }
1225
1226    fn push(&mut self, word: &'a str) {
1227        if self.len == 0 {
1228            self.lead = Lead::of(word);
1229        }
1230        if self.len < self.first.len() {
1231            self.first[self.len] = word;
1232            self.len += 1;
1233        }
1234        if self.lead == Lead::Copy {
1235            self.from_stdin |= self.after_from && word.eq_ignore_ascii_case("STDIN");
1236            self.after_from = word.eq_ignore_ascii_case("FROM");
1237        }
1238    }
1239
1240    /// Whether the rest of the statement can change nothing that
1241    /// [`refuse_on_shared`] decides.
1242    fn settled(&self) -> bool {
1243        self.len > 0 && self.len >= self.lead.words()
1244    }
1245}
1246
1247/// The statements of `sql`, split at `;` outside comments, string
1248/// constants, quoted identifiers and dollar-quoted bodies; empty ones are
1249/// skipped. With `first_only`, only the first statement, and only as far as
1250/// it needs reading.
1251struct Statements<'a> {
1252    sql: &'a str,
1253    i: usize,
1254    first_only: bool,
1255}
1256
1257impl<'a> Statements<'a> {
1258    fn next(&mut self) -> Option<Words<'a>> {
1259        let (sql, b) = (self.sql, self.sql.as_bytes());
1260        let mut i = self.i;
1261        let mut words = Words::default();
1262        while i < b.len() {
1263            if self.first_only && words.settled() {
1264                i = b.len();
1265                break;
1266            }
1267            match b[i] {
1268                b';' => {
1269                    i += 1;
1270                    if words.len > 0 {
1271                        break;
1272                    }
1273                }
1274                b'-' if b.get(i + 1) == Some(&b'-') => {
1275                    while i < b.len() && b[i] != b'\n' {
1276                        i += 1;
1277                    }
1278                }
1279                b'/' if b.get(i + 1) == Some(&b'*') => {
1280                    // PostgreSQL's block comments nest.
1281                    let mut depth = 0;
1282                    while i < b.len() {
1283                        if b[i..].starts_with(b"/*") {
1284                            depth += 1;
1285                            i += 2;
1286                        } else if b[i..].starts_with(b"*/") {
1287                            depth -= 1;
1288                            i += 2;
1289                            if depth == 0 {
1290                                break;
1291                            }
1292                        } else {
1293                            i += 1;
1294                        }
1295                    }
1296                }
1297                q @ (b'\'' | b'"') => {
1298                    i = skip_quoted(b, i + 1, q, false);
1299                    if q == b'"' {
1300                        words.push("\"");
1301                    }
1302                }
1303                b'$' => match dollar_tag(b, i) {
1304                    Some(tag_len) => {
1305                        let tag = &b[i..i + tag_len];
1306                        i += tag_len;
1307                        while i < b.len() && !b[i..].starts_with(tag) {
1308                            i += 1;
1309                        }
1310                        i = (i + tag_len).min(b.len());
1311                    }
1312                    // A parameter, $1.
1313                    None => i += 1,
1314                },
1315                c if c.is_ascii_alphabetic() || c == b'_' || c >= 0x80 => {
1316                    let start = i;
1317                    while i < b.len()
1318                        && (b[i].is_ascii_alphanumeric()
1319                            || matches!(b[i], b'_' | b'$')
1320                            || b[i] >= 0x80)
1321                    {
1322                        i += 1;
1323                    }
1324                    let word = &sql[start..i];
1325                    // E'...' takes backslash escapes; U&'...', B'...', X'...'
1326                    // and N'...' are ordinary string constants after their
1327                    // prefix.
1328                    if b.get(i) == Some(&b'\'') {
1329                        let escapes = word.eq_ignore_ascii_case("e");
1330                        if escapes || ["b", "x", "n"].iter().any(|p| word.eq_ignore_ascii_case(p)) {
1331                            i = skip_quoted(b, i + 1, b'\'', escapes);
1332                            continue;
1333                        }
1334                    }
1335                    if word.eq_ignore_ascii_case("u") && b[i..].starts_with(b"&'") {
1336                        i = skip_quoted(b, i + 2, b'\'', false);
1337                        continue;
1338                    }
1339                    words.push(word);
1340                }
1341                _ => i += 1,
1342            }
1343        }
1344        self.i = if self.first_only { b.len() } else { i };
1345        (words.len > 0).then_some(words)
1346    }
1347}
1348
1349/// The position after the quote that closes the one before `i`; a doubled
1350/// quote stands for itself, and with `escapes` so does a backslash and the
1351/// byte after it.
1352fn skip_quoted(b: &[u8], mut i: usize, quote: u8, escapes: bool) -> usize {
1353    while i < b.len() {
1354        if escapes && b[i] == b'\\' {
1355            i += 2;
1356        } else if b[i] == quote {
1357            if b.get(i + 1) == Some(&quote) {
1358                i += 2;
1359            } else {
1360                return i + 1;
1361            }
1362        } else {
1363            i += 1;
1364        }
1365    }
1366    b.len()
1367}
1368
1369/// The length of the dollar-quote tag at `i` (`$$` or `$name$`), if one
1370/// starts there.
1371fn dollar_tag(b: &[u8], i: usize) -> Option<usize> {
1372    let mut j = i + 1;
1373    if b.get(j).is_some_and(|c| c.is_ascii_digit()) {
1374        return None;
1375    }
1376    while j < b.len() && (b[j].is_ascii_alphanumeric() || b[j] == b'_' || b[j] >= 0x80) {
1377        j += 1;
1378    }
1379    (b.get(j) == Some(&b'$')).then_some(j + 1 - i)
1380}
1381
1382impl std::fmt::Debug for Pool {
1383    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1384        f.debug_struct("Pool")
1385            .field("server", &self.inner.config.target())
1386            .field("max_size", &self.inner.max_size)
1387            .field("stats", &self.stats())
1388            .finish()
1389    }
1390}
1391
1392/// A connection taken from a [`Pool`] with [`Pool::get`]. It dereferences to
1393/// the [`Client`], and goes back to the pool when dropped, where its session
1394/// is reset (see [`Pool`]).
1395pub struct PooledClient {
1396    client: Option<Client>,
1397    pool: Pool,
1398    /// When the connection is to be closed rather than go back.
1399    expires: Instant,
1400    /// The connection's request count when it was taken.
1401    requests: u64,
1402}
1403
1404impl PooledClient {
1405    /// Starts a transaction; see [`Client::transaction`].
1406    ///
1407    /// Cancel safe, like [`Client::transaction`].
1408    pub async fn transaction(&mut self) -> Result<Transaction<'_>, Error> {
1409        self.deref_mut().transaction().await
1410    }
1411}
1412
1413impl Deref for PooledClient {
1414    type Target = Client;
1415
1416    fn deref(&self) -> &Client {
1417        self.client.as_ref().expect("present until dropped")
1418    }
1419}
1420
1421impl DerefMut for PooledClient {
1422    fn deref_mut(&mut self) -> &mut Client {
1423        self.client.as_mut().expect("present until dropped")
1424    }
1425}
1426
1427impl Drop for PooledClient {
1428    fn drop(&mut self) {
1429        let client = self.client.take().expect("present until dropped");
1430        // A cancel request taken during the lease may still reach the
1431        // server: the connection is closed rather than lent to another task.
1432        let cancelling = client.end_lease();
1433        let now = Instant::now();
1434        let mut st = self.pool.inner.state.borrow_mut();
1435        st.taken -= 1;
1436        let old = now >= self.expires || client.should_retire();
1437        let retire = old || cancelling;
1438        if old && !client.is_closed() {
1439            // Closing rolls back whatever was left open.
1440            st.recycled += 1;
1441        }
1442        if !client.is_closed() && !retire {
1443            let used = client.requests() != self.requests;
1444            // A statement still on its way (its future was dropped, by a
1445            // timeout say) may be a BEGIN: the last answer cannot tell.
1446            // Queued ahead of anything a shared statement sends next.
1447            if client.in_flight() > 0 || client.in_transaction() {
1448                client.send_and_forget("ROLLBACK");
1449            }
1450            if used {
1451                client.reset_session();
1452            }
1453            client.set_shared(true);
1454            st.shared.push(Member {
1455                client: Rc::new(client),
1456                draining: false,
1457                used: now,
1458                expires: self.expires,
1459            });
1460            st.rebalance(self.pool.inner.max_size);
1461        }
1462        st.wake_all();
1463        drop(st);
1464        self.pool.flush_wakes();
1465    }
1466}
1467
1468impl std::fmt::Debug for PooledClient {
1469    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1470        f.debug_tuple("PooledClient").field(&**self).finish()
1471    }
1472}
1473
1474#[cfg(test)]
1475mod tests {
1476    use super::*;
1477
1478    /// `Duration::MAX` reads as "no limit" and must not overflow the clock
1479    /// when a task starts waiting (issue #298). Nothing listens on port 1,
1480    /// so the task fails to connect instead.
1481    #[test]
1482    fn an_unbounded_wait_timeout_does_not_overflow() {
1483        let pool = Pool::new(
1484            Config::new()
1485                .host("127.0.0.1")
1486                .port(1)
1487                .connect_timeout(Duration::from_secs(2)),
1488            1,
1489        )
1490        .wait_timeout(Duration::MAX);
1491        let got = giong::block_on(async move { pool.get().await.map(drop) });
1492        assert!(got.is_err());
1493    }
1494
1495    fn refused(sql: &str) -> bool {
1496        refuse_on_shared(sql, false).is_err()
1497    }
1498
1499    fn refused_in_batch(sql: &str) -> bool {
1500        refuse_on_shared(sql, true).is_err()
1501    }
1502
1503    #[test]
1504    fn only_select_statements_may_join_a_batch() {
1505        for sql in ["SELECT 1", "  select\n1", "Select(1)", "SELECT"] {
1506            assert!(is_select(sql), "{sql}");
1507        }
1508        for sql in [
1509            "SELECTED",
1510            "select_x()",
1511            "WITH a AS (SELECT 1) SELECT 1",
1512            "INSERT 1",
1513            "sel",
1514            "",
1515            "SELECT set_config('app.user', $1, true)",
1516            "select 1 from t where pg_catalog.SET_CONFIG('a', 'b', true) is not null",
1517        ] {
1518            assert!(!is_select(sql), "{sql}");
1519        }
1520    }
1521
1522    #[test]
1523    fn transaction_statements_are_refused_outside_batches() {
1524        for sql in [
1525            "BEGIN",
1526            " begin isolation level serializable",
1527            "/* x /* nested */ */ COMMIT",
1528            "-- c\nROLLBACK",
1529            "start transaction",
1530            "PREPARE TRANSACTION 'x'",
1531            "savepoint a",
1532        ] {
1533            assert!(refused(sql), "{sql}");
1534            assert!(!refused_in_batch(sql), "{sql}");
1535        }
1536        for sql in ["COMMIT PREPARED 'x'", "ROLLBACK PREPARED 'x'", "SELECT 1"] {
1537            assert!(!refused(sql), "{sql}");
1538        }
1539    }
1540
1541    #[test]
1542    fn session_changes_are_refused_everywhere() {
1543        for sql in [
1544            "SET search_path = tenant_a",
1545            "set session authorization app",
1546            "SET ROLE tenant",
1547            "SET statement_timeout = 0",
1548            "RESET ALL",
1549            "DISCARD ALL",
1550            "LISTEN jobs",
1551            "UNLISTEN *",
1552            "PREPARE q AS SELECT 1",
1553            "DEALLOCATE ALL",
1554            "DECLARE c CURSOR WITH HOLD FOR SELECT 1",
1555            "LOAD 'auto_explain'",
1556            "CREATE TEMP TABLE t (a int)",
1557            "create temporary table t (a int)",
1558            "CREATE LOCAL TEMPORARY TABLE t (a int)",
1559            "COPY t FROM STDIN",
1560            "copy t (a, b) from stdin with (format csv)",
1561            "BEGIN; SET work_mem = '1GB'; COMMIT",
1562        ] {
1563            assert!(refused(sql), "{sql}");
1564            assert!(refused_in_batch(sql), "{sql}");
1565        }
1566        // Statements after the first matter in a batch only: through the
1567        // extended protocol, the server refuses more than one.
1568        assert!(refused_in_batch("SELECT 1; SET search_path = x"));
1569        assert!(!refused("SELECT 1; SET search_path = x"));
1570        for sql in [
1571            "SET LOCAL work_mem = '1GB'",
1572            "SET TRANSACTION ISOLATION LEVEL SERIALIZABLE",
1573            "SET CONSTRAINTS ALL DEFERRED",
1574            "CREATE TABLE t (a int)",
1575            "COPY t TO STDOUT",
1576            "COPY t FROM '/tmp/x'",
1577            "SELECT 'SET x = 1; LISTEN y'",
1578            "SELECT E'it\\'s; SET x = 1'",
1579            "SELECT $$; SET x = 1$$, $f$ ; LISTEN y $f$",
1580            "SELECT \"set\" FROM t",
1581            "SELECT $1::text; SELECT 2",
1582            "SELECT 1 -- ; SET x = 1",
1583            "SELECT /* ; SET x = 1 */ 1",
1584            "UPDATE t SET a = 1",
1585            "INSERT INTO t SELECT 'from stdin'",
1586        ] {
1587            assert!(!refused_in_batch(sql), "{sql}");
1588        }
1589        assert!(refused_in_batch("BEGIN; SET LOCAL a = 1; COMMIT; LISTEN x"));
1590    }
1591
1592    #[test]
1593    fn statements_are_split_outside_quotes() {
1594        let all = |sql| {
1595            let mut s = Statements {
1596                sql,
1597                i: 0,
1598                first_only: false,
1599            };
1600            let mut all = Vec::new();
1601            while let Some(w) = s.next() {
1602                all.push((0..w.len).map(|i| w.get(i).to_owned()).collect::<Vec<_>>());
1603            }
1604            all
1605        };
1606        let s = all("SELECT 'a;b'; SELECT \"x;y\" ; ; /* ; */ -- ;\n VALUES (1)");
1607        assert_eq!(s.len(), 3);
1608        assert_eq!(s[1], ["SELECT", "\""]);
1609        assert_eq!(s[2], ["VALUES"]);
1610        // An unterminated quote swallows the rest, as the server would.
1611        assert_eq!(all("SELECT 'a; SET x = 1").len(), 1);
1612        assert_eq!(all("SELECT $q$ a; SET x $q").len(), 1);
1613        assert_eq!(all("SELECT a$b; SET x = 1")[1], ["SET", "x"]);
1614        // Only the first three words are kept, and FROM STDIN is seen anywhere.
1615        let mut s = Statements {
1616            sql: "copy t (a, b, c, d) from stdin; select 1",
1617            i: 0,
1618            first_only: true,
1619        };
1620        let w = s.next().unwrap();
1621        assert_eq!((w.lead, w.len, w.from_stdin), (Lead::Copy, 3, true));
1622        assert!(s.next().is_none());
1623    }
1624}