caxton 0.1.4

A secure WebAssembly runtime for multi-agent systems
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
//! Router configuration for development and production environments
//!
//! Provides pre-configured settings optimized for different deployment scenarios
//! with validation and builder pattern support.

#![allow(
    clippy::missing_errors_doc,
    clippy::missing_panics_doc,
    clippy::return_self_not_must_use
)]

#[allow(clippy::wildcard_imports)]
use crate::message_router::domain_types::*;
use serde::{Deserialize, Serialize};
use std::path::PathBuf;
use thiserror::Error;

/// Configuration errors
#[derive(Debug, Error)]
pub enum ConfigError {
    #[error("Invalid configuration: {field} - {reason}")]
    ValidationError { field: String, reason: String },

    #[error("I/O error: {source}")]
    IoError {
        #[from]
        source: std::io::Error,
    },

    #[error("Serialization error: {source}")]
    SerializationError {
        #[from]
        source: serde_json::Error,
    },
}

/// Observability configuration settings
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ObservabilityConfig {
    /// Trace sampling ratio (0.0 to 1.0)
    pub trace_sampling_ratio: TraceSamplingRatio,
    /// Enable Prometheus metrics collection
    pub enable_metrics: bool,
    /// Enable detailed structured logging
    pub enable_detailed_logs: bool,
}

impl ObservabilityConfig {
    /// High observability for development and debugging
    pub fn development() -> Self {
        Self {
            trace_sampling_ratio: TraceSamplingRatio::try_new(1.0).unwrap(),
            enable_metrics: true,
            enable_detailed_logs: true,
        }
    }

    /// Production observability with sampling
    pub fn production() -> Self {
        Self {
            trace_sampling_ratio: TraceSamplingRatio::try_new(0.01).unwrap(),
            enable_metrics: true,
            enable_detailed_logs: false,
        }
    }

    /// Minimal observability for testing
    pub fn testing() -> Self {
        Self {
            trace_sampling_ratio: TraceSamplingRatio::try_new(0.0).unwrap(),
            enable_metrics: false,
            enable_detailed_logs: false,
        }
    }
}

impl Default for ObservabilityConfig {
    fn default() -> Self {
        Self::development()
    }
}

/// Performance optimization settings
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PerformanceConfig {
    /// Enable message batching for throughput
    pub enable_batching: bool,
    /// Enable connection pooling for efficiency
    pub enable_connection_pooling: bool,
    /// Number of connections to pool
    pub connection_pool_size: usize,
    /// Enable message compression
    pub enable_compression: bool,
}

impl PerformanceConfig {
    /// Development performance settings
    pub fn development() -> Self {
        Self {
            enable_batching: true,
            enable_connection_pooling: false,
            connection_pool_size: 5,
            enable_compression: false,
        }
    }

    /// Production performance settings
    pub fn production() -> Self {
        Self {
            enable_batching: true,
            enable_connection_pooling: true,
            connection_pool_size: 50,
            enable_compression: true,
        }
    }

    /// Testing performance settings
    pub fn testing() -> Self {
        Self {
            enable_batching: false,
            enable_connection_pooling: false,
            connection_pool_size: 1,
            enable_compression: false,
        }
    }
}

impl Default for PerformanceConfig {
    fn default() -> Self {
        Self::development()
    }
}

/// Security and validation settings
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SecurityConfig {
    /// Enable message validation
    pub enable_message_validation: bool,
    /// Maximum message size in bytes
    pub max_message_size_bytes: usize,
    /// Enable rate limiting
    pub enable_rate_limiting: bool,
    /// Rate limit messages per second
    pub rate_limit_messages_per_second: usize,
}

impl SecurityConfig {
    /// Development security settings (relaxed)
    pub fn development() -> Self {
        Self {
            enable_message_validation: true,
            max_message_size_bytes: 1_048_576, // 1MB
            enable_rate_limiting: false,
            rate_limit_messages_per_second: 1000,
        }
    }

    /// Production security settings (strict)
    pub fn production() -> Self {
        Self {
            enable_message_validation: true,
            max_message_size_bytes: 10_485_760, // 10MB
            enable_rate_limiting: true,
            rate_limit_messages_per_second: 10_000,
        }
    }

    /// Testing security settings
    pub fn testing() -> Self {
        Self {
            enable_message_validation: true,
            max_message_size_bytes: 1024,
            enable_rate_limiting: false,
            rate_limit_messages_per_second: 100,
        }
    }
}

