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}
17
18/// HTTP server and logging settings. Environment variables use `APP_`.
19#[derive(Clone, Debug, Deserialize, Serialize)]
20#[serde(default, deny_unknown_fields)]
21pub struct AppSettings {
22    /// Display name of this application.
23    pub name: String,
24    /// `development`, `test`, or `production`.
25    pub environment: String,
26    /// Interface or hostname to bind.
27    pub host: String,
28    /// TCP port to bind (zero allows the OS to choose).
29    pub port: u16,
30}
31
32impl Default for AppSettings {
33    fn default() -> Self {
34        Self {
35            name: "Capy".into(),
36            environment: "development".into(),
37            host: "127.0.0.1".into(),
38            port: 8000,
39        }
40    }
41}
42
43/// SeaORM connection settings. Environment variables use `DATABASE_`.
44#[derive(Clone, Deserialize, Serialize)]
45#[serde(default, deny_unknown_fields)]
46pub struct DatabaseSettings {
47    /// PostgreSQL or SQLite connection URL. Debug output redacts this value.
48    pub url: String,
49    /// Maximum pool size; SQLite in-memory databases always use one connection.
50    pub max_connections: u32,
51    /// Maximum time to establish a connection, in seconds.
52    pub connect_timeout_seconds: u64,
53}
54
55impl std::fmt::Debug for DatabaseSettings {
56    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
57        f.debug_struct("DatabaseSettings")
58            .field("url", &"[redacted]")
59            .field("max_connections", &self.max_connections)
60            .field("connect_timeout_seconds", &self.connect_timeout_seconds)
61            .finish()
62    }
63}
64
65impl Default for DatabaseSettings {
66    fn default() -> Self {
67        Self {
68            url: String::new(),
69            max_connections: 10,
70            connect_timeout_seconds: 10,
71        }
72    }
73}
74
75impl AppConfig {
76    /// Load from the current project directory.
77    pub fn load() -> Result<Self> {
78        Self::load_from(".")
79    }
80
81    /// Resolve defaults < TOML files < `.env` < process environment.
82    /// Reading `.env` never mutates the process environment.
83    pub fn load_from(root: impl AsRef<Path>) -> Result<Self> {
84        let root = root.as_ref();
85        let mut app_env = BTreeMap::new();
86        let mut db_env = BTreeMap::new();
87        match dotenvy::from_path_iter(root.join(".env")) {
88            Ok(entries) => {
89                for entry in entries {
90                    let (key, value) = entry.map_err(|_| {
91                        AppError::Configuration("Could not parse .env. Check its syntax.".into())
92                    })?;
93                    let value = serde_json::from_str::<serde_json::Value>(&value)
94                        .unwrap_or(serde_json::Value::String(value));
95                    if let Some(key) = key.strip_prefix("APP_") {
96                        app_env.insert(key.to_lowercase(), value);
97                    } else if let Some(key) = key.strip_prefix("DATABASE_") {
98                        db_env.insert(key.to_lowercase(), value);
99                    }
100                }
101            }
102            Err(dotenvy::Error::Io(e)) if e.kind() == std::io::ErrorKind::NotFound => {}
103            Err(_) => return Err(AppError::Configuration("Could not read .env.".into())),
104        }
105        let app = Figment::from(Serialized::defaults(AppSettings::default()))
106            .merge(Toml::file(root.join("config/app.toml")))
107            .merge(Serialized::defaults(app_env))
108            .merge(Env::prefixed("APP_"))
109            .extract()
110            .map_err(|_| {
111                AppError::Configuration(
112                    "Invalid application settings. Check config/app.toml and APP_* variables."
113                        .into(),
114                )
115            })?;
116        let database = Figment::from(Serialized::defaults(DatabaseSettings::default()))
117            .merge(Toml::file(root.join("config/database.toml")))
118            .merge(Serialized::defaults(db_env))
119            .merge(Env::prefixed("DATABASE_"))
120            .extract()
121            .map_err(|_| AppError::Configuration(
122                "Invalid database settings. Check config/database.toml and DATABASE_* variables.".into(),
123            ))?;
124        let config = Self { app, database };
125        config.validate()?;
126        Ok(config)
127    }
128
129    /// Validate manually constructed configuration as well as loaded settings.
130    pub fn validate(&self) -> Result<()> {
131        if self.app.name.trim().is_empty() || self.app.host.trim().is_empty() {
132            return Err(AppError::Configuration(
133                "APP_NAME and APP_HOST cannot be empty.".into(),
134            ));
135        }
136        if !matches!(
137            self.app.environment.as_str(),
138            "development" | "test" | "production"
139        ) {
140            return Err(AppError::Configuration(
141                "APP_ENVIRONMENT must be development, test, or production.".into(),
142            ));
143        }
144        self.database.validate()
145    }
146}
147
148impl DatabaseSettings {
149    /// Validate supported backends and pool limits without exposing credentials.
150    pub fn validate(&self) -> Result<()> {
151        if self.url.trim().is_empty() {
152            return Err(AppError::Configuration(
153                "Database configuration error: DATABASE_URL is missing.".into(),
154            ));
155        }
156        if !(self.url.starts_with("postgres://")
157            || self.url.starts_with("postgresql://")
158            || self.url.starts_with("sqlite:"))
159        {
160            return Err(AppError::Configuration(
161                "DATABASE_URL must use PostgreSQL or SQLite.".into(),
162            ));
163        }
164        if self.max_connections == 0 || self.connect_timeout_seconds == 0 {
165            return Err(AppError::Configuration(
166                "Database pool size and connection timeout must be greater than zero.".into(),
167            ));
168        }
169        Ok(())
170    }
171}