Skip to main content

server/
exhausted_pool.rs

1//! A pool whose only connection is held, so the next acquire can only time out.
2
3use sqlx::pool::PoolConnection;
4use sqlx::postgres::PgPoolOptions;
5use sqlx::{PgPool, Postgres};
6use std::time::Duration;
7
8const WARM_DEADLINE: Duration = Duration::from_secs(60);
9const WARM_POLL: Duration = Duration::from_millis(5);
10
11/// A pool of one connection and the holder of that connection.
12///
13/// The connection is opened by the pool's maintenance task (spawned at once only without
14/// idle and lifetime timers), outside the tiny
15/// `acquire_timeout`, so a loaded host cannot fail the setup.
16///
17/// # Errors
18/// [`sqlx::Error`] when the connection is not idle within `WARM_DEADLINE`.
19pub async fn exhausted(
20    like: &PgPool,
21    acquire_timeout: Duration,
22) -> Result<(PgPool, PoolConnection<Postgres>), sqlx::Error> {
23    let pool = PgPoolOptions::new()
24        .max_connections(1)
25        .min_connections(1)
26        .test_before_acquire(false)
27        .idle_timeout(None)
28        .max_lifetime(None)
29        .acquire_timeout(acquire_timeout)
30        .connect_lazy_with((*like.connect_options()).clone());
31    tokio::time::timeout(WARM_DEADLINE, async {
32        while pool.num_idle() == 0 {
33            tokio::time::sleep(WARM_POLL).await;
34        }
35    })
36    .await
37    .map_err(|_| {
38        sqlx::Error::Protocol(format!(
39            "the pool did not open its connection within {WARM_DEADLINE:?}"
40        ))
41    })?;
42    let held = pool.acquire().await?;
43    Ok((pool, held))
44}