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
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
//! Observability for resilience operations.
//!
//! This module provides metrics collection, tracing instrumentation, and
//! monitoring capabilities for resilience operations, enabling visibility into
//! system reliability.
//!
//! # Features
//!
//! - **Metrics Collection**: Counters, histograms, and gauges for resilience
//!   operations
//! - **Tracing Instrumentation**: Detailed traces for policy execution and
//!   failures
//! - **Health Checks**: Circuit breaker and service health monitoring
//! - **Alerting Integration**: Threshold-based alerting for resilience events

use std::{
    sync::Arc,
    time::{Duration, Instant},
};

use crate::{
    application::resilience::{
        ResilienceMetrics, ResilienceOrchestrationError, ResilienceOrchestrator,
    },
    domain::resilience::{ResilienceDomainError, ResiliencePolicy},
};

#[cfg(feature = "resilience")]
use crate::resilience::{CircuitBreaker, RateLimiter};

#[cfg(not(feature = "resilience"))]
use crate::application::resilience::{CircuitBreaker, RateLimiter};

/// Observability service for resilience operations
#[derive(Clone)]
pub struct ResilienceObservability {
    metrics_collector: Arc<dyn MetricsCollector>,
    tracer: Arc<dyn ResilienceTracer>,
}

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

impl ResilienceObservability {
    /// Create a new observability service with default implementations
    pub fn new() -> Self {
        Self {
            metrics_collector: Arc::new(NoOpMetricsCollector),
            tracer: Arc::new(NoOpTracer),
        }
    }

    /// Create with custom collector and tracer
    pub fn with_components(
        metrics_collector: Arc<dyn MetricsCollector>,
        tracer: Arc<dyn ResilienceTracer>,
    ) -> Self {
        Self {
            metrics_collector,
            tracer,
        }
    }

    /// Record the start of a resilience operation
    pub fn record_operation_start(&self, operation_id: &str, policy: &ResiliencePolicy) {
        self.metrics_collector.increment_counter(
            "resilience_operations_total",
            &[("operation", operation_id)],
        );
        self.tracer.start_span(
            "resilience_operation",
            &[
                ("operation_id", operation_id),
                ("policy_type", &policy_type_name(policy)),
            ],
        );
    }

    /// Record the completion of a resilience operation
    pub fn record_operation_complete(
        &self,
        operation_id: &str,
        policy: &ResiliencePolicy,
        duration: Duration,
        result: &Result<(), ResilienceOrchestrationError>,
    ) {
        let status = if result.is_ok() { "success" } else { "failure" };
        let duration_ms = duration.as_millis() as f64;

        // Record metrics
        self.metrics_collector.increment_counter(
            "resilience_operations_completed_total",
            &[("operation", operation_id), ("status", status)],
        );

        self.metrics_collector.record_histogram(
            "resilience_operation_duration_ms",
            duration_ms,
            &[
                ("operation", operation_id),
                ("policy_type", &policy_type_name(policy)),
            ],
        );

        // Record policy-specific metrics
        match policy {
            ResiliencePolicy::Retry { max_attempts, .. } => {
                self.metrics_collector.record_histogram(
                    "resilience_retry_max_attempts",
                    *max_attempts as f64,
                    &[("operation", operation_id)],
                );
            }
            ResiliencePolicy::CircuitBreaker {
                failure_threshold, ..
            } => {
                self.metrics_collector.record_gauge(
                    "resilience_circuit_breaker_failure_threshold",
                    *failure_threshold as f64,
                    &[("operation", operation_id)],
                );
            }
            ResiliencePolicy::RateLimit {
                requests_per_second,
                ..
            } => {
                self.metrics_collector.record_gauge(
                    "resilience_rate_limit_rps",
                    *requests_per_second as f64,
                    &[("operation", operation_id)],
                );
            }
            _ => {}
        }

        // Handle errors specifically
        if let Err(error) = result {
            self.record_operation_error(operation_id, error);
        }

        // End tracing span
        self.tracer.end_span(&[
            ("duration_ms", &duration_ms.to_string()),
            ("status", status),
        ]);
    }

