use crate::{AppError, Result};
use figment::{
providers::{Env, Format, Serialized, Toml},
Figment,
};
use serde::{Deserialize, Serialize};
use std::{collections::BTreeMap, path::Path};
#[derive(Clone, Debug, Default, Deserialize, Serialize)]
pub struct AppConfig {
pub app: AppSettings,
pub database: DatabaseSettings,
}
#[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(default, deny_unknown_fields)]
pub struct AppSettings {
pub name: String,
pub environment: String,
pub host: String,
pub port: u16,
}
impl Default for AppSettings {
fn default() -> Self {
Self {
name: "Capy".into(),
environment: "development".into(),
host: "127.0.0.1".into(),
port: 8000,
}
}
}
#[derive(Clone, Deserialize, Serialize)]
#[serde(default, deny_unknown_fields)]
pub struct DatabaseSettings {
pub url: String,
pub max_connections: u32,
pub connect_timeout_seconds: u64,
}
impl std::fmt::Debug for DatabaseSettings {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("DatabaseSettings")
.field("url", &"[redacted]")
.field("max_connections", &self.max_connections)
.field("connect_timeout_seconds", &self.connect_timeout_seconds)
.finish()
}
}
impl Default for DatabaseSettings {
fn default() -> Self {
Self {
url: String::new(),
max_connections: 10,
connect_timeout_seconds: 10,
}
}
}
impl AppConfig {
pub fn load() -> Result<Self> {
Self::load_from(".")
}
pub fn load_from(root: impl AsRef<Path>) -> Result<Self> {
let root = root.as_ref();
let mut app_env = BTreeMap::new();
let mut db_env = BTreeMap::new();
match dotenvy::from_path_iter(root.join(".env")) {
Ok(entries) => {
for entry in entries {
let (key, value) = entry.map_err(|_| {
AppError::Configuration("Could not parse .env. Check its syntax.".into())
})?;
let value = serde_json::from_str::<serde_json::Value>(&value)
.unwrap_or(serde_json::Value::String(value));
if let Some(key) = key.strip_prefix("APP_") {
app_env.insert(key.to_lowercase(), value);
} else if let Some(key) = key.strip_prefix("DATABASE_") {
db_env.insert(key.to_lowercase(), value);
}
}
}
Err(dotenvy::Error::Io(e)) if e.kind() == std::io::ErrorKind::NotFound => {}
Err(_) => return Err(AppError::Configuration("Could not read .env.".into())),
}
let app = Figment::from(Serialized::defaults(AppSettings::default()))
.merge(Toml::file(root.join("config/app.toml")))
.merge(Serialized::defaults(app_env))
.merge(Env::prefixed("APP_"))
.extract()
.map_err(|_| {
AppError::Configuration(
"Invalid application settings. Check config/app.toml and APP_* variables."
.into(),
)
})?;
let database = Figment::from(Serialized::defaults(DatabaseSettings::default()))
.merge(Toml::file(root.join("config/database.toml")))
.merge(Serialized::defaults(db_env))
.merge(Env::prefixed("DATABASE_"))
.extract()
.map_err(|_| AppError::Configuration(
"Invalid database settings. Check config/database.toml and DATABASE_* variables.".into(),
))?;
let config = Self { app, database };
config.validate()?;
Ok(config)
}
pub fn validate(&self) -> Result<()> {
if self.app.name.trim().is_empty() || self.app.host.trim().is_empty() {
return Err(AppError::Configuration(
"APP_NAME and APP_HOST cannot be empty.".into(),
));
}
if !matches!(
self.app.environment.as_str(),
"development" | "test" | "production"
) {
return Err(AppError::Configuration(
"APP_ENVIRONMENT must be development, test, or production.".into(),
));
}
self.database.validate()
}
}
impl DatabaseSettings {
pub fn validate(&self) -> Result<()> {
if self.url.trim().is_empty() {
return Err(AppError::Configuration(
"Database configuration error: DATABASE_URL is missing.".into(),
));
}
if !(self.url.starts_with("postgres://")
|| self.url.starts_with("postgresql://")
|| self.url.starts_with("sqlite:"))
{
return Err(AppError::Configuration(
"DATABASE_URL must use PostgreSQL or SQLite.".into(),
));
}
if self.max_connections == 0 || self.connect_timeout_seconds == 0 {
return Err(AppError::Configuration(
"Database pool size and connection timeout must be greater than zero.".into(),
));
}
Ok(())
}
}