Skip to main content

capy_core/
config.rs

1use crate::{AppError, Result};
2use figment::{
3    providers::{Env, Format, Serialized, Toml},
4    Figment,
5};
6use serde::{Deserialize, Serialize};
7use std::{collections::BTreeMap, path::Path};
8
9/// Application and database settings, resolved before startup.
10#[derive(Clone, Debug, Default, Deserialize, Serialize)]
11pub struct AppConfig {
12    /// HTTP server settings.
13    pub app: AppSettings,
14    /// Database connection settings.
15    pub database: DatabaseSettings,
16    /// Listener overrides and bounded graceful shutdown (`SERVER_*`).
17    pub server: ServerSettings,
18    /// Request and readiness bounds (`HTTP_*`).
19    pub http: HttpSettings,
20}
21
22/// Listener settings. Unspecified host/port retain legacy `APP_HOST`/`APP_PORT`.
23#[derive(Clone, Debug, Deserialize, Serialize)]
24#[serde(default, deny_unknown_fields)]
25pub struct ServerSettings {
26    /// Explicit listener interface or hostname; overrides `app.host`.
27    pub host: Option<String>,
28    /// Explicit listener port; overrides `app.port`.
29    pub port: Option<u16>,
30    /// Maximum graceful drain time in seconds (1..=3600).
31    pub shutdown_timeout_seconds: u64,
32}
33
34impl Default for ServerSettings {
35    fn default() -> Self {
36        Self {
37            host: None,
38            port: None,
39            shutdown_timeout_seconds: 10,
40        }
41    }
42}
43
44/// Small HTTP policy surface, expressed in seconds and bytes to avoid ambiguous units.
45#[derive(Clone, Debug, Deserialize, Serialize)]
46#[serde(default, deny_unknown_fields)]
47pub struct HttpSettings {
48    /// Deadline until response headers (0 disables it, otherwise at most 86400).
49    pub request_timeout_seconds: u64,
50    /// Independent readiness database probe timeout (1..=30 seconds).
51    pub readiness_timeout_seconds: u64,
52    /// Default body limit in bytes (1..=1073741824); native route overrides remain possible.
53    pub max_body_bytes: usize,
54    /// Enable negotiated gzip response compression with Tower's default predicate.
55    pub compression: bool,
56}
57
58impl Default for HttpSettings {
59    fn default() -> Self {
60        Self {
61            request_timeout_seconds: 30,
62            readiness_timeout_seconds: 2,
63            max_body_bytes: 2 * 1024 * 1024,
64            compression: true,
65        }
66    }
67}
68
69/// HTTP server and logging settings. Environment variables use `APP_`.
70#[derive(Clone, Debug, Deserialize, Serialize)]
71#[serde(default, deny_unknown_fields)]
72pub struct AppSettings {
73    /// Display name of this application.
74    pub name: String,
75    /// `development`, `test`, or `production`.
76    pub environment: String,
77    /// Interface or hostname to bind.
78    pub host: String,
79    /// TCP port to bind (zero allows the OS to choose).
80    pub port: u16,
81}
82
83impl Default for AppSettings {
84    fn default() -> Self {
85        Self {
86            name: "Capy".into(),
87            environment: "development".into(),
88            host: "127.0.0.1".into(),
89            port: 8000,
90        }
91    }
92}
93
94/// SeaORM connection settings. Environment variables use `DATABASE_`.
95#[derive(Clone, Deserialize, Serialize)]
96#[serde(default, deny_unknown_fields)]
97pub struct DatabaseSettings {
98    /// PostgreSQL or SQLite connection URL. Debug output redacts this value.
99    pub url: String,
100    /// Maximum pool size; SQLite in-memory databases always use one connection.
101    pub max_connections: u32,
102    /// Maximum time to initialize the connection pool, in seconds.
103    pub connect_timeout_seconds: u64,
104    /// Minimum idle connections; cannot exceed the configured maximum.
105    pub min_connections: u32,
106    /// Maximum wait for an available connection, in seconds.
107    pub acquire_timeout_seconds: u64,
108    /// Maximum idle lifetime in seconds (1..=86400).
109    pub idle_timeout_seconds: u64,
110}
111
112impl std::fmt::Debug for DatabaseSettings {
113    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
114        f.debug_struct("DatabaseSettings")
115            .field("url", &"[redacted]")
116            .field("max_connections", &self.max_connections)
117            .field("connect_timeout_seconds", &self.connect_timeout_seconds)
118            .field("min_connections", &self.min_connections)
119            .field("acquire_timeout_seconds", &self.acquire_timeout_seconds)
120            .field("idle_timeout_seconds", &self.idle_timeout_seconds)
121            .finish()
122    }
123}
124
125impl Default for DatabaseSettings {
126    fn default() -> Self {
127        Self {
128            url: String::new(),
129            max_connections: 10,
130            connect_timeout_seconds: 10,
131            min_connections: 0,
132            acquire_timeout_seconds: 10,
133            idle_timeout_seconds: 600,
134        }
135    }
136}
137
138impl AppConfig {
139    /// Load from the current project directory.
140    pub fn load() -> Result<Self> {
141        Self::load_from(".")
142    }
143
144    /// Resolve defaults < TOML files < `.env` < process environment.
145    /// Reading `.env` never mutates the process environment.
146    pub fn load_from(root: impl AsRef<Path>) -> Result<Self> {
147        let root = root.as_ref();
148        let mut app_env = BTreeMap::new();
149        let mut db_env = BTreeMap::new();
150        let mut server_env = BTreeMap::new();
151        let mut http_env = BTreeMap::new();
152        match dotenvy::from_path_iter(root.join(".env")) {
153            Ok(entries) => {
154                for entry in entries {
155                    let (key, value) = entry.map_err(|_| {
156                        AppError::Configuration("Could not parse .env. Check its syntax.".into())
157                    })?;
158                    let value = serde_json::from_str::<serde_json::Value>(&value)
159                        .unwrap_or(serde_json::Value::String(value));
160                    if let Some(key) = key.strip_prefix("APP_") {
161                        app_env.insert(key.to_lowercase(), value);
162                    } else if let Some(key) = key.strip_prefix("DATABASE_") {
163                        db_env.insert(key.to_lowercase(), value);
164                    } else if let Some(key) = key.strip_prefix("SERVER_") {
165                        server_env.insert(key.to_lowercase(), value);
166                    } else if let Some(key) = key.strip_prefix("HTTP_") {
167                        http_env.insert(key.to_lowercase(), value);
168                    }
169                }
170            }
171            Err(dotenvy::Error::Io(e)) if e.kind() == std::io::ErrorKind::NotFound => {}
172            Err(_) => return Err(AppError::Configuration("Could not read .env.".into())),
173        }
174        let app = Figment::from(Serialized::defaults(AppSettings::default()))
175            .merge(Toml::file(root.join("config/app.toml")))
176            .merge(Serialized::defaults(app_env))
177            .merge(Env::prefixed("APP_"))
178            .extract()
179            .map_err(|_| {
180                AppError::Configuration(
181                    "Invalid application settings. Check config/app.toml and APP_* variables."
182                        .into(),
183                )
184            })?;
185        let database = Figment::from(Serialized::defaults(DatabaseSettings::default()))
186            .merge(Toml::file(root.join("config/database.toml")))
187            .merge(Serialized::defaults(db_env))
188            .merge(Env::prefixed("DATABASE_"))
189            .extract()
190            .map_err(|_| AppError::Configuration(
191                "Invalid database settings. Check config/database.toml and DATABASE_* variables.".into(),
192            ))?;
193        let server = Figment::from(Serialized::defaults(ServerSettings::default()))
194            .merge(Toml::file(root.join("config/server.toml")))
195            .merge(Serialized::defaults(server_env))
196            .merge(Env::prefixed("SERVER_"))
197            .extract()
198            .map_err(|_| AppError::Configuration(
199                "Invalid server settings. Check config/server.toml and SERVER_* variables; ports must be 0..=65535 and deadlines integer seconds.".into()))?;
200        let http = Figment::from(Serialized::defaults(HttpSettings::default()))
201            .merge(Toml::file(root.join("config/http.toml")))
202            .merge(Serialized::defaults(http_env))
203            .merge(Env::prefixed("HTTP_"))
204            .extract()
205            .map_err(|_| AppError::Configuration(
206                "Invalid HTTP settings. Check config/http.toml and HTTP_* variables; deadlines use integer seconds and body limits use integer bytes.".into()))?;
207        let config = Self {
208            app,
209            database,
210            server,
211            http,
212        };
213        config.validate()?;
214        Ok(config)
215    }
216
217    /// Validate manually constructed configuration as well as loaded settings.
218    pub fn validate(&self) -> Result<()> {
219        if self.app.name.trim().is_empty() || self.app.host.trim().is_empty() {
220            return Err(AppError::Configuration(
221                "APP_NAME and APP_HOST cannot be empty.".into(),
222            ));
223        }
224        if !matches!(
225            self.app.environment.as_str(),
226            "development" | "test" | "production"
227        ) {
228            return Err(AppError::Configuration(
229                "APP_ENVIRONMENT must be development, test, or production.".into(),
230            ));
231        }
232        if self.host().trim().is_empty() || self.host().chars().any(char::is_whitespace) {
233            return Err(AppError::Configuration(
234                "SERVER_HOST must be a hostname or IP address without whitespace.".into(),
235            ));
236        }
237        if self.app.environment == "production" && self.port() == 0 {
238            return Err(AppError::Configuration(
239                "The production server port must be 1..=65535.".into(),
240            ));
241        }
242        if !(1..=3600).contains(&self.server.shutdown_timeout_seconds) {
243            return Err(AppError::Configuration(
244                "SERVER_SHUTDOWN_TIMEOUT_SECONDS must be 1..=3600.".into(),
245            ));
246        }
247        if self.http.request_timeout_seconds > 86400 {
248            return Err(AppError::Configuration("HTTP_REQUEST_TIMEOUT_SECONDS must be 0..=86400 (0 intentionally disables the deadline).".into()));
249        }
250        if !(1..=30).contains(&self.http.readiness_timeout_seconds) {
251            return Err(AppError::Configuration(
252                "HTTP_READINESS_TIMEOUT_SECONDS must be 1..=30.".into(),
253            ));
254        }
255        if !(1..=1024 * 1024 * 1024).contains(&self.http.max_body_bytes) {
256            return Err(AppError::Configuration(
257                "HTTP_MAX_BODY_BYTES must be 1..=1073741824.".into(),
258            ));
259        }
260        self.database.validate()
261    }
262
263    /// Effective listener host, including explicit server overrides.
264    pub fn host(&self) -> &str {
265        self.server.host.as_deref().unwrap_or(&self.app.host)
266    }
267
268    /// Effective listener port, including explicit server overrides.
269    pub fn port(&self) -> u16 {
270        self.server.port.unwrap_or(self.app.port)
271    }
272}
273
274impl DatabaseSettings {
275    /// Validate supported backends and pool limits without exposing credentials.
276    pub fn validate(&self) -> Result<()> {
277        if self.url.trim().is_empty() {
278            return Err(AppError::Configuration(
279                "Database configuration error: DATABASE_URL is missing.".into(),
280            ));
281        }
282        if !(self.url.starts_with("postgres://")
283            || self.url.starts_with("postgresql://")
284            || self.url.starts_with("sqlite:"))
285        {
286            return Err(AppError::Configuration(
287                "DATABASE_URL must use PostgreSQL or SQLite.".into(),
288            ));
289        }
290        if self.max_connections == 0
291            || self.max_connections > 10_000
292            || self.min_connections > self.max_connections
293            || !(1..=3600).contains(&self.connect_timeout_seconds)
294            || !(1..=3600).contains(&self.acquire_timeout_seconds)
295            || !(1..=86400).contains(&self.idle_timeout_seconds)
296        {
297            return Err(AppError::Configuration(
298                "Invalid database pool: max_connections must be 1..=10000, min_connections <= max_connections, connect/acquire timeouts 1..=3600 seconds, idle timeout 1..=86400 seconds.".into(),
299            ));
300        }
301        Ok(())
302    }
303}