    /// Record resilience-specific errors
    pub fn record_operation_error(&self, operation_id: &str, error: &ResilienceOrchestrationError) {
        let error_type = match error {
            ResilienceOrchestrationError::Domain(domain_error) => match domain_error {
                ResilienceDomainError::RetryExhausted { .. } => "retry_exhausted",
                ResilienceDomainError::CircuitOpen => "circuit_open",
                ResilienceDomainError::RateLimited { .. } => "rate_limited",
                ResilienceDomainError::Timeout { .. } => "timeout",
                ResilienceDomainError::Infrastructure { .. } => "infrastructure",
                _ => "domain_error",
            },
            ResilienceOrchestrationError::Infrastructure(_) => "infrastructure",
            ResilienceOrchestrationError::Configuration(_) => "configuration",
            ResilienceOrchestrationError::Cancelled => "cancelled",
        };

        self.metrics_collector.increment_counter(
            "resilience_operation_errors_total",
            &[("operation", operation_id), ("error_type", error_type)],
        );

        self.tracer.add_event(
            "resilience_error",
            &[("operation_id", operation_id), ("error_type", error_type)],
        );
    }

    /// Record circuit breaker state changes
    pub fn record_circuit_breaker_state_change(
        &self,
        circuit_breaker_id: &str,
        old_state: CircuitBreakerState,
        new_state: CircuitBreakerState,
    ) {
        self.metrics_collector.increment_counter(
            "resilience_circuit_breaker_state_changes_total",
            &[
                ("circuit_breaker", circuit_breaker_id),
                ("old_state", old_state.as_str()),
                ("new_state", new_state.as_str()),
            ],
        );

        self.tracer.add_event(
            "circuit_breaker_state_change",
            &[
                ("circuit_breaker_id", circuit_breaker_id),
                ("old_state", old_state.as_str()),
                ("new_state", new_state.as_str()),
            ],
        );
    }

    /// Get current health status
    pub fn health_status(&self) -> ResilienceHealthStatus {
        // This would typically aggregate metrics to determine overall health
        ResilienceHealthStatus {
            overall_health: HealthLevel::Healthy,
            circuit_breakers_open: 0,
            services_degraded: 0,
            last_updated: std::time::SystemTime::now(),
        }
    }

    /// Export metrics in Prometheus format
    pub fn export_prometheus_metrics(&self) -> String {
        // This would collect all metrics and format them for Prometheus
        "# AllFrame Resilience Metrics\n# (Implementation would export actual metrics)\n"
            .to_string()
    }
}

/// Circuit breaker states for observability
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum CircuitBreakerState {
    Closed,
    Open,
    HalfOpen,
}

impl CircuitBreakerState {
    pub fn as_str(&self) -> &'static str {
        match self {
            CircuitBreakerState::Closed => "closed",
            CircuitBreakerState::Open => "open",
            CircuitBreakerState::HalfOpen => "half_open",
        }
    }
}

/// Overall health status of the resilience system
#[derive(Clone, Debug)]
pub struct ResilienceHealthStatus {
    pub overall_health: HealthLevel,
    pub circuit_breakers_open: u32,
    pub services_degraded: u32,
    pub last_updated: std::time::SystemTime,
}

/// Health levels for services
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum HealthLevel {
    Healthy,
    Degraded,
    Unhealthy,
    Unknown,
}

/// Metrics collection trait
#[async_trait::async_trait]
pub trait MetricsCollector: Send + Sync {
    /// Increment a counter metric
    fn increment_counter(&self, name: &str, labels: &[(&str, &str)]);

    /// Record a histogram value
    fn record_histogram(&self, name: &str, value: f64, labels: &[(&str, &str)]);

    /// Set a gauge value
    fn record_gauge(&self, name: &str, value: f64, labels: &[(&str, &str)]);
}

/// Tracing instrumentation trait
#[async_trait::async_trait]
pub trait ResilienceTracer: Send + Sync {
    /// Start a new trace span
    fn start_span(&self, name: &str, attributes: &[(&str, &str)]);

    /// End the current span
    fn end_span(&self, attributes: &[(&str, &str)]);

    /// Add an event to the current span
    fn add_event(&self, name: &str, attributes: &[(&str, &str)]);
}

/// No-op implementation for when observability is disabled
pub struct NoOpMetricsCollector;

impl MetricsCollector for NoOpMetricsCollector {
    fn increment_counter(&self, _name: &str, _labels: &[(&str, &str)]) {}
    fn record_histogram(&self, _name: &str, _value: f64, _labels: &[(&str, &str)]) {}
    fn record_gauge(&self, _name: &str, _value: f64, _labels: &[(&str, &str)]) {}
}

/// No-op tracer implementation
pub struct NoOpTracer;

#[async_trait::async_trait]
impl ResilienceTracer for NoOpTracer {
    fn start_span(&self, _name: &str, _attributes: &[(&str, &str)]) {}
    fn end_span(&self, _attributes: &[(&str, &str)]) {}
    fn add_event(&self, _name: &str, _attributes: &[(&str, &str)]) {}
}

