use crate::exec::transaction::{IsolationLevel, TransactionConfig};
use anyhow::{Context, Result};
use serde::{Deserialize, Serialize};
use std::time::Duration;
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct IgnisConfig {
pub database: DatabaseConfig,
pub pool: PoolConfig,
pub transaction: TransactionConfig,
pub cache: CacheConfig,
pub performance: PerformanceConfig,
pub monitoring: MonitoringConfig,
}
impl Default for IgnisConfig {
fn default() -> Self {
Self {
database: DatabaseConfig::default(),
pool: PoolConfig::default(),
transaction: TransactionConfig::default(),
cache: CacheConfig::default(),
performance: PerformanceConfig::default(),
monitoring: MonitoringConfig::default(),
}
}
}
impl IgnisConfig {
pub fn from_yaml_file(path: &str) -> Result<Self> {
let content = std::fs::read_to_string(path)
.with_context(|| format!("Failed to read config file: {}", path))?;
let config: Self = serde_yaml::from_str(&content)
.with_context(|| format!("Failed to parse YAML config from: {}", path))?;
Ok(config)
}
pub fn from_env() -> Result<Self> {
let mut config = Self::default();
if let Ok(url) = std::env::var("IGNIS_DATABASE_URL") {
config.database.url = url;
}
if let Ok(max_conn) = std::env::var("IGNIS_MAX_CONNECTIONS") {
config.pool.max_connections = max_conn.parse().ok();
}
if let Ok(min_conn) = std::env::var("IGNIS_MIN_CONNECTIONS") {
config.pool.min_connections = min_conn.parse().ok();
}
if let Ok(timeout) = std::env::var("IGNIS_TRANSACTION_TIMEOUT") {
if let Ok(secs) = timeout.parse::<u64>() {
config.transaction.timeout = Duration::from_secs(secs);
}
}
Ok(config)
}
pub fn save_to_yaml_file(&self, path: &str) -> Result<()> {
let content =
serde_yaml::to_string(self).with_context(|| "Failed to serialize config to YAML")?;
std::fs::write(path, content)
.with_context(|| format!("Failed to write config file: {}", path))?;
Ok(())
}
pub fn validate(&self) -> Result<()> {
if self.database.url.is_empty() {
anyhow::bail!("Database URL cannot be empty");
}
if let (Some(min), Some(max)) = (self.pool.min_connections, self.pool.max_connections) {
if min > max {
anyhow::bail!("min_connections cannot be greater than max_connections");
}
}
if self.pool.acquire_timeout.unwrap_or(Duration::from_secs(30)) < Duration::from_secs(1) {
anyhow::bail!("acquire_timeout must be at least 1 second");
}
Ok(())
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DatabaseConfig {
pub url: String,
pub name: Option<String>,
pub default_schema: Option<String>,
pub ssl_mode: Option<SslMode>,
pub connect_timeout: Option<Duration>,
}
impl Default for DatabaseConfig {
fn default() -> Self {
Self {
url: "postgresql://localhost/ignis_test".to_string(),
name: None,
default_schema: Some("public".to_string()),
ssl_mode: Some(SslMode::Prefer),
connect_timeout: Some(Duration::from_secs(10)),
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
pub enum SslMode {
Disable,
Allow,
Prefer,
Require,
VerifyCa,
VerifyFull,
}
impl std::fmt::Display for SslMode {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
SslMode::Disable => write!(f, "disable"),
SslMode::Allow => write!(f, "allow"),
SslMode::Prefer => write!(f, "prefer"),
SslMode::Require => write!(f, "require"),
SslMode::VerifyCa => write!(f, "verify-ca"),
SslMode::VerifyFull => write!(f, "verify-full"),
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PoolConfig {
pub max_connections: Option<u32>,
pub min_connections: Option<u32>,
pub acquire_timeout: Option<Duration>,
pub idle_timeout: Option<Duration>,
pub max_lifetime: Option<Duration>,
pub test_before_acquire: Option<bool>,
pub health_check_sql: Option<String>,
}
impl Default for PoolConfig {
fn default() -> Self {
Self {
max_connections: Some(10),
min_connections: Some(2),
acquire_timeout: Some(Duration::from_secs(30)),
idle_timeout: Some(Duration::from_secs(600)), max_lifetime: Some(Duration::from_secs(1800)), test_before_acquire: Some(true),
health_check_sql: Some("SELECT 1".to_string()),
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CacheConfig {
pub enable_caching: bool,
pub max_cached_queries: usize,
pub cache_ttl: Duration,
pub enable_lru_eviction: bool,
pub lru_eviction_threshold: u8,
}
impl Default for CacheConfig {
fn default() -> Self {
Self {
enable_caching: true,
max_cached_queries: 1000,
cache_ttl: Duration::from_secs(300), enable_lru_eviction: true,
lru_eviction_threshold: 80, }
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PerformanceConfig {
pub enable_query_monitoring: bool,
pub enable_pool_monitoring: bool,
pub enable_statement_caching: bool,
pub max_prepared_statements: usize,
pub enable_connection_pooling: bool,
pub pool_size_multiplier: f32,
}
impl Default for PerformanceConfig {
fn default() -> Self {
Self {
enable_query_monitoring: true,
enable_pool_monitoring: true,
enable_statement_caching: true,
max_prepared_statements: 100,
enable_connection_pooling: true,
pool_size_multiplier: 1.0,
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MonitoringConfig {
pub enable_query_monitoring: bool,
pub enable_pool_monitoring: bool,
pub enable_transaction_monitoring: bool,
pub enable_cache_monitoring: bool,
pub metrics_interval: Duration,
pub enable_slow_query_logging: bool,
pub slow_query_threshold: Duration,
pub enable_error_logging: bool,
pub log_level: LogLevel,
}
impl Default for MonitoringConfig {
fn default() -> Self {
Self {
enable_query_monitoring: true,
enable_pool_monitoring: true,
enable_transaction_monitoring: true,
enable_cache_monitoring: true,
metrics_interval: Duration::from_secs(60), enable_slow_query_logging: true,
slow_query_threshold: Duration::from_secs(1), enable_error_logging: true,
log_level: LogLevel::Info,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
pub enum LogLevel {
None,
Error,
Warn,
Info,
Debug,
Trace,
}
impl std::fmt::Display for LogLevel {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
LogLevel::None => write!(f, "none"),
LogLevel::Error => write!(f, "error"),
LogLevel::Warn => write!(f, "warn"),
LogLevel::Info => write!(f, "info"),
LogLevel::Debug => write!(f, "debug"),
LogLevel::Trace => write!(f, "trace"),
}
}
}
#[derive(Debug)]
pub struct IgnisConfigBuilder {
config: IgnisConfig,
}
impl IgnisConfigBuilder {
pub fn new() -> Self {
Self {
config: IgnisConfig::default(),
}
}
pub fn database_url(mut self, url: impl Into<String>) -> Self {
self.config.database.url = url.into();
self
}
pub fn max_connections(mut self, max: u32) -> Self {
self.config.pool.max_connections = Some(max);
self
}
pub fn min_connections(mut self, min: u32) -> Self {
self.config.pool.min_connections = Some(min);
self
}
pub fn transaction_timeout(mut self, timeout: Duration) -> Self {
self.config.transaction.timeout = timeout;
self
}
pub fn isolation_level(mut self, level: IsolationLevel) -> Self {
self.config.transaction.isolation_level = level;
self
}
pub fn enable_query_monitoring(mut self, enable: bool) -> Self {
self.config.monitoring.enable_query_monitoring = enable;
self
}
pub fn build(self) -> Result<IgnisConfig> {
self.config.validate()?;
Ok(self.config)
}
}
impl Default for IgnisConfigBuilder {
fn default() -> Self {
Self::new()
}
}