impl Default for SecurityConfig {
    fn default() -> Self {
        Self::development()
    }
}

/// Storage and persistence settings
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct StorageConfig {
    /// Path for persistent storage
    pub storage_path: Option<PathBuf>,
    /// Enable message persistence
    pub enable_persistence: bool,
    /// Storage cleanup interval in milliseconds
    pub storage_cleanup_interval_ms: u64,
}

impl StorageConfig {
    /// Development storage settings (in-memory)
    pub fn development() -> Self {
        Self {
            storage_path: None,
            enable_persistence: false,
            storage_cleanup_interval_ms: 60_000,
        }
    }

    /// Production storage settings (persistent)
    pub fn production() -> Self {
        Self {
            storage_path: Some(PathBuf::from("./data/message_router")),
            enable_persistence: true,
            storage_cleanup_interval_ms: 3_600_000, // 1 hour
        }
    }

    /// Testing storage settings
    pub fn testing() -> Self {
        Self {
            storage_path: None,
            enable_persistence: false,
            storage_cleanup_interval_ms: 30_000,
        }
    }
}

impl Default for StorageConfig {
    fn default() -> Self {
        Self::development()
    }
}

/// Complete router configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RouterConfig {
    // Core routing settings
    pub inbound_queue_size: ChannelCapacity,
    pub outbound_queue_size: ChannelCapacity,
    pub message_timeout_ms: MessageTimeoutMs,
    pub message_batch_size: MessageBatchSize,
    pub worker_thread_count: WorkerThreadCount,

    // Retry and failure handling
    pub max_retries: MaxRetries,
    pub retry_delay_ms: RetryDelayMs,
    pub retry_backoff_factor: RetryBackoffFactor,
    pub dead_letter_queue_size: DeadLetterQueueSize,

    // Circuit breaker settings
    pub circuit_breaker_threshold: CircuitBreakerThreshold,
    pub circuit_breaker_timeout_ms: CircuitBreakerTimeoutMs,

    // Conversation management
    pub conversation_timeout_ms: ConversationTimeoutMs,
    pub max_conversation_participants: MaxConversationParticipants,

    // Health monitoring
    pub health_check_interval_ms: HealthCheckIntervalMs,

    // Grouped configuration settings
    pub observability: ObservabilityConfig,
    pub storage: StorageConfig,
    pub performance: PerformanceConfig,
    pub security: SecurityConfig,
}

impl RouterConfig {
    // Backward compatibility methods for deprecated fields

    /// Backward compatibility: get trace sampling ratio
    pub fn trace_sampling_ratio(&self) -> TraceSamplingRatio {
        self.observability.trace_sampling_ratio
    }

    /// Backward compatibility: check if metrics are enabled
    pub fn enable_metrics(&self) -> bool {
        self.observability.enable_metrics
    }

    /// Backward compatibility: check if detailed logs are enabled
    pub fn enable_detailed_logs(&self) -> bool {
        self.observability.enable_detailed_logs
    }

    /// Backward compatibility: get storage path
    pub fn storage_path(&self) -> Option<&PathBuf> {
        self.storage.storage_path.as_ref()
    }

    /// Backward compatibility: check if persistence is enabled
    pub fn enable_persistence(&self) -> bool {
        self.storage.enable_persistence
    }

    /// Backward compatibility: get storage cleanup interval
    pub fn storage_cleanup_interval_ms(&self) -> u64 {
        self.storage.storage_cleanup_interval_ms
    }

    /// Backward compatibility: check if batching is enabled
    pub fn enable_batching(&self) -> bool {
        self.performance.enable_batching
    }

    /// Backward compatibility: check if connection pooling is enabled
    pub fn enable_connection_pooling(&self) -> bool {
        self.performance.enable_connection_pooling
    }

    /// Backward compatibility: get connection pool size
    pub fn connection_pool_size(&self) -> usize {
        self.performance.connection_pool_size
    }

    /// Backward compatibility: check if compression is enabled
    pub fn enable_compression(&self) -> bool {
        self.performance.enable_compression
    }

    /// Backward compatibility: check if message validation is enabled
    pub fn enable_message_validation(&self) -> bool {
        self.security.enable_message_validation
    }

