halephant_core/pool/
mod.rs1#![cfg_attr(test, allow(clippy::unwrap_used))]
2mod candidates;
3mod checkout;
4pub mod prepared;
5mod refill;
6pub mod types;
7mod wait;
8
9pub use types::{ConnGuard, Routing};
10
11use std::collections::HashMap;
12use std::sync::Arc;
13use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
14use std::time::Instant;
15
16use arc_swap::ArcSwap;
17use parking_lot::Mutex;
18use tracing::debug;
19
20use crate::auth::pgpass::Pgpass;
21use crate::config::Config;
22use crate::errors::ResolveError;
23use crate::o11y;
24use crate::topology;
25
26pub struct PoolManager {
34 pub(in crate::pool) inner: Mutex<types::Inner>,
35 pub(in crate::pool) config: Arc<ArcSwap<Config>>,
41 pub(in crate::pool) topology: Arc<topology::TopologyManager>,
42 pub(in crate::pool) pgpass: Arc<Pgpass>,
43 pub(in crate::pool) replica_rr: AtomicUsize,
45 pub(crate) stmt_store: Mutex<prepared::StatementStore>,
47 pub(in crate::pool) shutting_down: AtomicBool,
51}
52
53impl PoolManager {
58 pub fn new(
59 config: Arc<ArcSwap<Config>>,
60 topology: Arc<topology::TopologyManager>,
61 pgpass: Arc<Pgpass>,
62 ) -> Self {
63 Self {
64 inner: Mutex::new(types::Inner {
65 pools: HashMap::new(),
66 waits: HashMap::new(),
67 }),
68 config,
69 topology,
70 pgpass,
71 replica_rr: AtomicUsize::new(0),
72 stmt_store: Mutex::new(prepared::StatementStore::new()),
73 shutting_down: AtomicBool::new(false),
74 }
75 }
76
77 pub fn config(&self) -> &Arc<ArcSwap<Config>> {
82 &self.config
83 }
84
85 #[doc(hidden)]
87 pub fn has_prepared(&self, canon: &str) -> bool {
88 self.stmt_store.lock().get(canon).is_some()
89 }
90
91 pub fn pgpass(&self) -> &Pgpass {
93 &self.pgpass
94 }
95
96 pub fn shutdown(&self) {
104 self.shutting_down.store(true, Ordering::Release);
105 self.wake_all_waiters();
106 }
107
108 pub fn resolve(&self, database: &str, routing: Routing) -> Result<String, ResolveError> {
114 let cfg = self.config.load_full();
115 let (cluster_name, _, _) =
116 cfg.find_pool(database)
117 .ok_or_else(|| ResolveError::UnknownDatabase {
118 database: database.to_owned(),
119 })?;
120
121 match routing {
122 Routing::Primary => {
123 self.topology
124 .primary(cluster_name)
125 .ok_or_else(|| ResolveError::NoPrimary {
126 cluster: cluster_name.to_owned(),
127 })
128 }
129 Routing::Replica => {
130 let replicas = self.topology.replicas(cluster_name);
131 if replicas.is_empty() {
132 return Err(ResolveError::NoReplica {
133 cluster: cluster_name.to_owned(),
134 });
135 }
136 let idx = self.replica_rr.load(Ordering::Relaxed) % replicas.len();
143 Ok(replicas[idx].clone())
144 }
145 }
146 }
147
148 pub(in crate::pool) fn lookup_password(
151 &self,
152 addr: &str,
153 database: &str,
154 user: &str,
155 ) -> Option<String> {
156 self.pgpass
157 .lookup_addr(addr, database, user)
158 .map(str::to_owned)
159 }
160
161 pub fn drain_node(&self, node: &str) {
164 let drained = {
165 let mut inner = self.inner.lock();
166 let mut drained = 0u32;
167 for (key, pool) in &mut inner.pools {
168 if key.node == node {
169 drained += pool.idle.len() as u32;
170 pool.idle.clear();
171 }
172 }
173 drained
174 };
175 if drained > 0 {
176 debug!(node, drained, "drained idle connections for node");
177 }
178 self.wake_all_waiters();
179 }
180
181 pub fn drain_all(&self) {
182 let mut inner = self.inner.lock();
183 let mut drained = 0u32;
184 for pool in inner.pools.values_mut() {
185 drained += pool.idle.len() as u32;
186 pool.idle.clear();
187 }
188 if drained > 0 {
189 debug!(drained, "drained all idle connections for shutdown");
190 }
191 }
192
193 pub fn pool_stats(&self) -> Vec<(o11y::metrics::PoolKeyInfo, o11y::metrics::PoolStats)> {
195 let inner = self.inner.lock();
196 inner
197 .pools
198 .iter()
199 .map(|(key, pool)| {
200 (
201 o11y::metrics::PoolKeyInfo {
202 node: key.node.clone(),
203 database: key.database.clone(),
204 user: key.user.clone(),
205 },
206 o11y::metrics::PoolStats {
207 active: pool.active.len() as u32,
208 idle: pool.idle.len() as u32,
209 resetting: pool.resetting.len() as u32,
210 },
211 )
212 })
213 .collect()
214 }
215
216 #[must_use]
219 pub fn queue_stats(&self) -> Vec<o11y::metrics::QueueInfo> {
220 let now = Instant::now();
221 let inner = self.inner.lock();
222 let mut result = Vec::new();
223 for (key, queue) in &inner.waits {
224 let mut per_user: HashMap<&str, (u32, Instant)> = HashMap::new();
226 for waiter in &queue.waiters {
227 let entry = per_user
228 .entry(&waiter.user)
229 .or_insert((0, waiter.enqueued_at));
230 entry.0 += 1;
231 if waiter.enqueued_at < entry.1 {
232 entry.1 = waiter.enqueued_at;
233 }
234 }
235 for (user, (depth, oldest)) in per_user {
236 result.push(o11y::metrics::QueueInfo {
237 database: key.database.clone(),
238 user: user.to_owned(),
239 role: key.role,
240 depth,
241 oldest_wait_secs: now.saturating_duration_since(oldest).as_secs_f64(),
242 });
243 }
244 }
245 result
246 }
247
248 pub fn pool_limits(&self) -> Vec<o11y::metrics::PoolLimits> {
250 let cfg = self.config.load_full();
251 cfg.cluster
252 .values()
253 .flat_map(|cluster| {
254 cluster
255 .pool
256 .iter()
257 .map(|(db_name, pool)| o11y::metrics::PoolLimits {
258 database: pool.database_name(db_name).to_owned(),
259 max_primary: pool.max_connections.primary,
260 max_replica: pool.max_connections.replica,
261 })
262 })
263 .collect()
264 }
265}