anya_core/core/
reliability.rs

1//! [AIR-3][AIS-3][BPC-3][RES-3] Reliability and monitoring components for Anya Core
2
3use crate::{AnyaError, AnyaResult};
4use log::{error, info, warn};
5use std::future::Future;
6use std::time::{Duration, Instant};
7
8/// Confidence assessment for AI verification
9#[derive(Debug, Clone)]
10pub struct ConfidenceAssessment<T> {
11    pub output: AnyaResult<T>,
12    pub confidence: f64,
13    pub verification_steps: Vec<String>,
14    pub reasoning: String,
15}
16
17/// Watchdog timer for monitoring operations
18#[derive(Debug, Clone)]
19pub struct Watchdog {
20    name: String,
21    timeout: Duration,
22    start_time: Instant,
23    is_active: bool,
24}
25
26impl Watchdog {
27    /// Create a new watchdog with specified timeout
28    pub fn new(name: &str, timeout: Duration) -> Self {
29        Self {
30            name: name.to_string(),
31            timeout,
32            start_time: Instant::now(),
33            is_active: true,
34        }
35    }
36
37    /// Stop the watchdog
38    pub fn stop(&mut self) {
39        self.is_active = false;
40    }
41
42    /// Trigger an alert for timeout
43    pub fn trigger_alert(&self) {
44        error!(
45            "Watchdog '{}' triggered alert after {:?}",
46            self.name, self.timeout
47        );
48    }
49
50    /// Check if the watchdog has timed out
51    pub fn has_timed_out(&self) -> bool {
52        self.is_active && self.start_time.elapsed() > self.timeout
53    }
54}
55
56/// Progress tracker for long-running operations
57#[derive(Debug, Clone)]
58pub struct ProgressTracker {
59    name: String,
60    timeout: Duration,
61    verbose: bool,
62    start_time: Instant,
63}
64
65impl ProgressTracker {
66    /// Create a new progress tracker
67    pub fn new(name: &str) -> Self {
68        Self {
69            name: name.to_string(),
70            timeout: Duration::from_secs(300), // Default 5 minutes
71            verbose: false,
72            start_time: Instant::now(),
73        }
74    }
75
76    /// Set timeout for the operation
77    pub fn with_timeout(mut self, timeout: Duration) -> Self {
78        self.timeout = timeout;
79        self
80    }
81
82    /// Enable verbose logging
83    pub fn with_verbosity(mut self, verbose: bool) -> Self {
84        self.verbose = verbose;
85        self
86    }
87
88    /// Log progress if verbose mode is enabled
89    pub fn log_progress(&self, message: &str) {
90        if self.verbose {
91            info!("[{}] {}", self.name, message);
92        }
93    }
94
95    /// Get elapsed time since start
96    pub fn elapsed(&self) -> Duration {
97        self.start_time.elapsed()
98    }
99
100    /// Update progress with completion percentage
101    pub fn update(&self, progress: f64) -> AnyaResult<()> {
102        if !(0.0..=1.0).contains(&progress) {
103            return Err(AnyaError::InvalidInput(
104                "Progress must be between 0.0 and 1.0".to_string(),
105            ));
106        }
107
108        if self.verbose {
109            info!("[{}] Progress: {:.1}%", self.name, progress * 100.0);
110        }
111
112        Ok(())
113    }
114
115    /// Mark operation as complete
116    pub fn complete(&self) {
117        if self.verbose {
118            info!(
119                "[{}] Operation completed in {:?}",
120                self.name,
121                self.elapsed()
122            );
123        }
124    }
125}
126
127/// AI verification component for blockchain operations
128#[derive(Debug, Clone)]
129pub struct AiVerification {
130    min_confidence: f64,
131    blockchain_verification: bool,
132    external_data_verification: bool,
133    human_verification: bool,
134}
135
136impl AiVerification {
137    /// Create a new AI verification instance
138    pub fn new() -> Self {
139        Self {
140            min_confidence: 0.95,
141            blockchain_verification: true,
142            external_data_verification: true,
143            human_verification: false,
144        }
145    }
146
147    /// Set minimum confidence threshold
148    pub fn with_min_confidence(mut self, confidence: f64) -> Self {
149        self.min_confidence = confidence;
150        self
151    }
152
153    /// Enable/disable blockchain verification
154    pub fn with_blockchain_verification(mut self, enabled: bool) -> Self {
155        self.blockchain_verification = enabled;
156        self
157    }
158
159    /// Enable/disable external data verification
160    pub fn with_external_data_verification(mut self, enabled: bool) -> Self {
161        self.external_data_verification = enabled;
162        self
163    }
164
165    /// Enable/disable human verification requirement
166    pub fn with_human_verification(mut self, enabled: bool) -> Self {
167        self.human_verification = enabled;
168        self
169    }
170
171    /// Verify data with AI analysis
172    pub async fn verify(&self, data: &[u8]) -> AnyaResult<bool> {
173        // Simulate AI verification process
174        let confidence = self.calculate_confidence(data).await?;
175
176        if confidence >= self.min_confidence {
177            Ok(true)
178        } else {
179            Err(AnyaError::LowConfidence(format!(
180                "Verification confidence {} below threshold {}",
181                confidence, self.min_confidence
182            )))
183        }
184    }
185
186    /// Calculate confidence score for data
187    async fn calculate_confidence(&self, _data: &[u8]) -> AnyaResult<f64> {
188        // Placeholder for AI confidence calculation
189        // In real implementation, this would use ML models
190        Ok(0.98) // High confidence for now
191    }
192}
193
194impl Default for AiVerification {
195    fn default() -> Self {
196        Self::new()
197    }
198}
199
200/// [AIR-3][AIS-3][BPC-3][RES-3] Execute an async operation with timeout and progress tracking
201pub async fn execute_with_monitoring<T, F>(
202    operation_name: &str,
203    timeout_duration: Duration,
204    operation: F,
205) -> AnyaResult<T>
206where
207    F: Future<Output = AnyaResult<T>>,
208{
209    // Create watchdog
210    let mut watchdog = Watchdog::new(operation_name, timeout_duration);
211
212    // Execute with timeout
213    match tokio::time::timeout(timeout_duration, operation).await {
214        Ok(result) => {
215            // Operation completed within timeout
216            watchdog.stop();
217            result
218        }
219        Err(_) => {
220            // Operation timed out
221            watchdog.trigger_alert();
222            let error_msg =
223                format!("Operation '{operation_name}' timed out after {timeout_duration:?}");
224            error!("{error_msg}");
225            Err(AnyaError::Timeout(error_msg))
226        }
227    }
228}
229
230/// [AIR-3][AIS-3][BPC-3][RES-3] Execute with recovery attempt on timeout
231pub async fn execute_with_recovery<T, F, R>(
232    operation_name: &str,
233    primary_timeout: Duration,
234    recovery_timeout: Duration,
235    primary_operation: F,
236    recovery_operation: R,
237) -> AnyaResult<T>
238where
239    F: Future<Output = AnyaResult<T>>,
240    R: Future<Output = AnyaResult<T>>,
241{
242    // Create watchdog for the entire operation
243    let mut watchdog = Watchdog::new(
244        operation_name,
245        primary_timeout + recovery_timeout + Duration::from_secs(1),
246    );
247
248    // Try primary operation with timeout
249    match tokio::time::timeout(primary_timeout, primary_operation).await {
250        Ok(result) => {
251            // Primary operation completed within timeout
252            watchdog.stop();
253            result
254        }
255        Err(_) => {
256            // Primary operation timed out, try recovery
257            warn!(
258                "Operation '{operation_name}' timed out after {primary_timeout:?}, attempting recovery"
259            );
260
261            // Try recovery operation with timeout
262            match tokio::time::timeout(recovery_timeout, recovery_operation).await {
263                Ok(result) => {
264                    // Recovery completed within timeout
265                    watchdog.stop();
266                    info!("Recovery for '{operation_name}' succeeded");
267                    result
268                }
269                Err(_) => {
270                    // Recovery also timed out
271                    watchdog.trigger_alert();
272                    let error_msg = format!(
273                        "Operation '{operation_name}' and recovery both timed out (after {primary_timeout:?} and {recovery_timeout:?})"
274                    );
275                    error!("{error_msg}");
276                    Err(AnyaError::Timeout(error_msg))
277                }
278            }
279        }
280    }
281}