halephant_core/config/cluster/pool/
mod.rs1pub mod user;
2
3use std::collections::HashMap;
4use std::time::Duration;
5
6use serde::Deserialize;
7
8use crate::errors;
9
10#[derive(Debug, Deserialize)]
11pub struct PoolConfig {
12 pub database: Option<String>,
14
15 #[serde(default)]
16 pub mode: PoolMode,
17
18 pub listen_mode: Option<ListenMode>,
20
21 #[serde(default = "default_pool_max_connections")]
22 pub max_connections: ConnectionLimits,
23
24 #[serde(default = "default_idle_timeout", with = "humantime_serde")]
25 pub idle_timeout: Duration,
26
27 #[serde(default = "default_max_lifetime", with = "humantime_serde")]
28 pub max_lifetime: Duration,
29
30 #[serde(default, with = "humantime_serde")]
36 pub checkout_timeout: Option<Duration>,
37
38 #[serde(default)]
39 pub user: HashMap<String, user::UserConfig>,
40}
41
42impl PoolConfig {
43 pub fn database_name<'a>(&'a self, key: &'a str) -> &'a str {
46 self.database.as_deref().unwrap_or(key)
47 }
48
49 pub(crate) fn validate(&self, name: &str) -> Result<(), errors::ConfigError> {
50 if self.user.is_empty() {
51 return Err(errors::ConfigError::Validation(format!(
52 "pool {name:?}: at least one user is required"
53 )));
54 }
55
56 if self.mode == PoolMode::Session && self.listen_mode.is_some() {
57 return Err(errors::ConfigError::Validation(format!(
58 "pool {name:?}: listen_mode is only supported in transaction mode"
59 )));
60 }
61
62 let total_min_primary: u32 = self.user.values().map(|u| u.min_connections.primary).sum();
63 if total_min_primary > self.max_connections.primary {
64 return Err(errors::ConfigError::Validation(format!(
65 "pool {:?}: total min_connections.primary ({total_min_primary}) exceeds max_connections.primary ({})",
66 name, self.max_connections.primary
67 )));
68 }
69 let total_min_replica: u32 = self.user.values().map(|u| u.min_connections.replica).sum();
70 if total_min_replica > self.max_connections.replica {
71 return Err(errors::ConfigError::Validation(format!(
72 "pool {:?}: total min_connections.replica ({total_min_replica}) exceeds max_connections.replica ({})",
73 name, self.max_connections.replica
74 )));
75 }
76
77 Ok(())
78 }
79}
80
81#[derive(Debug, Default, PartialEq, Eq, Deserialize)]
83pub struct ConnectionLimits {
84 #[serde(default)]
85 pub primary: u32,
86 #[serde(default)]
87 pub replica: u32,
88}
89
90#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Deserialize)]
95#[serde(rename_all = "lowercase")]
96pub enum PoolMode {
97 #[default]
98 Transaction,
99 Session,
100}
101
102#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Deserialize)]
103#[serde(rename_all = "lowercase")]
104pub enum ListenMode {
105 #[default]
107 Pin,
108 Multiplex,
110}
111
112fn default_pool_max_connections() -> ConnectionLimits {
117 ConnectionLimits {
118 primary: 100,
119 replica: 0,
120 }
121}
122
123fn default_idle_timeout() -> Duration {
124 Duration::from_mins(5)
125}
126
127fn default_max_lifetime() -> Duration {
128 Duration::from_hours(1)
129}