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