use crate::config::AppConfig;
use crate::error::{Error, Result};
use once_cell::sync::OnceCell;
use serde_json::Value;
use std::sync::Arc;
static CONFIG: OnceCell<ConfigStore> = OnceCell::new();
struct ConfigStore {
config: Arc<AppConfig>,
json: Value,
}
pub struct CONF;
impl CONF {
pub fn init(config: AppConfig) -> Result<()> {
let json = serde_json::to_value(&config)
.map_err(|e| Error::internal(format!("Failed to serialize config: {}", e)))?;
let store = ConfigStore {
config: Arc::new(config),
json,
};
CONFIG.set(store).map_err(|_| {
Error::internal("Configuration has already been initialized".to_string())
})?;
log::debug!("Global configuration initialized");
Ok(())
}
pub fn get<T: serde::de::DeserializeOwned>(path: &str) -> Option<T> {
let store = CONFIG.get()?;
let value = Self::get_nested(&store.json, path)?;
crate::config_lenient::from_value(value).ok()
}
pub fn get_string(path: &str) -> Option<String> {
Self::get(path)
}
pub fn get_int(path: &str) -> Option<i64> {
let store = CONFIG.get()?;
let value = Self::get_nested(&store.json, path)?;
match value {
Value::Number(n) => n.as_i64().or_else(|| n.as_u64().map(|u| u as i64)),
Value::String(s) => s.trim().parse().ok(),
_ => None,
}
}
pub fn get_bool(path: &str) -> Option<bool> {
let store = CONFIG.get()?;
match Self::get_nested(&store.json, path)? {
Value::Bool(b) => Some(*b),
Value::String(s) => match s.trim().to_ascii_lowercase().as_str() {
"true" => Some(true),
"false" => Some(false),
_ => None,
},
_ => None,
}
}
pub fn get_float(path: &str) -> Option<f64> {
let store = CONFIG.get()?;
let value = Self::get_nested(&store.json, path)?;
match value {
Value::Number(n) => n.as_f64(),
Value::String(s) => s.trim().parse().ok(),
_ => None,
}
}
pub fn get_or<T: serde::de::DeserializeOwned>(path: &str, default: T) -> T {
Self::get(path).unwrap_or(default)
}
pub fn has(path: &str) -> bool {
CONFIG
.get()
.and_then(|store| Self::get_nested(&store.json, path))
.is_some()
}
pub fn all() -> Option<Arc<AppConfig>> {
CONFIG.get().map(|store| store.config.clone())
}
pub fn env() -> Option<String> {
Self::get_string("environment")
}
pub fn is_production() -> bool {
Self::env().map(|e| e == "production").unwrap_or(false)
}
pub fn is_development() -> bool {
Self::env().map(|e| e == "development").unwrap_or(true)
}
pub fn is_initialized() -> bool {
CONFIG.get().is_some()
}
fn get_nested<'a>(obj: &'a Value, path: &str) -> Option<&'a Value> {
let parts: Vec<&str> = path.split('.').collect();
let mut current = obj;
for part in parts {
match current {
Value::Object(map) => {
current = map.get(part)?;
}
_ => return None,
}
}
Some(current)
}
}
pub static DEBUG: Debug = Debug;
#[derive(Debug, Clone, Copy)]
pub struct Debug;
impl Debug {
pub fn get(&self) -> bool {
if CONF::is_initialized() {
CONF::is_development()
} else {
match crate::config::Environment::from_process_env() {
Ok(Some(env)) => env.is_development(),
Ok(None) => true,
Err(_) => false,
}
}
}
}
impl std::ops::Deref for Debug {
type Target = bool;
fn deref(&self) -> &bool {
if self.get() {
&true
} else {
&false
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::config::AppConfig;
#[test]
fn test_conf_initialization_and_access() {
let config_toml = r#"
[server]
port = 3000
host = "localhost"
[views]
directory = "/test/views"
[custom]
api_key = "secret"
"#;
let config: AppConfig = toml::from_str(config_toml).unwrap();
CONF::init(config).unwrap();
assert_eq!(CONF::get_int("server.port"), Some(3000));
assert_eq!(
CONF::get_string("server.host"),
Some("localhost".to_string())
);
assert_eq!(
CONF::get_string("views.directory"),
Some("/test/views".to_string())
);
assert_eq!(CONF::get_or("server.port", 8000), 3000);
assert_eq!(
CONF::get_or("non.existent", "default".to_string()),
"default".to_string()
);
assert!(CONF::has("server.port"));
assert!(CONF::has("custom.api_key"));
assert!(!CONF::has("non.existent.path"));
assert!(CONF::is_development());
assert!(!CONF::is_production());
}
#[test]
fn test_debug_reads_the_current_environment() {
assert_eq!(*DEBUG, DEBUG.get());
}
}