allframe-core 0.1.28

AllFrame core - complete web framework with HTTP/2 server, REST/GraphQL/gRPC, DI, CQRS
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
//! Configuration layer for resilience policies.
//!
//! This module provides TOML/YAML-based configuration for resilience policies,
//! allowing runtime configuration of resilience behavior without code changes.
//!
//! # Example TOML Configuration
//!
//! ```toml
//! [resilience]
//! enabled = true
//!
//! [resilience.policies]
//! default = { retry = { max_attempts = 3 } }
//! database = { retry = { max_attempts = 5 }, circuit_breaker = { failure_threshold = 10 } }
//! external_api = { retry = { max_attempts = 2 }, timeout = { duration_seconds = 30 } }
//!
//! [resilience.services]
//! payment_service = "database"
//! email_service = "external_api"
//! cache_service = "default"
//! ```
//!
//! # Example YAML Configuration
//!
//! ```yaml
//! resilience:
//!   enabled: true
//!   policies:
//!     default:
//!       retry:
//!         max_attempts: 3
//!     database:
//!       retry:
//!         max_attempts: 5
//!       circuit_breaker:
//!         failure_threshold: 10
//!   services:
//!     payment_service: database
//!     email_service: external_api
//! ```

use std::{collections::HashMap, time::Duration};

use serde::{Deserialize, Serialize};

use crate::domain::resilience::{BackoffStrategy, ResiliencePolicy};

/// Top-level resilience configuration
#[derive(Clone, Debug, Default, Serialize, Deserialize)]
pub struct ResilienceConfig {
    /// Whether resilience is enabled globally
    #[serde(default = "default_enabled")]
    pub enabled: bool,

    /// Named policy configurations
    #[serde(default)]
    pub policies: HashMap<String, PolicyConfig>,

    /// Service-to-policy mappings
    #[serde(default)]
    pub services: HashMap<String, String>,
}

fn default_enabled() -> bool {
    true
}

/// Configuration for a single resilience policy
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(untagged)]
pub enum PolicyConfig {
    /// Simple policy (single resilience mechanism)
    Simple(SimplePolicyConfig),

    /// Combined policy (multiple resilience mechanisms)
    Combined {
        /// Retry configuration
        retry: Option<RetryConfig>,

        /// Circuit breaker configuration
        circuit_breaker: Option<CircuitBreakerConfig>,

        /// Rate limiting configuration
        rate_limit: Option<RateLimitConfig>,

        /// Timeout configuration
        timeout: Option<TimeoutConfig>,
    },
}

/// Simple policy configuration for single resilience mechanisms
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum SimplePolicyConfig {
    /// No resilience
    None,

    /// Retry configuration
    Retry(RetryConfig),

    /// Circuit breaker configuration
    CircuitBreaker(CircuitBreakerConfig),

    /// Rate limiting configuration
    RateLimit(RateLimitConfig),

    /// Timeout configuration
    Timeout(TimeoutConfig),
}

/// Retry policy configuration
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct RetryConfig {
    /// Maximum number of retry attempts
    pub max_attempts: u32,

    /// Backoff strategy configuration
    #[serde(flatten)]
    pub backoff: BackoffConfig,
}

/// Backoff strategy configuration
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(tag = "backoff_type", rename_all = "snake_case")]
pub enum BackoffConfig {
    /// Fixed delay between attempts
    Fixed {
        /// Delay in milliseconds
        delay_ms: u64,
    },

    /// Exponential backoff
    Exponential {
        /// Initial delay in milliseconds
        initial_delay_ms: u64,

        /// Backoff multiplier
        #[serde(default = "default_multiplier")]
        multiplier: f64,

        /// Maximum delay in milliseconds (optional)
        max_delay_ms: Option<u64>,

        /// Whether to add jitter
        #[serde(default = "default_jitter")]
        jitter: bool,
    },

    /// Linear backoff
    Linear {
        /// Initial delay in milliseconds
        initial_delay_ms: u64,

        /// Increment in milliseconds per attempt
        increment_ms: u64,

        /// Maximum delay in milliseconds (optional)
        max_delay_ms: Option<u64>,
    },
}

fn default_multiplier() -> f64 {
    2.0
}

fn default_jitter() -> bool {
    true
}

/// Circuit breaker policy configuration
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct CircuitBreakerConfig {
    /// Number of failures before opening the circuit
    pub failure_threshold: u32,

    /// Recovery timeout in seconds
    pub recovery_timeout_seconds: u64,

    /// Number of successes required to close the circuit
    #[serde(default = "default_success_threshold")]
    pub success_threshold: u32,
}

fn default_success_threshold() -> u32 {
    3
}

/// Rate limiting policy configuration
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct RateLimitConfig {
    /// Maximum requests per second
    pub requests_per_second: u32,

    /// Burst capacity (additional requests allowed)
    #[serde(default = "default_burst_capacity")]
    pub burst_capacity: u32,
}

fn default_burst_capacity() -> u32 {
    10
}

/// Timeout policy configuration
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct TimeoutConfig {
    /// Timeout duration in seconds
    pub duration_seconds: u64,
}

