sklears_compose/
fault_core.rs

1//! Core Fault Tolerance Traits and Definitions
2//!
3//! This module provides the fundamental traits, types, and configurations that form
4//! the foundation of the fault tolerance system. It defines the core abstractions
5//! for fault detection, recovery, and resilience management.
6
7use serde::{Deserialize, Serialize};
8use sklears_core::error::Result as SklResult;
9use std::collections::HashMap;
10use std::time::{Duration, SystemTime};
11
12/// Core fault tolerance manager trait for pluggable fault handling implementations
13///
14/// Provides a flexible interface for different fault tolerance strategies
15/// that can detect failures, implement recovery mechanisms, and ensure system resilience.
16pub trait FaultToleranceManager: Send + Sync {
17    /// Initialize fault tolerance for a specific execution session
18    ///
19    /// # Arguments
20    /// * `session_id` - Unique identifier for the execution session
21    /// * `config` - Fault tolerance configuration
22    ///
23    /// # Returns
24    /// A fault tolerance session handle for management and control
25    fn initialize_fault_tolerance(
26        &mut self,
27        session_id: String,
28        config: FaultToleranceConfig,
29    ) -> SklResult<FaultToleranceSession>;
30
31    /// Register a component for fault tolerance monitoring
32    ///
33    /// # Arguments
34    /// * `session_id` - Session identifier
35    /// * `component` - Component to monitor for faults
36    ///
37    /// # Returns
38    /// Component handle for fault tolerance management
39    fn register_component(
40        &mut self,
41        session_id: String,
42        component: FaultToleranceComponent,
43    ) -> SklResult<ComponentHandle>;
44
45    /// Report a fault occurrence
46    ///
47    /// # Arguments
48    /// * `session_id` - Session identifier
49    /// * `fault` - Fault report with details
50    ///
51    /// # Returns
52    /// Fault response indicating action taken
53    fn report_fault(&mut self, session_id: String, fault: FaultReport) -> SklResult<FaultResponse>;
54
55    /// Get the current status of a fault tolerance session
56    ///
57    /// # Arguments
58    /// * `session_id` - Session identifier
59    ///
60    /// # Returns
61    /// Current session status
62    fn get_session_status(&self, session_id: String) -> SklResult<FaultToleranceSessionStatus>;
63
64    /// Shutdown fault tolerance for a session
65    ///
66    /// # Arguments
67    /// * `session_id` - Session identifier
68    ///
69    /// # Returns
70    /// Shutdown result with final statistics
71    fn shutdown_fault_tolerance(&mut self, session_id: String) -> SklResult<FaultToleranceReport>;
72}
73
74/// Fault tolerance session handle
75///
76/// Provides management and control for an active fault tolerance session
77/// including session lifecycle, component management, and recovery coordination.
78#[derive(Debug, Clone)]
79pub struct FaultToleranceSession {
80    /// Unique session identifier
81    pub session_id: String,
82    /// Session start time
83    pub start_time: SystemTime,
84    /// Fault tolerance configuration
85    pub config: FaultToleranceConfig,
86    /// Registered components
87    pub components: Vec<ComponentHandle>,
88    /// Current session status
89    pub status: FaultToleranceSessionStatus,
90    /// Active circuit breakers
91    pub circuit_breakers: Vec<CircuitBreakerHandle>,
92    /// Recovery history
93    pub recovery_history: Vec<RecoveryHistoryEntry>,
94    /// Session metadata
95    pub metadata: FaultToleranceMetadata,
96}
97
98/// Fault tolerance session status
99#[derive(Debug, Clone, PartialEq)]
100pub enum FaultToleranceSessionStatus {
101    /// Session initializing
102    Initializing,
103    /// Session active and monitoring
104    Active,
105    /// Session degraded (some components failing)
106    Degraded { failed_components: usize },
107    /// Session in recovery mode
108    Recovery,
109    /// Session suspended
110    Suspended,
111    /// Session shutting down
112    ShuttingDown,
113    /// Session terminated
114    Terminated,
115}
116
117/// Comprehensive fault tolerance configuration
118#[derive(Debug, Clone, Serialize, Deserialize)]
119pub struct FaultToleranceConfig {
120    /// Enable fault tolerance globally
121    pub enabled: bool,
122    /// Fault detection sensitivity (0.0 to 1.0)
123    pub sensitivity: f64,
124    /// Maximum concurrent recovery operations
125    pub max_concurrent_recoveries: usize,
126    /// Global timeout for operations
127    pub global_timeout: Duration,
128    /// Recovery strategy configuration
129    pub recovery_config: RecoveryConfig,
130    /// Circuit breaker configuration
131    pub circuit_breaker_config: CircuitBreakerConfig,
132    /// Retry configuration
133    pub retry_config: RetryConfig,
134    /// Bulkhead configuration
135    pub bulkhead_config: BulkheadConfig,
136    /// Health check configuration
137    pub health_check_config: HealthCheckConfig,
138    /// Performance monitoring configuration
139    pub performance_config: PerformanceConfig,
140    /// Advanced features configuration
141    pub advanced_config: AdvancedConfig,
142}
143
144/// Recovery configuration
145#[derive(Debug, Clone, Serialize, Deserialize)]
146pub struct RecoveryConfig {
147    /// Enable automatic recovery
148    pub automatic_recovery: bool,
149    /// Recovery timeout
150    pub recovery_timeout: Duration,
151    /// Maximum recovery attempts
152    pub max_recovery_attempts: usize,
153    /// Recovery strategies priority order
154    pub strategy_priority: Vec<RecoveryStrategyType>,
155    /// Recovery validation settings
156    pub validation: RecoveryValidationConfig,
157    /// Recovery escalation settings
158    pub escalation: RecoveryEscalationConfig,
159}
160
161/// Recovery strategy type enumeration
162#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
163pub enum RecoveryStrategyType {
164    /// Restart
165    Restart,
166    /// Failover
167    Failover,
168    /// Scale
169    Scale,
170    /// Reset
171    Reset,
172    /// Rollback
173    Rollback,
174    /// Manual
175    Manual,
176    /// Custom
177    Custom(String),
178}
179
180/// Recovery validation configuration
181#[derive(Debug, Clone, Serialize, Deserialize)]
182pub struct RecoveryValidationConfig {
183    /// Enable recovery validation
184    pub enabled: bool,
185    /// Validation timeout
186    pub timeout: Duration,
187    /// Validation criteria
188    pub criteria: Vec<ValidationCriterion>,
189    /// Validation depth
190    pub depth: ValidationDepth,
191}
192
193/// Validation criterion
194#[derive(Debug, Clone, Serialize, Deserialize)]
195pub struct ValidationCriterion {
196    /// Criterion name
197    pub name: String,
198    /// Criterion type
199    pub criterion_type: CriterionType,
200    /// Expected value
201    pub expected_value: String,
202    /// Tolerance
203    pub tolerance: f64,
204    /// Weight in overall validation
205    pub weight: f64,
206}
207
208/// Criterion type enumeration
209#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
210pub enum CriterionType {
211    /// HealthCheck
212    HealthCheck,
213    /// PerformanceMetric
214    PerformanceMetric,
215    /// ResourceUtilization
216    ResourceUtilization,
217    /// BusinessMetric
218    BusinessMetric,
219    /// Custom
220    Custom(String),
221}
222
223/// Validation depth enumeration
224#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
225pub enum ValidationDepth {
226    /// Shallow
227    Shallow,
228    /// Medium
229    Medium,
230    /// Deep
231    Deep,
232    /// Comprehensive
233    Comprehensive,
234}
235
236/// Recovery escalation configuration
237#[derive(Debug, Clone, Serialize, Deserialize)]
238pub struct RecoveryEscalationConfig {
239    /// Enable escalation
240    pub enabled: bool,
241    /// Escalation levels
242    pub levels: Vec<EscalationLevel>,
243    /// Escalation timeout
244    pub timeout: Duration,
245    /// Notification settings
246    pub notifications: NotificationConfig,
247}
248
249/// Escalation level
250#[derive(Debug, Clone, Serialize, Deserialize)]
251pub struct EscalationLevel {
252    /// Level identifier
253    pub level: u32,
254    /// Level name
255    pub name: String,
256    /// Recovery strategies available at this level
257    pub strategies: Vec<RecoveryStrategyType>,
258    /// Timeout before escalating to next level
259    pub timeout: Duration,
260    /// Approval required
261    pub requires_approval: bool,
262    /// Notification channels
263    pub notification_channels: Vec<String>,
264}
265
266/// Notification configuration
267#[derive(Debug, Clone, Serialize, Deserialize)]
268pub struct NotificationConfig {
269    /// Enable notifications
270    pub enabled: bool,
271    /// Notification channels
272    pub channels: Vec<NotificationChannel>,
273    /// Notification templates
274    pub templates: HashMap<String, NotificationTemplate>,
275    /// Rate limiting
276    pub rate_limit: RateLimitConfig,
277}
278
279/// Notification channel
280#[derive(Debug, Clone, Serialize, Deserialize)]
281pub struct NotificationChannel {
282    /// Channel name
283    pub name: String,
284    /// Channel type
285    pub channel_type: ChannelType,
286    /// Channel configuration
287    pub config: HashMap<String, String>,
288    /// Priority threshold
289    pub priority_threshold: Priority,
290}
291
292/// Channel type enumeration
293#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
294pub enum ChannelType {
295    /// Email
296    Email,
297    /// Slack
298    Slack,
299    /// PagerDuty
300    PagerDuty,
301    /// Webhook
302    Webhook,
303    /// SMS
304    SMS,
305    /// Custom
306    Custom(String),
307}
308
309/// Priority enumeration
310#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, PartialOrd)]
311pub enum Priority {
312    Low = 1,
313    Medium = 2,
314    High = 3,
315    Critical = 4,
316    Emergency = 5,
317}
318
319/// Notification template
320#[derive(Debug, Clone, Serialize, Deserialize)]
321pub struct NotificationTemplate {
322    /// Template name
323    pub name: String,
324    /// Subject template
325    pub subject: String,
326    /// Body template
327    pub body: String,
328    /// Template variables
329    pub variables: Vec<String>,
330}
331
332/// Rate limit configuration
333#[derive(Debug, Clone, Serialize, Deserialize)]
334pub struct RateLimitConfig {
335    /// Maximum notifications per time window
336    pub max_per_window: usize,
337    /// Time window duration
338    pub window_duration: Duration,
339    /// Burst allowance
340    pub burst_allowance: usize,
341}
342
343/// Circuit breaker configuration
344#[derive(Debug, Clone, Serialize, Deserialize)]
345pub struct CircuitBreakerConfig {
346    /// Enable circuit breakers
347    pub enabled: bool,
348    /// Failure threshold
349    pub failure_threshold: usize,
350    /// Success threshold for recovery
351    pub success_threshold: usize,
352    /// Timeout for half-open state
353    pub timeout: Duration,
354    /// Maximum calls in half-open state
355    pub half_open_max_calls: usize,
356    /// Circuit breaker policies
357    pub policies: Vec<CircuitBreakerPolicy>,
358    /// Failure detection configuration
359    pub failure_detection: FailureDetectionConfig,
360    /// Analytics configuration
361    pub analytics: crate::circuit_breaker::analytics_engine::AnalyticsConfig,
362}
363
364impl Default for CircuitBreakerConfig {
365    fn default() -> Self {
366        Self {
367            enabled: true,
368            failure_threshold: 5,
369            success_threshold: 3,
370            timeout: Duration::from_secs(60),
371            half_open_max_calls: 3,
372            policies: Vec::new(),
373            failure_detection: FailureDetectionConfig::default(),
374            analytics: crate::circuit_breaker::analytics_engine::AnalyticsConfig::default(),
375        }
376    }
377}
378
379/// Circuit breaker policy
380#[derive(Debug, Clone, Serialize, Deserialize)]
381pub struct CircuitBreakerPolicy {
382    /// Policy name
383    pub name: String,
384    /// Component patterns this policy applies to
385    pub component_patterns: Vec<String>,
386    /// Failure detection configuration
387    pub failure_detection: FailureDetectionConfig,
388    /// Recovery configuration
389    pub recovery_configuration: CircuitRecoveryConfig,
390}
391
392/// Failure detection configuration
393#[derive(Debug, Clone, Serialize, Deserialize)]
394pub struct FailureDetectionConfig {
395    /// Failure patterns
396    pub patterns: Vec<FailurePattern>,
397    /// Sliding window size
398    pub window_size: usize,
399    /// Minimum requests threshold
400    pub min_requests: usize,
401    /// Statistical analysis configuration
402    pub statistics: StatisticalConfig,
403}
404
405/// Failure pattern
406#[derive(Debug, Clone, Serialize, Deserialize)]
407pub struct FailurePattern {
408    /// Pattern name
409    pub name: String,
410    /// Pattern type
411    pub pattern_type: PatternType,
412    /// Pattern expression
413    pub expression: String,
414    /// Pattern weight
415    pub weight: f64,
416}
417
418/// Pattern type enumeration
419#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
420pub enum PatternType {
421    /// ErrorRate
422    ErrorRate,
423    /// ResponseTime
424    ResponseTime,
425    /// ResourceUtilization
426    ResourceUtilization,
427    /// Custom
428    Custom(String),
429}
430
431/// Statistical configuration
432#[derive(Debug, Clone, Serialize, Deserialize)]
433pub struct StatisticalConfig {
434    /// Statistical method
435    pub method: StatisticalMethod,
436    /// Confidence level
437    pub confidence_level: f64,
438    /// Outlier detection
439    pub outlier_detection: bool,
440    /// Trend analysis
441    pub trend_analysis: bool,
442}
443
444/// Statistical method enumeration
445#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
446pub enum StatisticalMethod {
447    /// Simple
448    Simple,
449    /// ExponentialMovingAverage
450    ExponentialMovingAverage,
451    /// WeightedAverage
452    WeightedAverage,
453    /// Percentile
454    Percentile(f64),
455    /// StandardDeviation
456    StandardDeviation,
457    /// Custom
458    Custom(String),
459}
460
461/// Circuit recovery configuration
462#[derive(Debug, Clone, Serialize, Deserialize)]
463pub struct CircuitRecoveryConfig {
464    /// Recovery strategy
465    pub strategy: CircuitRecoveryStrategy,
466    /// Progressive recovery settings
467    pub progressive: ProgressiveRecoveryConfig,
468    /// Health check configuration
469    pub health_check: CircuitHealthCheckConfig,
470}
471
472/// Circuit recovery strategy enumeration
473#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
474pub enum CircuitRecoveryStrategy {
475    /// Immediate
476    Immediate,
477    /// Progressive
478    Progressive,
479    /// HealthCheckBased
480    HealthCheckBased,
481    /// TimeBased
482    TimeBased,
483    /// Custom
484    Custom(String),
485}
486
487/// Progressive recovery configuration
488#[derive(Debug, Clone, Serialize, Deserialize)]
489pub struct ProgressiveRecoveryConfig {
490    /// Initial percentage of requests to allow
491    pub initial_percentage: f64,
492    /// Increment percentage on successful checks
493    pub increment_percentage: f64,
494    /// Maximum percentage
495    pub max_percentage: f64,
496    /// Check interval
497    pub check_interval: Duration,
498}
499
500/// Circuit health check configuration
501#[derive(Debug, Clone, Serialize, Deserialize)]
502pub struct CircuitHealthCheckConfig {
503    /// Health check endpoint
504    pub endpoint: String,
505    /// Health check interval
506    pub interval: Duration,
507    /// Health check timeout
508    pub timeout: Duration,
509    /// Expected response
510    pub expected_response: String,
511}
512
513/// Retry configuration
514#[derive(Debug, Clone, Serialize, Deserialize)]
515pub struct RetryConfig {
516    /// Enable retry mechanism
517    pub enabled: bool,
518    /// Maximum retry attempts
519    pub max_attempts: usize,
520    /// Base delay between retries
521    pub base_delay: Duration,
522    /// Maximum delay
523    pub max_delay: Duration,
524    /// Backoff strategy
525    pub backoff_strategy: BackoffStrategy,
526    /// Retry conditions
527    pub retry_conditions: Vec<RetryCondition>,
528    /// Jitter configuration
529    pub jitter: JitterConfig,
530}
531
532/// Backoff strategy enumeration
533#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
534pub enum BackoffStrategy {
535    /// Fixed
536    Fixed,
537    /// Linear
538    Linear,
539    /// Exponential
540    Exponential { multiplier: f64 },
541    /// Fibonacci
542    Fibonacci,
543    /// Custom
544    Custom(String),
545}
546
547/// Retry condition
548#[derive(Debug, Clone, Serialize, Deserialize)]
549pub struct RetryCondition {
550    /// Condition name
551    pub name: String,
552    /// Error patterns to retry on
553    pub error_patterns: Vec<String>,
554    /// HTTP status codes to retry on
555    pub status_codes: Vec<u16>,
556    /// Custom condition function
557    pub custom_condition: Option<String>,
558}
559
560/// Jitter configuration
561#[derive(Debug, Clone, Serialize, Deserialize)]
562pub struct JitterConfig {
563    /// Enable jitter
564    pub enabled: bool,
565    /// Jitter type
566    pub jitter_type: JitterType,
567    /// Jitter amount (0.0 to 1.0)
568    pub amount: f64,
569}
570
571/// Jitter type enumeration
572#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
573pub enum JitterType {
574    None,
575    /// Full
576    Full,
577    /// Equal
578    Equal,
579    /// Decorrelated
580    Decorrelated,
581}
582
583/// Bulkhead configuration
584#[derive(Debug, Clone, Serialize, Deserialize)]
585pub struct BulkheadConfig {
586    /// Enable bulkhead isolation
587    pub enabled: bool,
588    /// Default isolation settings
589    pub default_isolation: IsolationSettings,
590    /// Component-specific isolation settings
591    pub component_isolation: HashMap<String, IsolationSettings>,
592    /// Resource pool configuration
593    pub resource_pools: Vec<ResourcePoolConfig>,
594}
595
596/// Isolation settings
597#[derive(Debug, Clone, Serialize, Deserialize)]
598pub struct IsolationSettings {
599    /// Maximum concurrent calls
600    pub max_concurrent_calls: usize,
601    /// Queue size
602    pub queue_size: usize,
603    /// Queue timeout
604    pub queue_timeout: Duration,
605    /// Isolation type
606    pub isolation_type: IsolationType,
607}
608
609/// Isolation type enumeration
610#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
611pub enum IsolationType {
612    /// ThreadPool
613    ThreadPool,
614    /// Semaphore
615    Semaphore,
616    /// Actor
617    Actor,
618    /// Custom
619    Custom(String),
620}
621
622/// Resource pool configuration
623#[derive(Debug, Clone, Serialize, Deserialize)]
624pub struct ResourcePoolConfig {
625    /// Pool name
626    pub name: String,
627    /// Resource type
628    pub resource_type: ResourceType,
629    /// Pool size
630    pub size: usize,
631    /// Maximum pool size
632    pub max_size: Option<usize>,
633    /// Pool timeout
634    pub timeout: Duration,
635    /// Pool management strategy
636    pub management_strategy: PoolManagementStrategy,
637}
638
639/// Resource type enumeration
640#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
641pub enum ResourceType {
642    /// Thread
643    Thread,
644    /// Connection
645    Connection,
646    /// Memory
647    Memory,
648    /// CPU
649    CPU,
650    /// Custom
651    Custom(String),
652}
653
654/// Pool management strategy enumeration
655#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
656pub enum PoolManagementStrategy {
657    /// FIFO
658    FIFO,
659    /// LIFO
660    LIFO,
661    /// LeastRecentlyUsed
662    LeastRecentlyUsed,
663    /// MostRecentlyUsed
664    MostRecentlyUsed,
665    /// Custom
666    Custom(String),
667}
668
669/// Health check configuration
670#[derive(Debug, Clone, Serialize, Deserialize)]
671pub struct HealthCheckConfig {
672    /// Enable health checks
673    pub enabled: bool,
674    /// Default health check interval
675    pub default_interval: Duration,
676    /// Health check timeout
677    pub timeout: Duration,
678    /// Health check configurations by component type
679    pub component_configs: HashMap<ComponentType, ComponentHealthConfig>,
680    /// Global health thresholds
681    pub thresholds: HealthThresholds,
682}
683
684/// Component health configuration
685#[derive(Debug, Clone, Serialize, Deserialize)]
686pub struct ComponentHealthConfig {
687    /// Health check interval
688    pub interval: Duration,
689    /// Health check type
690    pub check_type: HealthCheckType,
691    /// Health check endpoint
692    pub endpoint: String,
693    /// Expected response
694    pub expected_response: Option<String>,
695    /// Failure threshold
696    pub failure_threshold: usize,
697    /// Success threshold
698    pub success_threshold: usize,
699}
700
701/// Health check type enumeration
702#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
703pub enum HealthCheckType {
704    /// Http
705    Http {
706        method: String,
707        headers: HashMap<String, String>,
708    },
709    /// Tcp
710    Tcp { host: String, port: u16 },
711    /// Function
712    Function { function_name: String },
713    /// Resource
714    Resource { resource_type: String },
715    /// Custom
716    Custom { check_name: String },
717}
718
719/// Health thresholds
720#[derive(Debug, Clone, Serialize, Deserialize)]
721pub struct HealthThresholds {
722    /// Critical health threshold
723    pub critical: f64,
724    /// Warning health threshold
725    pub warning: f64,
726    /// Good health threshold
727    pub good: f64,
728    /// Excellent health threshold
729    pub excellent: f64,
730}
731
732/// Performance configuration
733#[derive(Debug, Clone, Serialize, Deserialize)]
734pub struct PerformanceConfig {
735    /// Enable performance monitoring
736    pub enabled: bool,
737    /// Metrics collection interval
738    pub collection_interval: Duration,
739    /// Performance thresholds
740    pub thresholds: PerformanceThresholds,
741    /// Resource monitoring configuration
742    pub resource_monitoring: ResourceMonitoringConfig,
743    /// Performance optimization settings
744    pub optimization: PerformanceOptimizationConfig,
745}
746
747/// Performance thresholds
748#[derive(Debug, Clone, Serialize, Deserialize)]
749pub struct PerformanceThresholds {
750    /// Response time thresholds
751    pub response_time: ThresholdConfig,
752    /// Throughput thresholds
753    pub throughput: ThresholdConfig,
754    /// Error rate thresholds
755    pub error_rate: ThresholdConfig,
756    /// CPU utilization thresholds
757    pub cpu_utilization: ThresholdConfig,
758    /// Memory utilization thresholds
759    pub memory_utilization: ThresholdConfig,
760}
761
762/// Threshold configuration
763#[derive(Debug, Clone, Serialize, Deserialize)]
764pub struct ThresholdConfig {
765    /// Warning threshold
766    pub warning: f64,
767    /// Critical threshold
768    pub critical: f64,
769    /// Measurement unit
770    pub unit: String,
771}
772
773/// Resource monitoring configuration
774#[derive(Debug, Clone, Serialize, Deserialize)]
775pub struct ResourceMonitoringConfig {
776    /// Monitor CPU usage
777    pub monitor_cpu: bool,
778    /// Monitor memory usage
779    pub monitor_memory: bool,
780    /// Monitor disk usage
781    pub monitor_disk: bool,
782    /// Monitor network usage
783    pub monitor_network: bool,
784    /// Custom resource monitors
785    pub custom_monitors: Vec<CustomResourceMonitor>,
786}
787
788/// Custom resource monitor
789#[derive(Debug, Clone, Serialize, Deserialize)]
790pub struct CustomResourceMonitor {
791    /// Monitor name
792    pub name: String,
793    /// Monitor type
794    pub monitor_type: String,
795    /// Configuration
796    pub config: HashMap<String, String>,
797}
798
799/// Performance optimization configuration
800#[derive(Debug, Clone, Serialize, Deserialize)]
801pub struct PerformanceOptimizationConfig {
802    /// Enable automatic optimization
803    pub auto_optimization: bool,
804    /// Optimization strategies
805    pub strategies: Vec<OptimizationStrategy>,
806    /// Optimization interval
807    pub optimization_interval: Duration,
808    /// Learning configuration
809    pub learning: LearningConfig,
810}
811
812/// Optimization strategy enumeration
813#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
814pub enum OptimizationStrategy {
815    /// LoadBalancing
816    LoadBalancing,
817    /// Caching
818    Caching,
819    /// ResourceScaling
820    ResourceScaling,
821    /// RequestBatching
822    RequestBatching,
823    /// Custom
824    Custom(String),
825}
826
827/// Learning configuration
828#[derive(Debug, Clone, Serialize, Deserialize)]
829pub struct LearningConfig {
830    /// Enable machine learning
831    pub enabled: bool,
832    /// Learning algorithm
833    pub algorithm: LearningAlgorithm,
834    /// Training data retention
835    pub data_retention: Duration,
836    /// Model update interval
837    pub update_interval: Duration,
838}
839
840/// Learning algorithm enumeration
841#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
842pub enum LearningAlgorithm {
843    /// LinearRegression
844    LinearRegression,
845    /// DecisionTree
846    DecisionTree,
847    /// NeuralNetwork
848    NeuralNetwork,
849    /// ReinforcementLearning
850    ReinforcementLearning,
851    /// Custom
852    Custom(String),
853}
854
855/// Advanced configuration
856#[derive(Debug, Clone, Serialize, Deserialize)]
857pub struct AdvancedConfig {
858    /// Enable predictive analytics
859    pub predictive_analytics: bool,
860    /// Enable chaos engineering
861    pub chaos_engineering: bool,
862    /// Enable security monitoring
863    pub security_monitoring: bool,
864    /// Enable compliance reporting
865    pub compliance_reporting: bool,
866    /// Custom advanced features
867    pub custom_features: HashMap<String, bool>,
868}
869
870/// Fault tolerance component
871#[derive(Debug, Clone)]
872pub struct FaultToleranceComponent {
873    /// Component type
874    pub component_type: ComponentType,
875    /// Component identifier
876    pub component_id: String,
877    /// Component name
878    pub name: String,
879    /// Component description
880    pub description: String,
881    /// Health check configuration
882    pub health_config: ComponentHealthConfig,
883    /// Recovery configuration
884    pub recovery_config: ComponentRecoveryConfig,
885    /// Fault tolerance policies
886    pub policies: Vec<FaultTolerancePolicy>,
887    /// Component metadata
888    pub metadata: ComponentMetadata,
889    /// Component dependencies
890    pub dependencies: Vec<String>,
891    /// Component tags
892    pub tags: Vec<String>,
893}
894
895/// Component type enumeration
896#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Hash, Eq)]
897pub enum ComponentType {
898    /// Execution engine core
899    ExecutionEngine,
900    /// Task scheduler
901    TaskScheduler,
902    /// Resource manager
903    ResourceManager,
904    /// Monitoring system
905    MonitoringSystem,
906    /// Storage system
907    StorageSystem,
908    /// Network interface
909    NetworkInterface,
910    /// Database connection
911    Database,
912    /// Message queue
913    MessageQueue,
914    /// Cache system
915    Cache,
916    /// External service
917    ExternalService { service_name: String },
918    /// Custom component
919    Custom { type_name: String },
920}
921
922/// Component recovery configuration
923#[derive(Debug, Clone)]
924pub struct ComponentRecoveryConfig {
925    /// Enable automatic recovery
926    pub automatic_recovery: bool,
927    /// Recovery strategies
928    pub strategies: Vec<RecoveryStrategy>,
929    /// Recovery timeout
930    pub recovery_timeout: Duration,
931    /// Maximum recovery attempts
932    pub max_recovery_attempts: usize,
933    /// Recovery cooldown period
934    pub cooldown_period: Duration,
935    /// Recovery validation
936    pub validation: RecoveryValidationConfig,
937}
938
939/// Recovery strategy
940#[derive(Debug, Clone)]
941pub enum RecoveryStrategy {
942    /// Restart component
943    Restart {
944        restart_delay: Duration,
945        cleanup_before_restart: bool,
946    },
947    /// Replace with backup
948    Failover {
949        backup_component: String,
950        failover_delay: Duration,
951    },
952    /// Scale horizontally
953    Scale {
954        scale_factor: f64,
955        scale_timeout: Duration,
956    },
957    /// Reset to known good state
958    Reset {
959        checkpoint: String,
960        reset_timeout: Duration,
961    },
962    /// Manual intervention required
963    Manual {
964        notification_channels: Vec<String>,
965        instructions: String,
966    },
967    /// Custom recovery strategy
968    Custom {
969        strategy_name: String,
970        parameters: HashMap<String, String>,
971    },
972}
973
974/// Fault tolerance policy
975#[derive(Debug, Clone)]
976pub enum FaultTolerancePolicy {
977    /// Retry policy for transient failures
978    RetryPolicy {
979        max_attempts: usize,
980        backoff_strategy: BackoffStrategy,
981        retry_conditions: Vec<RetryCondition>,
982    },
983    /// Circuit breaker policy
984    CircuitBreakerPolicy {
985        failure_threshold: usize,
986        recovery_timeout: Duration,
987        half_open_max_calls: usize,
988    },
989    /// Bulkhead policy for resource isolation
990    BulkheadPolicy {
991        max_concurrent_calls: usize,
992        queue_size: usize,
993        timeout: Duration,
994    },
995    /// Fallback policy
996    FallbackPolicy {
997        fallback_action: FallbackAction,
998        fallback_conditions: Vec<FallbackCondition>,
999    },
1000    /// Timeout policy
1001    TimeoutPolicy {
1002        timeout: Duration,
1003        timeout_action: TimeoutAction,
1004    },
1005    /// Rate limiting policy
1006    RateLimitPolicy {
1007        max_requests: usize,
1008        time_window: Duration,
1009        rate_limit_action: RateLimitAction,
1010    },
1011    /// Custom policy
1012    CustomPolicy {
1013        policy_name: String,
1014        parameters: HashMap<String, String>,
1015    },
1016}
1017
1018/// Fallback action enumeration
1019#[derive(Debug, Clone)]
1020pub enum FallbackAction {
1021    /// Return default value
1022    DefaultValue { value: String },
1023    /// Call alternative service
1024    AlternativeService { service_name: String },
1025    /// Use cached response
1026    CachedResponse { cache_key: String },
1027    /// Queue for later processing
1028    QueueRequest { queue_name: String },
1029    /// Manual action required
1030    Manual { action: ManualAction },
1031    /// Custom fallback
1032    Custom {
1033        action_name: String,
1034        parameters: HashMap<String, String>,
1035    },
1036}
1037
1038/// Fallback condition
1039#[derive(Debug, Clone)]
1040pub struct FallbackCondition {
1041    /// Condition name
1042    pub name: String,
1043    /// Trigger patterns
1044    pub patterns: Vec<String>,
1045    /// Condition priority
1046    pub priority: i32,
1047}
1048
1049/// Timeout action enumeration
1050#[derive(Debug, Clone)]
1051pub enum TimeoutAction {
1052    /// Cancel operation
1053    Cancel,
1054    /// Return partial result
1055    PartialResult,
1056    /// Retry with extended timeout
1057    ExtendTimeout { extension: Duration },
1058    /// Fallback to alternative
1059    Fallback { action: FallbackAction },
1060    /// Custom timeout action
1061    Custom { action_name: String },
1062}
1063
1064/// Rate limit action enumeration
1065#[derive(Debug, Clone)]
1066pub enum RateLimitAction {
1067    /// Reject request
1068    Reject,
1069    /// Queue request
1070    Queue { max_queue_size: usize },
1071    /// Delay request
1072    Delay { delay: Duration },
1073    /// Throttle request
1074    Throttle { factor: f64 },
1075    /// Custom action
1076    Custom { action_name: String },
1077}
1078
1079/// Manual action
1080#[derive(Debug, Clone)]
1081pub struct ManualAction {
1082    /// Action identifier
1083    pub action_id: String,
1084    /// Action description
1085    pub description: String,
1086    /// Required skills/roles
1087    pub required_skills: Vec<String>,
1088    /// Estimated duration
1089    pub estimated_duration: Duration,
1090    /// Priority level
1091    pub priority: i32,
1092    /// Instructions
1093    pub instructions: String,
1094    /// Dependencies
1095    pub dependencies: Vec<String>,
1096}
1097
1098/// Component metadata
1099#[derive(Debug, Clone)]
1100pub struct ComponentMetadata {
1101    /// Component version
1102    pub version: String,
1103    /// Component owner
1104    pub owner: String,
1105    /// Creation timestamp
1106    pub created_at: SystemTime,
1107    /// Last updated timestamp
1108    pub updated_at: SystemTime,
1109    /// Environment
1110    pub environment: String,
1111    /// Custom metadata
1112    pub custom: HashMap<String, String>,
1113}
1114
1115/// Component handle for fault tolerance management
1116#[derive(Debug, Clone)]
1117pub struct ComponentHandle {
1118    /// Component unique identifier
1119    pub id: String,
1120    /// Component type
1121    pub component_type: ComponentType,
1122    /// Health check configuration
1123    pub health_config: ComponentHealthConfig,
1124    /// Recovery configuration
1125    pub recovery_config: ComponentRecoveryConfig,
1126    /// Active policies
1127    pub policies: Vec<FaultTolerancePolicy>,
1128    /// Component metadata
1129    pub metadata: ComponentMetadata,
1130    /// Registration timestamp
1131    pub registered_at: SystemTime,
1132    /// Last health check timestamp
1133    pub last_health_check: SystemTime,
1134}
1135
1136/// Component health status
1137#[derive(Debug, Clone)]
1138pub enum ComponentHealth {
1139    /// Component healthy and operational
1140    Healthy {
1141        uptime: Duration,
1142        performance_score: f64,
1143    },
1144    /// Component degraded but functional
1145    Degraded { reason: String, impact_level: f64 },
1146    /// Component unhealthy but recoverable
1147    Unhealthy {
1148        error_count: usize,
1149        last_error: String,
1150    },
1151    /// Component failed and needs recovery
1152    Failed {
1153        failure_reason: String,
1154        failure_time: SystemTime,
1155    },
1156    /// Component unknown status
1157    Unknown { last_check: SystemTime },
1158}
1159
1160/// Circuit breaker handle
1161#[derive(Debug, Clone)]
1162pub struct CircuitBreakerHandle {
1163    /// Circuit breaker identifier
1164    pub id: String,
1165    /// Circuit breaker name
1166    pub name: String,
1167    /// Current state
1168    pub state: CircuitBreakerState,
1169    /// Configuration
1170    pub config: CircuitBreakerConfig,
1171    /// Statistics
1172    pub stats: CircuitBreakerStats,
1173    /// Creation timestamp
1174    pub created_at: SystemTime,
1175    /// Last state change timestamp
1176    pub last_state_change: SystemTime,
1177}
1178
1179/// Circuit breaker state enumeration
1180#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1181pub enum CircuitBreakerState {
1182    /// Closed
1183    Closed,
1184    /// Open
1185    Open,
1186    /// HalfOpen
1187    HalfOpen,
1188}
1189
1190/// Circuit breaker statistics
1191#[derive(Debug, Clone)]
1192pub struct CircuitBreakerStats {
1193    /// Total requests
1194    pub total_requests: u64,
1195    /// Successful requests
1196    pub successful_requests: u64,
1197    /// Failed requests
1198    pub failed_requests: u64,
1199    /// Consecutive failures
1200    pub consecutive_failures: u64,
1201    /// State changes
1202    pub state_changes: u64,
1203    /// Last failure time
1204    pub last_failure_time: Option<SystemTime>,
1205    /// Last success time
1206    pub last_success_time: Option<SystemTime>,
1207    /// Half-open state requests (for monitoring half-open behavior)
1208    pub half_open_requests: u64,
1209    /// Half-open state successful requests
1210    pub half_open_successes: u64,
1211}
1212
1213/// Recovery history entry
1214#[derive(Debug, Clone)]
1215pub struct RecoveryHistoryEntry {
1216    /// Entry identifier
1217    pub id: String,
1218    /// Component identifier
1219    pub component_id: String,
1220    /// Recovery strategy used
1221    pub strategy: RecoveryStrategyType,
1222    /// Recovery start time
1223    pub start_time: SystemTime,
1224    /// Recovery end time
1225    pub end_time: Option<SystemTime>,
1226    /// Recovery result
1227    pub result: RecoveryResult,
1228    /// Recovery details
1229    pub details: String,
1230    /// Recovery metadata
1231    pub metadata: HashMap<String, String>,
1232}
1233
1234/// Recovery result enumeration
1235#[derive(Debug, Clone)]
1236pub enum RecoveryResult {
1237    /// Success
1238    Success,
1239    /// Failure
1240    Failure { reason: String },
1241    /// Partial
1242    Partial { details: String },
1243    /// InProgress
1244    InProgress,
1245    /// Cancelled
1246    Cancelled,
1247}
1248
1249/// Fault tolerance metadata
1250#[derive(Debug, Clone, Default)]
1251pub struct FaultToleranceMetadata {
1252    /// Session tags
1253    pub tags: Vec<String>,
1254    /// Custom metadata
1255    pub custom: HashMap<String, String>,
1256    /// Performance metrics
1257    pub performance_metrics: HashMap<String, f64>,
1258    /// Configuration overrides
1259    pub config_overrides: HashMap<String, String>,
1260}
1261
1262/// Fault report for reporting failures
1263#[derive(Debug, Clone)]
1264pub struct FaultReport {
1265    /// Fault identifier
1266    pub fault_id: String,
1267    /// Component identifier
1268    pub component_id: String,
1269    /// Fault type
1270    pub fault_type: FaultType,
1271    /// Fault severity
1272    pub severity: FaultSeverity,
1273    /// Fault timestamp
1274    pub timestamp: SystemTime,
1275    /// Fault description
1276    pub description: String,
1277    /// Error details
1278    pub error_details: ErrorDetails,
1279    /// Context information
1280    pub context: FaultContext,
1281}
1282
1283/// Fault type enumeration
1284#[derive(Debug, Clone)]
1285pub enum FaultType {
1286    /// Timeout
1287    Timeout,
1288    /// ConnectionFailure
1289    ConnectionFailure,
1290    /// ServiceUnavailable
1291    ServiceUnavailable,
1292    /// ResourceExhaustion
1293    ResourceExhaustion,
1294    /// ConfigurationError
1295    ConfigurationError,
1296    /// SecurityViolation
1297    SecurityViolation,
1298    /// DataCorruption
1299    DataCorruption,
1300    /// PerformanceDegradation
1301    PerformanceDegradation,
1302    /// Custom
1303    Custom(String),
1304}
1305
1306/// Fault severity enumeration
1307#[derive(Debug, Clone, PartialEq, PartialOrd)]
1308pub enum FaultSeverity {
1309    Low = 1,
1310    Medium = 2,
1311    High = 3,
1312    Critical = 4,
1313    Emergency = 5,
1314}
1315
1316/// Error details
1317#[derive(Debug, Clone)]
1318pub struct ErrorDetails {
1319    /// Error code
1320    pub error_code: String,
1321    /// Error message
1322    pub error_message: String,
1323    /// Stack trace
1324    pub stack_trace: Option<String>,
1325    /// Additional error data
1326    pub additional_data: HashMap<String, String>,
1327}
1328
1329/// Fault context
1330#[derive(Debug, Clone)]
1331pub struct FaultContext {
1332    /// Request identifier
1333    pub request_id: Option<String>,
1334    /// User identifier
1335    pub user_id: Option<String>,
1336    /// Session identifier
1337    pub session_id: Option<String>,
1338    /// Environment context
1339    pub environment: HashMap<String, String>,
1340    /// System state
1341    pub system_state: HashMap<String, String>,
1342}
1343
1344/// Fault response enumeration
1345#[derive(Debug, Clone)]
1346pub enum FaultResponse {
1347    /// Acknowledged
1348    Acknowledged,
1349    /// RecoveryInitiated
1350    RecoveryInitiated { strategy: RecoveryStrategyType },
1351    /// EscalationRequired
1352    EscalationRequired { level: u32 },
1353    /// ManualInterventionRequired
1354    ManualInterventionRequired,
1355    /// Ignored
1356    Ignored { reason: String },
1357}
1358
1359/// Fault tolerance report
1360#[derive(Debug, Clone, Default)]
1361pub struct FaultToleranceReport {
1362    /// Session identifier
1363    pub session_id: String,
1364    /// Report type
1365    pub report_type: ReportType,
1366    /// Overall resilience score (0.0 to 1.0)
1367    pub resilience_score: f64,
1368    /// System availability (0.0 to 1.0)
1369    pub availability: f64,
1370    /// Performance metrics
1371    pub performance_metrics: PerformanceMetrics,
1372    /// Health summary
1373    pub health_summary: HealthSummary,
1374    /// Recovery summary
1375    pub recovery_summary: RecoverySummary,
1376    /// Recommendations
1377    pub recommendations: Vec<Recommendation>,
1378}
1379
1380/// Report type enumeration
1381#[derive(Debug, Clone, Default)]
1382pub enum ReportType {
1383    #[default]
1384    Summary,
1385    /// Detailed
1386    Detailed,
1387    /// Comprehensive
1388    Comprehensive,
1389    /// Custom
1390    Custom(String),
1391}
1392
1393impl Default for HealthSummary {
1394    fn default() -> Self {
1395        Self {
1396            overall_health: 1.0,
1397            critical_issues: 0,
1398            component_count: 0,
1399            healthy_components: 0,
1400        }
1401    }
1402}
1403
1404impl Default for RecoverySummary {
1405    fn default() -> Self {
1406        Self {
1407            total_attempts: 0,
1408            successful_recoveries: 0,
1409            failed_recoveries: 0,
1410            avg_recovery_time: Duration::from_secs(0),
1411        }
1412    }
1413}
1414
1415/// Performance metrics summary
1416#[derive(Debug, Clone, Default)]
1417pub struct PerformanceMetrics {
1418    /// Average response time
1419    pub avg_response_time: Duration,
1420    /// Peak response time
1421    pub peak_response_time: Duration,
1422    /// Throughput (requests per second)
1423    pub throughput: f64,
1424    /// Error rate (0.0 to 1.0)
1425    pub error_rate: f64,
1426    /// Resource utilization
1427    pub resource_utilization: f64,
1428}
1429
1430/// Health summary
1431#[derive(Debug, Clone)]
1432pub struct HealthSummary {
1433    /// Overall health score
1434    pub overall_health: f64,
1435    /// Number of critical issues
1436    pub critical_issues: usize,
1437    /// Total component count
1438    pub component_count: usize,
1439    /// Healthy component count
1440    pub healthy_components: usize,
1441}
1442
1443/// Recovery summary
1444#[derive(Debug, Clone)]
1445pub struct RecoverySummary {
1446    /// Total recovery attempts
1447    pub total_attempts: usize,
1448    /// Successful recoveries
1449    pub successful_recoveries: usize,
1450    /// Failed recoveries
1451    pub failed_recoveries: usize,
1452    /// Average recovery time
1453    pub avg_recovery_time: Duration,
1454}
1455
1456/// Recommendation for system improvement
1457#[derive(Debug, Clone)]
1458pub struct Recommendation {
1459    /// Recommendation type
1460    pub recommendation_type: RecommendationType,
1461    /// Recommendation priority
1462    pub priority: Priority,
1463    /// Recommendation description
1464    pub description: String,
1465    /// Implementation steps
1466    pub implementation_steps: Vec<String>,
1467    /// Expected impact
1468    pub expected_impact: String,
1469}
1470
1471/// Recommendation type enumeration
1472#[derive(Debug, Clone)]
1473pub enum RecommendationType {
1474    /// Configuration
1475    Configuration,
1476    /// Infrastructure
1477    Infrastructure,
1478    /// Architecture
1479    Architecture,
1480    /// Monitoring
1481    Monitoring,
1482    /// Process
1483    Process,
1484    /// Custom
1485    Custom(String),
1486}
1487
1488// Default implementations
1489impl Default for FaultToleranceConfig {
1490    fn default() -> Self {
1491        Self {
1492            enabled: true,
1493            sensitivity: 0.7,
1494            max_concurrent_recoveries: 5,
1495            global_timeout: Duration::from_secs(30),
1496            recovery_config: RecoveryConfig {
1497                automatic_recovery: true,
1498                recovery_timeout: Duration::from_secs(60),
1499                max_recovery_attempts: 3,
1500                strategy_priority: vec![
1501                    RecoveryStrategyType::Restart,
1502                    RecoveryStrategyType::Failover,
1503                    RecoveryStrategyType::Scale,
1504                ],
1505                validation: RecoveryValidationConfig {
1506                    enabled: true,
1507                    timeout: Duration::from_secs(10),
1508                    criteria: Vec::new(),
1509                    depth: ValidationDepth::Medium,
1510                },
1511                escalation: RecoveryEscalationConfig {
1512                    enabled: false,
1513                    levels: Vec::new(),
1514                    timeout: Duration::from_secs(300),
1515                    notifications: NotificationConfig {
1516                        enabled: false,
1517                        channels: Vec::new(),
1518                        templates: HashMap::new(),
1519                        rate_limit: RateLimitConfig {
1520                            max_per_window: 10,
1521                            window_duration: Duration::from_secs(60),
1522                            burst_allowance: 2,
1523                        },
1524                    },
1525                },
1526            },
1527            circuit_breaker_config: CircuitBreakerConfig {
1528                enabled: true,
1529                failure_threshold: 5,
1530                success_threshold: 3,
1531                timeout: Duration::from_secs(60),
1532                half_open_max_calls: 3,
1533                policies: Vec::new(),
1534                failure_detection: FailureDetectionConfig::default(),
1535                analytics: crate::circuit_breaker::analytics_engine::AnalyticsConfig::default(),
1536            },
1537            retry_config: RetryConfig {
1538                enabled: true,
1539                max_attempts: 3,
1540                base_delay: Duration::from_millis(100),
1541                max_delay: Duration::from_secs(30),
1542                backoff_strategy: BackoffStrategy::Exponential { multiplier: 2.0 },
1543                retry_conditions: Vec::new(),
1544                jitter: JitterConfig {
1545                    enabled: true,
1546                    jitter_type: JitterType::Equal,
1547                    amount: 0.1,
1548                },
1549            },
1550            bulkhead_config: BulkheadConfig {
1551                enabled: true,
1552                default_isolation: IsolationSettings {
1553                    max_concurrent_calls: 10,
1554                    queue_size: 20,
1555                    queue_timeout: Duration::from_secs(5),
1556                    isolation_type: IsolationType::Semaphore,
1557                },
1558                component_isolation: HashMap::new(),
1559                resource_pools: Vec::new(),
1560            },
1561            health_check_config: HealthCheckConfig {
1562                enabled: true,
1563                default_interval: Duration::from_secs(30),
1564                timeout: Duration::from_secs(5),
1565                component_configs: HashMap::new(),
1566                thresholds: HealthThresholds {
1567                    critical: 0.3,
1568                    warning: 0.6,
1569                    good: 0.8,
1570                    excellent: 0.95,
1571                },
1572            },
1573            performance_config: PerformanceConfig {
1574                enabled: true,
1575                collection_interval: Duration::from_secs(10),
1576                thresholds: PerformanceThresholds {
1577                    response_time: ThresholdConfig {
1578                        warning: 1000.0,
1579                        critical: 5000.0,
1580                        unit: "ms".to_string(),
1581                    },
1582                    throughput: ThresholdConfig {
1583                        warning: 10.0,
1584                        critical: 1.0,
1585                        unit: "rps".to_string(),
1586                    },
1587                    error_rate: ThresholdConfig {
1588                        warning: 0.05,
1589                        critical: 0.1,
1590                        unit: "ratio".to_string(),
1591                    },
1592                    cpu_utilization: ThresholdConfig {
1593                        warning: 0.8,
1594                        critical: 0.95,
1595                        unit: "ratio".to_string(),
1596                    },
1597                    memory_utilization: ThresholdConfig {
1598                        warning: 0.85,
1599                        critical: 0.95,
1600                        unit: "ratio".to_string(),
1601                    },
1602                },
1603                resource_monitoring: ResourceMonitoringConfig {
1604                    monitor_cpu: true,
1605                    monitor_memory: true,
1606                    monitor_disk: false,
1607                    monitor_network: false,
1608                    custom_monitors: Vec::new(),
1609                },
1610                optimization: PerformanceOptimizationConfig {
1611                    auto_optimization: false,
1612                    strategies: vec![OptimizationStrategy::LoadBalancing],
1613                    optimization_interval: Duration::from_secs(300),
1614                    learning: LearningConfig {
1615                        enabled: false,
1616                        algorithm: LearningAlgorithm::LinearRegression,
1617                        data_retention: Duration::from_secs(86400),
1618                        update_interval: Duration::from_secs(3600),
1619                    },
1620                },
1621            },
1622            advanced_config: AdvancedConfig {
1623                predictive_analytics: false,
1624                chaos_engineering: false,
1625                security_monitoring: false,
1626                compliance_reporting: false,
1627                custom_features: HashMap::new(),
1628            },
1629        }
1630    }
1631}
1632
1633impl Default for RetryConfig {
1634    fn default() -> Self {
1635        Self {
1636            enabled: true,
1637            max_attempts: 3,
1638            base_delay: Duration::from_millis(100),
1639            max_delay: Duration::from_secs(30),
1640            backoff_strategy: BackoffStrategy::Exponential { multiplier: 2.0 },
1641            retry_conditions: vec![
1642                /// RetryCondition
1643                RetryCondition {
1644                    name: "NetworkError".to_string(),
1645                    error_patterns: vec!["connection".to_string(), "timeout".to_string()],
1646                    status_codes: vec![],
1647                    custom_condition: None,
1648                },
1649                /// RetryCondition
1650                RetryCondition {
1651                    name: "ServiceUnavailable".to_string(),
1652                    error_patterns: vec!["unavailable".to_string()],
1653                    status_codes: vec![503],
1654                    custom_condition: None,
1655                },
1656            ],
1657            jitter: JitterConfig {
1658                enabled: true,
1659                jitter_type: JitterType::Equal,
1660                amount: 0.1,
1661            },
1662        }
1663    }
1664}
1665
1666impl Default for FailureDetectionConfig {
1667    fn default() -> Self {
1668        Self {
1669            patterns: vec![],
1670            window_size: 100,
1671            min_requests: 10,
1672            statistics: StatisticalConfig {
1673                method: StatisticalMethod::Simple,
1674                confidence_level: 0.95,
1675                outlier_detection: true,
1676                trend_analysis: false,
1677            },
1678        }
1679    }
1680}
1681
1682// Note: Core types are already public and don't need re-export