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