Skip to main content

prax_postgres/
pool.rs

1//! Connection pool for PostgreSQL.
2
3use std::sync::Arc;
4use std::time::Duration;
5
6use deadpool_postgres::{Hook, HookError, Manager, ManagerConfig, Pool, RecyclingMethod, Runtime};
7use tokio_postgres::NoTls;
8use tracing::{debug, info, warn};
9
10use crate::config::{PgConfig, redact_url};
11use crate::connection::PgConnection;
12use crate::connector::{Connector, select_connector};
13use crate::error::{PgError, PgResult};
14use crate::statement::PreparedStatementCache;
15
16/// A connection pool for PostgreSQL.
17#[derive(Clone)]
18pub struct PgPool {
19    inner: Pool,
20    config: Arc<PgConfig>,
21    statement_cache: Arc<PreparedStatementCache>,
22}
23
24/// Shows the configuration (password redacted) and the pool status.
25impl std::fmt::Debug for PgPool {
26    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
27        f.debug_struct("PgPool")
28            .field("config", &self.config)
29            .field("status", &self.status())
30            .finish_non_exhaustive()
31    }
32}
33
34impl PgPool {
35    /// Create a new connection pool from configuration.
36    pub async fn new(config: PgConfig) -> PgResult<Self> {
37        Self::with_pool_config(config, PoolConfig::default()).await
38    }
39
40    /// Create a new connection pool with custom pool configuration.
41    pub async fn with_pool_config(config: PgConfig, pool_config: PoolConfig) -> PgResult<Self> {
42        let pg_config = config.to_pg_config();
43
44        let mgr_config = ManagerConfig {
45            recycling_method: pool_config.recycling.to_deadpool(),
46        };
47
48        // Select the TLS connector by ssl_mode (see `select_connector` for the
49        // rules). A TLS-requiring mode without the `tls` feature, or an
50        // unreadable `ssl_root_cert`, fails pool construction here.
51        let mgr = match select_connector(&config)? {
52            Connector::NoTls => Manager::from_config(pg_config, NoTls, mgr_config),
53            #[cfg(feature = "tls")]
54            Connector::Rustls(connector) => Manager::from_config(pg_config, connector, mgr_config),
55        };
56
57        // Build pool - set runtime to tokio for timeout support
58        let mut builder = Pool::builder(mgr).max_size(pool_config.max_connections);
59
60        // Only set timeouts if they are configured
61        if let Some(timeout) = pool_config.connection_timeout {
62            builder = builder
63                .wait_timeout(Some(timeout))
64                .create_timeout(Some(timeout));
65        }
66        // Bounds the recycle check (Verified/Clean round trip) at checkout.
67        // A recycle that times out discards the connection and a new one is
68        // created, so a hung connection cannot stall `get()` forever.
69        if let Some(timeout) = pool_config.recycle_timeout {
70            builder = builder.recycle_timeout(Some(timeout));
71        }
72
73        // Enforce `max_lifetime` and `idle_timeout`: deadpool runs
74        // `pre_recycle` hooks at checkout, and a hook error discards the
75        // object and creates a new one. Connections are therefore retired
76        // lazily, when an aged or idle one is next checked out. Each
77        // connection's lifetime deadline is shortened by a stable
78        // per-connection jitter (up to ~10%) so a batch of connections
79        // created together does not expire together.
80        if let Some(policy) =
81            RetirementPolicy::new(pool_config.max_lifetime, pool_config.idle_timeout)
82        {
83            builder = builder.pre_recycle(Hook::sync_fn(move |_, metrics| {
84                let age = metrics.age();
85                // deadpool records when a connection was last handed out
86                // (`recycled`, else `created`), not when it was returned.
87                let idle = metrics.last_used();
88                let jitter = policy.max_lifetime.map_or(Duration::ZERO, |max_lifetime| {
89                    lifetime_jitter(max_lifetime, &metrics.created)
90                });
91                match policy.check(age, idle, jitter) {
92                    None => Ok(()),
93                    Some(reason) => {
94                        debug!(
95                            age = ?age,
96                            idle = ?idle,
97                            reason = reason.as_str(),
98                            "retiring pooled connection"
99                        );
100                        Err(HookError::message(reason.as_str()))
101                    }
102                }
103            }));
104        }
105
106        // Set runtime for timeout support
107        builder = builder.runtime(Runtime::Tokio1);
108
109        let pool = builder
110            .build()
111            .map_err(|e| PgError::config(format!("failed to create pool: {}", e)))?;
112
113        // deadpool has no native min-connections knob, so pre-establish
114        // `min_connections` on a background task. Acquired connections are
115        // released back to the pool, which retains them (deadpool never
116        // reaps idle connections). Best-effort: pool creation neither
117        // blocks on nor fails because of this warmup.
118        let min_connections = pool_config.min_connections.min(pool_config.max_connections);
119        if min_connections > 0 {
120            let warm_pool = pool.clone();
121            tokio::spawn(async move {
122                let mut held = Vec::with_capacity(min_connections);
123                for _ in 0..min_connections {
124                    match warm_pool.get().await {
125                        Ok(conn) => {
126                            debug!(
127                                established = held.len() + 1,
128                                min_connections = min_connections,
129                                "min_connections warmup established connection"
130                            );
131                            held.push(conn);
132                        }
133                        Err(e) => {
134                            // Operator-visible: the pool is starting below
135                            // its configured minimum.
136                            warn!(
137                                error = %e,
138                                min_connections = min_connections,
139                                established = held.len(),
140                                "min_connections warmup could not acquire connection; \
141                                 pool starts below its configured minimum"
142                            );
143                            break;
144                        }
145                    }
146                }
147                drop(held);
148            });
149        }
150
151        info!(
152            host = %config.host,
153            port = %config.port,
154            database = %config.database,
155            max_connections = %pool_config.max_connections,
156            "PostgreSQL connection pool created"
157        );
158
159        Ok(Self {
160            inner: pool,
161            config: Arc::new(config),
162            statement_cache: Arc::new(PreparedStatementCache::new(
163                pool_config.statement_cache_size,
164            )),
165        })
166    }
167
168    /// Get a connection from the pool.
169    pub async fn get(&self) -> PgResult<PgConnection> {
170        debug!("Acquiring connection from pool");
171        let client = self.inner.get().await?;
172        Ok(PgConnection::new(client, self.statement_cache.clone()))
173    }
174
175    /// Borrow the underlying `deadpool_postgres::Pool`.
176    ///
177    /// Reserved for intra-crate paths that need a raw `Object` (e.g.
178    /// [`crate::engine::PgEngine::transaction`], which pins a single
179    /// connection for the lifetime of an in-flight transaction). The
180    /// standard path is [`PgPool::get`], which returns a
181    /// cache-wrapped [`PgConnection`].
182    pub(crate) fn inner(&self) -> &Pool {
183        &self.inner
184    }
185
186    /// Get the current pool status.
187    pub fn status(&self) -> PoolStatus {
188        let status = self.inner.status();
189        PoolStatus {
190            available: status.available,
191            size: status.size,
192            max_size: status.max_size,
193            waiting: status.waiting,
194        }
195    }
196
197    /// Get the pool configuration.
198    pub fn config(&self) -> &PgConfig {
199        &self.config
200    }
201
202    /// Check if the pool is healthy by attempting to get a connection.
203    pub async fn is_healthy(&self) -> bool {
204        match self.inner.get().await {
205            Ok(client) => {
206                // Try a simple query to verify the connection is actually working
207                client.query_one("SELECT 1", &[]).await.is_ok()
208            }
209            Err(_) => false,
210        }
211    }
212
213    /// Close the pool and all connections.
214    pub fn close(&self) {
215        self.inner.close();
216        info!("PostgreSQL connection pool closed");
217    }
218
219    /// Create a builder for configuring the pool.
220    pub fn builder() -> PgPoolBuilder {
221        PgPoolBuilder::new()
222    }
223
224    /// Warm up the connection pool by pre-establishing connections.
225    ///
226    /// This eliminates the latency of establishing connections on the first queries.
227    /// The `count` parameter specifies how many connections to pre-establish.
228    ///
229    /// # Example
230    ///
231    /// ```rust,ignore
232    /// let pool = PgPool::builder()
233    ///     .url("postgresql://localhost/db")
234    ///     .max_connections(10)
235    ///     .build()
236    ///     .await?;
237    ///
238    /// // Pre-establish 5 connections
239    /// pool.warmup(5).await?;
240    /// ```
241    pub async fn warmup(&self, count: usize) -> PgResult<()> {
242        info!(count = count, "Warming up connection pool");
243
244        let count = count.min(self.inner.status().max_size);
245        let mut connections = Vec::with_capacity(count);
246
247        // Acquire connections to force establishment
248        for i in 0..count {
249            match self.inner.get().await {
250                Ok(conn) => {
251                    // Validate the connection with a simple query
252                    if let Err(e) = conn.query_one("SELECT 1", &[]).await {
253                        debug!(error = %e, "Warmup connection {} failed validation", i);
254                    } else {
255                        debug!("Warmup connection {} established", i);
256                        connections.push(conn);
257                    }
258                }
259                Err(e) => {
260                    debug!(error = %e, "Failed to establish warmup connection {}", i);
261                }
262            }
263        }
264
265        // Connections are returned to pool when dropped
266        let established = connections.len();
267        drop(connections);
268
269        info!(
270            established = established,
271            requested = count,
272            "Connection pool warmup complete"
273        );
274
275        Ok(())
276    }
277
278    /// Warm up with common prepared statements.
279    ///
280    /// This pre-prepares common SQL statements on warmed connections,
281    /// eliminating the prepare latency on first use.
282    pub async fn warmup_with_statements(&self, count: usize, statements: &[&str]) -> PgResult<()> {
283        info!(
284            count = count,
285            statements = statements.len(),
286            "Warming up connection pool with prepared statements"
287        );
288
289        let count = count.min(self.inner.status().max_size);
290        let mut connections = Vec::with_capacity(count);
291
292        for i in 0..count {
293            match self.inner.get().await {
294                Ok(conn) => {
295                    // Pre-prepare all statements
296                    for sql in statements {
297                        if let Err(e) = conn.prepare_cached(sql).await {
298                            debug!(error = %e, sql = %sql, "Failed to prepare statement");
299                        }
300                    }
301                    debug!(
302                        connection = i,
303                        statements = statements.len(),
304                        "Prepared statements on connection"
305                    );
306                    connections.push(conn);
307                }
308                Err(e) => {
309                    debug!(error = %e, "Failed to establish warmup connection {}", i);
310                }
311            }
312        }
313
314        let established = connections.len();
315        drop(connections);
316
317        info!(
318            established = established,
319            "Connection pool warmup with statements complete"
320        );
321
322        Ok(())
323    }
324}
325
326/// Why the pool replaces a connection at checkout instead of handing it out.
327#[derive(Debug, Clone, Copy, PartialEq, Eq)]
328enum Retirement {
329    /// Older than `max_lifetime` (less its jitter).
330    MaxLifetime,
331    /// Not handed out for longer than `idle_timeout`.
332    IdleTimeout,
333}
334
335impl Retirement {
336    fn as_str(self) -> &'static str {
337        match self {
338            Self::MaxLifetime => "max_lifetime exceeded",
339            Self::IdleTimeout => "idle_timeout exceeded",
340        }
341    }
342}
343
344/// The limits the pool's `pre_recycle` hook enforces at checkout.
345#[derive(Debug, Clone, Copy)]
346struct RetirementPolicy {
347    max_lifetime: Option<Duration>,
348    idle_timeout: Option<Duration>,
349}
350
351impl RetirementPolicy {
352    /// `None` when neither limit is set (no hook is needed).
353    fn new(max_lifetime: Option<Duration>, idle_timeout: Option<Duration>) -> Option<Self> {
354        (max_lifetime.is_some() || idle_timeout.is_some()).then_some(Self {
355            max_lifetime,
356            idle_timeout,
357        })
358    }
359
360    /// Whether a connection `age` old, last handed out `idle` ago and with
361    /// lifetime `jitter`, must be replaced. The lifetime is checked first.
362    fn check(&self, age: Duration, idle: Duration, jitter: Duration) -> Option<Retirement> {
363        if let Some(max_lifetime) = self.max_lifetime
364            && age > max_lifetime.saturating_sub(jitter)
365        {
366            return Some(Retirement::MaxLifetime);
367        }
368        if let Some(idle_timeout) = self.idle_timeout
369            && idle > idle_timeout
370        {
371            return Some(Retirement::IdleTimeout);
372        }
373        None
374    }
375}
376
377/// Stable per-connection offset in `[0, max_lifetime / 10)`, derived from the
378/// connection's creation instant so it is identical on every checkout.
379fn lifetime_jitter(max_lifetime: Duration, created: &std::time::Instant) -> Duration {
380    use std::hash::{Hash, Hasher};
381
382    let window = (max_lifetime / 10).as_nanos();
383    if window == 0 {
384        return Duration::ZERO;
385    }
386    let mut hasher = std::collections::hash_map::DefaultHasher::new();
387    created.hash(&mut hasher);
388    let nanos = (hasher.finish() as u128) % window;
389    Duration::from_nanos(nanos as u64)
390}
391
392/// Pool status information.
393#[non_exhaustive]
394#[derive(Debug, Clone)]
395pub struct PoolStatus {
396    /// Number of available (idle) connections.
397    pub available: usize,
398    /// Current total size of the pool.
399    pub size: usize,
400    /// Maximum size of the pool.
401    pub max_size: usize,
402    /// Number of tasks waiting for a connection.
403    pub waiting: usize,
404}
405
406/// How the pool validates a connection when it is checked out again.
407///
408/// None of these methods roll back an open transaction; `Clean` resets
409/// session state but runs inside whatever transaction is still open.
410///
411/// **Session state and multi-tenant / RLS use.** Under `Fast` and `Verified`,
412/// session state (`SET`, `SET ROLE`, `search_path`, custom GUCs such as a
413/// tenant id read by row-level-security policies, advisory locks, temp
414/// tables) persists across checkouts: the next caller of the same physical
415/// connection inherits it. If you rely on such state for isolation, use
416/// [`PgRecycling::Clean`] or scope it with `SET LOCAL` inside a transaction.
417#[non_exhaustive]
418#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
419pub enum PgRecycling {
420    /// Only discard connections that are already closed (default).
421    ///
422    /// Does **not** reset session state; see the type-level warning about
423    /// leaking `SET` / `SET ROLE` / tenant GUCs between checkouts. Prefer
424    /// [`PgRecycling::Clean`] for RLS or tenant-scoped workloads.
425    #[default]
426    Fast,
427    /// Run a trivial query to verify the connection is alive.
428    ///
429    /// The check is bounded by [`PoolConfig::recycle_timeout`]. Session
430    /// state is **not** reset (see the type-level warning).
431    Verified,
432    /// `Verified` plus a session-state reset: closes cursors, resets
433    /// session settings and authorization, `UNLISTEN *`, releases advisory
434    /// locks, and drops temp tables and sequence state. Prepared
435    /// statements are preserved, so Prax's statement cache stays valid.
436    ///
437    /// The check and reset are bounded by [`PoolConfig::recycle_timeout`].
438    /// Recommended for RLS / tenant users.
439    Clean,
440}
441
442impl PgRecycling {
443    pub(crate) fn to_deadpool(self) -> RecyclingMethod {
444        match self {
445            PgRecycling::Fast => RecyclingMethod::Fast,
446            PgRecycling::Verified => RecyclingMethod::Verified,
447            PgRecycling::Clean => RecyclingMethod::Clean,
448        }
449    }
450}
451
452/// Configuration for the connection pool.
453#[non_exhaustive]
454#[derive(Debug, Clone)]
455pub struct PoolConfig {
456    /// Maximum number of connections in the pool.
457    pub max_connections: usize,
458    /// Minimum number of connections to pre-establish and keep alive.
459    ///
460    /// deadpool exposes no minimum-size knob, so these are established by a
461    /// best-effort background warmup when the pool is created; the released
462    /// connections are then retained by the pool.
463    pub min_connections: usize,
464    /// Maximum time to wait for a connection.
465    pub connection_timeout: Option<Duration>,
466    /// Idle timeout: a connection that was not handed out for longer than
467    /// this is discarded and replaced at its next checkout instead of being
468    /// reused (so a connection a server, proxy or NAT may have dropped while
469    /// idle is not handed out).
470    ///
471    /// Enforced at checkout, like [`max_lifetime`](Self::max_lifetime):
472    /// idle connections are not reaped in the background. The idle time is
473    /// measured from when the connection was last **handed out** (deadpool
474    /// does not record when it is returned), so a connection held for
475    /// longer than this is also replaced at its next checkout.
476    /// `Duration::ZERO` replaces every reused connection; `None` disables
477    /// the limit. It does not bound the recycle check; use
478    /// [`PoolConfig::recycle_timeout`] for that. Default: 10 minutes.
479    pub idle_timeout: Option<Duration>,
480    /// Upper bound on the recycle check run when a connection is checked out
481    /// again (the `Verified` / `Clean` round trip).
482    ///
483    /// Mapped to deadpool's `recycle_timeout`. A recycle that exceeds it
484    /// discards the connection and a fresh one is created. `None` disables
485    /// the bound. Default: 5 seconds.
486    pub recycle_timeout: Option<Duration>,
487    /// Maximum lifetime of a connection.
488    ///
489    /// Enforced at checkout: a connection older than this is discarded and
490    /// replaced instead of being handed out. Connections are not reaped
491    /// while idle. Each connection's limit is shortened by a stable jitter of
492    /// up to ~10% so connections created together do not all expire at once.
493    /// `Duration::ZERO` replaces the connection on every checkout, which
494    /// effectively disables pooling.
495    pub max_lifetime: Option<Duration>,
496    /// Recycling method applied when a connection is checked out again.
497    ///
498    /// Defaults to [`PgRecycling::Fast`], which does not reset session state
499    /// (`SET`, `SET ROLE`, tenant GUCs persist across checkouts). Use
500    /// [`PgRecycling::Clean`] for RLS / tenant-scoped workloads.
501    pub recycling: PgRecycling,
502    /// Number of SQL strings tracked for prepared-statement cache metrics.
503    ///
504    /// [`PreparedStatementCache`] records only which SQL strings have been
505    /// seen (hit/miss tracing); actual statement caching is per-connection
506    /// inside tokio-postgres and is not bounded by this value.
507    pub statement_cache_size: usize,
508}
509
510impl Default for PoolConfig {
511    fn default() -> Self {
512        Self {
513            max_connections: 10,
514            min_connections: 1,
515            connection_timeout: Some(Duration::from_secs(30)),
516            idle_timeout: Some(Duration::from_secs(600)), // 10 minutes
517            recycle_timeout: Some(Duration::from_secs(5)),
518            max_lifetime: Some(Duration::from_secs(1800)), // 30 minutes
519            recycling: PgRecycling::Fast,
520            statement_cache_size: 100,
521        }
522    }
523}
524
525/// Builder for creating a connection pool.
526///
527/// `Debug` output redacts passwords (in the config and in the URL).
528#[derive(Default)]
529pub struct PgPoolBuilder {
530    config: Option<PgConfig>,
531    url: Option<String>,
532    pool_config: PoolConfig,
533}
534
535impl std::fmt::Debug for PgPoolBuilder {
536    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
537        f.debug_struct("PgPoolBuilder")
538            .field("config", &self.config)
539            .field("url", &self.url.as_deref().map(|url| redact_url(url, None)))
540            .field("pool_config", &self.pool_config)
541            .finish()
542    }
543}
544
545impl PgPoolBuilder {
546    /// Create a new pool builder.
547    pub fn new() -> Self {
548        Self {
549            config: None,
550            url: None,
551            pool_config: PoolConfig::default(),
552        }
553    }
554
555    /// Set the database URL.
556    pub fn url(mut self, url: impl Into<String>) -> Self {
557        self.url = Some(url.into());
558        self
559    }
560
561    /// Set the configuration.
562    pub fn config(mut self, config: PgConfig) -> Self {
563        self.config = Some(config);
564        self
565    }
566
567    /// Set the maximum number of connections.
568    pub fn max_connections(mut self, n: usize) -> Self {
569        self.pool_config.max_connections = n;
570        self
571    }
572
573    /// Set the minimum number of connections.
574    pub fn min_connections(mut self, n: usize) -> Self {
575        self.pool_config.min_connections = n;
576        self
577    }
578
579    /// Set the connection timeout.
580    pub fn connection_timeout(mut self, timeout: Duration) -> Self {
581        self.pool_config.connection_timeout = Some(timeout);
582        self
583    }
584
585    /// Set the idle timeout enforced at checkout (see
586    /// [`PoolConfig::idle_timeout`]). Pass `None` to disable.
587    pub fn idle_timeout(mut self, timeout: impl Into<Option<Duration>>) -> Self {
588        self.pool_config.idle_timeout = timeout.into();
589        self
590    }
591
592    /// Set the bound on the recycle check at checkout
593    /// (see [`PoolConfig::recycle_timeout`]). Pass `None` to disable.
594    pub fn recycle_timeout(mut self, timeout: impl Into<Option<Duration>>) -> Self {
595        self.pool_config.recycle_timeout = timeout.into();
596        self
597    }
598
599    /// Set the maximum connection lifetime. Pass `None` to disable.
600    pub fn max_lifetime(mut self, lifetime: impl Into<Option<Duration>>) -> Self {
601        self.pool_config.max_lifetime = lifetime.into();
602        self
603    }
604
605    /// Set the recycling method used when a connection is checked out again.
606    pub fn recycling(mut self, recycling: PgRecycling) -> Self {
607        self.pool_config.recycling = recycling;
608        self
609    }
610
611    /// Set the prepared statement cache size.
612    pub fn statement_cache_size(mut self, size: usize) -> Self {
613        self.pool_config.statement_cache_size = size;
614        self
615    }
616
617    /// Build the connection pool.
618    pub async fn build(self) -> PgResult<PgPool> {
619        let config = if let Some(config) = self.config {
620            config
621        } else if let Some(url) = self.url {
622            PgConfig::from_url(url)?
623        } else {
624            return Err(PgError::config("no database URL or config provided"));
625        };
626
627        PgPool::with_pool_config(config, self.pool_config).await
628    }
629}
630
631#[cfg(test)]
632mod tests {
633    use super::*;
634
635    #[test]
636    fn test_pool_config_default() {
637        let config = PoolConfig::default();
638        assert_eq!(config.max_connections, 10);
639        assert_eq!(config.min_connections, 1);
640        assert_eq!(config.statement_cache_size, 100);
641    }
642
643    #[test]
644    fn test_pool_config_default_recycling_is_fast() {
645        assert_eq!(PoolConfig::default().recycling, PgRecycling::Fast);
646    }
647
648    #[test]
649    fn test_pg_recycling_maps_to_deadpool() {
650        assert!(matches!(
651            PgRecycling::Fast.to_deadpool(),
652            RecyclingMethod::Fast
653        ));
654        assert!(matches!(
655            PgRecycling::Verified.to_deadpool(),
656            RecyclingMethod::Verified
657        ));
658        assert!(matches!(
659            PgRecycling::Clean.to_deadpool(),
660            RecyclingMethod::Clean
661        ));
662    }
663
664    #[test]
665    fn test_recycle_timeout_default_and_plumbing() {
666        assert_eq!(
667            PoolConfig::default().recycle_timeout,
668            Some(Duration::from_secs(5))
669        );
670        let b = PgPoolBuilder::new().recycle_timeout(Duration::from_millis(250));
671        assert_eq!(
672            b.pool_config.recycle_timeout,
673            Some(Duration::from_millis(250))
674        );
675        let b = PgPoolBuilder::new().recycle_timeout(None);
676        assert_eq!(b.pool_config.recycle_timeout, None);
677    }
678
679    #[test]
680    fn test_max_lifetime_accepts_duration_and_none() {
681        let b = PgPoolBuilder::new().max_lifetime(Duration::from_secs(60));
682        assert_eq!(b.pool_config.max_lifetime, Some(Duration::from_secs(60)));
683        let b = PgPoolBuilder::new().max_lifetime(None);
684        assert_eq!(b.pool_config.max_lifetime, None);
685    }
686
687    #[test]
688    fn test_lifetime_jitter_bounds_and_stability() {
689        let max = Duration::from_secs(1800);
690        let created = std::time::Instant::now();
691        let j = lifetime_jitter(max, &created);
692        assert!(j < max / 10);
693        assert_eq!(j, lifetime_jitter(max, &created), "stable per connection");
694        assert_eq!(
695            lifetime_jitter(Duration::ZERO, &created),
696            Duration::ZERO,
697            "ZERO guarded"
698        );
699    }
700
701    #[test]
702    fn retirement_checks_lifetime_then_idle_time() {
703        let minutes = |m: u64| Duration::from_secs(m * 60);
704        let policy = RetirementPolicy::new(Some(minutes(30)), Some(minutes(10))).unwrap();
705        let none = Duration::ZERO;
706        assert_eq!(policy.check(minutes(5), minutes(1), none), None);
707        assert_eq!(
708            policy.check(minutes(31), minutes(1), none),
709            Some(Retirement::MaxLifetime)
710        );
711        // The jitter brings the lifetime deadline forward.
712        assert_eq!(
713            policy.check(minutes(29), minutes(1), minutes(2)),
714            Some(Retirement::MaxLifetime)
715        );
716        assert_eq!(
717            policy.check(minutes(20), minutes(11), none),
718            Some(Retirement::IdleTimeout)
719        );
720        // Only idle *longer* than the timeout retires.
721        assert_eq!(policy.check(minutes(20), minutes(10), none), None);
722        // Both exceeded: the lifetime is reported.
723        assert_eq!(
724            policy.check(minutes(31), minutes(11), none),
725            Some(Retirement::MaxLifetime)
726        );
727    }
728
729    #[test]
730    fn retirement_limits_apply_independently() {
731        let secs = Duration::from_secs;
732        assert!(
733            RetirementPolicy::new(None, None).is_none(),
734            "no hook needed"
735        );
736        let idle_only = RetirementPolicy::new(None, Some(secs(60))).unwrap();
737        assert_eq!(idle_only.check(secs(86_400), secs(1), Duration::ZERO), None);
738        assert_eq!(
739            idle_only.check(secs(5), secs(61), Duration::ZERO),
740            Some(Retirement::IdleTimeout)
741        );
742        let lifetime_only = RetirementPolicy::new(Some(secs(60)), None).unwrap();
743        assert_eq!(
744            lifetime_only.check(secs(5), secs(86_400), Duration::ZERO),
745            None
746        );
747        // `Duration::ZERO` idle timeout replaces every reused connection.
748        let zero = RetirementPolicy::new(None, Some(Duration::ZERO)).unwrap();
749        assert_eq!(
750            zero.check(secs(1), Duration::from_nanos(1), Duration::ZERO),
751            Some(Retirement::IdleTimeout)
752        );
753    }
754
755    #[test]
756    fn test_idle_timeout_accepts_duration_and_none() {
757        let b = PgPoolBuilder::new().idle_timeout(Duration::from_secs(60));
758        assert_eq!(b.pool_config.idle_timeout, Some(Duration::from_secs(60)));
759        let b = PgPoolBuilder::new().idle_timeout(None);
760        assert_eq!(b.pool_config.idle_timeout, None);
761    }
762
763    const SENTINEL: &str = "hunter2-sentinel";
764
765    #[test]
766    fn pool_builder_debug_redacts_passwords() {
767        let url = format!("postgres://prax:{SENTINEL}@db.internal/prax");
768        let builder = PgPoolBuilder::new().url(&url);
769        let debug = format!("{builder:?}");
770        assert!(!debug.contains(SENTINEL), "{debug}");
771        assert!(debug.contains("db.internal"), "{debug}");
772
773        let builder = PgPoolBuilder::new().config(PgConfig::from_url(&url).unwrap());
774        let debug = format!("{builder:?}");
775        assert!(!debug.contains(SENTINEL), "{debug}");
776    }
777
778    #[tokio::test]
779    async fn pool_debug_redacts_passwords() {
780        // deadpool connects lazily: nothing listens on port 1.
781        let pool = PgPoolBuilder::new()
782            .url(format!("postgres://prax:{SENTINEL}@127.0.0.1:1/prax"))
783            .min_connections(0)
784            .build()
785            .await
786            .unwrap();
787        let debug = format!("{pool:?}");
788        assert!(!debug.contains(SENTINEL), "{debug}");
789        assert!(debug.contains("127.0.0.1"), "{debug}");
790    }
791
792    #[test]
793    fn test_pool_builder() {
794        let builder = PgPoolBuilder::new()
795            .url("postgresql://localhost/test")
796            .max_connections(20)
797            .statement_cache_size(200);
798
799        assert!(builder.url.is_some());
800        assert_eq!(builder.pool_config.max_connections, 20);
801        assert_eq!(builder.pool_config.statement_cache_size, 200);
802    }
803}