giong_postgres/pool.rs
1//! A pool of connections for one worker thread.
2
3use std::cell::RefCell;
4use std::future::poll_fn;
5use std::ops::{Deref, DerefMut};
6use std::rc::Rc;
7use std::task::{Poll, Waker};
8use std::time::Duration;
9
10use giong::time::Instant;
11
12use crate::client::{Client, Transaction};
13use crate::config::Config;
14use crate::error::{Error, ErrorKind};
15use crate::row::Row;
16use crate::types::ToSql;
17
18/// How long a connection's oldest statement may have been running before
19/// shared statements avoid that connection.
20const STALLED: Duration = Duration::from_millis(5);
21
22/// Connections to one server, for the tasks of one worker thread.
23///
24/// Make one pool per worker, inside [`giong::Runtime::run`]: nothing is
25/// shared between threads, so nothing is locked.
26///
27/// ```no_run
28/// use giong_postgres::{Config, Pool};
29///
30/// fn main() -> std::io::Result<()> {
31/// let config = Config::from_url("postgres://app:secret@db.internal/shop")?;
32/// giong::Builder::new().build()?.run(move |_worker| {
33/// let pool = Pool::new(config.clone(), 4);
34/// async move {
35/// let row = pool.query_one("SELECT count(*) FROM orders", &[]).await.unwrap();
36/// let n: i64 = row.get(0).unwrap();
37/// println!("{n} orders");
38/// }
39/// })
40/// }
41/// ```
42///
43/// [`query`](Self::query) and the other statement methods do not take a
44/// connection for themselves: they run on the least busy connection, beside
45/// statements from other tasks (pipelining), and the pool opens another
46/// connection, up to its maximum, when every open one is busy. That is the
47/// fast path for statements that stand alone. On one connection the server
48/// answers in order, so a statement waits for those sent before it; the pool
49/// steers new statements away from a connection whose oldest statement has
50/// been running for more than 5 ms. Run statements known to be slow (reports,
51/// migrations) on a connection of their own, from [`get`](Self::get).
52///
53/// **How many connections.** Because statements pipeline, a few connections
54/// keep the server busy: start with the server's cores, shared among the
55/// workers' pools. More than that adds no throughput and raises tail latency,
56/// since a backend waiting for a core holds up every statement queued on its
57/// connection. Statements that wait on disk or on locks need more.
58///
59/// [`get`](Self::get) takes a connection for one task alone, for a
60/// transaction or for session settings. While it is out, no shared statement
61/// runs on it. It comes back when the [`PooledClient`] is dropped; if a
62/// transaction was left open, it is rolled back first.
63///
64/// Connections the server closed, or that broke, are left behind as soon as
65/// that is noticed, which is when it happens: each connection is read
66/// continuously.
67#[derive(Clone)]
68pub struct Pool {
69 inner: Rc<Inner>,
70}
71
72struct Inner {
73 config: Config,
74 max_size: usize,
75 wait_timeout: Duration,
76 state: RefCell<State>,
77}
78
79#[derive(Default)]
80struct State {
81 /// Open connections that are not taken.
82 shared: Vec<Rc<Client>>,
83 taken: usize,
84 connecting: usize,
85 waiting: usize,
86 waiters: Vec<Waker>,
87 opened: u64,
88 connect_errors: u64,
89 timeouts: u64,
90}
91
92/// What a pool is doing, from [`Pool::stats`].
93#[derive(Clone, Copy, Debug, PartialEq, Eq)]
94#[non_exhaustive]
95pub struct PoolStats {
96 /// Open connections, taken or not.
97 pub connections: usize,
98 /// Connections taken with [`Pool::get`].
99 pub taken: usize,
100 /// Connections being opened.
101 pub connecting: usize,
102 /// Requests sent on the shared connections and not answered yet.
103 pub in_flight: usize,
104 /// Tasks waiting for a connection.
105 pub waiting: usize,
106 /// Connections opened since the pool was made.
107 pub opened: u64,
108 /// Attempts to open a connection that failed.
109 pub connect_errors: u64,
110 /// Waits that ended with [`ErrorKind::PoolTimeout`].
111 pub timeouts: u64,
112}
113
114enum Decision<T> {
115 Ready(T),
116 Connect,
117 Wait,
118}
119
120/// Undoes the `connecting` count however the attempt ends.
121struct Connecting<'a>(&'a Pool);
122
123impl Drop for Connecting<'_> {
124 fn drop(&mut self) {
125 self.0.inner.state.borrow_mut().connecting -= 1;
126 self.0.notify();
127 }
128}
129
130/// Undoes the `waiting` count however the wait ends.
131struct Waiting<'a>(&'a Pool);
132
133impl Drop for Waiting<'_> {
134 fn drop(&mut self) {
135 self.0.inner.state.borrow_mut().waiting -= 1;
136 }
137}
138
139impl Pool {
140 /// A pool of at most `max_size` connections to the server in `config`.
141 /// Connections are opened when needed, not here.
142 ///
143 /// Size it from the server's `max_connections`: the pools of all workers
144 /// of all processes together must stay below it.
145 ///
146 /// # Panics
147 ///
148 /// Panics if `max_size` is 0.
149 pub fn new(config: Config, max_size: usize) -> Self {
150 assert!(
151 max_size > 0,
152 "a pool needs room for at least one connection"
153 );
154 Self {
155 inner: Rc::new(Inner {
156 config,
157 max_size,
158 wait_timeout: Duration::from_secs(5),
159 state: RefCell::default(),
160 }),
161 }
162 }
163
164 /// The longest a task waits for a connection when all `max_size` are
165 /// taken: 5 seconds by default. A longer wait fails with
166 /// [`ErrorKind::PoolTimeout`].
167 ///
168 /// # Panics
169 ///
170 /// Panics if other clones of this pool exist; set it right after
171 /// [`new`](Self::new).
172 pub fn wait_timeout(mut self, timeout: Duration) -> Self {
173 Rc::get_mut(&mut self.inner)
174 .expect("set the wait timeout before cloning the pool")
175 .wait_timeout = timeout;
176 self
177 }
178
179 /// Runs a statement on a shared connection and returns its rows; see
180 /// [`Client::query`].
181 pub async fn query(&self, sql: &str, params: &[&dyn ToSql]) -> Result<Vec<Row>, Error> {
182 let client = self.shared().await?;
183 let result = client.query(sql, params).await;
184 self.release(client);
185 result
186 }
187
188 /// Runs a statement that returns exactly one row; see
189 /// [`Client::query_one`].
190 pub async fn query_one(&self, sql: &str, params: &[&dyn ToSql]) -> Result<Row, Error> {
191 let client = self.shared().await?;
192 let result = client.query_one(sql, params).await;
193 self.release(client);
194 result
195 }
196
197 /// Runs a statement that returns at most one row; see
198 /// [`Client::query_opt`].
199 pub async fn query_opt(&self, sql: &str, params: &[&dyn ToSql]) -> Result<Option<Row>, Error> {
200 let client = self.shared().await?;
201 let result = client.query_opt(sql, params).await;
202 self.release(client);
203 result
204 }
205
206 /// Runs a statement and returns the number of rows it changed; see
207 /// [`Client::execute`].
208 pub async fn execute(&self, sql: &str, params: &[&dyn ToSql]) -> Result<u64, Error> {
209 let client = self.shared().await?;
210 let result = client.execute(sql, params).await;
211 self.release(client);
212 result
213 }
214
215 /// Runs several statements without parameters; see
216 /// [`Client::batch_execute`].
217 pub async fn batch_execute(&self, sql: &str) -> Result<(), Error> {
218 let client = self.shared().await?;
219 let result = client.batch_execute(sql).await;
220 self.release(client);
221 result
222 }
223
224 /// Takes a connection for this task alone, for a transaction or session
225 /// settings:
226 ///
227 /// ```no_run
228 /// # async fn f(pool: &giong_postgres::Pool) -> Result<(), giong_postgres::Error> {
229 /// let mut conn = pool.get().await?;
230 /// let tx = conn.transaction().await?;
231 /// tx.execute("INSERT INTO audit (what) VALUES ($1)", &[&"signup"]).await?;
232 /// tx.commit().await?;
233 /// # Ok(()) }
234 /// ```
235 ///
236 /// Waits up to the [wait timeout](Self::wait_timeout) when every
237 /// connection is taken or busy and the pool is full.
238 pub async fn get(&self) -> Result<PooledClient, Error> {
239 let client = self
240 .acquire(|st, max| {
241 let idle = st
242 .shared
243 .iter()
244 .position(|c| Rc::strong_count(c) == 1 && c.in_flight() == 0);
245 if let Some(i) = idle {
246 let c = st.shared.swap_remove(i);
247 st.taken += 1;
248 return match Rc::try_unwrap(c) {
249 Ok(client) => Decision::Ready(client),
250 Err(_) => unreachable!("checked: nobody else holds it"),
251 };
252 }
253 if st.shared.len() + st.taken + st.connecting < max {
254 st.connecting += 1;
255 Decision::Connect
256 } else {
257 Decision::Wait
258 }
259 })
260 .await?;
261 let client = match client {
262 Ok(c) => c,
263 Err(new) => {
264 self.inner.state.borrow_mut().taken += 1;
265 new
266 }
267 };
268 Ok(PooledClient {
269 client: Some(client),
270 pool: self.clone(),
271 })
272 }
273
274 /// The pool's current state and counters.
275 pub fn stats(&self) -> PoolStats {
276 let st = self.inner.state.borrow();
277 PoolStats {
278 connections: st.shared.len() + st.taken,
279 taken: st.taken,
280 connecting: st.connecting,
281 in_flight: st.shared.iter().map(|c| c.in_flight()).sum(),
282 waiting: st.waiting,
283 opened: st.opened,
284 connect_errors: st.connect_errors,
285 timeouts: st.timeouts,
286 }
287 }
288
289 /// The least busy shared connection, or a new one if every open one is
290 /// busy and there is room.
291 ///
292 /// A connection whose oldest statement has been running for more than
293 /// [`STALLED`] is passed over while another will do: statements queue
294 /// behind it in order, so a slow one would hold up everything sent after
295 /// it on that connection.
296 async fn shared(&self) -> Result<Rc<Client>, Error> {
297 let client = self
298 .acquire(|st, max| {
299 let now = Instant::now();
300 let room = st.shared.len() + st.taken + st.connecting < max;
301 // Busy means used by other tasks right now.
302 let best = st
303 .shared
304 .iter()
305 .filter(|c| c.waiting_for(now) <= STALLED)
306 .min_by_key(|c| Rc::strong_count(c))
307 .cloned();
308 match best {
309 Some(c) if Rc::strong_count(&c) == 2 || !room => Decision::Ready(c),
310 _ if room => {
311 st.connecting += 1;
312 Decision::Connect
313 }
314 // Every connection is stalled and the pool is full: the
315 // one whose oldest statement has waited least, which is
316 // the one most likely to be moving.
317 _ => match st.shared.iter().min_by_key(|c| c.waiting_for(now)) {
318 Some(c) => Decision::Ready(c.clone()),
319 None => Decision::Wait,
320 },
321 }
322 })
323 .await?;
324 Ok(match client {
325 Ok(c) => c,
326 Err(new) => {
327 let c = Rc::new(new);
328 self.inner.state.borrow_mut().shared.push(c.clone());
329 c
330 }
331 })
332 }
333
334 fn release(&self, client: Rc<Client>) {
335 drop(client);
336 self.notify();
337 }
338
339 /// Wakes every task waiting for a connection, to look again.
340 fn notify(&self) {
341 let waiters = std::mem::take(&mut self.inner.state.borrow_mut().waiters);
342 for w in waiters {
343 w.wake();
344 }
345 }
346
347 /// Runs `decide` until it hands out a connection (`Ok`), or a new one is
348 /// opened for the caller (`Err(client)`), or the wait times out.
349 async fn acquire<T>(
350 &self,
351 mut decide: impl FnMut(&mut State, usize) -> Decision<T>,
352 ) -> Result<Result<T, Client>, Error> {
353 let deadline = Instant::now() + self.inner.wait_timeout;
354 loop {
355 let decision = {
356 let mut st = self.inner.state.borrow_mut();
357 st.shared.retain(|c| !c.is_closed());
358 decide(&mut st, self.inner.max_size)
359 };
360 match decision {
361 Decision::Ready(c) => return Ok(Ok(c)),
362 Decision::Connect => {
363 let _connecting = Connecting(self);
364 let result = Client::connect(&self.inner.config).await;
365 let mut st = self.inner.state.borrow_mut();
366 return match result {
367 Ok(client) => {
368 st.opened += 1;
369 Ok(Err(client))
370 }
371 Err(e) => {
372 st.connect_errors += 1;
373 Err(e)
374 }
375 };
376 }
377 Decision::Wait => {
378 self.inner.state.borrow_mut().waiting += 1;
379 let _waiting = Waiting(self);
380 let mut registered = false;
381 let woken = poll_fn(|cx| {
382 if registered {
383 return Poll::Ready(());
384 }
385 registered = true;
386 self.inner
387 .state
388 .borrow_mut()
389 .waiters
390 .push(cx.waker().clone());
391 Poll::Pending
392 });
393 let left = deadline.saturating_duration_since(Instant::now());
394 if giong::time::timeout(left, woken).await.is_err() {
395 let mut st = self.inner.state.borrow_mut();
396 st.timeouts += 1;
397 return Err(Error::new(
398 ErrorKind::PoolTimeout,
399 format!(
400 "no connection to {} became free within {:?}: all {} are taken or \
401 busy. Raise the pool's max_size (the server's max_connections \
402 allowing), look for transactions held open too long, or raise \
403 Pool::wait_timeout",
404 self.inner.config.target(),
405 self.inner.wait_timeout,
406 self.inner.max_size
407 ),
408 ));
409 }
410 }
411 }
412 }
413 }
414}
415
416impl std::fmt::Debug for Pool {
417 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
418 f.debug_struct("Pool")
419 .field("server", &self.inner.config.target())
420 .field("max_size", &self.inner.max_size)
421 .field("stats", &self.stats())
422 .finish()
423 }
424}
425
426/// A connection taken from a [`Pool`] with [`Pool::get`]. It dereferences to
427/// the [`Client`], and goes back to the pool when dropped.
428pub struct PooledClient {
429 client: Option<Client>,
430 pool: Pool,
431}
432
433impl PooledClient {
434 /// Starts a transaction; see [`Client::transaction`].
435 pub async fn transaction(&mut self) -> Result<Transaction<'_>, Error> {
436 self.deref_mut().transaction().await
437 }
438}
439
440impl Deref for PooledClient {
441 type Target = Client;
442
443 fn deref(&self) -> &Client {
444 self.client.as_ref().expect("present until dropped")
445 }
446}
447
448impl DerefMut for PooledClient {
449 fn deref_mut(&mut self) -> &mut Client {
450 self.client.as_mut().expect("present until dropped")
451 }
452}
453
454impl Drop for PooledClient {
455 fn drop(&mut self) {
456 let client = self.client.take().expect("present until dropped");
457 {
458 let mut st = self.pool.inner.state.borrow_mut();
459 st.taken -= 1;
460 if !client.is_closed() {
461 // Queued ahead of anything a shared statement sends next.
462 if client.in_transaction() {
463 client.send_and_forget("ROLLBACK");
464 }
465 st.shared.push(Rc::new(client));
466 }
467 }
468 self.pool.notify();
469 }
470}
471
472impl std::fmt::Debug for PooledClient {
473 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
474 f.debug_tuple("PooledClient").field(&**self).finish()
475 }
476}