    /// Backward compatibility: get max message size
    pub fn max_message_size_bytes(&self) -> usize {
        self.security.max_message_size_bytes
    }

    /// Backward compatibility: check if rate limiting is enabled
    pub fn enable_rate_limiting(&self) -> bool {
        self.security.enable_rate_limiting
    }

    /// Backward compatibility: get rate limit
    pub fn rate_limit_messages_per_second(&self) -> usize {
        self.security.rate_limit_messages_per_second
    }
}

impl RouterConfig {
    /// Creates a development configuration optimized for debugging and testing
    ///
    /// Development settings prioritize:
    /// - High observability (detailed logs, high trace sampling)
    /// - Smaller queues for faster debugging
    /// - Shorter timeouts for faster feedback
    /// - In-memory storage for simplicity
    ///
    /// # Panics
    /// Panics if any of the hardcoded values are out of range for their domain types
    pub fn development() -> Self {
        Self {
            // Core routing - smaller queues for dev
            inbound_queue_size: ChannelCapacity::try_new(1_000).unwrap(),
            outbound_queue_size: ChannelCapacity::try_new(1_000).unwrap(),
            message_timeout_ms: MessageTimeoutMs::try_new(10_000).unwrap(), // 10 seconds
            message_batch_size: MessageBatchSize::try_new(10).unwrap(),
            worker_thread_count: WorkerThreadCount::try_new(2).unwrap(),

            // Retry settings - more aggressive for faster feedback
            max_retries: MaxRetries::try_new(2).unwrap(),
            retry_delay_ms: RetryDelayMs::try_new(500).unwrap(),
            retry_backoff_factor: RetryBackoffFactor::try_new(1.5).unwrap(),
            dead_letter_queue_size: DeadLetterQueueSize::try_new(10_000).unwrap(),

            // Circuit breaker - more sensitive in dev
            circuit_breaker_threshold: CircuitBreakerThreshold::try_new(3).unwrap(),
            circuit_breaker_timeout_ms: CircuitBreakerTimeoutMs::try_new(30_000).unwrap(),

            // Conversation management - shorter timeouts
            conversation_timeout_ms: ConversationTimeoutMs::try_new(600_000).unwrap(), // 10 minutes
            max_conversation_participants: MaxConversationParticipants::try_new(5).unwrap(),

            // Health monitoring - frequent checks
            health_check_interval_ms: HealthCheckIntervalMs::try_new(10_000).unwrap(),

            // Grouped configurations
            observability: ObservabilityConfig::development(),
            storage: StorageConfig::development(),
            performance: PerformanceConfig::development(),
            security: SecurityConfig::development(),
        }
    }

    /// Creates a production configuration optimized for performance and reliability
    ///
    /// Production settings prioritize:
    /// - High throughput (large queues, batching)
    /// - Reliability (persistence, longer timeouts)
    /// - Efficient resource usage (connection pooling, compression)
    /// - Appropriate observability (sampled tracing)
    ///
    /// # Panics
    /// Panics if any of the hardcoded values are out of range for their domain types
    pub fn production() -> Self {
        Self {
            // Core routing - optimized for throughput
            inbound_queue_size: ChannelCapacity::try_new(100_000).unwrap(),
            outbound_queue_size: ChannelCapacity::try_new(50_000).unwrap(),
            message_timeout_ms: MessageTimeoutMs::try_new(30_000).unwrap(), // 30 seconds
            message_batch_size: MessageBatchSize::try_new(1000).unwrap(),
            worker_thread_count: WorkerThreadCount::try_new(8).unwrap(),

            // Retry settings - balanced for reliability
            max_retries: MaxRetries::try_new(3).unwrap(),
            retry_delay_ms: RetryDelayMs::try_new(1000).unwrap(),
            retry_backoff_factor: RetryBackoffFactor::try_new(2.0).unwrap(),
            dead_letter_queue_size: DeadLetterQueueSize::try_new(1_000_000).unwrap(),

            // Circuit breaker - production resilience
            circuit_breaker_threshold: CircuitBreakerThreshold::try_new(10).unwrap(),
            circuit_breaker_timeout_ms: CircuitBreakerTimeoutMs::try_new(60_000).unwrap(),

            // Conversation management - longer timeouts for production workflows
            conversation_timeout_ms: ConversationTimeoutMs::default(), // 30 minutes
            max_conversation_participants: MaxConversationParticipants::try_new(20).unwrap(),

            // Health monitoring - less frequent to reduce overhead
            health_check_interval_ms: HealthCheckIntervalMs::try_new(60_000).unwrap(),

            // Grouped configurations
            observability: ObservabilityConfig::production(),
            storage: StorageConfig::production(),
            performance: PerformanceConfig::production(),
            security: SecurityConfig::production(),
        }
    }

