Skip to main content

forge_core/config/
database.rs

1use serde::{Deserialize, Serialize};
2
3use crate::error::{ForgeError, Result};
4
5/// Database configuration.
6#[derive(Debug, Clone, Serialize, Deserialize)]
7pub struct DatabaseConfig {
8    /// PostgreSQL connection URL.
9    #[serde(default)]
10    pub url: String,
11
12    /// Connection pool size.
13    #[serde(default = "default_pool_size")]
14    pub pool_size: u32,
15
16    /// Pool checkout timeout in seconds.
17    #[serde(default = "default_pool_timeout")]
18    pub pool_timeout_secs: u64,
19
20    /// Statement timeout in seconds.
21    #[serde(default = "default_statement_timeout")]
22    pub statement_timeout_secs: u64,
23
24    /// Read replica URLs for scaling reads.
25    #[serde(default)]
26    pub replica_urls: Vec<String>,
27
28    /// Whether to route read queries to replicas.
29    #[serde(default)]
30    pub read_from_replica: bool,
31
32    /// Minimum connections to keep alive in the pool (pre-warming).
33    #[serde(default)]
34    pub min_pool_size: u32,
35
36    /// Run a health check query before handing out connections.
37    /// Disabling this halves round-trips for read queries.
38    #[serde(default = "default_true")]
39    pub test_before_acquire: bool,
40
41    /// Connection pool isolation configuration.
42    #[serde(default)]
43    pub pools: PoolsConfig,
44}
45
46impl Default for DatabaseConfig {
47    fn default() -> Self {
48        Self {
49            url: String::new(),
50            pool_size: default_pool_size(),
51            pool_timeout_secs: default_pool_timeout(),
52            statement_timeout_secs: default_statement_timeout(),
53            replica_urls: Vec::new(),
54            read_from_replica: false,
55            min_pool_size: 0,
56            test_before_acquire: true,
57            pools: PoolsConfig::default(),
58        }
59    }
60}
61
62impl DatabaseConfig {
63    /// Create a config with a database URL.
64    pub fn new(url: impl Into<String>) -> Self {
65        Self {
66            url: url.into(),
67            ..Default::default()
68        }
69    }
70
71    /// Get the database URL.
72    pub fn url(&self) -> &str {
73        &self.url
74    }
75
76    /// Validate the database configuration.
77    pub fn validate(&self) -> Result<()> {
78        if self.url.is_empty() {
79            return Err(ForgeError::Config(
80                "database.url is required. \
81                 Set database.url to a PostgreSQL connection string \
82                 (e.g., \"postgres://user:pass@localhost/mydb\")."
83                    .into(),
84            ));
85        }
86        Ok(())
87    }
88}
89
90fn default_pool_size() -> u32 {
91    50
92}
93
94fn default_pool_timeout() -> u64 {
95    30
96}
97
98fn default_statement_timeout() -> u64 {
99    30
100}
101
102use super::default_true;
103
104/// Pool isolation configuration for different workloads.
105#[derive(Debug, Clone, Serialize, Deserialize, Default)]
106pub struct PoolsConfig {
107    /// Default pool for queries/mutations.
108    #[serde(default)]
109    pub default: Option<PoolConfig>,
110
111    /// Pool for background jobs.
112    #[serde(default)]
113    pub jobs: Option<PoolConfig>,
114
115    /// Pool for observability writes.
116    #[serde(default)]
117    pub observability: Option<PoolConfig>,
118
119    /// Pool for long-running analytics.
120    #[serde(default)]
121    pub analytics: Option<PoolConfig>,
122}
123
124/// Individual pool configuration.
125#[derive(Debug, Clone, Serialize, Deserialize)]
126pub struct PoolConfig {
127    /// Pool size.
128    pub size: u32,
129
130    /// Checkout timeout in seconds.
131    #[serde(default = "default_pool_timeout")]
132    pub timeout_secs: u64,
133
134    /// Statement timeout in seconds (optional override).
135    pub statement_timeout_secs: Option<u64>,
136
137    /// Minimum connections to keep alive.
138    #[serde(default)]
139    pub min_size: u32,
140
141    /// Run a health check query before handing out connections.
142    #[serde(default = "default_true")]
143    pub test_before_acquire: bool,
144}
145
146#[cfg(test)]
147#[allow(clippy::unwrap_used, clippy::indexing_slicing)]
148mod tests {
149    use super::*;
150
151    #[test]
152    fn test_default_database_config() {
153        let config = DatabaseConfig::default();
154        assert_eq!(config.pool_size, 50);
155        assert_eq!(config.pool_timeout_secs, 30);
156        assert!(config.url.is_empty());
157    }
158
159    #[test]
160    fn test_new_config() {
161        let config = DatabaseConfig::new("postgres://localhost/test");
162        assert_eq!(config.url(), "postgres://localhost/test");
163    }
164
165    #[test]
166    fn test_parse_config() {
167        let toml = r#"
168            url = "postgres://localhost/test"
169            pool_size = 100
170            replica_urls = ["postgres://replica1/test", "postgres://replica2/test"]
171            read_from_replica = true
172        "#;
173
174        let config: DatabaseConfig = toml::from_str(toml).unwrap();
175        assert_eq!(config.pool_size, 100);
176        assert_eq!(config.url(), "postgres://localhost/test");
177        assert_eq!(config.replica_urls.len(), 2);
178        assert!(config.read_from_replica);
179    }
180
181    #[test]
182    fn test_validate_with_url() {
183        let config = DatabaseConfig::new("postgres://localhost/test");
184        assert!(config.validate().is_ok());
185    }
186
187    #[test]
188    fn test_validate_empty_url() {
189        let config = DatabaseConfig::default();
190        let result = config.validate();
191        assert!(result.is_err());
192        let err_msg = result.unwrap_err().to_string();
193        assert!(err_msg.contains("database.url is required"));
194    }
195}