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