1#![allow(clippy::result_large_err)]
4
5use std::sync::atomic::{AtomicBool, Ordering};
6use std::sync::{Arc, Mutex};
7use std::time::Duration;
8
9use rustls::ClientConfig;
10use tokio::sync::{Semaphore, SemaphorePermit};
11
12use crate::pg::wire::{AuthPolicy, ConnectConfig, Connection, WireError};
13use crate::typeinfo::TypeCache;
14
15pub struct Pool {
17 name: String,
19 connect: ConnectConfig,
20 auth: AuthPolicy,
21 tls: Option<Arc<ClientConfig>>,
23 permits: Semaphore,
24 idle: Mutex<Vec<Connection>>,
25 types: TypeCache,
26 closed: AtomicBool,
27 superuser_checked: AtomicBool,
29}
30
31impl Pool {
32 pub fn new(connect: ConnectConfig, max_connections: usize) -> Pool {
34 Pool::with_auth(connect, max_connections, AuthPolicy::default())
35 }
36
37 pub fn with_auth(connect: ConnectConfig, max_connections: usize, auth: AuthPolicy) -> Pool {
39 Pool {
40 name: String::new(),
41 connect,
42 auth,
43 tls: None,
44 permits: Semaphore::new(max_connections),
45 idle: Mutex::new(Vec::new()),
46 types: TypeCache::new(),
47 closed: AtomicBool::new(false),
48 superuser_checked: AtomicBool::new(false),
49 }
50 }
51
52 pub fn with_name(mut self, name: &str) -> Pool {
54 self.name = name.to_owned();
55 self
56 }
57
58 pub fn with_tls(mut self, tls: Option<Arc<ClientConfig>>) -> Pool {
60 self.tls = tls;
61 self
62 }
63
64 pub async fn checkout(&self, wait: Duration) -> Result<Lease<'_>, PoolError> {
66 let permit = self.acquire(wait).await?;
67 let idle = self.idle.lock().unwrap_or_else(|e| e.into_inner()).pop();
68 match idle {
69 Some(conn) => Ok(Lease {
70 pool: self,
71 _permit: permit,
72 conn,
73 reused: true,
74 }),
75 None => self.open(permit).await,
76 }
77 }
78
79 pub(crate) async fn checkout_fresh(&self, wait: Duration) -> Result<Lease<'_>, PoolError> {
81 let permit = self.acquire(wait).await?;
82 self.open(permit).await
83 }
84
85 pub fn type_cache(&self) -> &TypeCache {
86 &self.types
87 }
88
89 pub fn idle_count(&self) -> usize {
90 self.idle.lock().unwrap_or_else(|e| e.into_inner()).len()
91 }
92
93 pub async fn close(&self) {
95 self.closed.store(true, Ordering::SeqCst);
96 self.permits.close();
97 let idle = std::mem::take(&mut *self.idle.lock().unwrap_or_else(|e| e.into_inner()));
98 for conn in idle {
99 conn.close().await;
100 }
101 }
102
103 async fn acquire(&self, wait: Duration) -> Result<SemaphorePermit<'_>, PoolError> {
104 if self.closed.load(Ordering::SeqCst) {
105 return Err(PoolError::Closed);
106 }
107 match tokio::time::timeout(wait, self.permits.acquire()).await {
108 Err(_elapsed) => Err(PoolError::Busy),
109 Ok(Err(_closed)) => Err(PoolError::Closed),
110 Ok(Ok(permit)) => Ok(permit),
111 }
112 }
113
114 async fn open<'a>(&'a self, permit: SemaphorePermit<'a>) -> Result<Lease<'a>, PoolError> {
115 let conn =
116 match Connection::connect_with_tls(&self.connect, &self.auth, self.tls.clone()).await {
117 Ok(conn) => {
118 self.check_superuser_once(&conn);
119 conn
120 }
121 Err(error) => {
122 let reason = connect_failure_text(&error);
123 tracing::warn!(
124 connection = %self.name,
125 host = %self.connect.host,
126 port = self.connect.port,
127 reason = %crate::scrub::scrub(&reason),
128 error = %crate::scrub::scrub(&log_cause(&error, &self.connect.user)),
129 "connection failed"
130 );
131 return Err(PoolError::Connect(reason));
132 }
133 };
134 Ok(Lease {
135 pool: self,
136 _permit: permit,
137 conn,
138 reused: false,
139 })
140 }
141
142 fn check_superuser_once(&self, conn: &Connection) {
144 if self.superuser_checked.swap(true, Ordering::SeqCst) {
145 return;
146 }
147 if conn.parameter("is_superuser") == Some("on") {
148 tracing::warn!(
149 "database \"{}\": the role is a superuser; the read-only transaction is then the only barrier against the functions it may call. Use a least-privilege role.",
150 self.name
151 );
152 }
153 }
154
155 fn give_back(&self, conn: Connection) {
157 let mut idle = self.idle.lock().unwrap_or_else(|e| e.into_inner());
158 if !self.closed.load(Ordering::SeqCst) {
159 idle.push(conn);
160 }
161 }
162}
163
164pub struct Lease<'a> {
166 pool: &'a Pool,
167 _permit: SemaphorePermit<'a>,
168 conn: Connection,
169 reused: bool,
170}
171
172impl Lease<'_> {
173 pub fn conn(&mut self) -> &mut Connection {
174 &mut self.conn
175 }
176
177 pub(crate) fn reused(&self) -> bool {
179 self.reused
180 }
181
182 pub fn release(self, clean: bool) {
184 let Lease {
185 pool,
186 _permit,
187 conn,
188 reused: _,
189 } = self;
190 if clean && !conn.is_poisoned() {
191 pool.give_back(conn);
192 }
193 }
194}
195
196#[derive(Debug, thiserror::Error)]
197pub enum PoolError {
198 #[error("all connections are busy")]
199 Busy,
200 #[error("the pool is closed")]
201 Closed,
202 #[error("{0}")]
204 Connect(String),
205}
206
207fn log_cause(error: &WireError, user: &str) -> String {
210 match error {
211 WireError::Db(db) if !user.is_empty() => format!(
212 "{} (SQLSTATE {})",
213 db.message.replace(user, "<user>"),
214 db.code
215 ),
216 WireError::Db(db) => format!("{} (SQLSTATE {})", db.message, db.code),
217 other => other.to_string(),
218 }
219}
220
221fn connect_failure_text(error: &WireError) -> String {
223 match error {
224 WireError::Auth(_) => "authentication failed".to_owned(),
225 WireError::Db(db) => match db.code.as_str() {
226 code if code.starts_with("28") => "authentication failed".to_owned(),
227 "3D000" => "the database does not exist".to_owned(),
228 "53300" => "too many connections".to_owned(),
229 code => format!("the server refused the connection (SQLSTATE {code})"),
230 },
231 WireError::Io(_) => "cannot connect to the server".to_owned(),
232 WireError::Tls(_) => "TLS negotiation failed".to_owned(),
233 WireError::Timeout => "connection timed out".to_owned(),
234 WireError::Protocol(_) | WireError::Refused(_) => {
235 "unexpected reply from the server".to_owned()
236 }
237 }
238}