Skip to main content

halephant_core/config/cluster/pool/
mod.rs

1pub 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    /// Override the PostgreSQL database name when it differs from the TOML key.
13    pub database: Option<String>,
14
15    #[serde(default)]
16    pub mode: PoolMode,
17
18    /// LISTEN/NOTIFY handling in transaction mode. Not applicable to session mode.
19    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    /// Per-pool override of `[server] checkout_timeout`. When set, the
31    /// pool uses this value instead of the server-wide default. Useful
32    /// for mixing latency-sensitive OLTP pools (short timeout) with
33    /// analytics pools (long or no timeout) in the same halephant
34    /// process.
35    #[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    /// The effective database name — the explicit `database` field if set,
44    /// otherwise the TOML key is used by the caller.
45    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/// Connection limits split by primary (rw) and replica (ro).
82#[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// ---------------------------------------------------------------------------
91// Enums
92// ---------------------------------------------------------------------------
93
94#[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    /// Pin the connection on LISTEN (switches to session mode for that client).
106    #[default]
107    Pin,
108    /// Multiplex LISTEN across a shared connection with fan-out.
109    Multiplex,
110}
111
112// ---------------------------------------------------------------------------
113// Defaults
114// ---------------------------------------------------------------------------
115
116fn 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}