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    /// Optional outbound communication settings (`MAIL_*`).
13    #[serde(default)]
14    pub mail: crate::MailSettings,
15    /// Optional durable worker settings (`JOBS_*`).
16    #[serde(default)]
17    pub jobs: crate::JobsSettings,
18    /// Optional identity subsystem settings (`AUTH_*`); activated by `App::auth`.
19    #[serde(default)]
20    pub auth: crate::AuthSettings,
21    /// HTTP server settings.
22    pub app: AppSettings,
23    /// Database connection settings.
24    pub database: DatabaseSettings,
25    /// Listener overrides and bounded graceful shutdown (`SERVER_*`).
26    pub server: ServerSettings,
27    /// Request and readiness bounds (`HTTP_*`).
28    pub http: HttpSettings,
29    /// API document metadata and explicit documentation exposure (`API_*`).
30    pub api: ApiSettings,
31}
32
33/// Small application-owned API metadata. Documentation is disabled by default.
34#[derive(Clone, Debug, Deserialize, Serialize)]
35#[serde(default, deny_unknown_fields)]
36pub struct ApiSettings {
37    /// Document title; defaults to the application name when omitted.
38    pub title: Option<String>,
39    /// Public API contract version, independent of the Capy package version.
40    pub version: String,
41    /// Explicitly expose GET /openapi.json, including in production.
42    pub openapi: bool,
43    /// Expose Scalar at /docs/api in development/test only; also enables the schema there.
44    pub docs: bool,
45}
46
47impl Default for ApiSettings {
48    fn default() -> Self {
49        Self {
50            title: None,
51            version: "1.0.0".into(),
52            openapi: false,
53            docs: false,
54        }
55    }
56}
57
58/// Listener settings. Unspecified host/port retain legacy `APP_HOST`/`APP_PORT`.
59#[derive(Clone, Debug, Deserialize, Serialize)]
60#[serde(default, deny_unknown_fields)]
61pub struct ServerSettings {
62    /// Explicit listener interface or hostname; overrides `app.host`.
63    pub host: Option<String>,
64    /// Explicit listener port; overrides `app.port`.
65    pub port: Option<u16>,
66    /// Maximum graceful drain time in seconds (1..=3600).
67    pub shutdown_timeout_seconds: u64,
68}
69
70impl Default for ServerSettings {
71    fn default() -> Self {
72        Self {
73            host: None,
74            port: None,
75            shutdown_timeout_seconds: 10,
76        }
77    }
78}
79
80/// Small HTTP policy surface, expressed in seconds and bytes to avoid ambiguous units.
81#[derive(Clone, Debug, Deserialize, Serialize)]
82#[serde(default, deny_unknown_fields)]
83pub struct HttpSettings {
84    /// Deadline until response headers (0 disables it, otherwise at most 86400).
85    pub request_timeout_seconds: u64,
86    /// Independent readiness database probe timeout (1..=30 seconds).
87    pub readiness_timeout_seconds: u64,
88    /// Default body limit in bytes (1..=1073741824); native route overrides remain possible.
89    pub max_body_bytes: usize,
90    /// Enable negotiated gzip response compression with Tower's default predicate.
91    pub compression: bool,
92}
93
94impl Default for HttpSettings {
95    fn default() -> Self {
96        Self {
97            request_timeout_seconds: 30,
98            readiness_timeout_seconds: 2,
99            max_body_bytes: 2 * 1024 * 1024,
100            compression: true,
101        }
102    }
103}
104
105/// HTTP server and logging settings. Environment variables use `APP_`.
106#[derive(Clone, Debug, Deserialize, Serialize)]
107#[serde(default, deny_unknown_fields)]
108pub struct AppSettings {
109    /// Explicit public application URL, never inferred from request headers.
110    pub url: Option<String>,
111    /// Display name of this application.
112    pub name: String,
113    /// `development`, `test`, or `production`.
114    pub environment: String,
115    /// Interface or hostname to bind.
116    pub host: String,
117    /// TCP port to bind (zero allows the OS to choose).
118    pub port: u16,
119}
120
121impl Default for AppSettings {
122    fn default() -> Self {
123        Self {
124            url: None,
125            name: "Capy".into(),
126            environment: "development".into(),
127            host: "127.0.0.1".into(),
128            port: 8000,
129        }
130    }
131}
132
133/// SeaORM connection settings. Environment variables use `DATABASE_`.
134#[derive(Clone, Deserialize, Serialize)]
135#[serde(default, deny_unknown_fields)]
136pub struct DatabaseSettings {
137    /// PostgreSQL or SQLite connection URL. Debug output redacts this value.
138    pub url: String,
139    /// Maximum pool size; SQLite in-memory databases always use one connection.
140    pub max_connections: u32,
141    /// Maximum time to initialize the connection pool, in seconds.
142    pub connect_timeout_seconds: u64,
143    /// Minimum idle connections; cannot exceed the configured maximum.
144    pub min_connections: u32,
145    /// Maximum wait for an available connection, in seconds.
146    pub acquire_timeout_seconds: u64,
147    /// Maximum idle lifetime in seconds (1..=86400).
148    pub idle_timeout_seconds: u64,
149}
150
151impl std::fmt::Debug for DatabaseSettings {
152    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
153        f.debug_struct("DatabaseSettings")
154            .field("url", &"[redacted]")
155            .field("max_connections", &self.max_connections)
156            .field("connect_timeout_seconds", &self.connect_timeout_seconds)
157            .field("min_connections", &self.min_connections)
158            .field("acquire_timeout_seconds", &self.acquire_timeout_seconds)
159            .field("idle_timeout_seconds", &self.idle_timeout_seconds)
160            .finish()
161    }
162}
163
164impl Default for DatabaseSettings {
165    fn default() -> Self {
166        Self {
167            url: String::new(),
168            max_connections: 10,
169            connect_timeout_seconds: 10,
170            min_connections: 0,
171            acquire_timeout_seconds: 10,
172            idle_timeout_seconds: 600,
173        }
174    }
175}
176
177impl AppConfig {
178    /// Load from the current project directory.
179    pub fn load() -> Result<Self> {
180        Self::load_from(".")
181    }
182
183    /// Resolve defaults < TOML files < `.env` < process environment.
184    /// Reading `.env` never mutates the process environment.
185    pub fn load_from(root: impl AsRef<Path>) -> Result<Self> {
186        Self::load_sections(root.as_ref(), true)
187    }
188
189    /// Load metadata for offline contract export. A database URL is not required.
190    /// All supplied configuration is parsed, but no connection is ever opened.
191    pub fn load_for_contracts() -> Result<Self> {
192        Self::load_sections(Path::new("."), false)
193    }
194
195    fn load_sections(root: &Path, require_database: bool) -> Result<Self> {
196        let mut app_env = BTreeMap::new();
197        let mut db_env = BTreeMap::new();
198        let mut server_env = BTreeMap::new();
199        let mut http_env = BTreeMap::new();
200        let mut api_env = BTreeMap::new();
201        let mut auth_env = BTreeMap::new();
202        let mut jobs_env = BTreeMap::new();
203        let mut mail_env = serde_json::Map::new();
204        let mut smtp_env = serde_json::Map::new();
205        match dotenvy::from_path_iter(root.join(".env")) {
206            Ok(entries) => {
207                for entry in entries {
208                    let (key, value) = entry.map_err(|_| {
209                        AppError::Configuration("Could not parse .env. Check its syntax.".into())
210                    })?;
211                    let value =
212                        if matches!(key.as_str(), "MAIL_SMTP_USERNAME" | "MAIL_SMTP_PASSWORD") {
213                            serde_json::Value::String(value)
214                        } else {
215                            serde_json::from_str::<serde_json::Value>(&value)
216                                .unwrap_or(serde_json::Value::String(value))
217                        };
218                    if let Some(key) = key.strip_prefix("MAIL_SMTP_") {
219                        smtp_env.insert(key.to_lowercase(), value);
220                    } else if let Some(key) = key.strip_prefix("MAIL_") {
221                        mail_env.insert(key.to_lowercase(), value);
222                    } else if let Some(key) = key.strip_prefix("JOBS_") {
223                        jobs_env.insert(key.to_lowercase(), value);
224                    } else if let Some(key) = key.strip_prefix("AUTH_") {
225                        auth_env.insert(key.to_lowercase(), value);
226                    } else if let Some(key) = key.strip_prefix("APP_") {
227                        app_env.insert(key.to_lowercase(), value);
228                    } else if let Some(key) = key.strip_prefix("DATABASE_") {
229                        db_env.insert(key.to_lowercase(), value);
230                    } else if let Some(key) = key.strip_prefix("SERVER_") {
231                        server_env.insert(key.to_lowercase(), value);
232                    } else if let Some(key) = key.strip_prefix("HTTP_") {
233                        http_env.insert(key.to_lowercase(), value);
234                    } else if let Some(key) = key.strip_prefix("API_") {
235                        api_env.insert(key.to_lowercase(), value);
236                    }
237                }
238            }
239            Err(dotenvy::Error::Io(e)) if e.kind() == std::io::ErrorKind::NotFound => {}
240            Err(_) => return Err(AppError::Configuration("Could not read .env.".into())),
241        }
242        let app = Figment::from(Serialized::defaults(AppSettings::default()))
243            .merge(Toml::file(root.join("config/app.toml")))
244            .merge(Serialized::defaults(app_env))
245            .merge(Env::prefixed("APP_"))
246            .extract()
247            .map_err(|_| {
248                AppError::Configuration(
249                    "Invalid application settings. Check config/app.toml and APP_* variables."
250                        .into(),
251                )
252            })?;
253        let database = Figment::from(Serialized::defaults(DatabaseSettings::default()))
254            .merge(Toml::file(root.join("config/database.toml")))
255            .merge(Serialized::defaults(db_env))
256            .merge(Env::prefixed("DATABASE_"))
257            .extract()
258            .map_err(|_| AppError::Configuration(
259                "Invalid database settings. Check config/database.toml and DATABASE_* variables.".into(),
260            ))?;
261        let server = Figment::from(Serialized::defaults(ServerSettings::default()))
262            .merge(Toml::file(root.join("config/server.toml")))
263            .merge(Serialized::defaults(server_env))
264            .merge(Env::prefixed("SERVER_"))
265            .extract()
266            .map_err(|_| AppError::Configuration(
267                "Invalid server settings. Check config/server.toml and SERVER_* variables; ports must be 0..=65535 and deadlines integer seconds.".into()))?;
268        let http = Figment::from(Serialized::defaults(HttpSettings::default()))
269            .merge(Toml::file(root.join("config/http.toml")))
270            .merge(Serialized::defaults(http_env))
271            .merge(Env::prefixed("HTTP_"))
272            .extract()
273            .map_err(|_| AppError::Configuration(
274                "Invalid HTTP settings. Check config/http.toml and HTTP_* variables; deadlines use integer seconds and body limits use integer bytes.".into()))?;
275        let api = Figment::from(Serialized::defaults(ApiSettings::default()))
276            .merge(Toml::file(root.join("config/api.toml")))
277            .merge(Serialized::defaults(api_env))
278            .merge(Env::prefixed("API_"))
279            .extract()
280            .map_err(|_| {
281                AppError::Configuration(
282                    "Invalid API settings. Check config/api.toml and API_* variables.".into(),
283                )
284            })?;
285        let auth = Figment::from(Serialized::defaults(crate::AuthSettings::default()))
286            .merge(Toml::file(root.join("config/auth.toml")))
287            .merge(Serialized::defaults(auth_env))
288            .merge(Env::prefixed("AUTH_"))
289            .extract()
290            .map_err(|_| {
291                AppError::Configuration(
292                    "Invalid auth settings. Check config/auth.toml and AUTH_* variables.".into(),
293                )
294            })?;
295        let jobs = Figment::from(Serialized::defaults(crate::JobsSettings::default()))
296            .merge(Toml::file(root.join("config/jobs.toml")))
297            .merge(Serialized::defaults(jobs_env))
298            .merge(Env::prefixed("JOBS_"))
299            .extract()
300            .map_err(|_| {
301                AppError::Configuration(
302                    "Invalid jobs settings. Check config/jobs.toml and JOBS_* variables.".into(),
303                )
304            })?;
305        // Credentials are literal text, even when they resemble numbers, booleans
306        // or JSON. Preserve their bytes instead of applying environment coercion.
307        for (key, variable) in [
308            ("username", "MAIL_SMTP_USERNAME"),
309            ("password", "MAIL_SMTP_PASSWORD"),
310        ] {
311            match std::env::var(variable) {
312                Ok(value) => {
313                    smtp_env.insert(key.into(), serde_json::Value::String(value));
314                }
315                Err(std::env::VarError::NotPresent) => {}
316                Err(_) => {
317                    return Err(AppError::Configuration(
318                        "SMTP credentials must be valid UTF-8 (values redacted).".into(),
319                    ));
320                }
321            }
322        }
323        mail_env.insert("smtp".into(), serde_json::Value::Object(smtp_env));
324        let mail = Figment::from(Serialized::defaults(crate::MailSettings::default()))
325            .merge(Toml::file(root.join("config/mail.toml")))
326            .merge(Serialized::defaults(mail_env))
327            .merge(Env::prefixed("MAIL_").ignore(&["smtp_username", "smtp_password"]).map(|key| key.as_str().to_lowercase().replacen("smtp_", "smtp.", 1).into()))
328            .extract()
329            .map_err(|_| AppError::Configuration("Invalid mail settings. Check config/mail.toml and MAIL_* variables (credentials redacted).".into()))?;
330        let config = Self {
331            mail,
332            jobs,
333            auth,
334            app,
335            database,
336            server,
337            http,
338            api,
339        };
340        config.validate_application()?;
341        if require_database {
342            config.database.validate()?;
343        }
344        Ok(config)
345    }
346
347    /// Validate manually constructed configuration as well as loaded settings.
348    pub fn validate(&self) -> Result<()> {
349        self.validate_application()?;
350        self.database.validate()
351    }
352
353    fn validate_application(&self) -> Result<()> {
354        self.jobs.validate()?;
355        self.mail.validate()?;
356        if self
357            .api
358            .title
359            .as_ref()
360            .is_some_and(|title| title.trim().is_empty())
361            || self.api.version.trim().is_empty()
362        {
363            return Err(AppError::Configuration(
364                "API_TITLE (when set) and API_VERSION must not be empty.".into(),
365            ));
366        }
367        if self.app.name.trim().is_empty() || self.app.host.trim().is_empty() {
368            return Err(AppError::Configuration(
369                "APP_NAME and APP_HOST cannot be empty.".into(),
370            ));
371        }
372        if !matches!(
373            self.app.environment.as_str(),
374            "development" | "test" | "production"
375        ) {
376            return Err(AppError::Configuration(
377                "APP_ENVIRONMENT must be development, test, or production.".into(),
378            ));
379        }
380        if self.host().trim().is_empty() || self.host().chars().any(char::is_whitespace) {
381            return Err(AppError::Configuration(
382                "SERVER_HOST must be a hostname or IP address without whitespace.".into(),
383            ));
384        }
385        if self.app.environment == "production" && self.port() == 0 {
386            return Err(AppError::Configuration(
387                "The production server port must be 1..=65535.".into(),
388            ));
389        }
390        if !(1..=3600).contains(&self.server.shutdown_timeout_seconds) {
391            return Err(AppError::Configuration(
392                "SERVER_SHUTDOWN_TIMEOUT_SECONDS must be 1..=3600.".into(),
393            ));
394        }
395        if self.http.request_timeout_seconds > 86400 {
396            return Err(AppError::Configuration("HTTP_REQUEST_TIMEOUT_SECONDS must be 0..=86400 (0 intentionally disables the deadline).".into()));
397        }
398        if !(1..=30).contains(&self.http.readiness_timeout_seconds) {
399            return Err(AppError::Configuration(
400                "HTTP_READINESS_TIMEOUT_SECONDS must be 1..=30.".into(),
401            ));
402        }
403        if !(1..=1024 * 1024 * 1024).contains(&self.http.max_body_bytes) {
404            return Err(AppError::Configuration(
405                "HTTP_MAX_BODY_BYTES must be 1..=1073741824.".into(),
406            ));
407        }
408        Ok(())
409    }
410
411    /// Effective listener host, including explicit server overrides.
412    pub fn host(&self) -> &str {
413        self.server.host.as_deref().unwrap_or(&self.app.host)
414    }
415
416    /// Effective listener port, including explicit server overrides.
417    pub fn port(&self) -> u16 {
418        self.server.port.unwrap_or(self.app.port)
419    }
420}
421
422impl DatabaseSettings {
423    /// Validate supported backends and pool limits without exposing credentials.
424    pub fn validate(&self) -> Result<()> {
425        if self.url.trim().is_empty() {
426            return Err(AppError::Configuration(
427                "Database configuration error: DATABASE_URL is missing.".into(),
428            ));
429        }
430        if !(self.url.starts_with("postgres://")
431            || self.url.starts_with("postgresql://")
432            || self.url.starts_with("sqlite:"))
433        {
434            return Err(AppError::Configuration(
435                "DATABASE_URL must use PostgreSQL or SQLite.".into(),
436            ));
437        }
438        if self.max_connections == 0
439            || self.max_connections > 10_000
440            || self.min_connections > self.max_connections
441            || !(1..=3600).contains(&self.connect_timeout_seconds)
442            || !(1..=3600).contains(&self.acquire_timeout_seconds)
443            || !(1..=86400).contains(&self.idle_timeout_seconds)
444        {
445            return Err(AppError::Configuration(
446                "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(),
447            ));
448        }
449        Ok(())
450    }
451}