impl ResilienceConfig {
    /// Load configuration from a TOML string
    pub fn from_toml(content: &str) -> Result<Self, ResilienceConfigError> {
        toml::from_str(content).map_err(|e| ResilienceConfigError::Toml(e.to_string()))
    }

    /// Load configuration from a YAML string
    pub fn from_yaml(_content: &str) -> Result<Self, ResilienceConfigError> {
        // YAML support is not currently available - serde_yaml is not a dependency
        Err(ResilienceConfigError::Yaml(
            "YAML support not available".to_string(),
        ))
    }

    /// Load configuration from a file (auto-detects TOML vs YAML based on
    /// extension)
    pub fn from_file(path: &std::path::Path) -> Result<Self, ResilienceConfigError> {
        let content =
            std::fs::read_to_string(path).map_err(|e| ResilienceConfigError::Io(e.to_string()))?;

        match path.extension().and_then(|s| s.to_str()) {
            Some("toml") => Self::from_toml(&content),
            Some("yaml") | Some("yml") => Self::from_yaml(&content),
            _ => Err(ResilienceConfigError::UnsupportedFormat(
                path.display().to_string(),
            )),
        }
    }

    /// Get the policy for a specific service
    pub fn get_policy_for_service(&self, service_name: &str) -> Option<ResiliencePolicy> {
        if !self.enabled {
            return Some(ResiliencePolicy::None);
        }

        // Check if service has a specific policy mapping
        let policy_name = self.services.get(service_name)?;

        // Get the policy configuration
        let policy_config = self.policies.get(policy_name)?;

        Some(policy_config.to_policy())
    }

    /// Get a named policy directly
    pub fn get_policy(&self, policy_name: &str) -> Option<ResiliencePolicy> {
        if !self.enabled {
            return Some(ResiliencePolicy::None);
        }

        self.policies
            .get(policy_name)
            .map(|config| config.to_policy())
    }

    /// Get the default policy (or None if no policies configured)
    pub fn get_default_policy(&self) -> ResiliencePolicy {
        if !self.enabled {
            return ResiliencePolicy::None;
        }

        self.policies
            .get("default")
            .map(|config| config.to_policy())
            .unwrap_or(ResiliencePolicy::None)
    }
}

impl PolicyConfig {
    /// Convert configuration to a resilience policy
    pub fn to_policy(&self) -> ResiliencePolicy {
        match self {
            PolicyConfig::Simple(simple) => match simple {
                SimplePolicyConfig::None => ResiliencePolicy::None,
                SimplePolicyConfig::Retry(config) => ResiliencePolicy::Retry {
                    max_attempts: config.max_attempts,
                    backoff: config.backoff.to_backoff_strategy(),
                },
                SimplePolicyConfig::CircuitBreaker(config) => ResiliencePolicy::CircuitBreaker {
                    failure_threshold: config.failure_threshold,
                    recovery_timeout: Duration::from_secs(config.recovery_timeout_seconds),
                    success_threshold: config.success_threshold,
                },
                SimplePolicyConfig::RateLimit(config) => ResiliencePolicy::RateLimit {
                    requests_per_second: config.requests_per_second,
                    burst_capacity: config.burst_capacity,
                },
                SimplePolicyConfig::Timeout(config) => ResiliencePolicy::Timeout {
                    duration: Duration::from_secs(config.duration_seconds),
                },
            },

            PolicyConfig::Combined {
                retry,
                circuit_breaker,
                rate_limit,
                timeout,
            } => {
                let mut policies = Vec::new();

                if let Some(config) = retry {
                    policies.push(ResiliencePolicy::Retry {
                        max_attempts: config.max_attempts,
                        backoff: config.backoff.to_backoff_strategy(),
                    });
                }

                if let Some(config) = circuit_breaker {
                    policies.push(ResiliencePolicy::CircuitBreaker {
                        failure_threshold: config.failure_threshold,
                        recovery_timeout: Duration::from_secs(config.recovery_timeout_seconds),
                        success_threshold: config.success_threshold,
                    });
                }

                if let Some(config) = rate_limit {
                    policies.push(ResiliencePolicy::RateLimit {
                        requests_per_second: config.requests_per_second,
                        burst_capacity: config.burst_capacity,
                    });
                }

                if let Some(config) = timeout {
                    policies.push(ResiliencePolicy::Timeout {
                        duration: Duration::from_secs(config.duration_seconds),
                    });
                }

                match policies.len() {
                    0 => ResiliencePolicy::None,
                    1 => policies.into_iter().next().unwrap(),
                    _ => ResiliencePolicy::Combined { policies },
                }
            }
        }
    }
}