/// Prometheus metrics collector implementation
#[cfg(feature = "prometheus")]
pub mod prometheus_metrics {
    use std::collections::HashMap;
    use std::sync::RwLock;

    use ::prometheus::{CounterVec, GaugeVec, HistogramVec, Opts};

    use super::*;

    /// Prometheus-backed metrics collector for resilience observability
    pub struct PrometheusMetricsCollector {
        counters: RwLock<HashMap<String, CounterVec>>,
        histograms: RwLock<HashMap<String, HistogramVec>>,
        gauges: RwLock<HashMap<String, GaugeVec>>,
    }

    impl PrometheusMetricsCollector {
        /// Create a new Prometheus metrics collector
        pub fn new() -> Self {
            Self {
                counters: RwLock::new(HashMap::new()),
                histograms: RwLock::new(HashMap::new()),
                gauges: RwLock::new(HashMap::new()),
            }
        }

        fn label_values<'a>(labels: &'a [(&'a str, &'a str)]) -> Vec<&'a str> {
            labels.iter().map(|(_, v)| *v).collect()
        }
    }

    impl MetricsCollector for PrometheusMetricsCollector {
        fn increment_counter(&self, name: &str, labels: &[(&str, &str)]) {
            let label_names: Vec<&str> = labels.iter().map(|(k, _)| *k).collect();
            let label_vals = Self::label_values(labels);

            let counters = self.counters.read().unwrap();
            if let Some(counter) = counters.get(name) {
                if let Ok(m) = counter.get_metric_with_label_values(&label_vals) {
                    m.inc();
                }
                return;
            }
            drop(counters);

            let mut counters = self.counters.write().unwrap();
            let counter = counters.entry(name.to_string()).or_insert_with(|| {
                let c = CounterVec::new(Opts::new(name, name), &label_names)
                    .expect("Failed to create counter");
                let _ = ::prometheus::register(Box::new(c.clone()));
                c
            });
            if let Ok(m) = counter.get_metric_with_label_values(&label_vals) {
                m.inc();
            }
        }

        fn record_histogram(&self, name: &str, value: f64, labels: &[(&str, &str)]) {
            let label_names: Vec<&str> = labels.iter().map(|(k, _)| *k).collect();
            let label_vals = Self::label_values(labels);

            let histograms = self.histograms.read().unwrap();
            if let Some(hist) = histograms.get(name) {
                if let Ok(m) = hist.get_metric_with_label_values(&label_vals) {
                    m.observe(value);
                }
                return;
            }
            drop(histograms);

            let mut histograms = self.histograms.write().unwrap();
            let hist = histograms.entry(name.to_string()).or_insert_with(|| {
                let h = HistogramVec::new(
                    ::prometheus::HistogramOpts::new(name, name),
                    &label_names,
                )
                .expect("Failed to create histogram");
                let _ = ::prometheus::register(Box::new(h.clone()));
                h
            });
            if let Ok(m) = hist.get_metric_with_label_values(&label_vals) {
                m.observe(value);
            }
        }

        fn record_gauge(&self, name: &str, value: f64, labels: &[(&str, &str)]) {
            let label_names: Vec<&str> = labels.iter().map(|(k, _)| *k).collect();
            let label_vals = Self::label_values(labels);

            let gauges = self.gauges.read().unwrap();
            if let Some(gauge) = gauges.get(name) {
                if let Ok(m) = gauge.get_metric_with_label_values(&label_vals) {
                    m.set(value);
                }
                return;
            }
            drop(gauges);

            let mut gauges = self.gauges.write().unwrap();
            let gauge = gauges.entry(name.to_string()).or_insert_with(|| {
                let g = GaugeVec::new(Opts::new(name, name), &label_names)
                    .expect("Failed to create gauge");
                let _ = ::prometheus::register(Box::new(g.clone()));
                g
            });
            if let Ok(m) = gauge.get_metric_with_label_values(&label_vals) {
                m.set(value);
            }
        }
    }
}

/// Helper function to get policy type name for metrics
fn policy_type_name(policy: &ResiliencePolicy) -> String {
    match policy {
        ResiliencePolicy::None => "none".to_string(),
        ResiliencePolicy::Retry { .. } => "retry".to_string(),
        ResiliencePolicy::CircuitBreaker { .. } => "circuit_breaker".to_string(),
        ResiliencePolicy::RateLimit { .. } => "rate_limit".to_string(),
        ResiliencePolicy::Timeout { .. } => "timeout".to_string(),
        ResiliencePolicy::Combined { .. } => "combined".to_string(),
    }
}

