kode_bridge/
config.rs

1use crate::errors::{KodeBridgeError, Result};
2use crate::pool::PoolConfig;
3use serde::{Deserialize, Serialize};
4use std::path::Path;
5use std::time::Duration;
6
7/// Global configuration for kode-bridge
8#[derive(Debug, Clone, Serialize, Deserialize, Default)]
9pub struct GlobalConfig {
10    /// Default client configuration
11    pub client: ClientGlobalConfig,
12    /// Streaming client configuration
13    pub streaming: StreamingGlobalConfig,
14    /// Logging configuration
15    pub logging: LoggingConfig,
16    /// Feature flags
17    pub features: FeatureFlags,
18}
19
20/// Client configuration
21#[derive(Debug, Clone, Serialize, Deserialize)]
22pub struct ClientGlobalConfig {
23    /// Default timeout for requests
24    pub default_timeout_ms: u64,
25    /// Enable connection pooling by default
26    pub enable_pooling: bool,
27    /// Pool configuration
28    pub pool: PoolConfig,
29    /// Retry configuration
30    pub max_retries: usize,
31    pub retry_delay_ms: u64,
32    /// Connection timeout
33    pub connection_timeout_ms: u64,
34}
35
36impl Default for ClientGlobalConfig {
37    fn default() -> Self {
38        Self {
39            default_timeout_ms: 10_000, // Reduce default timeout to 10 seconds
40            enable_pooling: true,
41            pool: PoolConfig::default(),
42            max_retries: 5,               // Increase retry attempts
43            retry_delay_ms: 50,           // Reduce retry delay
44            connection_timeout_ms: 5_000, // Reduce connection timeout
45        }
46    }
47}
48
49/// Streaming client configuration
50#[derive(Debug, Clone, Serialize, Deserialize)]
51pub struct StreamingGlobalConfig {
52    /// Default timeout for streaming connections
53    pub default_timeout_ms: u64,
54    /// Buffer size for streaming
55    pub buffer_size: usize,
56    /// Max retries for streaming connections
57    pub max_retries: usize,
58    /// Retry delay for streaming connections
59    pub retry_delay_ms: u64,
60}
61
62impl Default for StreamingGlobalConfig {
63    fn default() -> Self {
64        Self {
65            default_timeout_ms: 60_000,
66            buffer_size: 8192,
67            max_retries: 3,
68            retry_delay_ms: 100,
69        }
70    }
71}
72
73/// Logging configuration
74#[derive(Debug, Clone, Serialize, Deserialize)]
75pub struct LoggingConfig {
76    /// Enable tracing
77    pub enabled: bool,
78    /// Log level (trace, debug, info, warn, error)
79    pub level: String,
80    /// Enable structured logging
81    pub structured: bool,
82    /// Log request/response details
83    pub log_requests: bool,
84    /// Log connection events
85    pub log_connections: bool,
86}
87
88impl Default for LoggingConfig {
89    fn default() -> Self {
90        Self {
91            enabled: false,
92            level: "info".to_string(),
93            structured: false,
94            log_requests: false,
95            log_connections: false,
96        }
97    }
98}
99
100/// Feature flags for experimental or optional features
101#[derive(Debug, Clone, Serialize, Deserialize)]
102pub struct FeatureFlags {
103    /// Enable HTTP/2 support (future feature)
104    pub http2_support: bool,
105    /// Enable compression
106    pub compression: bool,
107    /// Enable request/response caching
108    pub caching: bool,
109    /// Enable metrics collection
110    pub metrics: bool,
111    /// Enable connection keep-alive optimization
112    pub keep_alive: bool,
113    /// Enable automatic reconnection
114    pub auto_reconnect: bool,
115}
116
117impl Default for FeatureFlags {
118    fn default() -> Self {
119        Self {
120            http2_support: false,
121            compression: false,
122            caching: false,
123            metrics: false,
124            keep_alive: true,
125            auto_reconnect: true,
126        }
127    }
128}
129
130impl GlobalConfig {
131    /// Load configuration from a TOML file
132    pub fn from_toml_file<P: AsRef<Path>>(path: P) -> Result<Self> {
133        let content = std::fs::read_to_string(path)
134            .map_err(|e| KodeBridgeError::configuration(format!("Failed to read config file: {}", e)))?;
135
136        toml::from_str(&content)
137            .map_err(|e| KodeBridgeError::configuration(format!("Failed to parse TOML config: {}", e)))
138    }
139
140    /// Load configuration from a JSON file
141    pub fn from_json_file<P: AsRef<Path>>(path: P) -> Result<Self> {
142        let content = std::fs::read_to_string(path)
143            .map_err(|e| KodeBridgeError::configuration(format!("Failed to read config file: {}", e)))?;
144
145        serde_json::from_str(&content)
146            .map_err(|e| KodeBridgeError::configuration(format!("Failed to parse JSON config: {}", e)))
147    }
148
149    /// Save configuration to a TOML file
150    pub fn save_toml_file<P: AsRef<Path>>(&self, path: P) -> Result<()> {
151        let content = toml::to_string_pretty(self)
152            .map_err(|e| KodeBridgeError::configuration(format!("Failed to serialize config: {}", e)))?;
153
154        std::fs::write(path, content)
155            .map_err(|e| KodeBridgeError::configuration(format!("Failed to write config file: {}", e)))
156    }
157
158    /// Save configuration to a JSON file
159    pub fn save_json_file<P: AsRef<Path>>(&self, path: P) -> Result<()> {
160        let content = serde_json::to_string_pretty(self)
161            .map_err(|e| KodeBridgeError::configuration(format!("Failed to serialize config: {}", e)))?;
162
163        std::fs::write(path, content)
164            .map_err(|e| KodeBridgeError::configuration(format!("Failed to write config file: {}", e)))
165    }
166
167    /// Apply environment variable overrides
168    pub fn apply_env_overrides(&mut self) {
169        if let Ok(timeout) = std::env::var("KODE_BRIDGE_TIMEOUT_MS") {
170            if let Ok(timeout_ms) = timeout.parse::<u64>() {
171                self.client.default_timeout_ms = timeout_ms;
172            }
173        }
174
175        if let Ok(pooling) = std::env::var("KODE_BRIDGE_ENABLE_POOLING") {
176            self.client.enable_pooling = pooling.to_lowercase() == "true";
177        }
178
179        if let Ok(retries) = std::env::var("KODE_BRIDGE_MAX_RETRIES") {
180            if let Ok(retries_num) = retries.parse::<usize>() {
181                self.client.max_retries = retries_num;
182            }
183        }
184
185        if let Ok(log_level) = std::env::var("KODE_BRIDGE_LOG_LEVEL") {
186            self.logging.level = log_level;
187            self.logging.enabled = true;
188        }
189
190        if let Ok(pool_size) = std::env::var("KODE_BRIDGE_POOL_SIZE") {
191            if let Ok(size) = pool_size.parse::<usize>() {
192                self.client.pool.max_size = size;
193            }
194        }
195    }
196
197    /// Convert client timeout to Duration
198    pub const fn client_timeout(&self) -> Duration {
199        Duration::from_millis(self.client.default_timeout_ms)
200    }
201
202    /// Convert streaming timeout to Duration
203    pub const fn streaming_timeout(&self) -> Duration {
204        Duration::from_millis(self.streaming.default_timeout_ms)
205    }
206
207    /// Convert retry delay to Duration
208    pub const fn retry_delay(&self) -> Duration {
209        Duration::from_millis(self.client.retry_delay_ms)
210    }
211
212    /// Convert connection timeout to Duration
213    pub const fn connection_timeout(&self) -> Duration {
214        Duration::from_millis(self.client.connection_timeout_ms)
215    }
216
217    /// Check if feature is enabled
218    pub fn is_feature_enabled(&self, feature: &str) -> bool {
219        match feature {
220            "http2" => self.features.http2_support,
221            "compression" => self.features.compression,
222            "caching" => self.features.caching,
223            "metrics" => self.features.metrics,
224            "keep_alive" => self.features.keep_alive,
225            "auto_reconnect" => self.features.auto_reconnect,
226            _ => false,
227        }
228    }
229
230    /// Validate configuration
231    pub fn validate(&self) -> Result<()> {
232        if self.client.default_timeout_ms == 0 {
233            return Err(KodeBridgeError::configuration("Client timeout cannot be zero"));
234        }
235
236        if self.client.max_retries > 10 {
237            return Err(KodeBridgeError::configuration("Max retries should be <= 10"));
238        }
239
240        if self.client.pool.max_size == 0 {
241            return Err(KodeBridgeError::configuration("Pool max size cannot be zero"));
242        }
243
244        if self.client.pool.min_idle > self.client.pool.max_size {
245            return Err(KodeBridgeError::configuration(
246                "Pool min_idle cannot be greater than max_size",
247            ));
248        }
249
250        if !["trace", "debug", "info", "warn", "error"].contains(&self.logging.level.as_str()) {
251            return Err(KodeBridgeError::configuration("Invalid log level"));
252        }
253
254        Ok(())
255    }
256}
257
258/// Configuration builder for fluent configuration setup
259pub struct ConfigBuilder {
260    config: GlobalConfig,
261}
262
263impl ConfigBuilder {
264    pub fn new() -> Self {
265        Self {
266            config: GlobalConfig::default(),
267        }
268    }
269
270    /// Set client timeout
271    pub const fn client_timeout(mut self, timeout: Duration) -> Self {
272        self.config.client.default_timeout_ms = timeout.as_millis() as u64;
273        self
274    }
275
276    /// Enable or disable connection pooling
277    pub const fn enable_pooling(mut self, enabled: bool) -> Self {
278        self.config.client.enable_pooling = enabled;
279        self
280    }
281
282    /// Set pool configuration
283    pub const fn pool_config(mut self, pool_config: PoolConfig) -> Self {
284        self.config.client.pool = pool_config;
285        self
286    }
287
288    /// Set max retries
289    pub const fn max_retries(mut self, retries: usize) -> Self {
290        self.config.client.max_retries = retries;
291        self
292    }
293
294    /// Enable logging
295    pub fn enable_logging(mut self, level: &str) -> Self {
296        self.config.logging.enabled = true;
297        self.config.logging.level = level.to_string();
298        self
299    }
300
301    /// Enable feature
302    pub fn enable_feature(mut self, feature: &str) -> Self {
303        match feature {
304            "compression" => self.config.features.compression = true,
305            "caching" => self.config.features.caching = true,
306            "metrics" => self.config.features.metrics = true,
307            "keep_alive" => self.config.features.keep_alive = true,
308            "auto_reconnect" => self.config.features.auto_reconnect = true,
309            _ => {}
310        }
311        self
312    }
313
314    /// Build the configuration
315    pub fn build(self) -> Result<GlobalConfig> {
316        self.config.validate()?;
317        Ok(self.config)
318    }
319}
320
321impl Default for ConfigBuilder {
322    fn default() -> Self {
323        Self::new()
324    }
325}