    /// Creates a configuration builder for custom settings
    pub fn builder() -> RouterConfigBuilder {
        RouterConfigBuilder::new()
    }

    /// Validates the configuration for consistency and reasonable values
    ///
    /// # Errors
    /// Returns `ConfigError` if any configuration values are inconsistent or invalid
    pub fn validate(&self) -> Result<(), ConfigError> {
        // Validate queue sizes are reasonable
        if self.inbound_queue_size.as_usize() < 10 {
            return Err(ConfigError::ValidationError {
                field: "inbound_queue_size".to_string(),
                reason: "Must be at least 10".to_string(),
            });
        }

        if self.outbound_queue_size.as_usize() < 10 {
            return Err(ConfigError::ValidationError {
                field: "outbound_queue_size".to_string(),
                reason: "Must be at least 10".to_string(),
            });
        }

        // Validate timeouts are reasonable
        if self.message_timeout_ms.as_u64() < 1000 {
            return Err(ConfigError::ValidationError {
                field: "message_timeout_ms".to_string(),
                reason: "Must be at least 1 second".to_string(),
            });
        }

        if self.conversation_timeout_ms.as_u64() < 60_000 {
            return Err(ConfigError::ValidationError {
                field: "conversation_timeout_ms".to_string(),
                reason: "Must be at least 1 minute".to_string(),
            });
        }

        // Validate worker thread count
        if self.worker_thread_count.as_usize() > num_cpus::get() * 2 {
            return Err(ConfigError::ValidationError {
                field: "worker_thread_count".to_string(),
                reason: format!("Should not exceed 2x CPU cores ({})", num_cpus::get() * 2),
            });
        }

        // Validate batch size is reasonable
        if self.message_batch_size.as_usize() > self.inbound_queue_size.as_usize() / 10 {
            return Err(ConfigError::ValidationError {
                field: "message_batch_size".to_string(),
                reason: "Should not exceed 10% of inbound queue size".to_string(),
            });
        }

        // Validate retry settings
        if self.retry_delay_ms.as_u64() >= self.message_timeout_ms.as_u64() {
            return Err(ConfigError::ValidationError {
                field: "retry_delay_ms".to_string(),
                reason: "Should be less than message timeout".to_string(),
            });
        }

        // Validate circuit breaker settings
        if self.circuit_breaker_timeout_ms.as_u64()
            < self.retry_delay_ms.as_u64() * u64::from(self.max_retries.as_u8())
        {
            return Err(ConfigError::ValidationError {
                field: "circuit_breaker_timeout_ms".to_string(),
                reason: "Should be longer than total retry time".to_string(),
            });
        }

        // Validate storage path if persistence enabled
        if self.storage.enable_persistence && self.storage.storage_path.is_none() {
            return Err(ConfigError::ValidationError {
                field: "storage_path".to_string(),
                reason: "Must specify storage path when persistence is enabled".to_string(),
            });
        }

        // Validate rate limiting settings
        if self.security.enable_rate_limiting && self.security.rate_limit_messages_per_second == 0 {
            return Err(ConfigError::ValidationError {
                field: "rate_limit_messages_per_second".to_string(),
                reason: "Must be greater than 0 when rate limiting is enabled".to_string(),
            });
        }

        Ok(())
    }

    /// Saves configuration to JSON file
    pub fn save_to_file<P: AsRef<std::path::Path>>(&self, path: P) -> Result<(), ConfigError> {
        let json = serde_json::to_string_pretty(self)?;
        std::fs::write(path, json)?;
        Ok(())
    }

    /// Loads configuration from JSON file
    pub fn load_from_file<P: AsRef<std::path::Path>>(path: P) -> Result<Self, ConfigError> {
        let json = std::fs::read_to_string(path)?;
        let config: Self = serde_json::from_str(&json)?;
        config.validate()?;
        Ok(config)
    }

