1use anyhow::{anyhow, Result};
12use serde::{Deserialize, Serialize};
13use std::collections::HashMap;
14use std::fs;
15use std::path::{Path, PathBuf};
16use std::sync::Arc;
17use std::time::Duration;
18use tokio::sync::{broadcast, RwLock};
19use tracing::info;
20
21use crate::{CompressionType, StreamBackendType, StreamConfig, StreamPerformanceConfig};
22
23#[derive(Debug, Clone, Serialize, Deserialize)]
25pub enum ConfigSource {
26 File { path: PathBuf },
28 Environment { prefix: String },
30 Remote { url: String, key: String },
32 Memory { data: HashMap<String, String> },
34}
35
36pub struct ConfigManager {
38 current_config: Arc<RwLock<StreamConfig>>,
40 sources: Vec<ConfigSource>,
42 change_notifier: broadcast::Sender<ConfigChangeEvent>,
44 secret_manager: Arc<SecretManager>,
46 environment: Environment,
48 performance_profiles: HashMap<String, PerformanceProfile>,
50 tls_manager: Arc<TlsManager>,
52}
53
54#[derive(Debug, Clone)]
56pub enum ConfigChangeEvent {
57 Reloaded {
59 old_config: Box<StreamConfig>,
60 new_config: Box<StreamConfig>,
61 },
62 ValidationFailed { reason: String },
64 SecretRotated { secret_name: String },
66 TlsCertificateUpdated { cert_type: String },
68}
69
70#[derive(Debug, Clone, Serialize, Deserialize)]
72pub enum Environment {
73 Development,
74 Testing,
75 Staging,
76 Production,
77}
78
79impl Environment {
80 pub fn detect() -> Self {
82 if let Ok(env) = std::env::var("OXIRS_ENV") {
83 match env.to_lowercase().as_str() {
84 "dev" | "development" => Environment::Development,
85 "test" | "testing" => Environment::Testing,
86 "staging" | "stage" => Environment::Staging,
87 "prod" | "production" => Environment::Production,
88 _ => Environment::Development,
89 }
90 } else if let Ok(env) = std::env::var("RUST_ENV") {
91 match env.to_lowercase().as_str() {
92 "production" => Environment::Production,
93 _ => Environment::Development,
94 }
95 } else {
96 Environment::Development
97 }
98 }
99
100 pub fn get_defaults(&self) -> ConfigDefaults {
102 match self {
103 Environment::Development => ConfigDefaults {
104 log_level: "debug".to_string(),
105 enable_debug_endpoints: true,
106 connection_timeout_secs: 60,
107 max_connections: 10,
108 enable_compression: false,
109 enable_metrics: true,
110 enable_profiling: true,
111 },
112 Environment::Testing => ConfigDefaults {
113 log_level: "info".to_string(),
114 enable_debug_endpoints: true,
115 connection_timeout_secs: 30,
116 max_connections: 5,
117 enable_compression: false,
118 enable_metrics: true,
119 enable_profiling: false,
120 },
121 Environment::Staging => ConfigDefaults {
122 log_level: "info".to_string(),
123 enable_debug_endpoints: false,
124 connection_timeout_secs: 30,
125 max_connections: 50,
126 enable_compression: true,
127 enable_metrics: true,
128 enable_profiling: false,
129 },
130 Environment::Production => ConfigDefaults {
131 log_level: "warn".to_string(),
132 enable_debug_endpoints: false,
133 connection_timeout_secs: 30,
134 max_connections: 100,
135 enable_compression: true,
136 enable_metrics: true,
137 enable_profiling: false,
138 },
139 }
140 }
141}
142
143#[derive(Debug, Clone, Serialize, Deserialize)]
145pub struct ConfigDefaults {
146 pub log_level: String,
147 pub enable_debug_endpoints: bool,
148 pub connection_timeout_secs: u64,
149 pub max_connections: usize,
150 pub enable_compression: bool,
151 pub enable_metrics: bool,
152 pub enable_profiling: bool,
153}
154
155pub struct SecretManager {
157 backend: SecretBackend,
159 cache: Arc<RwLock<HashMap<String, CachedSecret>>>,
161 rotation_interval: Duration,
163}
164
165#[derive(Debug, Clone)]
167pub enum SecretBackend {
168 Environment { prefix: String },
170 File { directory: PathBuf },
172 Vault {
174 url: String,
175 token: String,
176 mount_path: String,
177 },
178 AwsSecretsManager { region: String },
180 Memory {
182 secrets: Arc<RwLock<HashMap<String, String>>>,
183 },
184}
185
186#[derive(Debug, Clone)]
188struct CachedSecret {
189 value: String,
190 cached_at: std::time::Instant,
191 expires_at: Option<std::time::Instant>,
192 version: u64,
193}
194
195impl SecretManager {
196 pub fn new(backend: SecretBackend, rotation_interval: Duration) -> Self {
198 Self {
199 backend,
200 cache: Arc::new(RwLock::new(HashMap::new())),
201 rotation_interval,
202 }
203 }
204
205 pub async fn get_secret(&self, name: &str) -> Result<String> {
207 {
209 let cache = self.cache.read().await;
210 if let Some(cached) = cache.get(name) {
211 if cached
212 .expires_at
213 .map_or(true, |exp| exp > std::time::Instant::now())
214 {
215 return Ok(cached.value.clone());
216 }
217 }
218 }
219
220 let value = match &self.backend {
222 SecretBackend::Environment { prefix } => {
223 let key = format!("{prefix}_{}", name.to_uppercase());
224 std::env::var(key).map_err(|_| anyhow!("Secret {name} not found in environment"))
225 }
226 SecretBackend::File { directory } => {
227 let path = directory.join(name);
228 fs::read_to_string(&path)
229 .map_err(|e| anyhow!("Failed to read secret from {path:?}: {e}"))
230 .map(|s| s.trim().to_string())
231 }
232 SecretBackend::Memory { secrets } => {
233 let secrets = secrets.read().await;
234 secrets
235 .get(name)
236 .cloned()
237 .ok_or_else(|| anyhow!("Secret {name} not found"))
238 }
239 _ => {
240 return Err(anyhow!(
243 "Secret backend requires an external service connection (Vault/AWS) \
244 that is not available in this configuration"
245 ));
246 }
247 }?;
248
249 let cached = CachedSecret {
251 value: value.clone(),
252 cached_at: std::time::Instant::now(),
253 expires_at: Some(std::time::Instant::now() + self.rotation_interval),
254 version: 1,
255 };
256
257 self.cache.write().await.insert(name.to_string(), cached);
258 Ok(value)
259 }
260
261 pub async fn set_secret(&self, name: &str, value: &str) -> Result<()> {
263 match &self.backend {
264 SecretBackend::Memory { secrets } => {
265 secrets
266 .write()
267 .await
268 .insert(name.to_string(), value.to_string());
269 self.cache.write().await.remove(name);
270 Ok(())
271 }
272 _ => Err(anyhow!("Set secret only supported for memory backend")),
273 }
274 }
275
276 pub async fn rotate_secrets(&self) -> Result<()> {
278 self.cache.write().await.clear();
279 info!("Rotated all cached secrets");
280 Ok(())
281 }
282}
283
284pub struct TlsManager {
286 certs: Arc<RwLock<HashMap<String, TlsCertificate>>>,
288 cert_paths: HashMap<String, CertPaths>,
290 auto_reload: bool,
292}
293
294#[derive(Debug, Clone)]
296pub struct TlsCertificate {
297 pub cert_pem: Vec<u8>,
298 pub key_pem: Vec<u8>,
299 pub ca_pem: Option<Vec<u8>>,
300 pub loaded_at: std::time::Instant,
301 pub expires_at: Option<chrono::DateTime<chrono::Utc>>,
302}
303
304#[derive(Debug, Clone)]
306struct CertPaths {
307 cert_path: PathBuf,
308 key_path: PathBuf,
309 ca_path: Option<PathBuf>,
310}
311
312impl TlsManager {
313 pub fn new(auto_reload: bool) -> Self {
315 Self {
316 certs: Arc::new(RwLock::new(HashMap::new())),
317 cert_paths: HashMap::new(),
318 auto_reload,
319 }
320 }
321
322 fn parse_certificate_expiration(cert_pem: &[u8]) -> Option<chrono::DateTime<chrono::Utc>> {
324 let cert_str = String::from_utf8_lossy(cert_pem);
327
328 if cert_str.contains("-----BEGIN CERTIFICATE-----") {
331 Some(chrono::Utc::now() + chrono::Duration::days(365))
334 } else {
335 None
336 }
337 }
338
339 pub async fn load_certificate(
341 &self,
342 name: &str,
343 cert_path: &Path,
344 key_path: &Path,
345 ca_path: Option<&Path>,
346 ) -> Result<()> {
347 let cert_pem = fs::read(cert_path)
348 .map_err(|e| anyhow!("Failed to read certificate {}: {}", cert_path.display(), e))?;
349
350 let key_pem = fs::read(key_path)
351 .map_err(|e| anyhow!("Failed to read key {}: {}", key_path.display(), e))?;
352
353 let ca_pem = if let Some(ca) = ca_path {
354 Some(fs::read(ca).map_err(|e| anyhow!("Failed to read CA {}: {}", ca.display(), e))?)
355 } else {
356 None
357 };
358
359 let expires_at = Self::parse_certificate_expiration(&cert_pem);
360
361 let cert = TlsCertificate {
362 cert_pem,
363 key_pem,
364 ca_pem,
365 loaded_at: std::time::Instant::now(),
366 expires_at,
367 };
368
369 self.certs.write().await.insert(name.to_string(), cert);
370
371 info!("Loaded TLS certificate: {}", name);
372 Ok(())
373 }
374
375 pub async fn get_certificate(&self, name: &str) -> Result<TlsCertificate> {
377 self.certs
378 .read()
379 .await
380 .get(name)
381 .cloned()
382 .ok_or_else(|| anyhow!("Certificate {} not found", name))
383 }
384
385 pub async fn check_expiration(&self) -> Vec<(String, chrono::DateTime<chrono::Utc>)> {
387 let certs = self.certs.read().await;
388 let mut expiring = Vec::new();
389
390 for (name, cert) in certs.iter() {
391 if let Some(expires) = cert.expires_at {
392 let days_until = (expires - chrono::Utc::now()).num_days();
393 if days_until < 30 {
394 expiring.push((name.clone(), expires));
395 }
396 }
397 }
398
399 expiring
400 }
401}
402
403#[derive(Debug, Clone, Serialize, Deserialize)]
405pub struct PerformanceProfile {
406 pub name: String,
407 pub description: String,
408 pub settings: StreamPerformanceConfig,
409 pub recommended_for: Vec<String>,
410}
411
412impl ConfigManager {
413 pub async fn new(sources: Vec<ConfigSource>) -> Result<Self> {
415 let environment = Environment::detect();
416 let (tx, _) = broadcast::channel(100);
417
418 let secret_backend = SecretBackend::Environment {
420 prefix: "OXIRS_SECRET".to_string(),
421 };
422 let secret_manager = Arc::new(SecretManager::new(
423 secret_backend,
424 Duration::from_secs(3600),
425 ));
426
427 let tls_manager = Arc::new(TlsManager::new(true));
429
430 let initial_config = StreamConfig::default();
432
433 let mut manager = Self {
434 current_config: Arc::new(RwLock::new(initial_config)),
435 sources,
436 change_notifier: tx,
437 secret_manager,
438 environment,
439 performance_profiles: Self::create_default_profiles(),
440 tls_manager,
441 };
442
443 manager.reload().await?;
445
446 Ok(manager)
447 }
448
449 fn create_default_profiles() -> HashMap<String, PerformanceProfile> {
451 let mut profiles = HashMap::new();
452
453 profiles.insert(
455 "low-latency".to_string(),
456 PerformanceProfile {
457 name: "low-latency".to_string(),
458 description: "Optimized for minimal latency".to_string(),
459 settings: StreamPerformanceConfig {
460 enable_batching: false,
461 enable_pipelining: true,
462 buffer_size: 4096,
463 prefetch_count: 10,
464 enable_zero_copy: true,
465 enable_simd: true,
466 parallel_processing: true,
467 worker_threads: Some(4),
468 },
469 recommended_for: vec!["real-time".to_string(), "trading".to_string()],
470 },
471 );
472
473 profiles.insert(
475 "high-throughput".to_string(),
476 PerformanceProfile {
477 name: "high-throughput".to_string(),
478 description: "Optimized for maximum throughput".to_string(),
479 settings: StreamPerformanceConfig {
480 enable_batching: true,
481 enable_pipelining: true,
482 buffer_size: 65536,
483 prefetch_count: 1000,
484 enable_zero_copy: true,
485 enable_simd: true,
486 parallel_processing: true,
487 worker_threads: None, },
489 recommended_for: vec!["batch-processing".to_string(), "etl".to_string()],
490 },
491 );
492
493 profiles.insert(
495 "balanced".to_string(),
496 PerformanceProfile {
497 name: "balanced".to_string(),
498 description: "Balanced between latency and throughput".to_string(),
499 settings: StreamPerformanceConfig::default(),
500 recommended_for: vec!["general".to_string(), "web-services".to_string()],
501 },
502 );
503
504 profiles.insert(
506 "resource-constrained".to_string(),
507 PerformanceProfile {
508 name: "resource-constrained".to_string(),
509 description: "Optimized for limited resources".to_string(),
510 settings: StreamPerformanceConfig {
511 enable_batching: true,
512 enable_pipelining: false,
513 buffer_size: 2048,
514 prefetch_count: 10,
515 enable_zero_copy: false,
516 enable_simd: false,
517 parallel_processing: false,
518 worker_threads: Some(2),
519 },
520 recommended_for: vec!["edge".to_string(), "iot".to_string()],
521 },
522 );
523
524 profiles
525 }
526
527 pub async fn reload(&mut self) -> Result<()> {
529 let old_config = self.current_config.read().await.clone();
530 let mut new_config = old_config.clone();
531
532 let defaults = self.environment.get_defaults();
534 new_config.max_connections = defaults.max_connections;
535 new_config.connection_timeout = Duration::from_secs(defaults.connection_timeout_secs);
536 new_config.enable_compression = defaults.enable_compression;
537 new_config.monitoring.enable_metrics = defaults.enable_metrics;
538 new_config.monitoring.enable_profiling = defaults.enable_profiling;
539
540 for source in &self.sources {
542 match source {
543 ConfigSource::File { path } => {
544 if let Ok(content) = fs::read_to_string(path) {
545 if let Ok(file_config) = toml::from_str::<StreamConfig>(&content) {
546 new_config = self.merge_configs(new_config, file_config);
547 }
548 }
549 }
550 ConfigSource::Environment { prefix } => {
551 new_config = self.load_from_env(new_config, prefix).await?;
552 }
553 ConfigSource::Memory { data } => {
554 new_config = self.apply_overrides(new_config, data.clone());
555 }
556 _ => {
557 }
559 }
560 }
561
562 new_config = self.apply_secrets(new_config).await?;
564
565 self.validate_config(&new_config)?;
567
568 *self.current_config.write().await = new_config.clone();
570
571 let _ = self.change_notifier.send(ConfigChangeEvent::Reloaded {
573 old_config: Box::new(old_config),
574 new_config: Box::new(new_config),
575 });
576
577 info!("Configuration reloaded successfully");
578 Ok(())
579 }
580
581 async fn load_from_env(&self, mut config: StreamConfig, prefix: &str) -> Result<StreamConfig> {
583 if let Ok(backend) = std::env::var(format!("{prefix}_BACKEND")) {
585 config.backend = match backend.as_str() {
586 "kafka" => {
590 return Err(anyhow!(
591 "{prefix}_BACKEND=kafka is no longer supported: the rdkafka-backed \
592 Kafka backend was removed in 0.4.1 (it required a C toolchain and \
593 was never published). Use `nats`, `redis`, or `memory`. The Confluent \
594 Schema Registry client is unaffected — see `oxirs_stream::confluent_registry`."
595 ));
596 }
597 "memory" => StreamBackendType::Memory {
598 max_size: Some(10000),
599 persistence: false,
600 },
601 _ => config.backend,
602 };
603 }
604
605 if let Ok(max_conn) = std::env::var(format!("{prefix}_MAX_CONNECTIONS")) {
607 if let Ok(val) = max_conn.parse() {
608 config.max_connections = val;
609 }
610 }
611
612 if let Ok(compression) = std::env::var(format!("{prefix}_COMPRESSION")) {
614 config.compression_type = match compression.as_str() {
615 "gzip" => CompressionType::Gzip,
616 "snappy" => CompressionType::Snappy,
617 "lz4" => CompressionType::Lz4,
618 "zstd" => CompressionType::Zstd,
619 _ => CompressionType::None,
620 };
621 config.enable_compression = compression != "none";
622 }
623
624 Ok(config)
625 }
626
627 async fn apply_secrets(&self, mut config: StreamConfig) -> Result<StreamConfig> {
629 if config.security.enable_tls {
635 if let Ok(_cert) = self.tls_manager.get_certificate("client").await {
636 config.security.client_cert_path = Some("/tmp/client.crt".to_string());
638 config.security.client_key_path = Some("/tmp/client.key".to_string());
639 }
640 }
641
642 Ok(config)
643 }
644
645 fn merge_configs(&self, _base: StreamConfig, override_config: StreamConfig) -> StreamConfig {
647 override_config
650 }
651
652 fn apply_overrides(
654 &self,
655 mut config: StreamConfig,
656 overrides: HashMap<String, String>,
657 ) -> StreamConfig {
658 for (key, value) in overrides {
659 match key.as_str() {
660 "topic" => config.topic = value,
661 "batch_size" => {
662 if let Ok(size) = value.parse() {
663 config.batch_size = size;
664 }
665 }
666 "max_connections" => {
667 if let Ok(max) = value.parse() {
668 config.max_connections = max;
669 }
670 }
671 _ => {}
672 }
673 }
674 config
675 }
676
677 fn validate_config(&self, config: &StreamConfig) -> Result<()> {
679 if config.max_connections == 0 {
681 return Err(anyhow!("max_connections must be greater than 0"));
682 }
683
684 if config.batch_size == 0 {
686 return Err(anyhow!("batch_size must be greater than 0"));
687 }
688
689 if config.topic.is_empty() {
691 return Err(anyhow!("topic name cannot be empty"));
692 }
693
694 Ok(())
695 }
696
697 pub async fn get_config(&self) -> StreamConfig {
699 self.current_config.read().await.clone()
700 }
701
702 pub fn subscribe(&self) -> broadcast::Receiver<ConfigChangeEvent> {
704 self.change_notifier.subscribe()
705 }
706
707 pub async fn apply_performance_profile(&mut self, profile_name: &str) -> Result<()> {
709 let profile = self
710 .performance_profiles
711 .get(profile_name)
712 .ok_or_else(|| anyhow!("Performance profile {} not found", profile_name))?
713 .clone();
714
715 let mut config = self.current_config.write().await;
716 config.performance = profile.settings;
717
718 info!("Applied performance profile: {}", profile_name);
719 Ok(())
720 }
721
722 pub fn get_performance_profiles(&self) -> Vec<&PerformanceProfile> {
724 self.performance_profiles.values().collect()
725 }
726
727 pub async fn update_value(&mut self, key: &str, value: String) -> Result<()> {
729 let mut overrides = HashMap::new();
730 overrides.insert(key.to_string(), value);
731
732 let current = self.current_config.read().await.clone();
733 let updated = self.apply_overrides(current, overrides);
734
735 self.validate_config(&updated)?;
736 *self.current_config.write().await = updated;
737
738 info!("Updated configuration key: {}", key);
739 Ok(())
740 }
741
742 pub fn secret_manager(&self) -> &Arc<SecretManager> {
744 &self.secret_manager
745 }
746
747 pub fn tls_manager(&self) -> &Arc<TlsManager> {
749 &self.tls_manager
750 }
751}
752
753pub struct ConfigBuilder {
755 sources: Vec<ConfigSource>,
756 environment: Option<Environment>,
757}
758
759impl ConfigBuilder {
760 pub fn new() -> Self {
762 Self {
763 sources: Vec::new(),
764 environment: None,
765 }
766 }
767
768 pub fn with_file(mut self, path: impl Into<PathBuf>) -> Self {
770 self.sources.push(ConfigSource::File { path: path.into() });
771 self
772 }
773
774 pub fn with_env(mut self, prefix: impl Into<String>) -> Self {
776 self.sources.push(ConfigSource::Environment {
777 prefix: prefix.into(),
778 });
779 self
780 }
781
782 pub fn with_overrides(mut self, overrides: HashMap<String, String>) -> Self {
784 self.sources.push(ConfigSource::Memory { data: overrides });
785 self
786 }
787
788 pub fn with_environment(mut self, env: Environment) -> Self {
790 self.environment = Some(env);
791 self
792 }
793
794 pub async fn build(self) -> Result<ConfigManager> {
796 ConfigManager::new(self.sources).await
797 }
798}
799
800impl Default for ConfigBuilder {
801 fn default() -> Self {
802 Self::new()
803 }
804}
805
806#[cfg(test)]
807mod tests {
808 use super::*;
809
810 #[tokio::test]
811 async fn test_environment_detection() {
812 let env = Environment::detect();
813 let defaults = env.get_defaults();
814 assert!(defaults.max_connections > 0);
815 }
816
817 #[tokio::test]
818 async fn test_config_builder() {
819 let mut overrides = HashMap::new();
820 overrides.insert("topic".to_string(), "test-topic".to_string());
821
822 let manager = ConfigBuilder::new()
823 .with_env("OXIRS")
824 .with_overrides(overrides)
825 .build()
826 .await
827 .unwrap();
828
829 let config = manager.get_config().await;
830 assert_eq!(config.topic, "test-topic");
831 }
832
833 #[tokio::test]
834 async fn test_secret_manager() {
835 let backend = SecretBackend::Memory {
836 secrets: Arc::new(RwLock::new(HashMap::new())),
837 };
838 let manager = SecretManager::new(backend, Duration::from_secs(60));
839
840 manager.set_secret("test_key", "test_value").await.unwrap();
842 let value = manager.get_secret("test_key").await.unwrap();
843 assert_eq!(value, "test_value");
844
845 let value2 = manager.get_secret("test_key").await.unwrap();
847 assert_eq!(value2, "test_value");
848 }
849
850 #[tokio::test]
851 async fn test_performance_profiles() {
852 let manager = ConfigBuilder::new().build().await.unwrap();
853 let profiles = manager.get_performance_profiles();
854
855 assert!(profiles.len() >= 4);
856 assert!(profiles.iter().any(|p| p.name == "low-latency"));
857 assert!(profiles.iter().any(|p| p.name == "high-throughput"));
858 }
859
860 #[tokio::test]
861 async fn test_config_validation() {
862 let manager = ConfigBuilder::new().build().await.unwrap();
863
864 let invalid_config = StreamConfig {
866 max_connections: 0,
867 ..Default::default()
868 };
869
870 assert!(manager.validate_config(&invalid_config).is_err());
871 }
872}