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