use crate::config::AppConfig;
use crate::error::{Error, Result};
use once_cell::sync::{Lazy, 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)?;
serde_json::from_value(value.clone()).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)),
_ => None,
}
}
pub fn get_bool(path: &str) -> Option<bool> {
Self::get(path)
}
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(),
_ => 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: Lazy<bool> = Lazy::new(|| {
if CONF::is_initialized() {
CONF::is_development()
} else {
let env = std::env::var("RUSTF_ENVIRONMENT")
.or_else(|_| std::env::var("RUST_ENV"))
.or_else(|_| std::env::var("NODE_ENV"))
.unwrap_or_else(|_| "development".to_string());
env.to_lowercase() != "production" && env.to_lowercase() != "prod"
}
});
#[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_is_enabled() {
let _ = *DEBUG;
}
}