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#[derive(Clone, Debug, Default, Deserialize, Serialize)]
11pub struct AppConfig {
12 #[serde(default)]
14 pub mail: crate::MailSettings,
15 #[serde(default)]
17 pub jobs: crate::JobsSettings,
18 #[serde(default)]
20 pub auth: crate::AuthSettings,
21 pub app: AppSettings,
23 pub database: DatabaseSettings,
25 pub server: ServerSettings,
27 pub http: HttpSettings,
29 pub api: ApiSettings,
31}
32
33#[derive(Clone, Debug, Deserialize, Serialize)]
35#[serde(default, deny_unknown_fields)]
36pub struct ApiSettings {
37 pub title: Option<String>,
39 pub version: String,
41 pub openapi: bool,
43 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#[derive(Clone, Debug, Deserialize, Serialize)]
60#[serde(default, deny_unknown_fields)]
61pub struct ServerSettings {
62 pub host: Option<String>,
64 pub port: Option<u16>,
66 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#[derive(Clone, Debug, Deserialize, Serialize)]
82#[serde(default, deny_unknown_fields)]
83pub struct HttpSettings {
84 pub client_ip: crate::ClientIpSettings,
86 pub request_timeout_seconds: u64,
88 pub readiness_timeout_seconds: u64,
90 pub max_body_bytes: usize,
92 pub compression: bool,
94}
95
96impl Default for HttpSettings {
97 fn default() -> Self {
98 Self {
99 client_ip: crate::ClientIpSettings::default(),
100 request_timeout_seconds: 30,
101 readiness_timeout_seconds: 2,
102 max_body_bytes: 2 * 1024 * 1024,
103 compression: true,
104 }
105 }
106}
107
108#[derive(Clone, Debug, Deserialize, Serialize)]
110#[serde(default, deny_unknown_fields)]
111pub struct AppSettings {
112 pub url: Option<String>,
114 pub name: String,
116 pub environment: String,
118 pub host: String,
120 pub port: u16,
122}
123
124impl Default for AppSettings {
125 fn default() -> Self {
126 Self {
127 url: None,
128 name: "Capy".into(),
129 environment: "development".into(),
130 host: "127.0.0.1".into(),
131 port: 8000,
132 }
133 }
134}
135
136#[derive(Clone, Deserialize, Serialize)]
138#[serde(default, deny_unknown_fields)]
139pub struct DatabaseSettings {
140 pub url: String,
142 pub max_connections: u32,
144 pub connect_timeout_seconds: u64,
146 pub min_connections: u32,
148 pub acquire_timeout_seconds: u64,
150 pub idle_timeout_seconds: u64,
152}
153
154impl std::fmt::Debug for DatabaseSettings {
155 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
156 f.debug_struct("DatabaseSettings")
157 .field("url", &"[redacted]")
158 .field("max_connections", &self.max_connections)
159 .field("connect_timeout_seconds", &self.connect_timeout_seconds)
160 .field("min_connections", &self.min_connections)
161 .field("acquire_timeout_seconds", &self.acquire_timeout_seconds)
162 .field("idle_timeout_seconds", &self.idle_timeout_seconds)
163 .finish()
164 }
165}
166
167impl Default for DatabaseSettings {
168 fn default() -> Self {
169 Self {
170 url: String::new(),
171 max_connections: 10,
172 connect_timeout_seconds: 10,
173 min_connections: 0,
174 acquire_timeout_seconds: 10,
175 idle_timeout_seconds: 600,
176 }
177 }
178}
179
180impl AppConfig {
181 pub fn load() -> Result<Self> {
183 Self::load_from(".")
184 }
185
186 pub fn load_from(root: impl AsRef<Path>) -> Result<Self> {
189 Self::load_sections(root.as_ref(), true)
190 }
191
192 pub fn load_for_contracts() -> Result<Self> {
195 Self::load_sections(Path::new("."), false)
196 }
197
198 fn load_sections(root: &Path, require_database: bool) -> Result<Self> {
199 let mut app_env = BTreeMap::new();
200 let mut db_env = BTreeMap::new();
201 let mut server_env = BTreeMap::new();
202 let mut http_env = serde_json::Map::new();
203 let mut client_ip_env = serde_json::Map::new();
204 let mut api_env = BTreeMap::new();
205 let mut auth_env = serde_json::Map::new();
206 let mut password_env = serde_json::Map::new();
207 let mut jobs_env = BTreeMap::new();
208 let mut mail_env = serde_json::Map::new();
209 let mut smtp_env = serde_json::Map::new();
210 match dotenvy::from_path_iter(root.join(".env")) {
211 Ok(entries) => {
212 for entry in entries {
213 let (key, value) = entry.map_err(|_| {
214 AppError::Configuration("Could not parse .env. Check its syntax.".into())
215 })?;
216 let value =
217 if matches!(key.as_str(), "MAIL_SMTP_USERNAME" | "MAIL_SMTP_PASSWORD") {
218 serde_json::Value::String(value)
219 } else {
220 serde_json::from_str::<serde_json::Value>(&value)
221 .unwrap_or(serde_json::Value::String(value))
222 };
223 if let Some(key) = key.strip_prefix("MAIL_SMTP_") {
224 smtp_env.insert(key.to_lowercase(), value);
225 } else if let Some(key) = key.strip_prefix("MAIL_") {
226 mail_env.insert(key.to_lowercase(), value);
227 } else if let Some(key) = key.strip_prefix("JOBS_") {
228 jobs_env.insert(key.to_lowercase(), value);
229 } else if key.starts_with("AUTH_PASSWORD_")
230 && key != "AUTH_PASSWORD_RESET_LIFETIME_SECONDS"
231 {
232 password_env.insert(key[14..].to_lowercase(), value);
233 } else if let Some(key) = key.strip_prefix("AUTH_") {
234 auth_env.insert(key.to_lowercase(), value);
235 } else if let Some(key) = key.strip_prefix("APP_") {
236 app_env.insert(key.to_lowercase(), value);
237 } else if let Some(key) = key.strip_prefix("DATABASE_") {
238 db_env.insert(key.to_lowercase(), value);
239 } else if let Some(key) = key.strip_prefix("SERVER_") {
240 server_env.insert(key.to_lowercase(), value);
241 } else if let Some(key) = key.strip_prefix("HTTP_CLIENT_IP_") {
242 client_ip_env.insert(key.to_lowercase(), value);
243 } else if let Some(key) = key.strip_prefix("HTTP_") {
244 http_env.insert(key.to_lowercase(), value);
245 } else if let Some(key) = key.strip_prefix("API_") {
246 api_env.insert(key.to_lowercase(), value);
247 }
248 }
249 }
250 Err(dotenvy::Error::Io(e)) if e.kind() == std::io::ErrorKind::NotFound => {}
251 Err(_) => return Err(AppError::Configuration("Could not read .env.".into())),
252 }
253 let app = Figment::from(Serialized::defaults(AppSettings::default()))
254 .merge(Toml::file(root.join("config/app.toml")))
255 .merge(Serialized::defaults(app_env))
256 .merge(Env::prefixed("APP_"))
257 .extract()
258 .map_err(|_| {
259 AppError::Configuration(
260 "Invalid application settings. Check config/app.toml and APP_* variables."
261 .into(),
262 )
263 })?;
264 let database = Figment::from(Serialized::defaults(DatabaseSettings::default()))
265 .merge(Toml::file(root.join("config/database.toml")))
266 .merge(Serialized::defaults(db_env))
267 .merge(Env::prefixed("DATABASE_"))
268 .extract()
269 .map_err(|_| AppError::Configuration(
270 "Invalid database settings. Check config/database.toml and DATABASE_* variables.".into(),
271 ))?;
272 let server = Figment::from(Serialized::defaults(ServerSettings::default()))
273 .merge(Toml::file(root.join("config/server.toml")))
274 .merge(Serialized::defaults(server_env))
275 .merge(Env::prefixed("SERVER_"))
276 .extract()
277 .map_err(|_| AppError::Configuration(
278 "Invalid server settings. Check config/server.toml and SERVER_* variables; ports must be 0..=65535 and deadlines integer seconds.".into()))?;
279 http_env.insert("client_ip".into(), serde_json::Value::Object(client_ip_env));
280 let http = Figment::from(Serialized::defaults(HttpSettings::default()))
281 .merge(Toml::file(root.join("config/http.toml")))
282 .merge(Serialized::defaults(http_env))
283 .merge(Env::prefixed("HTTP_").map(|key| key.as_str().to_lowercase().replacen("client_ip_", "client_ip.", 1).into()))
284 .extract()
285 .map_err(|_| AppError::Configuration(
286 "Invalid HTTP settings. Check config/http.toml and HTTP_* variables: deadlines use integer seconds, body limits integer bytes; client_ip.strategy must be direct/forwarded/x-forwarded-for/x-real-ip, trusted_proxies a CIDR array, and require_proxy a boolean.".into()))?;
287 let api = Figment::from(Serialized::defaults(ApiSettings::default()))
288 .merge(Toml::file(root.join("config/api.toml")))
289 .merge(Serialized::defaults(api_env))
290 .merge(Env::prefixed("API_"))
291 .extract()
292 .map_err(|_| {
293 AppError::Configuration(
294 "Invalid API settings. Check config/api.toml and API_* variables.".into(),
295 )
296 })?;
297 auth_env.insert("password".into(), serde_json::Value::Object(password_env));
298 let auth = Figment::from(Serialized::defaults(crate::AuthSettings::default()))
299 .merge(Toml::file(root.join("config/auth.toml")))
300 .merge(Serialized::defaults(auth_env))
301 .merge(Env::prefixed("AUTH_").map(|key| {
302 let key = key.as_str().to_lowercase();
303 match key.strip_prefix("password_") {
304 Some(setting) if setting != "reset_lifetime_seconds" => {
305 format!("password.{setting}").into()
306 }
307 _ => key.into(),
308 }
309 }))
310 .extract()
311 .map_err(|_| {
312 AppError::Configuration(
313 "Invalid auth settings. Check config/auth.toml and AUTH_* variables; use [password] hash_concurrency = \"auto\" or an integer, integer cost/queue limits, and AUTH_PASSWORD_* environment overrides.".into(),
314 )
315 })?;
316 let jobs = Figment::from(Serialized::defaults(crate::JobsSettings::default()))
317 .merge(Toml::file(root.join("config/jobs.toml")))
318 .merge(Serialized::defaults(jobs_env))
319 .merge(Env::prefixed("JOBS_"))
320 .extract()
321 .map_err(|_| {
322 AppError::Configuration(
323 "Invalid jobs settings. Check config/jobs.toml and JOBS_* variables.".into(),
324 )
325 })?;
326 for (key, variable) in [
329 ("username", "MAIL_SMTP_USERNAME"),
330 ("password", "MAIL_SMTP_PASSWORD"),
331 ] {
332 match std::env::var(variable) {
333 Ok(value) => {
334 smtp_env.insert(key.into(), serde_json::Value::String(value));
335 }
336 Err(std::env::VarError::NotPresent) => {}
337 Err(_) => {
338 return Err(AppError::Configuration(
339 "SMTP credentials must be valid UTF-8 (values redacted).".into(),
340 ));
341 }
342 }
343 }
344 mail_env.insert("smtp".into(), serde_json::Value::Object(smtp_env));
345 let mail = Figment::from(Serialized::defaults(crate::MailSettings::default()))
346 .merge(Toml::file(root.join("config/mail.toml")))
347 .merge(Serialized::defaults(mail_env))
348 .merge(Env::prefixed("MAIL_").ignore(&["smtp_username", "smtp_password"]).map(|key| key.as_str().to_lowercase().replacen("smtp_", "smtp.", 1).into()))
349 .extract()
350 .map_err(|_| AppError::Configuration("Invalid mail settings. Check config/mail.toml and MAIL_* variables (credentials redacted).".into()))?;
351 let config = Self {
352 mail,
353 jobs,
354 auth,
355 app,
356 database,
357 server,
358 http,
359 api,
360 };
361 config.validate_application()?;
362 if require_database {
363 config.database.validate()?;
364 }
365 Ok(config)
366 }
367
368 pub fn validate(&self) -> Result<()> {
370 self.validate_application()?;
371 self.database.validate()
372 }
373
374 fn validate_application(&self) -> Result<()> {
375 self.http.client_ip.validate()?;
376 self.auth.password.concurrency()?;
377 self.jobs.validate()?;
378 self.mail.validate()?;
379 if self
380 .api
381 .title
382 .as_ref()
383 .is_some_and(|title| title.trim().is_empty())
384 || self.api.version.trim().is_empty()
385 {
386 return Err(AppError::Configuration(
387 "API_TITLE (when set) and API_VERSION must not be empty.".into(),
388 ));
389 }
390 if self.app.name.trim().is_empty() || self.app.host.trim().is_empty() {
391 return Err(AppError::Configuration(
392 "APP_NAME and APP_HOST cannot be empty.".into(),
393 ));
394 }
395 if !matches!(
396 self.app.environment.as_str(),
397 "development" | "test" | "production"
398 ) {
399 return Err(AppError::Configuration(
400 "APP_ENVIRONMENT must be development, test, or production.".into(),
401 ));
402 }
403 if self.host().trim().is_empty() || self.host().chars().any(char::is_whitespace) {
404 return Err(AppError::Configuration(
405 "SERVER_HOST must be a hostname or IP address without whitespace.".into(),
406 ));
407 }
408 if self.app.environment == "production" && self.port() == 0 {
409 return Err(AppError::Configuration(
410 "The production server port must be 1..=65535.".into(),
411 ));
412 }
413 if !(1..=3600).contains(&self.server.shutdown_timeout_seconds) {
414 return Err(AppError::Configuration(
415 "SERVER_SHUTDOWN_TIMEOUT_SECONDS must be 1..=3600.".into(),
416 ));
417 }
418 if self.http.request_timeout_seconds > 86400 {
419 return Err(AppError::Configuration("HTTP_REQUEST_TIMEOUT_SECONDS must be 0..=86400 (0 intentionally disables the deadline).".into()));
420 }
421 if !(1..=30).contains(&self.http.readiness_timeout_seconds) {
422 return Err(AppError::Configuration(
423 "HTTP_READINESS_TIMEOUT_SECONDS must be 1..=30.".into(),
424 ));
425 }
426 if !(1..=1024 * 1024 * 1024).contains(&self.http.max_body_bytes) {
427 return Err(AppError::Configuration(
428 "HTTP_MAX_BODY_BYTES must be 1..=1073741824.".into(),
429 ));
430 }
431 Ok(())
432 }
433
434 pub fn host(&self) -> &str {
436 self.server.host.as_deref().unwrap_or(&self.app.host)
437 }
438
439 pub fn port(&self) -> u16 {
441 self.server.port.unwrap_or(self.app.port)
442 }
443}
444
445impl DatabaseSettings {
446 pub fn validate(&self) -> Result<()> {
448 if self.url.trim().is_empty() {
449 return Err(AppError::Configuration(
450 "Database configuration error: DATABASE_URL is missing.".into(),
451 ));
452 }
453 if !(self.url.starts_with("postgres://")
454 || self.url.starts_with("postgresql://")
455 || self.url.starts_with("sqlite:"))
456 {
457 return Err(AppError::Configuration(
458 "DATABASE_URL must use PostgreSQL or SQLite.".into(),
459 ));
460 }
461 if self.max_connections == 0
462 || self.max_connections > 10_000
463 || self.min_connections > self.max_connections
464 || !(1..=3600).contains(&self.connect_timeout_seconds)
465 || !(1..=3600).contains(&self.acquire_timeout_seconds)
466 || !(1..=86400).contains(&self.idle_timeout_seconds)
467 {
468 return Err(AppError::Configuration(
469 "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(),
470 ));
471 }
472 Ok(())
473 }
474}