1use 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#[derive(Clone)]
18pub struct PgPool {
19 inner: Pool,
20 config: Arc<PgConfig>,
21 statement_cache: Arc<PreparedStatementCache>,
22}
23
24impl 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 pub async fn new(config: PgConfig) -> PgResult<Self> {
37 Self::with_pool_config(config, PoolConfig::default()).await
38 }
39
40 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 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 let mut builder = Pool::builder(mgr).max_size(pool_config.max_connections);
59
60 if let Some(timeout) = pool_config.connection_timeout {
62 builder = builder
63 .wait_timeout(Some(timeout))
64 .create_timeout(Some(timeout));
65 }
66 if let Some(timeout) = pool_config.recycle_timeout {
70 builder = builder.recycle_timeout(Some(timeout));
71 }
72
73 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 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 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 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 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 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 pub(crate) fn inner(&self) -> &Pool {
183 &self.inner
184 }
185
186 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 pub fn config(&self) -> &PgConfig {
199 &self.config
200 }
201
202 pub async fn is_healthy(&self) -> bool {
204 match self.inner.get().await {
205 Ok(client) => {
206 client.query_one("SELECT 1", &[]).await.is_ok()
208 }
209 Err(_) => false,
210 }
211 }
212
213 pub fn close(&self) {
215 self.inner.close();
216 info!("PostgreSQL connection pool closed");
217 }
218
219 pub fn builder() -> PgPoolBuilder {
221 PgPoolBuilder::new()
222 }
223
224 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 for i in 0..count {
249 match self.inner.get().await {
250 Ok(conn) => {
251 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 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 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 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#[derive(Debug, Clone, Copy, PartialEq, Eq)]
328enum Retirement {
329 MaxLifetime,
331 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#[derive(Debug, Clone, Copy)]
346struct RetirementPolicy {
347 max_lifetime: Option<Duration>,
348 idle_timeout: Option<Duration>,
349}
350
351impl RetirementPolicy {
352 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 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
377fn 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#[non_exhaustive]
394#[derive(Debug, Clone)]
395pub struct PoolStatus {
396 pub available: usize,
398 pub size: usize,
400 pub max_size: usize,
402 pub waiting: usize,
404}
405
406#[non_exhaustive]
418#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
419pub enum PgRecycling {
420 #[default]
426 Fast,
427 Verified,
432 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#[non_exhaustive]
454#[derive(Debug, Clone)]
455pub struct PoolConfig {
456 pub max_connections: usize,
458 pub min_connections: usize,
464 pub connection_timeout: Option<Duration>,
466 pub idle_timeout: Option<Duration>,
480 pub recycle_timeout: Option<Duration>,
487 pub max_lifetime: Option<Duration>,
496 pub recycling: PgRecycling,
502 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)), recycle_timeout: Some(Duration::from_secs(5)),
518 max_lifetime: Some(Duration::from_secs(1800)), recycling: PgRecycling::Fast,
520 statement_cache_size: 100,
521 }
522 }
523}
524
525#[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 pub fn new() -> Self {
548 Self {
549 config: None,
550 url: None,
551 pool_config: PoolConfig::default(),
552 }
553 }
554
555 pub fn url(mut self, url: impl Into<String>) -> Self {
557 self.url = Some(url.into());
558 self
559 }
560
561 pub fn config(mut self, config: PgConfig) -> Self {
563 self.config = Some(config);
564 self
565 }
566
567 pub fn max_connections(mut self, n: usize) -> Self {
569 self.pool_config.max_connections = n;
570 self
571 }
572
573 pub fn min_connections(mut self, n: usize) -> Self {
575 self.pool_config.min_connections = n;
576 self
577 }
578
579 pub fn connection_timeout(mut self, timeout: Duration) -> Self {
581 self.pool_config.connection_timeout = Some(timeout);
582 self
583 }
584
585 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 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 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 pub fn recycling(mut self, recycling: PgRecycling) -> Self {
607 self.pool_config.recycling = recycling;
608 self
609 }
610
611 pub fn statement_cache_size(mut self, size: usize) -> Self {
613 self.pool_config.statement_cache_size = size;
614 self
615 }
616
617 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 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 assert_eq!(policy.check(minutes(20), minutes(10), none), None);
722 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 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 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}