/// Instrumented wrapper for resilience orchestrator
pub struct InstrumentedResilienceOrchestrator<T: ResilienceOrchestrator> {
    inner: T,
    observability: ResilienceObservability,
}

impl<T: ResilienceOrchestrator> InstrumentedResilienceOrchestrator<T> {
    pub fn new(inner: T, observability: ResilienceObservability) -> Self {
        Self {
            inner,
            observability,
        }
    }
}

#[async_trait::async_trait]
impl<T: ResilienceOrchestrator> ResilienceOrchestrator for InstrumentedResilienceOrchestrator<T> {
    async fn execute_with_policy<V, F, Fut, E>(
        &self,
        policy: ResiliencePolicy,
        operation: F,
    ) -> Result<V, ResilienceOrchestrationError>
    where
        F: FnMut() -> Fut + Send,
        Fut: std::future::Future<Output = Result<V, E>> + Send,
        E: Into<ResilienceOrchestrationError> + Send,
    {
        let operation_id = "anonymous_operation"; // In a real implementation, this would be configurable
        let start_time = Instant::now();

        let policy_clone = policy.clone();

        self.observability
            .record_operation_start(operation_id, &policy_clone);

        let result = self.inner.execute_with_policy(policy, operation).await;

        let duration = start_time.elapsed();
        match &result {
            Ok(_) => {
                self.observability.record_operation_complete(
                    operation_id,
                    &policy_clone,
                    duration,
                    &Ok(()),
                );
            }
            Err(ref err) => {
                // Clone the original error to preserve its type for observability
                let cloned_err = match err {
                    ResilienceOrchestrationError::Domain(d) => {
                        ResilienceOrchestrationError::Domain(d.clone())
                    }
                    ResilienceOrchestrationError::Infrastructure(s) => {
                        ResilienceOrchestrationError::Infrastructure(s.clone())
                    }
                    ResilienceOrchestrationError::Configuration(s) => {
                        ResilienceOrchestrationError::Configuration(s.clone())
                    }
                    ResilienceOrchestrationError::Cancelled => {
                        ResilienceOrchestrationError::Cancelled
                    }
                };
                self.observability.record_operation_complete(
                    operation_id,
                    &policy_clone,
                    duration,
                    &Err(cloned_err),
                );
            }
        }

        result
    }

    fn get_circuit_breaker(&self, name: &str) -> Option<&CircuitBreaker> {
        self.inner.get_circuit_breaker(name)
    }

    fn get_rate_limiter(&self, name: &str) -> Option<&RateLimiter> {
        self.inner.get_rate_limiter(name)
    }

    fn metrics(&self) -> ResilienceMetrics {
        self.inner.metrics()
    }
}

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

    #[tokio::test]
    async fn test_observability_recording() {
        let observability = ResilienceObservability::new();
        let policy = ResiliencePolicy::Retry {
            max_attempts: 3,
            backoff: crate::domain::resilience::BackoffStrategy::default(),
        };

        // Record operation lifecycle
        observability.record_operation_start("test_operation", &policy);

        let duration = Duration::from_millis(150);
        let result = Ok(());

        observability.record_operation_complete("test_operation", &policy, duration, &result);

        // Verify health status works
        let health = observability.health_status();
        assert_eq!(health.overall_health, HealthLevel::Healthy);
    }

    #[test]
    fn test_policy_type_name() {
        assert_eq!(policy_type_name(&ResiliencePolicy::None), "none");
        assert_eq!(
            policy_type_name(&ResiliencePolicy::Retry {
                max_attempts: 3,
                backoff: crate::domain::resilience::BackoffStrategy::default(),
            }),
            "retry"
        );
        assert_eq!(
            policy_type_name(&ResiliencePolicy::CircuitBreaker {
                failure_threshold: 5,
                recovery_timeout: Duration::from_secs(30),
                success_threshold: 3,
            }),
            "circuit_breaker"
        );
    }

    #[test]
    fn test_circuit_breaker_state_transitions() {
        let observability = ResilienceObservability::new();

        observability.record_circuit_breaker_state_change(
            "test_circuit",
            CircuitBreakerState::Closed,
            CircuitBreakerState::Open,
        );

        // In a real implementation, this would update metrics
        let health = observability.health_status();
        assert_eq!(health.circuit_breakers_open, 0); // No-op implementation
    }

    #[test]
    fn test_prometheus_export() {
        let observability = ResilienceObservability::new();
        let metrics = observability.export_prometheus_metrics();
        assert!(metrics.contains("#"));
    }
}