1
//! A pool whose only connection is held, so the next acquire can only time out.
2

            
3
use sqlx::pool::PoolConnection;
4
use sqlx::postgres::PgPoolOptions;
5
use sqlx::{PgPool, Postgres};
6
use std::time::Duration;
7

            
8
const WARM_DEADLINE: Duration = Duration::from_secs(60);
9
const 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`.
19
366
pub async fn exhausted(
20
366
    like: &PgPool,
21
366
    acquire_timeout: Duration,
22
366
) -> Result<(PgPool, PoolConnection<Postgres>), sqlx::Error> {
23
366
    let pool = PgPoolOptions::new()
24
366
        .max_connections(1)
25
366
        .min_connections(1)
26
366
        .test_before_acquire(false)
27
366
        .idle_timeout(None)
28
366
        .max_lifetime(None)
29
366
        .acquire_timeout(acquire_timeout)
30
366
        .connect_lazy_with((*like.connect_options()).clone());
31
366
    tokio::time::timeout(WARM_DEADLINE, async {
32
733
        while pool.num_idle() == 0 {
33
367
            tokio::time::sleep(WARM_POLL).await;
34
        }
35
366
    })
36
366
    .await
37
    .map_err(|_| {
38
        sqlx::Error::Protocol(format!(
39
            "the pool did not open its connection within {WARM_DEADLINE:?}"
40
        ))
41
    })?;
42
366
    let held = pool.acquire().await?;
43
366
    Ok((pool, held))
44
366
}