    /// Creates a configuration suitable for testing with minimal resources
    pub fn testing() -> Self {
        Self {
            inbound_queue_size: ChannelCapacity::try_new(10000).unwrap(),
            outbound_queue_size: ChannelCapacity::try_new(10000).unwrap(),
            message_timeout_ms: MessageTimeoutMs::try_new(5_000).unwrap(),
            message_batch_size: MessageBatchSize::try_new(5).unwrap(),
            worker_thread_count: WorkerThreadCount::try_new(1).unwrap(),

            max_retries: MaxRetries::try_new(1).unwrap(),
            retry_delay_ms: RetryDelayMs::try_new(100).unwrap(),
            retry_backoff_factor: RetryBackoffFactor::try_new(1.1).unwrap(),
            dead_letter_queue_size: DeadLetterQueueSize::try_new(10_000).unwrap(),

            circuit_breaker_threshold: CircuitBreakerThreshold::try_new(1).unwrap(),
            circuit_breaker_timeout_ms: CircuitBreakerTimeoutMs::try_new(5_000).unwrap(),

            conversation_timeout_ms: ConversationTimeoutMs::try_new(300_000).unwrap(), // 5 minutes
            max_conversation_participants: MaxConversationParticipants::try_new(3).unwrap(),

            health_check_interval_ms: HealthCheckIntervalMs::try_new(5_000).unwrap(),

            // Grouped configurations
            observability: ObservabilityConfig::testing(),
            storage: StorageConfig::testing(),
            performance: PerformanceConfig::testing(),
            security: SecurityConfig::testing(),
        }
    }
}

impl Default for RouterConfig {
    fn default() -> Self {
        Self::development()
    }
}

/// Builder for custom router configurations
pub struct RouterConfigBuilder {
    config: RouterConfig,
}

impl RouterConfigBuilder {
    /// Creates a new builder starting with development defaults
    pub fn new() -> Self {
        Self {
            config: RouterConfig::development(),
        }
    }

    /// Sets the inbound queue size
    pub fn inbound_queue_size(mut self, size: ChannelCapacity) -> Self {
        self.config.inbound_queue_size = size;
        self
    }

    /// Sets the outbound queue size
    pub fn outbound_queue_size(mut self, size: ChannelCapacity) -> Self {
        self.config.outbound_queue_size = size;
        self
    }

    /// Sets the message timeout
    pub fn message_timeout_ms(mut self, timeout: MessageTimeoutMs) -> Self {
        self.config.message_timeout_ms = timeout;
        self
    }

    /// Sets the message batch size
    pub fn message_batch_size(mut self, size: MessageBatchSize) -> Self {
        self.config.message_batch_size = size;
        self
    }

    /// Sets the worker thread count
    pub fn worker_thread_count(mut self, count: WorkerThreadCount) -> Self {
        self.config.worker_thread_count = count;
        self
    }

    /// Sets the maximum retry attempts
    pub fn max_retries(mut self, retries: MaxRetries) -> Self {
        self.config.max_retries = retries;
        self
    }

    /// Sets the retry delay
    pub fn retry_delay_ms(mut self, delay: RetryDelayMs) -> Self {
        self.config.retry_delay_ms = delay;
        self
    }

    /// Sets the conversation timeout
    pub fn conversation_timeout_ms(mut self, timeout: ConversationTimeoutMs) -> Self {
        self.config.conversation_timeout_ms = timeout;
        self
    }

    /// Sets the trace sampling ratio
    pub fn trace_sampling_ratio(mut self, ratio: TraceSamplingRatio) -> Self {
        self.config.observability.trace_sampling_ratio = ratio;
        self
    }

    /// Enables or disables persistence
    pub fn enable_persistence(mut self, enable: bool) -> Self {
        self.config.storage.enable_persistence = enable;
        self
    }

    /// Sets the storage path
    pub fn storage_path<P: Into<PathBuf>>(mut self, path: P) -> Self {
        self.config.storage.storage_path = Some(path.into());
        self
    }

    /// Enables or disables batching
    pub fn enable_batching(mut self, enable: bool) -> Self {
        self.config.performance.enable_batching = enable;
        self
    }

    /// Enables or disables connection pooling
    pub fn enable_connection_pooling(mut self, enable: bool) -> Self {
        self.config.performance.enable_connection_pooling = enable;
        self
    }

    /// Sets the connection pool size
    pub fn connection_pool_size(mut self, size: usize) -> Self {
        self.config.performance.connection_pool_size = size;
        self
    }

