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 _wait = giong::observe::wait(giong::observe::Wait::Pool, "postgres");
846 let deadline = Instant::now() + self.inner.wait_timeout;
847 let mut waiting: Option<Waiting<'_>> = None;
848 // Failed attempts to open a connection so far: when one fails while
849 // this task waits, and the pool has no connection open to wait for,
850 // the task fails with its error rather than try again at once.
851 let failed_before = self.inner.state.borrow().connect_errors;
852 loop {
853 let decision = {
854 let mut st = self.inner.state.borrow_mut();
855 let none_open = st.shared.is_empty() && st.taken == 0;
856 if waiting.is_some() && none_open && st.connect_errors != failed_before {
857 if let Some(e) = st.failing.clone() {
858 drop(st);
859 return Err(e);
860 }
861 }
862 if none_open && st.connecting == 0 {
863 if let (Some(e), Some(at)) = (&st.failing, st.retry_at) {
864 if Instant::now() < at {
865 let e = e.clone();
866 drop(st);
867 return Err(e);
868 }
869 }
870 }
871 let now = Instant::now();
872 st.sweep(now, self.inner.idle_timeout);
873 let d = decide(&mut st, now);
874 if matches!(d, Decision::Wait) && waiting.is_none() {
875 st.waiting += 1;
876 }
877 d
878 };
879 self.flush_wakes();
880 match decision {
881 Decision::Ready(c) => {
882 if let Some(w) = &mut waiting {
883 w.served = true;
884 }
885 return Ok(Ok(c));
886 }
887 Decision::Connect => {
888 if let Some(w) = &mut waiting {
889 w.served = true;
890 }
891 drop(waiting);
892 let _connecting = Connecting(self);
893 let result = Client::connect(&self.inner.config).await;
894 let mut st = self.inner.state.borrow_mut();
895 return match result {
896 Ok(client) => {
897 st.opened += 1;
898 st.failing = None;
899 st.failures_in_row = 0;
900 st.retry_at = None;
901 self.start_reaper(&mut st);
902 Ok(Err(client))
903 }
904 Err(e) => {
905 st.connect_errors += 1;
906 st.failing = Some(e.clone());
907 st.failures_in_row = st.failures_in_row.saturating_add(1);
908 st.retry_at =
909 Some(Instant::now() + connect_backoff(st.failures_in_row));
910 Err(e)
911 }
912 };
913 }
914 Decision::Wait => {
915 if waiting.is_none() {
916 waiting = Some(Waiting {
917 pool: self,
918 kind,
919 served: false,
920 });
921 }
922 let mut registered = false;
923 let woken = poll_fn(|cx| {
924 if registered {
925 return Poll::Ready(());
926 }
927 registered = true;
928 let mut st = self.inner.state.borrow_mut();
929 match kind {
930 Waiter::Shared => st.shared_waiters.push_back(cx.waker().clone()),
931 Waiter::Get => st.get_waiters.push(cx.waker().clone()),
932 }
933 // A connection kept busy only by requests whose tasks
934 // stopped waiting (a timeout dropped them) frees up
935 // once they are answered, which nothing else would
936 // announce.
937 for m in &st.shared {
938 if m.is_free() && m.client.in_flight() > 0 {
939 m.client.wake_when_idle(cx.waker());
940 }
941 }
942 Poll::Pending
943 });
944 let left = deadline.saturating_duration_since(Instant::now());
945 if giong::time::timeout(left, woken).await.is_err() {
946 let mut st = self.inner.state.borrow_mut();
947 st.timeouts += 1;
948 let (taken, max) = (st.taken, self.inner.max_size);
949 drop(st);
950 let why = if taken == max {
951 format!("all {max} are taken with Pool::get")
952 } else {
953 format!("all {max} are taken or busy ({taken} taken with Pool::get)")
954 };
955 return Err(Error::new(
956 ErrorKind::PoolTimeout,
957 format!(
958 "no connection to {} became free within {:?}: {why}. Raise the \
959 pool's max_size (the server's max_connections allowing), look \
960 for transactions or connections from Pool::get held too long, \
961 or raise Pool::wait_timeout",
962 self.inner.config.target(),
963 self.inner.wait_timeout,
964 ),
965 ));
966 }
967 }
968 }
969 }
970 }
971}
972
973/// Closes idle and old connections now and then, until the pool is dropped.
974async fn reap(state: Weak<RefCell<State>>, idle_timeout: Duration, period: Duration) {
975 loop {
976 let mut sleep = pin!(giong::time::sleep(period));
977 let stopped = poll_fn(|cx| {
978 let Some(state) = state.upgrade() else {
979 return Poll::Ready(true);
980 };
981 let mut st = state.borrow_mut();
982 if st.stopped {
983 return Poll::Ready(true);
984 }
985 st.reaper_waker = Some(cx.waker().clone());
986 drop(st);
987 sleep.as_mut().poll(cx).map(|()| false)
988 })
989 .await;
990 if stopped {
991 return;
992 }
993 let Some(state) = state.upgrade() else { return };
994 let wakers = {
995 let mut st = state.borrow_mut();
996 st.sweep(Instant::now(), idle_timeout);
997 std::mem::take(&mut st.to_wake)
998 };
999 for w in wakers {
1000 w.wake();
1001 }
1002 }
1003}
1004
1005/// A shared connection lent to one statement. Dropping it, when the
1006/// statement is answered or its future is dropped, tells waiting tasks to
1007/// look again: there is room for one more statement, and the connection may
1008/// have become free.
1009struct Lent<'a> {
1010 pool: &'a Pool,
1011 client: Option<Rc<Client>>,
1012}
1013
1014impl Deref for Lent<'_> {
1015 type Target = Client;
1016
1017 fn deref(&self) -> &Client {
1018 self.client.as_ref().expect("present until dropped")
1019 }
1020}
1021
1022impl Drop for Lent<'_> {
1023 fn drop(&mut self) {
1024 let client = self.client.take().expect("present until dropped");
1025 // The pool's reference and this one.
1026 let free = Rc::strong_count(&client) == 2;
1027 drop(client);
1028 let mut st = self.pool.inner.state.borrow_mut();
1029 st.wake_one_shared();
1030 if free {
1031 if st
1032 .shared
1033 .iter()
1034 .any(|m| m.is_free() && m.client.should_retire())
1035 {
1036 st.sweep(Instant::now(), self.pool.inner.idle_timeout);
1037 }
1038 st.wake_gets();
1039 }
1040 drop(st);
1041 self.pool.flush_wakes();
1042 }
1043}
1044
1045/// Whether `sql` starts with the word `SELECT`, the statements a batch may
1046/// take ([`Config::batch_reads`]), and does not contain `set_config`: a
1047/// transaction-local setting made that way (`set_config(..., true)`, as
1048/// row-level security policies read) would reach the rest of its batch.
1049/// Matched anywhere in the text, quoted or commented too, since a false
1050/// match only runs a statement alone. A call hidden inside a function is
1051/// not seen; [`Config::batch_reads`] says so.
1052fn is_select(sql: &str) -> bool {
1053 let sql = sql.trim_start();
1054 sql.get(..6)
1055 .is_some_and(|w| w.eq_ignore_ascii_case("select"))
1056 && !sql[6..].starts_with(|c: char| c.is_ascii_alphanumeric() || c == '_')
1057 && !sql
1058 .as_bytes()
1059 .windows(10)
1060 .any(|w| w.eq_ignore_ascii_case(b"set_config"))
1061}
1062
1063/// Refuses, before anything is sent, a statement that must not run on a
1064/// shared connection: one that controls a transaction (unless in a `batch`),
1065/// changes the session, or starts `COPY ... FROM STDIN`. It is on the path of
1066/// every shared statement, so it reads no further than the first word or
1067/// three that decide.
1068fn refuse_on_shared(sql: &str, batch: bool) -> Result<(), Error> {
1069 // Through the extended protocol the server refuses more than one
1070 // statement, so only a batch needs looking at past its first.
1071 let mut statements = Statements {
1072 sql,
1073 i: 0,
1074 first_only: !batch,
1075 };
1076 while let Some(words) = statements.next() {
1077 let word = |i: usize| words.get(i);
1078 let is = |i: usize, any: &[&str]| any.iter().any(|w| word(i).eq_ignore_ascii_case(w));
1079 let transaction = match words.lead {
1080 Lead::Transaction => true,
1081 // Two-phase commit's second phase may run on any connection.
1082 Lead::CommitOrRollback => !is(1, &["PREPARED"]),
1083 Lead::Prepare => is(1, &["TRANSACTION"]),
1084 _ => false,
1085 };
1086 if transaction && !batch {
1087 return Err(Error::new(
1088 ErrorKind::Statement,
1089 format!(
1090 "{} controls a transaction, and the pool's own methods run statements on \
1091 connections that other tasks share, whose statements would run inside it; \
1092 nothing was sent. Run the transaction on a connection of this task's own: \
1093 let mut conn = pool.get().await?; let tx = conn.transaction().await?; ...; \
1094 tx.commit().await?",
1095 word(0).to_ascii_uppercase()
1096 ),
1097 ));
1098 }
1099 if transaction {
1100 continue;
1101 }
1102 let session = match words.lead {
1103 // SET LOCAL and the transaction's own settings end with it.
1104 Lead::Set => !is(1, &["LOCAL", "TRANSACTION", "CONSTRAINTS"]),
1105 Lead::Create => {
1106 is(1, &["TEMP", "TEMPORARY"])
1107 || (is(1, &["LOCAL", "GLOBAL"]) && is(2, &["TEMP", "TEMPORARY"]))
1108 }
1109 Lead::Prepare | Lead::Session => true,
1110 _ => false,
1111 };
1112 if session {
1113 let what = match words.lead {
1114 Lead::Create => "CREATE TEMP".to_owned(),
1115 Lead::Set => format!("SET {}", word(1).to_ascii_uppercase()),
1116 _ => word(0).to_ascii_uppercase(),
1117 };
1118 return Err(Error::new(
1119 ErrorKind::Statement,
1120 format!(
1121 "{what} changes the session, and the pool's own methods run statements on \
1122 connections that other tasks share, which would then run under it; nothing \
1123 was sent. Run it on a connection of this task's own, from pool.get(): its \
1124 session is reset when it goes back to the pool. For a setting that every \
1125 connection needs, use Config::param"
1126 ),
1127 ));
1128 }
1129 if words.lead == Lead::Copy && words.from_stdin {
1130 return Err(Error::new(
1131 ErrorKind::Statement,
1132 "COPY ... FROM STDIN is not supported by giong-postgres yet, and on a connection \
1133 that other tasks share it would fail their statements too; nothing was sent. \
1134 Insert the rows with INSERT, several per statement",
1135 ));
1136 }
1137 }
1138 Ok(())
1139}
1140
1141/// What the first word of a statement says about it, for
1142/// [`refuse_on_shared`].
1143#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
1144enum Lead {
1145 /// Anything else (`SELECT`, `INSERT`, `WITH`...): the rest of the
1146 /// statement does not matter.
1147 #[default]
1148 Other,
1149 /// `BEGIN`, `START`, `END`, `ABORT`, `SAVEPOINT`, `RELEASE`.
1150 Transaction,
1151 /// `COMMIT` or `ROLLBACK`, unless `PREPARED` follows.
1152 CommitOrRollback,
1153 /// `PREPARE`, or `PREPARE TRANSACTION`.
1154 Prepare,
1155 /// `SET`, unless `LOCAL`, `TRANSACTION` or `CONSTRAINTS` follows.
1156 Set,
1157 /// `CREATE`, which matters when a temporary object follows.
1158 Create,
1159 /// `RESET`, `DISCARD`, `LISTEN`, `UNLISTEN`, `DEALLOCATE`, `DECLARE`,
1160 /// `LOAD`.
1161 Session,
1162 /// `COPY`, which matters when `FROM STDIN` appears in it.
1163 Copy,
1164}
1165
1166impl Lead {
1167 fn of(word: &str) -> Lead {
1168 let mut upper = [0u8; 10];
1169 let Some(upper) = upper.get_mut(..word.len()) else {
1170 return Lead::Other;
1171 };
1172 for (u, b) in upper.iter_mut().zip(word.bytes()) {
1173 *u = b.to_ascii_uppercase();
1174 }
1175 match &*upper {
1176 b"BEGIN" | b"START" | b"END" | b"ABORT" | b"SAVEPOINT" | b"RELEASE" => {
1177 Lead::Transaction
1178 }
1179 b"COMMIT" | b"ROLLBACK" => Lead::CommitOrRollback,
1180 b"PREPARE" => Lead::Prepare,
1181 b"SET" => Lead::Set,
1182 b"CREATE" => Lead::Create,
1183 b"RESET" | b"DISCARD" | b"LISTEN" | b"UNLISTEN" | b"DEALLOCATE" | b"DECLARE"
1184 | b"LOAD" => Lead::Session,
1185 b"COPY" => Lead::Copy,
1186 _ => Lead::Other,
1187 }
1188 }
1189
1190 /// How many words decide the statement (the whole of it for `COPY`).
1191 fn words(self) -> usize {
1192 match self {
1193 Lead::Other | Lead::Transaction | Lead::Session => 1,
1194 Lead::CommitOrRollback | Lead::Prepare | Lead::Set => 2,
1195 Lead::Create => 3,
1196 Lead::Copy => usize::MAX,
1197 }
1198 }
1199}
1200
1201/// The first words of one statement, as they are written, and whether
1202/// `FROM STDIN` appears in it. A quoted identifier counts as the word `"`.
1203#[derive(Default)]
1204struct Words<'a> {
1205 lead: Lead,
1206 first: [&'a str; 3],
1207 len: usize,
1208 from_stdin: bool,
1209 after_from: bool,
1210}
1211
1212impl<'a> Words<'a> {
1213 /// Word `i`, or `""` past the last one kept.
1214 fn get(&self, i: usize) -> &'a str {
1215 if i < self.len {
1216 self.first[i]
1217 } else {
1218 ""
1219 }
1220 }
1221
1222 fn push(&mut self, word: &'a str) {
1223 if self.len == 0 {
1224 self.lead = Lead::of(word);
1225 }
1226 if self.len < self.first.len() {
1227 self.first[self.len] = word;
1228 self.len += 1;
1229 }
1230 if self.lead == Lead::Copy {
1231 self.from_stdin |= self.after_from && word.eq_ignore_ascii_case("STDIN");
1232 self.after_from = word.eq_ignore_ascii_case("FROM");
1233 }
1234 }
1235
1236 /// Whether the rest of the statement can change nothing that
1237 /// [`refuse_on_shared`] decides.
1238 fn settled(&self) -> bool {
1239 self.len > 0 && self.len >= self.lead.words()
1240 }
1241}
1242
1243/// The statements of `sql`, split at `;` outside comments, string
1244/// constants, quoted identifiers and dollar-quoted bodies; empty ones are
1245/// skipped. With `first_only`, only the first statement, and only as far as
1246/// it needs reading.
1247struct Statements<'a> {
1248 sql: &'a str,
1249 i: usize,
1250 first_only: bool,
1251}
1252
1253impl<'a> Statements<'a> {
1254 fn next(&mut self) -> Option<Words<'a>> {
1255 let (sql, b) = (self.sql, self.sql.as_bytes());
1256 let mut i = self.i;
1257 let mut words = Words::default();
1258 while i < b.len() {
1259 if self.first_only && words.settled() {
1260 i = b.len();
1261 break;
1262 }
1263 match b[i] {
1264 b';' => {
1265 i += 1;
1266 if words.len > 0 {
1267 break;
1268 }
1269 }
1270 b'-' if b.get(i + 1) == Some(&b'-') => {
1271 while i < b.len() && b[i] != b'\n' {
1272 i += 1;
1273 }
1274 }
1275 b'/' if b.get(i + 1) == Some(&b'*') => {
1276 // PostgreSQL's block comments nest.
1277 let mut depth = 0;
1278 while i < b.len() {
1279 if b[i..].starts_with(b"/*") {
1280 depth += 1;
1281 i += 2;
1282 } else if b[i..].starts_with(b"*/") {
1283 depth -= 1;
1284 i += 2;
1285 if depth == 0 {
1286 break;
1287 }
1288 } else {
1289 i += 1;
1290 }
1291 }
1292 }
1293 q @ (b'\'' | b'"') => {
1294 i = skip_quoted(b, i + 1, q, false);
1295 if q == b'"' {
1296 words.push("\"");
1297 }
1298 }
1299 b'$' => match dollar_tag(b, i) {
1300 Some(tag_len) => {
1301 let tag = &b[i..i + tag_len];
1302 i += tag_len;
1303 while i < b.len() && !b[i..].starts_with(tag) {
1304 i += 1;
1305 }
1306 i = (i + tag_len).min(b.len());
1307 }
1308 // A parameter, $1.
1309 None => i += 1,
1310 },
1311 c if c.is_ascii_alphabetic() || c == b'_' || c >= 0x80 => {
1312 let start = i;
1313 while i < b.len()
1314 && (b[i].is_ascii_alphanumeric()
1315 || matches!(b[i], b'_' | b'$')
1316 || b[i] >= 0x80)
1317 {
1318 i += 1;
1319 }
1320 let word = &sql[start..i];
1321 // E'...' takes backslash escapes; U&'...', B'...', X'...'
1322 // and N'...' are ordinary string constants after their
1323 // prefix.
1324 if b.get(i) == Some(&b'\'') {
1325 let escapes = word.eq_ignore_ascii_case("e");
1326 if escapes || ["b", "x", "n"].iter().any(|p| word.eq_ignore_ascii_case(p)) {
1327 i = skip_quoted(b, i + 1, b'\'', escapes);
1328 continue;
1329 }
1330 }
1331 if word.eq_ignore_ascii_case("u") && b[i..].starts_with(b"&'") {
1332 i = skip_quoted(b, i + 2, b'\'', false);
1333 continue;
1334 }
1335 words.push(word);
1336 }
1337 _ => i += 1,
1338 }
1339 }
1340 self.i = if self.first_only { b.len() } else { i };
1341 (words.len > 0).then_some(words)
1342 }
1343}
1344
1345/// The position after the quote that closes the one before `i`; a doubled
1346/// quote stands for itself, and with `escapes` so does a backslash and the
1347/// byte after it.
1348fn skip_quoted(b: &[u8], mut i: usize, quote: u8, escapes: bool) -> usize {
1349 while i < b.len() {
1350 if escapes && b[i] == b'\\' {
1351 i += 2;
1352 } else if b[i] == quote {
1353 if b.get(i + 1) == Some("e) {
1354 i += 2;
1355 } else {
1356 return i + 1;
1357 }
1358 } else {
1359 i += 1;
1360 }
1361 }
1362 b.len()
1363}
1364
1365/// The length of the dollar-quote tag at `i` (`$$` or `$name$`), if one
1366/// starts there.
1367fn dollar_tag(b: &[u8], i: usize) -> Option<usize> {
1368 let mut j = i + 1;
1369 if b.get(j).is_some_and(|c| c.is_ascii_digit()) {
1370 return None;
1371 }
1372 while j < b.len() && (b[j].is_ascii_alphanumeric() || b[j] == b'_' || b[j] >= 0x80) {
1373 j += 1;
1374 }
1375 (b.get(j) == Some(&b'$')).then_some(j + 1 - i)
1376}
1377
1378impl std::fmt::Debug for Pool {
1379 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1380 f.debug_struct("Pool")
1381 .field("server", &self.inner.config.target())
1382 .field("max_size", &self.inner.max_size)
1383 .field("stats", &self.stats())
1384 .finish()
1385 }
1386}
1387
1388/// A connection taken from a [`Pool`] with [`Pool::get`]. It dereferences to
1389/// the [`Client`], and goes back to the pool when dropped, where its session
1390/// is reset (see [`Pool`]).
1391pub struct PooledClient {
1392 client: Option<Client>,
1393 pool: Pool,
1394 /// When the connection is to be closed rather than go back.
1395 expires: Instant,
1396 /// The connection's request count when it was taken.
1397 requests: u64,
1398}
1399
1400impl PooledClient {
1401 /// Starts a transaction; see [`Client::transaction`].
1402 ///
1403 /// Cancel safe, like [`Client::transaction`].
1404 pub async fn transaction(&mut self) -> Result<Transaction<'_>, Error> {
1405 self.deref_mut().transaction().await
1406 }
1407}
1408
1409impl Deref for PooledClient {
1410 type Target = Client;
1411
1412 fn deref(&self) -> &Client {
1413 self.client.as_ref().expect("present until dropped")
1414 }
1415}
1416
1417impl DerefMut for PooledClient {
1418 fn deref_mut(&mut self) -> &mut Client {
1419 self.client.as_mut().expect("present until dropped")
1420 }
1421}
1422
1423impl Drop for PooledClient {
1424 fn drop(&mut self) {
1425 let client = self.client.take().expect("present until dropped");
1426 // A cancel request taken during the lease may still reach the
1427 // server: the connection is closed rather than lent to another task.
1428 let cancelling = client.end_lease();
1429 let now = Instant::now();
1430 let mut st = self.pool.inner.state.borrow_mut();
1431 st.taken -= 1;
1432 let old = now >= self.expires || client.should_retire();
1433 let retire = old || cancelling;
1434 if old && !client.is_closed() {
1435 // Closing rolls back whatever was left open.
1436 st.recycled += 1;
1437 }
1438 if !client.is_closed() && !retire {
1439 let used = client.requests() != self.requests;
1440 // A statement still on its way (its future was dropped, by a
1441 // timeout say) may be a BEGIN: the last answer cannot tell.
1442 // Queued ahead of anything a shared statement sends next.
1443 if client.in_flight() > 0 || client.in_transaction() {
1444 client.send_and_forget("ROLLBACK");
1445 }
1446 if used {
1447 client.reset_session();
1448 }
1449 client.set_shared(true);
1450 st.shared.push(Member {
1451 client: Rc::new(client),
1452 draining: false,
1453 used: now,
1454 expires: self.expires,
1455 });
1456 st.rebalance(self.pool.inner.max_size);
1457 }
1458 st.wake_all();
1459 drop(st);
1460 self.pool.flush_wakes();
1461 }
1462}
1463
1464impl std::fmt::Debug for PooledClient {
1465 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1466 f.debug_tuple("PooledClient").field(&**self).finish()
1467 }
1468}
1469
1470#[cfg(test)]
1471mod tests {
1472 use super::*;
1473
1474 fn refused(sql: &str) -> bool {
1475 refuse_on_shared(sql, false).is_err()
1476 }
1477
1478 fn refused_in_batch(sql: &str) -> bool {
1479 refuse_on_shared(sql, true).is_err()
1480 }
1481
1482 #[test]
1483 fn only_select_statements_may_join_a_batch() {
1484 for sql in ["SELECT 1", " select\n1", "Select(1)", "SELECT"] {
1485 assert!(is_select(sql), "{sql}");
1486 }
1487 for sql in [
1488 "SELECTED",
1489 "select_x()",
1490 "WITH a AS (SELECT 1) SELECT 1",
1491 "INSERT 1",
1492 "sel",
1493 "",
1494 "SELECT set_config('app.user', $1, true)",
1495 "select 1 from t where pg_catalog.SET_CONFIG('a', 'b', true) is not null",
1496 ] {
1497 assert!(!is_select(sql), "{sql}");
1498 }
1499 }
1500
1501 #[test]
1502 fn transaction_statements_are_refused_outside_batches() {
1503 for sql in [
1504 "BEGIN",
1505 " begin isolation level serializable",
1506 "/* x /* nested */ */ COMMIT",
1507 "-- c\nROLLBACK",
1508 "start transaction",
1509 "PREPARE TRANSACTION 'x'",
1510 "savepoint a",
1511 ] {
1512 assert!(refused(sql), "{sql}");
1513 assert!(!refused_in_batch(sql), "{sql}");
1514 }
1515 for sql in ["COMMIT PREPARED 'x'", "ROLLBACK PREPARED 'x'", "SELECT 1"] {
1516 assert!(!refused(sql), "{sql}");
1517 }
1518 }
1519
1520 #[test]
1521 fn session_changes_are_refused_everywhere() {
1522 for sql in [
1523 "SET search_path = tenant_a",
1524 "set session authorization app",
1525 "SET ROLE tenant",
1526 "SET statement_timeout = 0",
1527 "RESET ALL",
1528 "DISCARD ALL",
1529 "LISTEN jobs",
1530 "UNLISTEN *",
1531 "PREPARE q AS SELECT 1",
1532 "DEALLOCATE ALL",
1533 "DECLARE c CURSOR WITH HOLD FOR SELECT 1",
1534 "LOAD 'auto_explain'",
1535 "CREATE TEMP TABLE t (a int)",
1536 "create temporary table t (a int)",
1537 "CREATE LOCAL TEMPORARY TABLE t (a int)",
1538 "COPY t FROM STDIN",
1539 "copy t (a, b) from stdin with (format csv)",
1540 "BEGIN; SET work_mem = '1GB'; COMMIT",
1541 ] {
1542 assert!(refused(sql), "{sql}");
1543 assert!(refused_in_batch(sql), "{sql}");
1544 }
1545 // Statements after the first matter in a batch only: through the
1546 // extended protocol, the server refuses more than one.
1547 assert!(refused_in_batch("SELECT 1; SET search_path = x"));
1548 assert!(!refused("SELECT 1; SET search_path = x"));
1549 for sql in [
1550 "SET LOCAL work_mem = '1GB'",
1551 "SET TRANSACTION ISOLATION LEVEL SERIALIZABLE",
1552 "SET CONSTRAINTS ALL DEFERRED",
1553 "CREATE TABLE t (a int)",
1554 "COPY t TO STDOUT",
1555 "COPY t FROM '/tmp/x'",
1556 "SELECT 'SET x = 1; LISTEN y'",
1557 "SELECT E'it\\'s; SET x = 1'",
1558 "SELECT $$; SET x = 1$$, $f$ ; LISTEN y $f$",
1559 "SELECT \"set\" FROM t",
1560 "SELECT $1::text; SELECT 2",
1561 "SELECT 1 -- ; SET x = 1",
1562 "SELECT /* ; SET x = 1 */ 1",
1563 "UPDATE t SET a = 1",
1564 "INSERT INTO t SELECT 'from stdin'",
1565 ] {
1566 assert!(!refused_in_batch(sql), "{sql}");
1567 }
1568 assert!(refused_in_batch("BEGIN; SET LOCAL a = 1; COMMIT; LISTEN x"));
1569 }
1570
1571 #[test]
1572 fn statements_are_split_outside_quotes() {
1573 let all = |sql| {
1574 let mut s = Statements {
1575 sql,
1576 i: 0,
1577 first_only: false,
1578 };
1579 let mut all = Vec::new();
1580 while let Some(w) = s.next() {
1581 all.push((0..w.len).map(|i| w.get(i).to_owned()).collect::<Vec<_>>());
1582 }
1583 all
1584 };
1585 let s = all("SELECT 'a;b'; SELECT \"x;y\" ; ; /* ; */ -- ;\n VALUES (1)");
1586 assert_eq!(s.len(), 3);
1587 assert_eq!(s[1], ["SELECT", "\""]);
1588 assert_eq!(s[2], ["VALUES"]);
1589 // An unterminated quote swallows the rest, as the server would.
1590 assert_eq!(all("SELECT 'a; SET x = 1").len(), 1);
1591 assert_eq!(all("SELECT $q$ a; SET x $q").len(), 1);
1592 assert_eq!(all("SELECT a$b; SET x = 1")[1], ["SET", "x"]);
1593 // Only the first three words are kept, and FROM STDIN is seen anywhere.
1594 let mut s = Statements {
1595 sql: "copy t (a, b, c, d) from stdin; select 1",
1596 i: 0,
1597 first_only: true,
1598 };
1599 let w = s.next().unwrap();
1600 assert_eq!((w.lead, w.len, w.from_stdin), (Lead::Copy, 3, true));
1601 assert!(s.next().is_none());
1602 }
1603}