sklears_compose/
execution_config.rs

1//! Execution Engine Configuration System
2//!
3//! This module provides comprehensive configuration management for the composable execution engine,
4//! including resource constraints, performance goals, fault tolerance settings, and monitoring
5//! configurations. The configuration system is designed to be flexible, extensible, and
6//! production-ready with validation and best practices built-in.
7//!
8//! # Configuration Architecture
9//!
10//! The configuration system follows a hierarchical structure:
11//!
12//! ```text
13//! ExecutionEngineConfig
14//! ├── ResourceConstraints       // CPU, memory, GPU, network limits
15//! ├── PerformanceGoals          // Throughput, latency, utilization targets
16//! ├── EnergyEfficiencyGoal      // Power consumption optimization
17//! ├── FaultToleranceConfig      // Retry, failover, circuit breaker settings
18//! ├── MonitoringConfig          // Metrics collection and observability
19//! └── IoLimits                  // I/O bandwidth and operation limits
20//! ```
21//!
22//! # Configuration Examples
23//!
24//! ## High-Performance Computing Configuration
25//! ```rust,ignore
26//! use sklears_compose::execution_config::*;
27//!
28//! let config = ExecutionEngineConfig {
29//!     name: "hpc_cluster".to_string(),
30//!     default_strategy: "distributed".to_string(),
31//!     resource_constraints: ResourceConstraints {
32//!         max_cpu_cores: Some(128),
33//!         max_memory: Some(1024 * 1024 * 1024 * 1024), // 1TB
34//!         max_gpu_devices: Some(8),
35//!         max_concurrent_tasks: Some(1000),
36//!         max_task_time: Some(Duration::from_hours(24)),
37//!         memory_limit_per_task: Some(8 * 1024 * 1024 * 1024), // 8GB per task
38//!         ..Default::default()
39//!     },
40//!     performance_goals: PerformanceGoals {
41//!         target_throughput: Some(10000.0), // 10k tasks/sec
42//!         target_latency: Some(1.0),         // 1ms avg latency
43//!         target_utilization: Some(95.0),   // 95% resource utilization
44//!         target_efficiency: Some(98.0),    // 98% efficiency
45//!         ..Default::default()
46//!     },
47//!     energy_efficiency: EnergyEfficiencyGoal {
48//!         target_power_consumption: Some(50000.0), // 50kW
49//!         enable_power_capping: true,
50//!         dynamic_frequency_scaling: true,
51//!         energy_aware_scheduling: true,
52//!         ..Default::default()
53//!     },
54//!     fault_tolerance: FaultToleranceConfig {
55//!         enable_retry: true,
56//!         max_retries: 5,
57//!         backoff_strategy: BackoffStrategy::ExponentialWithJitter {
58//!             base_delay: Duration::from_millis(100),
59//!             max_delay: Duration::from_secs(60),
60//!             jitter_factor: 0.1,
61//!         },
62//!         enable_circuit_breaker: true,
63//!         circuit_breaker_threshold: 50,
64//!         enable_failover: true,
65//!         failover_targets: vec!["backup_cluster".to_string()],
66//!         health_check: HealthCheckConfig {
67//!             enabled: true,
68//!             interval: Duration::from_secs(30),
69//!             timeout: Duration::from_secs(5),
70//!             failure_threshold: 3,
71//!             recovery_threshold: 2,
72//!         },
73//!         ..Default::default()
74//!     },
75//!     monitoring: MonitoringConfig {
76//!         collection_interval: Duration::from_secs(1),
77//!         enable_detailed_metrics: true,
78//!         enable_distributed_tracing: true,
79//!         enable_profiling: true,
80//!         export_prometheus: true,
81//!         export_jaeger: true,
82//!         custom_metrics: vec!["gpu_utilization", "memory_bandwidth"].iter().map(|s| s.to_string()).collect(),
83//!         ..Default::default()
84//!     },
85//!     io_limits: IoLimits {
86//!         max_read_bandwidth: Some(100 * 1024 * 1024 * 1024), // 100 GB/s
87//!         max_write_bandwidth: Some(80 * 1024 * 1024 * 1024), // 80 GB/s
88//!         max_iops: Some(1000000), // 1M IOPS
89//!         max_concurrent_io: Some(10000),
90//!         io_priority: IoPriority::High,
91//!         ..Default::default()
92//!     },
93//! };
94//! ```
95//!
96//! ## Edge Computing Configuration
97//! ```rust,ignore
98//! let edge_config = ExecutionEngineConfig {
99//!     name: "edge_device".to_string(),
100//!     default_strategy: "streaming".to_string(),
101//!     resource_constraints: ResourceConstraints {
102//!         max_cpu_cores: Some(4),
103//!         max_memory: Some(8 * 1024 * 1024 * 1024), // 8GB
104//!         max_concurrent_tasks: Some(50),
105//!         max_task_time: Some(Duration::from_secs(30)),
106//!         memory_limit_per_task: Some(100 * 1024 * 1024), // 100MB per task
107//!         ..Default::default()
108//!     },
109//!     energy_efficiency: EnergyEfficiencyGoal {
110//!         target_power_consumption: Some(50.0), // 50W
111//!         enable_power_capping: true,
112//!         dynamic_frequency_scaling: true,
113//!         thermal_throttling: true,
114//!         ..Default::default()
115//!     },
116//!     performance_goals: PerformanceGoals {
117//!         target_latency: Some(10.0), // 10ms for real-time processing
118//!         target_efficiency: Some(85.0),
119//!         ..Default::default()
120//!     },
121//!     ..Default::default()
122//! };
123//! ```
124//!
125//! ## Development Configuration
126//! ```rust,ignore
127//! let dev_config = ExecutionEngineConfig {
128//!     name: "development".to_string(),
129//!     default_strategy: "sequential".to_string(),
130//!     resource_constraints: ResourceConstraints {
131//!         max_cpu_cores: Some(2),
132//!         max_memory: Some(4 * 1024 * 1024 * 1024), // 4GB
133//!         max_concurrent_tasks: Some(10),
134//!         ..Default::default()
135//!     },
136//!     monitoring: MonitoringConfig {
137//!         collection_interval: Duration::from_secs(5),
138//!         enable_detailed_metrics: true,
139//!         enable_debug_logging: true,
140//!         ..Default::default()
141//!     },
142//!     fault_tolerance: FaultToleranceConfig {
143//!         enable_retry: true,
144//!         max_retries: 2,
145//!         backoff_strategy: BackoffStrategy::Linear {
146//!             delay: Duration::from_millis(500),
147//!         },
148//!         ..Default::default()
149//!     },
150//!     ..Default::default()
151//! };
152//! ```
153
154use sklears_core::error::{Result as SklResult, SklearsError};
155use std::collections::HashMap;
156use std::time::Duration;
157
158/// Main configuration for the execution engine
159#[derive(Debug, Clone)]
160pub struct ExecutionEngineConfig {
161    /// Engine name identifier
162    pub name: String,
163    /// Default execution strategy to use
164    pub default_strategy: String,
165    /// Resource allocation constraints
166    pub resource_constraints: ResourceConstraints,
167    /// Performance optimization goals
168    pub performance_goals: PerformanceGoals,
169    /// Energy efficiency optimization goals
170    pub energy_efficiency: EnergyEfficiencyGoal,
171    /// Fault tolerance and reliability settings
172    pub fault_tolerance: FaultToleranceConfig,
173    /// Monitoring and observability configuration
174    pub monitoring: MonitoringConfig,
175    /// I/O operation limits and constraints
176    pub io_limits: IoLimits,
177}
178
179/// Resource allocation constraints and limits
180#[derive(Debug, Clone)]
181pub struct ResourceConstraints {
182    pub max_cpu_cores: Option<usize>,
183    pub max_memory: Option<u64>,
184    pub max_gpu_devices: Option<usize>,
185    pub max_concurrent_tasks: Option<usize>,
186    pub max_task_time: Option<Duration>,
187    pub memory_limit_per_task: Option<u64>,
188    pub cpu_quota_per_task: Option<f64>,
189    pub gpu_memory_per_task: Option<u64>,
190    pub network_bandwidth_per_task: Option<u64>,
191    pub max_queue_depth: Option<usize>,
192    pub priority_levels: Option<u8>,
193    pub isolation_mode: ResourceIsolationMode,
194}
195
196/// Resource isolation modes
197#[derive(Debug, Clone, PartialEq)]
198pub enum ResourceIsolationMode {
199    /// No isolation - shared resources
200    None,
201    /// Soft limits with best-effort isolation
202    Soft,
203    /// Hard limits with strict isolation
204    Hard,
205    /// Container-based isolation
206    Container,
207    /// Virtual machine isolation
208    VirtualMachine,
209}
210
211/// Performance optimization goals and targets
212#[derive(Debug, Clone)]
213pub struct PerformanceGoals {
214    /// Target throughput (tasks per second)
215    pub target_throughput: Option<f64>,
216    /// Target average latency in milliseconds
217    pub target_latency: Option<f64>,
218    /// Target resource utilization percentage (0-100)
219    pub target_utilization: Option<f64>,
220    /// Target system efficiency percentage (0-100)
221    pub target_efficiency: Option<f64>,
222    /// Target cache hit ratio (0-1)
223    pub target_cache_hit_ratio: Option<f64>,
224    /// Target memory bandwidth utilization
225    pub target_memory_bandwidth: Option<f64>,
226    /// Target CPU frequency scaling
227    pub target_cpu_frequency: Option<f64>,
228    /// Performance optimization mode
229    pub optimization_mode: PerformanceMode,
230    /// Quality of Service level
231    pub qos_level: QualityOfService,
232}
233
234/// Performance optimization modes
235#[derive(Debug, Clone, PartialEq)]
236pub enum PerformanceMode {
237    /// Optimize for maximum throughput
238    Throughput,
239    /// Optimize for minimum latency
240    Latency,
241    /// Balance between throughput and latency
242    Balanced,
243    /// Optimize for energy efficiency
244    EnergyEfficient,
245    /// Optimize for cost effectiveness
246    CostOptimized,
247    /// Custom optimization profile
248    Custom(String),
249}
250
251/// Quality of Service levels
252#[derive(Debug, Clone, PartialEq)]
253pub enum QualityOfService {
254    /// Best effort - no guarantees
255    BestEffort,
256    /// Guaranteed resources and performance
257    Guaranteed,
258    /// Burstable performance with baseline
259    Burstable { baseline: f64 },
260    /// Real-time guarantees
261    RealTime { deadline: Duration },
262}
263
264/// Energy efficiency optimization goals
265#[derive(Debug, Clone)]
266pub struct EnergyEfficiencyGoal {
267    /// Target power consumption in watts
268    pub target_power_consumption: Option<f64>,
269    /// Enable power capping
270    pub enable_power_capping: bool,
271    /// Enable dynamic voltage and frequency scaling
272    pub dynamic_frequency_scaling: bool,
273    /// Enable energy-aware task scheduling
274    pub energy_aware_scheduling: bool,
275    /// Enable thermal throttling
276    pub thermal_throttling: bool,
277    /// Target temperature threshold
278    pub target_temperature: Option<f64>,
279    /// Power efficiency mode
280    pub power_mode: PowerMode,
281    /// Carbon footprint optimization
282    pub carbon_awareness: CarbonAwareness,
283}
284
285/// Power consumption modes
286#[derive(Debug, Clone, PartialEq)]
287pub enum PowerMode {
288    /// Maximum performance regardless of power
289    PerformanceFirst,
290    /// Balance performance and power consumption
291    Balanced,
292    /// Minimize power consumption
293    PowerSaver,
294    /// Eco-friendly mode with renewable energy preference
295    EcoMode,
296    /// Custom power profile
297    Custom {
298        max_watts: f64,
299        efficiency_target: f64,
300    },
301}
302
303/// Carbon footprint awareness settings
304#[derive(Debug, Clone, Default)]
305pub struct CarbonAwareness {
306    /// Enable carbon-aware scheduling
307    pub enabled: bool,
308    /// Prefer renewable energy sources
309    pub prefer_renewable: bool,
310    /// Carbon intensity threshold (gCO2/kWh)
311    pub carbon_intensity_threshold: Option<f64>,
312    /// Time-of-use optimization for green energy
313    pub time_of_use_optimization: bool,
314}
315
316/// Fault tolerance and reliability configuration
317#[derive(Debug, Clone)]
318pub struct FaultToleranceConfig {
319    pub enable_retry: bool,
320    pub max_retries: u32,
321    pub backoff_strategy: BackoffStrategy,
322    pub enable_circuit_breaker: bool,
323    pub circuit_breaker_threshold: u32,
324    pub circuit_breaker_timeout: Duration,
325    pub enable_failover: bool,
326    pub failover_targets: Vec<String>,
327    pub health_check: HealthCheckConfig,
328    pub enable_graceful_degradation: bool,
329    pub failure_detection: FailureDetectionStrategy,
330    pub recovery_strategy: RecoveryStrategy,
331}
332
333/// Backoff strategies for retry mechanisms
334#[derive(Debug, Clone)]
335pub enum BackoffStrategy {
336    /// Fixed delay between retries
337    Fixed { delay: Duration },
338    /// Linear increase in delay
339    Linear { delay: Duration },
340    /// Exponential backoff
341    Exponential {
342        base_delay: Duration,
343        max_delay: Duration,
344    },
345    /// Exponential backoff with random jitter
346    ExponentialWithJitter {
347        base_delay: Duration,
348        max_delay: Duration,
349        jitter_factor: f64,
350    },
351    /// Custom backoff function
352    Custom(fn(u32) -> Duration),
353}
354
355/// Health check configuration
356#[derive(Debug, Clone)]
357pub struct HealthCheckConfig {
358    /// Enable health checks
359    pub enabled: bool,
360    /// Health check interval
361    pub interval: Duration,
362    /// Health check timeout
363    pub timeout: Duration,
364    /// Number of consecutive failures before marking unhealthy
365    pub failure_threshold: u32,
366    /// Number of consecutive successes before marking healthy
367    pub recovery_threshold: u32,
368    /// Health check endpoints
369    pub endpoints: Vec<HealthCheckEndpoint>,
370    /// Custom health check functions
371    pub custom_checks: Vec<String>,
372}
373
374/// Health check endpoint configuration
375#[derive(Debug, Clone)]
376pub struct HealthCheckEndpoint {
377    /// Endpoint name
378    pub name: String,
379    /// Endpoint URL or path
380    pub url: String,
381    /// HTTP method for the check
382    pub method: String,
383    /// Expected response code
384    pub expected_status: u16,
385    /// Request timeout
386    pub timeout: Duration,
387}
388
389/// Failure detection strategies
390#[derive(Debug, Clone, PartialEq)]
391pub enum FailureDetectionStrategy {
392    /// Simple timeout-based detection
393    Timeout,
394    /// Heartbeat-based detection
395    Heartbeat { interval: Duration },
396    /// Performance degradation detection
397    PerformanceDegradation { threshold: f64 },
398    /// Resource exhaustion detection
399    ResourceExhaustion,
400    /// Multi-criteria detection
401    MultiCriteria(Vec<FailureDetectionStrategy>),
402}
403
404/// Recovery strategies after failures
405#[derive(Debug, Clone, PartialEq)]
406pub enum RecoveryStrategy {
407    /// Restart the failed component
408    Restart,
409    /// Failover to backup instance
410    Failover,
411    /// Graceful degradation with reduced functionality
412    GracefulDegradation,
413    /// Manual intervention required
414    Manual,
415    /// Custom recovery procedure
416    Custom(String),
417}
418
419/// Monitoring and observability configuration
420#[derive(Debug, Clone)]
421pub struct MonitoringConfig {
422    /// Metrics collection interval
423    pub collection_interval: Duration,
424    /// Enable detailed performance metrics
425    pub enable_detailed_metrics: bool,
426    /// Enable distributed tracing
427    pub enable_distributed_tracing: bool,
428    /// Enable execution profiling
429    pub enable_profiling: bool,
430    /// Enable debug logging
431    pub enable_debug_logging: bool,
432    /// Export metrics to Prometheus
433    pub export_prometheus: bool,
434    /// Export traces to Jaeger
435    pub export_jaeger: bool,
436    /// Export metrics to `InfluxDB`
437    pub export_influxdb: bool,
438    /// Custom metrics to collect
439    pub custom_metrics: Vec<String>,
440    /// Alerting configuration
441    pub alerting: AlertingConfig,
442    /// Sampling configuration for tracing
443    pub sampling_config: SamplingConfig,
444}
445
446/// Alerting system configuration
447#[derive(Debug, Clone)]
448pub struct AlertingConfig {
449    /// Enable alerting
450    pub enabled: bool,
451    /// Alert channels (email, slack, webhook, etc.)
452    pub channels: Vec<AlertChannel>,
453    /// Alert rules and thresholds
454    pub rules: Vec<AlertRule>,
455    /// Alert aggregation window
456    pub aggregation_window: Duration,
457    /// Rate limiting for alerts
458    pub rate_limit: AlertRateLimit,
459}
460
461/// Alert channel configuration
462#[derive(Debug, Clone)]
463pub struct AlertChannel {
464    /// Channel type (email, slack, webhook, etc.)
465    pub channel_type: String,
466    /// Channel configuration
467    pub config: HashMap<String, String>,
468    /// Channel priority
469    pub priority: AlertPriority,
470}
471
472/// Alert rule definition
473#[derive(Debug, Clone)]
474pub struct AlertRule {
475    /// Rule name
476    pub name: String,
477    /// Metric to monitor
478    pub metric: String,
479    /// Threshold value
480    pub threshold: f64,
481    /// Comparison operator
482    pub operator: ComparisonOperator,
483    /// Alert severity
484    pub severity: AlertSeverity,
485    /// Alert message template
486    pub message_template: String,
487}
488
489/// Alert priority levels
490#[derive(Debug, Clone, PartialEq)]
491pub enum AlertPriority {
492    /// Low
493    Low,
494    /// Medium
495    Medium,
496    /// High
497    High,
498    /// Critical
499    Critical,
500}
501
502/// Alert severity levels
503#[derive(Debug, Clone, PartialEq)]
504pub enum AlertSeverity {
505    /// Info
506    Info,
507    /// Warning
508    Warning,
509    /// Error
510    Error,
511    /// Critical
512    Critical,
513}
514
515/// Comparison operators for alert rules
516#[derive(Debug, Clone, PartialEq)]
517pub enum ComparisonOperator {
518    /// Greater
519    Greater,
520    /// GreaterEqual
521    GreaterEqual,
522    /// Less
523    Less,
524    /// LessEqual
525    LessEqual,
526    /// Equal
527    Equal,
528    /// NotEqual
529    NotEqual,
530}
531
532/// Alert rate limiting configuration
533#[derive(Debug, Clone)]
534pub struct AlertRateLimit {
535    /// Maximum alerts per time window
536    pub max_alerts: u32,
537    /// Time window for rate limiting
538    pub time_window: Duration,
539    /// Burst allowance
540    pub burst_allowance: u32,
541}
542
543/// Sampling configuration for tracing
544#[derive(Debug, Clone)]
545pub struct SamplingConfig {
546    /// Sampling rate (0.0 to 1.0)
547    pub sampling_rate: f64,
548    /// Adaptive sampling based on system load
549    pub adaptive_sampling: bool,
550    /// Minimum samples per second
551    pub min_samples_per_second: u32,
552    /// Maximum samples per second
553    pub max_samples_per_second: u32,
554}
555
556/// I/O operation limits and constraints
557#[derive(Debug, Clone)]
558pub struct IoLimits {
559    /// Maximum read bandwidth in bytes per second
560    pub max_read_bandwidth: Option<u64>,
561    /// Maximum write bandwidth in bytes per second
562    pub max_write_bandwidth: Option<u64>,
563    /// Maximum I/O operations per second
564    pub max_iops: Option<u64>,
565    /// Maximum concurrent I/O operations
566    pub max_concurrent_io: Option<usize>,
567    /// I/O priority level
568    pub io_priority: IoPriority,
569    /// I/O scheduler type
570    pub io_scheduler: IoScheduler,
571    /// Buffer size for I/O operations
572    pub buffer_size: Option<usize>,
573    /// Enable direct I/O
574    pub direct_io: bool,
575    /// Enable I/O compression
576    pub compression: IoCompression,
577}
578
579/// I/O priority levels
580#[derive(Debug, Clone, PartialEq)]
581pub enum IoPriority {
582    /// Low
583    Low,
584    /// Normal
585    Normal,
586    /// High
587    High,
588    /// RealTime
589    RealTime,
590}
591
592/// I/O scheduler types
593#[derive(Debug, Clone, PartialEq)]
594pub enum IoScheduler {
595    /// Completely Fair Queuing
596    CFQ,
597    /// Deadline scheduler
598    Deadline,
599    /// NOOP scheduler
600    Noop,
601    /// Budget Fair Queueing
602    BFQ,
603    /// Multiqueue Block Layer
604    MQ,
605}
606
607/// I/O compression settings
608#[derive(Debug, Clone)]
609pub struct IoCompression {
610    /// Enable compression
611    pub enabled: bool,
612    /// Compression algorithm
613    pub algorithm: CompressionAlgorithm,
614    /// Compression level (1-9)
615    pub level: u8,
616    /// Compression threshold (minimum file size)
617    pub threshold: usize,
618}
619
620/// Compression algorithms
621#[derive(Debug, Clone, PartialEq)]
622pub enum CompressionAlgorithm {
623    /// Gzip
624    Gzip,
625    /// Lz4
626    Lz4,
627    /// Zstd
628    Zstd,
629    /// Snappy
630    Snappy,
631    /// Brotli
632    Brotli,
633}
634
635/// Default implementation for `ExecutionEngineConfig`
636impl Default for ExecutionEngineConfig {
637    fn default() -> Self {
638        Self {
639            name: "default_engine".to_string(),
640            default_strategy: "sequential".to_string(),
641            resource_constraints: ResourceConstraints::default(),
642            performance_goals: PerformanceGoals::default(),
643            energy_efficiency: EnergyEfficiencyGoal::default(),
644            fault_tolerance: FaultToleranceConfig::default(),
645            monitoring: MonitoringConfig::default(),
646            io_limits: IoLimits::default(),
647        }
648    }
649}
650
651impl Default for ResourceConstraints {
652    fn default() -> Self {
653        Self {
654            max_cpu_cores: None,
655            max_memory: None,
656            max_gpu_devices: None,
657            max_concurrent_tasks: Some(100),
658            max_task_time: Some(Duration::from_secs(3600)), // 1 hour
659            memory_limit_per_task: None,
660            cpu_quota_per_task: None,
661            gpu_memory_per_task: None,
662            network_bandwidth_per_task: None,
663            max_queue_depth: Some(1000),
664            priority_levels: Some(3),
665            isolation_mode: ResourceIsolationMode::Soft,
666        }
667    }
668}
669
670impl Default for PerformanceGoals {
671    fn default() -> Self {
672        Self {
673            target_throughput: None,
674            target_latency: None,
675            target_utilization: Some(80.0),    // 80% utilization
676            target_efficiency: Some(90.0),     // 90% efficiency
677            target_cache_hit_ratio: Some(0.8), // 80% cache hits
678            target_memory_bandwidth: None,
679            target_cpu_frequency: None,
680            optimization_mode: PerformanceMode::Balanced,
681            qos_level: QualityOfService::BestEffort,
682        }
683    }
684}
685
686impl Default for EnergyEfficiencyGoal {
687    fn default() -> Self {
688        Self {
689            target_power_consumption: None,
690            enable_power_capping: false,
691            dynamic_frequency_scaling: true,
692            energy_aware_scheduling: false,
693            thermal_throttling: true,
694            target_temperature: Some(75.0), // 75°C
695            power_mode: PowerMode::Balanced,
696            carbon_awareness: CarbonAwareness::default(),
697        }
698    }
699}
700
701impl Default for FaultToleranceConfig {
702    fn default() -> Self {
703        Self {
704            enable_retry: true,
705            max_retries: 3,
706            backoff_strategy: BackoffStrategy::Exponential {
707                base_delay: Duration::from_millis(100),
708                max_delay: Duration::from_secs(30),
709            },
710            enable_circuit_breaker: false,
711            circuit_breaker_threshold: 10,
712            circuit_breaker_timeout: Duration::from_secs(60),
713            enable_failover: false,
714            failover_targets: Vec::new(),
715            health_check: HealthCheckConfig::default(),
716            enable_graceful_degradation: true,
717            failure_detection: FailureDetectionStrategy::Timeout,
718            recovery_strategy: RecoveryStrategy::Restart,
719        }
720    }
721}
722
723impl Default for HealthCheckConfig {
724    fn default() -> Self {
725        Self {
726            enabled: true,
727            interval: Duration::from_secs(30),
728            timeout: Duration::from_secs(5),
729            failure_threshold: 3,
730            recovery_threshold: 2,
731            endpoints: Vec::new(),
732            custom_checks: Vec::new(),
733        }
734    }
735}
736
737impl Default for MonitoringConfig {
738    fn default() -> Self {
739        Self {
740            collection_interval: Duration::from_secs(10),
741            enable_detailed_metrics: false,
742            enable_distributed_tracing: false,
743            enable_profiling: false,
744            enable_debug_logging: false,
745            export_prometheus: false,
746            export_jaeger: false,
747            export_influxdb: false,
748            custom_metrics: Vec::new(),
749            alerting: AlertingConfig::default(),
750            sampling_config: SamplingConfig::default(),
751        }
752    }
753}
754
755impl Default for AlertingConfig {
756    fn default() -> Self {
757        Self {
758            enabled: false,
759            channels: Vec::new(),
760            rules: Vec::new(),
761            aggregation_window: Duration::from_secs(60),
762            rate_limit: AlertRateLimit::default(),
763        }
764    }
765}
766
767impl Default for AlertRateLimit {
768    fn default() -> Self {
769        Self {
770            max_alerts: 10,
771            time_window: Duration::from_secs(300), // 5 minutes
772            burst_allowance: 3,
773        }
774    }
775}
776
777impl Default for SamplingConfig {
778    fn default() -> Self {
779        Self {
780            sampling_rate: 0.1, // 10% sampling
781            adaptive_sampling: false,
782            min_samples_per_second: 1,
783            max_samples_per_second: 100,
784        }
785    }
786}
787
788impl Default for IoLimits {
789    fn default() -> Self {
790        Self {
791            max_read_bandwidth: None,
792            max_write_bandwidth: None,
793            max_iops: None,
794            max_concurrent_io: Some(100),
795            io_priority: IoPriority::Normal,
796            io_scheduler: IoScheduler::CFQ,
797            buffer_size: Some(64 * 1024), // 64KB
798            direct_io: false,
799            compression: IoCompression::default(),
800        }
801    }
802}
803
804impl Default for IoCompression {
805    fn default() -> Self {
806        Self {
807            enabled: false,
808            algorithm: CompressionAlgorithm::Lz4,
809            level: 6,
810            threshold: 1024, // 1KB
811        }
812    }
813}
814
815/// Type alias for convenient default configuration
816pub type DefaultExecutionEngineConfig = ExecutionEngineConfig;
817
818/// Configuration validation
819impl ExecutionEngineConfig {
820    /// Validate the configuration for consistency and correctness
821    pub fn validate(&self) -> SklResult<()> {
822        // Validate resource constraints
823        self.resource_constraints.validate()?;
824
825        // Validate performance goals
826        self.performance_goals.validate()?;
827
828        // Validate fault tolerance settings
829        self.fault_tolerance.validate()?;
830
831        // Validate monitoring configuration
832        self.monitoring.validate()?;
833
834        // Validate I/O limits
835        self.io_limits.validate()?;
836
837        Ok(())
838    }
839}
840
841impl ResourceConstraints {
842    pub fn validate(&self) -> SklResult<()> {
843        if let Some(cores) = self.max_cpu_cores {
844            if cores == 0 {
845                return Err(SklearsError::InvalidInput(
846                    "CPU cores must be greater than 0".to_string(),
847                ));
848            }
849        }
850
851        if let Some(memory) = self.max_memory {
852            if memory == 0 {
853                return Err(SklearsError::InvalidInput(
854                    "Memory must be greater than 0".to_string(),
855                ));
856            }
857        }
858
859        if let Some(tasks) = self.max_concurrent_tasks {
860            if tasks == 0 {
861                return Err(SklearsError::InvalidInput(
862                    "Concurrent tasks must be greater than 0".to_string(),
863                ));
864            }
865        }
866
867        Ok(())
868    }
869}
870
871impl PerformanceGoals {
872    pub fn validate(&self) -> SklResult<()> {
873        if let Some(throughput) = self.target_throughput {
874            if throughput <= 0.0 {
875                return Err(SklearsError::InvalidInput(
876                    "Throughput must be positive".to_string(),
877                ));
878            }
879        }
880
881        if let Some(latency) = self.target_latency {
882            if latency <= 0.0 {
883                return Err(SklearsError::InvalidInput(
884                    "Latency must be positive".to_string(),
885                ));
886            }
887        }
888
889        if let Some(utilization) = self.target_utilization {
890            if !(0.0..=100.0).contains(&utilization) {
891                return Err(SklearsError::InvalidInput(
892                    "Utilization must be between 0 and 100".to_string(),
893                ));
894            }
895        }
896
897        Ok(())
898    }
899}
900
901impl FaultToleranceConfig {
902    pub fn validate(&self) -> SklResult<()> {
903        if self.enable_retry && self.max_retries == 0 {
904            return Err(SklearsError::InvalidInput(
905                "Max retries must be greater than 0 when retry is enabled".to_string(),
906            ));
907        }
908
909        if self.enable_circuit_breaker && self.circuit_breaker_threshold == 0 {
910            return Err(SklearsError::InvalidInput(
911                "Circuit breaker threshold must be greater than 0".to_string(),
912            ));
913        }
914
915        Ok(())
916    }
917}
918
919impl MonitoringConfig {
920    pub fn validate(&self) -> SklResult<()> {
921        if self.collection_interval.as_millis() == 0 {
922            return Err(SklearsError::InvalidInput(
923                "Collection interval must be greater than 0".to_string(),
924            ));
925        }
926
927        Ok(())
928    }
929}
930
931impl IoLimits {
932    pub fn validate(&self) -> SklResult<()> {
933        if let Some(concurrent) = self.max_concurrent_io {
934            if concurrent == 0 {
935                return Err(SklearsError::InvalidInput(
936                    "Concurrent I/O must be greater than 0".to_string(),
937                ));
938            }
939        }
940
941        if let Some(buffer_size) = self.buffer_size {
942            if buffer_size == 0 {
943                return Err(SklearsError::InvalidInput(
944                    "Buffer size must be greater than 0".to_string(),
945                ));
946            }
947        }
948
949        Ok(())
950    }
951}
952
953#[allow(non_snake_case)]
954#[cfg(test)]
955mod tests {
956    use super::*;
957
958    #[test]
959    fn test_default_config() {
960        let config = ExecutionEngineConfig::default();
961        assert_eq!(config.name, "default_engine");
962        assert_eq!(config.default_strategy, "sequential");
963        assert!(config.validate().is_ok());
964    }
965
966    #[test]
967    fn test_resource_constraints_validation() {
968        let mut constraints = ResourceConstraints::default();
969        assert!(constraints.validate().is_ok());
970
971        // Test invalid CPU cores
972        constraints.max_cpu_cores = Some(0);
973        assert!(constraints.validate().is_err());
974
975        // Test invalid memory
976        constraints.max_cpu_cores = Some(4);
977        constraints.max_memory = Some(0);
978        assert!(constraints.validate().is_err());
979    }
980
981    #[test]
982    fn test_performance_goals_validation() {
983        let mut goals = PerformanceGoals::default();
984        assert!(goals.validate().is_ok());
985
986        // Test invalid throughput
987        goals.target_throughput = Some(-1.0);
988        assert!(goals.validate().is_err());
989
990        // Test invalid utilization
991        goals.target_throughput = Some(100.0);
992        goals.target_utilization = Some(150.0);
993        assert!(goals.validate().is_err());
994    }
995
996    #[test]
997    fn test_fault_tolerance_validation() {
998        let mut config = FaultToleranceConfig::default();
999        assert!(config.validate().is_ok());
1000
1001        // Test invalid retry configuration
1002        config.enable_retry = true;
1003        config.max_retries = 0;
1004        assert!(config.validate().is_err());
1005    }
1006
1007    #[test]
1008    fn test_backoff_strategy() {
1009        let fixed = BackoffStrategy::Fixed {
1010            delay: Duration::from_millis(100),
1011        };
1012        let linear = BackoffStrategy::Linear {
1013            delay: Duration::from_millis(100),
1014        };
1015        let exponential = BackoffStrategy::Exponential {
1016            base_delay: Duration::from_millis(100),
1017            max_delay: Duration::from_secs(30),
1018        };
1019
1020        // Test that all variants can be created
1021        assert!(matches!(fixed, BackoffStrategy::Fixed { .. }));
1022        assert!(matches!(linear, BackoffStrategy::Linear { .. }));
1023        assert!(matches!(exponential, BackoffStrategy::Exponential { .. }));
1024    }
1025
1026    #[test]
1027    fn test_energy_efficiency_config() {
1028        let mut config = EnergyEfficiencyGoal::default();
1029        assert!(!config.enable_power_capping);
1030        assert!(config.dynamic_frequency_scaling);
1031
1032        config.enable_power_capping = true;
1033        config.target_power_consumption = Some(100.0);
1034        assert_eq!(config.target_power_consumption, Some(100.0));
1035    }
1036
1037    #[test]
1038    fn test_monitoring_config() {
1039        let config = MonitoringConfig::default();
1040        assert!(!config.enable_detailed_metrics);
1041        assert!(!config.enable_distributed_tracing);
1042        assert_eq!(config.collection_interval, Duration::from_secs(10));
1043    }
1044
1045    #[test]
1046    fn test_io_limits() {
1047        let limits = IoLimits::default();
1048        assert_eq!(limits.io_priority, IoPriority::Normal);
1049        assert_eq!(limits.io_scheduler, IoScheduler::CFQ);
1050        assert_eq!(limits.buffer_size, Some(64 * 1024));
1051    }
1052}