impl BackoffConfig {
    /// Convert configuration to a backoff strategy
    pub fn to_backoff_strategy(&self) -> BackoffStrategy {
        match self {
            BackoffConfig::Fixed { delay_ms } => BackoffStrategy::Fixed {
                delay: Duration::from_millis(*delay_ms),
            },

            BackoffConfig::Exponential {
                initial_delay_ms,
                multiplier,
                max_delay_ms,
                jitter,
            } => BackoffStrategy::Exponential {
                initial_delay: Duration::from_millis(*initial_delay_ms),
                multiplier: *multiplier,
                max_delay: max_delay_ms.map(Duration::from_millis),
                jitter: *jitter,
            },

            BackoffConfig::Linear {
                initial_delay_ms,
                increment_ms,
                max_delay_ms,
            } => BackoffStrategy::Linear {
                initial_delay: Duration::from_millis(*initial_delay_ms),
                increment: Duration::from_millis(*increment_ms),
                max_delay: max_delay_ms.map(Duration::from_millis),
            },
        }
    }
}

/// Errors that can occur during configuration loading
#[derive(thiserror::Error, Debug)]
pub enum ResilienceConfigError {
    #[error("IO error: {0}")]
    Io(String),

    #[error("TOML parsing error: {0}")]
    Toml(String),

    #[error("YAML parsing error: {0}")]
    Yaml(String),

    #[error("Unsupported file format: {0}")]
    UnsupportedFormat(String),
}

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

    #[test]
    fn test_simple_retry_policy_config() {
        let config = PolicyConfig::Simple(SimplePolicyConfig::Retry(RetryConfig {
            max_attempts: 3,
            backoff: BackoffConfig::Exponential {
                initial_delay_ms: 100,
                multiplier: 2.0,
                max_delay_ms: Some(10000),
                jitter: true,
            },
        }));

        let policy = config.to_policy();
        match policy {
            ResiliencePolicy::Retry {
                max_attempts,
                backoff: BackoffStrategy::Exponential { .. },
            } => {
                assert_eq!(max_attempts, 3);
            }
            _ => panic!("Expected retry policy"),
        }
    }

    #[test]
    fn test_combined_policy_config() {
        let config = PolicyConfig::Combined {
            retry: Some(RetryConfig {
                max_attempts: 3,
                backoff: BackoffConfig::Fixed { delay_ms: 1000 },
            }),
            circuit_breaker: Some(CircuitBreakerConfig {
                failure_threshold: 5,
                recovery_timeout_seconds: 30,
                success_threshold: 2,
            }),
            rate_limit: None,
            timeout: Some(TimeoutConfig {
                duration_seconds: 60,
            }),
        };

        let policy = config.to_policy();
        match policy {
            ResiliencePolicy::Combined { policies } => {
                assert_eq!(policies.len(), 3);
            }
            _ => panic!("Expected combined policy"),
        }
    }

    #[test]
    fn test_resilience_config_from_toml() {
        let toml_content = r#"
            enabled = true

            [policies.default]
            retry = { max_attempts = 3, backoff_type = "exponential", initial_delay_ms = 100 }

            [policies.database]
            retry = { max_attempts = 5, backoff_type = "fixed", delay_ms = 1000 }
            circuit_breaker = { failure_threshold = 10, recovery_timeout_seconds = 30 }

            [services]
            payment_service = "database"
            cache_service = "default"
        "#;

        let config = ResilienceConfig::from_toml(toml_content).unwrap();
        assert!(config.enabled);
        assert_eq!(config.policies.len(), 2);
        assert_eq!(config.services.len(), 2);

        // Test service policy resolution
        let payment_policy = config.get_policy_for_service("payment_service").unwrap();
        match payment_policy {
            ResiliencePolicy::Combined { policies } => {
                assert_eq!(policies.len(), 2); // retry + circuit breaker
            }
            _ => panic!("Expected combined policy for payment service"),
        }
    }

    #[test]
    fn test_backoff_config_conversion() {
        let fixed_config = BackoffConfig::Fixed { delay_ms: 500 };
        let fixed_strategy = fixed_config.to_backoff_strategy();
        match fixed_strategy {
            BackoffStrategy::Fixed { delay } => {
                assert_eq!(delay, Duration::from_millis(500));
            }
            _ => panic!("Expected fixed backoff"),
        }

        let exp_config = BackoffConfig::Exponential {
            initial_delay_ms: 100,
            multiplier: 2.0,
            max_delay_ms: Some(5000),
            jitter: true,
        };
        let exp_strategy = exp_config.to_backoff_strategy();
        match exp_strategy {
            BackoffStrategy::Exponential {
                initial_delay,
                multiplier,
                max_delay,
                jitter,
            } => {
                assert_eq!(initial_delay, Duration::from_millis(100));
                assert_eq!(multiplier, 2.0);
                assert_eq!(max_delay, Some(Duration::from_millis(5000)));
                assert!(jitter);
            }
            _ => panic!("Expected exponential backoff"),
        }
    }

    #[test]
    fn test_config_disabled_behavior() {
        let config = ResilienceConfig::from_toml("enabled = false").unwrap();
        assert!(!config.enabled);

        // All policies should return None when disabled
        assert_eq!(config.get_default_policy(), ResiliencePolicy::None);
        assert_eq!(config.get_policy("any"), Some(ResiliencePolicy::None));
        assert_eq!(
            config.get_policy_for_service("any"),
            Some(ResiliencePolicy::None)
        );
    }
}