    /// Enables or disables metrics
    pub fn enable_metrics(mut self, enable: bool) -> Self {
        self.config.observability.enable_metrics = enable;
        self
    }

    /// Enables or disables detailed logging
    pub fn enable_detailed_logs(mut self, enable: bool) -> Self {
        self.config.observability.enable_detailed_logs = enable;
        self
    }

    /// Enables or disables rate limiting
    pub fn enable_rate_limiting(mut self, enable: bool) -> Self {
        self.config.security.enable_rate_limiting = enable;
        self
    }

    /// Sets the rate limit
    pub fn rate_limit_messages_per_second(mut self, rate: usize) -> Self {
        self.config.security.rate_limit_messages_per_second = rate;
        self
    }

    /// Sets the entire observability configuration
    pub fn observability(mut self, observability: ObservabilityConfig) -> Self {
        self.config.observability = observability;
        self
    }

    /// Sets the entire storage configuration
    pub fn storage(mut self, storage: StorageConfig) -> Self {
        self.config.storage = storage;
        self
    }

    /// Sets the entire performance configuration
    pub fn performance(mut self, performance: PerformanceConfig) -> Self {
        self.config.performance = performance;
        self
    }

    /// Sets the entire security configuration
    pub fn security(mut self, security: SecurityConfig) -> Self {
        self.config.security = security;
        self
    }

    /// Builds and validates the configuration
    pub fn build(self) -> Result<RouterConfig, ConfigError> {
        self.config.validate()?;
        Ok(self.config)
    }
}

impl Default for RouterConfigBuilder {
    fn default() -> Self {
        Self::new()
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use tempfile::NamedTempFile;

    #[test]
    fn test_development_config_is_valid() {
        let config = RouterConfig::development();
        assert!(config.validate().is_ok());
    }

    #[test]
    fn test_production_config_is_valid() {
        let config = RouterConfig::production();
        assert!(config.validate().is_ok());
    }

    #[test]
    fn test_testing_config_is_valid() {
        let config = RouterConfig::testing();
        assert!(config.validate().is_ok());
    }

    #[test]
    fn test_config_builder() {
        let config = RouterConfig::builder()
            .inbound_queue_size(ChannelCapacity::try_new(5000).unwrap())
            .message_timeout_ms(MessageTimeoutMs::try_new(15000).unwrap())
            .enable_persistence(false)
            .build()
            .unwrap();

        assert_eq!(config.inbound_queue_size.as_usize(), 5000);
        assert_eq!(config.message_timeout_ms.as_u64(), 15000);
        assert!(!config.enable_persistence());
    }

    #[test]
    fn test_config_validation_errors() {
        // Test invalid queue size
        let invalid_config = RouterConfig::builder()
            .inbound_queue_size(ChannelCapacity::try_new(5).unwrap()) // Too small
            .build();
        assert!(invalid_config.is_err());

        // Test invalid timeout
        let invalid_config = RouterConfig::builder()
            .message_timeout_ms(MessageTimeoutMs::try_new(1000).unwrap()) // Minimum valid value
            .retry_delay_ms(RetryDelayMs::try_new(2000).unwrap()) // Longer than timeout - should fail validation
            .build();
        assert!(invalid_config.is_err());
    }

    #[test]
    fn test_config_serialization() {
        let config = RouterConfig::development();

        // Test JSON serialization
        let json = serde_json::to_string(&config).unwrap();
        let deserialized: RouterConfig = serde_json::from_str(&json).unwrap();

        assert_eq!(config.inbound_queue_size, deserialized.inbound_queue_size);
        assert_eq!(config.message_timeout_ms, deserialized.message_timeout_ms);
        assert_eq!(
            config.enable_persistence(),
            deserialized.enable_persistence()
        );
    }

    #[test]
    fn test_config_file_operations() {
        let config = RouterConfig::development();
        let temp_file = NamedTempFile::new().unwrap();

        // Save to file
        config.save_to_file(temp_file.path()).unwrap();

        // Load from file
        let loaded_config = RouterConfig::load_from_file(temp_file.path()).unwrap();

        assert_eq!(config.inbound_queue_size, loaded_config.inbound_queue_size);
        assert_eq!(config.message_timeout_ms, loaded_config.message_timeout_ms);
    }
}