1use crate::errors::{KodeBridgeError, Result};
2use crate::pool::PoolConfig;
3use serde::{Deserialize, Serialize};
4use std::path::Path;
5use std::time::Duration;
6
7#[derive(Debug, Clone, Serialize, Deserialize, Default)]
9pub struct GlobalConfig {
10 pub client: ClientGlobalConfig,
12 pub streaming: StreamingGlobalConfig,
14 pub logging: LoggingConfig,
16 pub features: FeatureFlags,
18}
19
20#[derive(Debug, Clone, Serialize, Deserialize)]
22pub struct ClientGlobalConfig {
23 pub default_timeout_ms: u64,
25 pub enable_pooling: bool,
27 pub pool: PoolConfig,
29 pub max_retries: usize,
31 pub retry_delay_ms: u64,
32 pub connection_timeout_ms: u64,
34}
35
36impl Default for ClientGlobalConfig {
37 fn default() -> Self {
38 Self {
39 default_timeout_ms: 10_000, enable_pooling: true,
41 pool: PoolConfig::default(),
42 max_retries: 5, retry_delay_ms: 50, connection_timeout_ms: 5_000, }
46 }
47}
48
49#[derive(Debug, Clone, Serialize, Deserialize)]
51pub struct StreamingGlobalConfig {
52 pub default_timeout_ms: u64,
54 pub buffer_size: usize,
56 pub max_retries: usize,
58 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#[derive(Debug, Clone, Serialize, Deserialize)]
75pub struct LoggingConfig {
76 pub enabled: bool,
78 pub level: String,
80 pub structured: bool,
82 pub log_requests: bool,
84 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#[derive(Debug, Clone, Serialize, Deserialize)]
102pub struct FeatureFlags {
103 pub http2_support: bool,
105 pub compression: bool,
107 pub caching: bool,
109 pub metrics: bool,
111 pub keep_alive: bool,
113 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 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 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 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 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 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 pub const fn client_timeout(&self) -> Duration {
199 Duration::from_millis(self.client.default_timeout_ms)
200 }
201
202 pub const fn streaming_timeout(&self) -> Duration {
204 Duration::from_millis(self.streaming.default_timeout_ms)
205 }
206
207 pub const fn retry_delay(&self) -> Duration {
209 Duration::from_millis(self.client.retry_delay_ms)
210 }
211
212 pub const fn connection_timeout(&self) -> Duration {
214 Duration::from_millis(self.client.connection_timeout_ms)
215 }
216
217 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 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
258pub struct ConfigBuilder {
260 config: GlobalConfig,
261}
262
263impl ConfigBuilder {
264 pub fn new() -> Self {
265 Self {
266 config: GlobalConfig::default(),
267 }
268 }
269
270 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 pub const fn enable_pooling(mut self, enabled: bool) -> Self {
278 self.config.client.enable_pooling = enabled;
279 self
280 }
281
282 pub const fn pool_config(mut self, pool_config: PoolConfig) -> Self {
284 self.config.client.pool = pool_config;
285 self
286 }
287
288 pub const fn max_retries(mut self, retries: usize) -> Self {
290 self.config.client.max_retries = retries;
291 self
292 }
293
294 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 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 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}