use dirs;
use dotenv::dotenv;
use once_cell::sync::Lazy;
use serde::{Deserialize, Serialize};
use std::env;
use std::fs;
use std::path::PathBuf;
#[derive(Serialize, Deserialize, Default)]
pub struct GlobalConfig {
pub api_key: Option<String>,
pub server: Option<String>,
}
impl GlobalConfig {
pub fn write(&self) -> Result<(), Box<dyn std::error::Error>> {
let config_path = get_config_file_path()?;
if let Some(parent) = config_path.parent() {
fs::create_dir_all(parent)?;
}
let yaml = serde_yaml::to_string(self)?;
fs::write(config_path, yaml)?;
Ok(())
}
pub fn read() -> Result<Self, Box<dyn std::error::Error>> {
let config_path = get_config_file_path()?;
if config_path.exists() {
let yaml = fs::read_to_string(config_path)?;
let config: GlobalConfig = serde_yaml::from_str(&yaml)?;
if config.api_key.is_none() {
return Err("Please login first using 'orign login'".into());
}
if config.server.is_none() {
return Err("Please login first using 'orign login'".into());
}
Ok(config)
} else {
let default_config = GlobalConfig::default();
default_config.write()?;
Ok(default_config)
}
}
}
fn get_config_file_path() -> Result<PathBuf, Box<dyn std::error::Error>> {
let home_dir = dirs::home_dir().ok_or("Could not determine home directory")?;
let config_dir = home_dir.join(".agentsea");
let config_path = config_dir.join("orign.yaml");
Ok(config_path)
}
pub struct Config {
pub message_queue_type: String,
pub kafka_bootstrap_servers: String,
pub kafka_timeout_ms: String,
pub redis_host: String,
pub redis_port: String,
pub redis_password: Option<String>,
pub redis_url: Option<String>,
pub database_url: String,
pub nebu_proxy_url: String,
pub auth_server_url: String,
pub orign_slack_url: String,
pub dataset_dir: String,
}
impl Config {
fn new() -> Self {
dotenv().ok();
Self {
message_queue_type: env::var("MESSAGE_QUEUE_TYPE")
.unwrap_or_else(|_| "redis".to_string()),
kafka_bootstrap_servers: env::var("KAFKA_BOOTSTRAP_SERVERS")
.unwrap_or_else(|_| "localhost:9092".to_string()),
kafka_timeout_ms: env::var("KAFKA_TIMEOUT_MS").unwrap_or_else(|_| "5000".to_string()),
redis_host: env::var("REDIS_HOST").unwrap_or_else(|_| "127.0.0.1".to_string()),
redis_port: env::var("REDIS_PORT").unwrap_or_else(|_| "6379".to_string()),
redis_password: env::var("REDIS_PASSWORD").ok(),
redis_url: env::var("REDIS_URL").ok(),
database_url: env::var("DATABASE_URL")
.unwrap_or_else(|_| "sqlite://.data/data.db".to_string()),
nebu_proxy_url: env::var("NEBU_PROXY_URL")
.unwrap_or_else(|_| "http://localhost:8000".to_string()),
auth_server_url: env::var("ORIGN_AUTH_SERVER")
.unwrap_or_else(|_| "https://auth.hub.agentlabs.xyz".to_string()),
orign_slack_url: env::var("ORIGN_SLACK_URL")
.unwrap_or_else(|_| "https://localhost:3000".to_string()),
dataset_dir: env::var("DATASET_DIR").unwrap_or_else(|_| {
let home_dir = dirs::home_dir().unwrap_or_default();
home_dir
.join(".agentsea/datasets")
.to_string_lossy()
.to_string()
}),
}
}
}
pub static CONFIG: Lazy<Config> = Lazy::new(Config::new);