anya_core/core/
reliability.rs1use crate::{AnyaError, AnyaResult};
4use log::{error, info, warn};
5use std::future::Future;
6use std::time::{Duration, Instant};
7
8#[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#[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 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 pub fn stop(&mut self) {
39 self.is_active = false;
40 }
41
42 pub fn trigger_alert(&self) {
44 error!(
45 "Watchdog '{}' triggered alert after {:?}",
46 self.name, self.timeout
47 );
48 }
49
50 pub fn has_timed_out(&self) -> bool {
52 self.is_active && self.start_time.elapsed() > self.timeout
53 }
54}
55
56#[derive(Debug, Clone)]
58pub struct ProgressTracker {
59 name: String,
60 timeout: Duration,
61 verbose: bool,
62 start_time: Instant,
63}
64
65impl ProgressTracker {
66 pub fn new(name: &str) -> Self {
68 Self {
69 name: name.to_string(),
70 timeout: Duration::from_secs(300), verbose: false,
72 start_time: Instant::now(),
73 }
74 }
75
76 pub fn with_timeout(mut self, timeout: Duration) -> Self {
78 self.timeout = timeout;
79 self
80 }
81
82 pub fn with_verbosity(mut self, verbose: bool) -> Self {
84 self.verbose = verbose;
85 self
86 }
87
88 pub fn log_progress(&self, message: &str) {
90 if self.verbose {
91 info!("[{}] {}", self.name, message);
92 }
93 }
94
95 pub fn elapsed(&self) -> Duration {
97 self.start_time.elapsed()
98 }
99
100 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 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#[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 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 pub fn with_min_confidence(mut self, confidence: f64) -> Self {
149 self.min_confidence = confidence;
150 self
151 }
152
153 pub fn with_blockchain_verification(mut self, enabled: bool) -> Self {
155 self.blockchain_verification = enabled;
156 self
157 }
158
159 pub fn with_external_data_verification(mut self, enabled: bool) -> Self {
161 self.external_data_verification = enabled;
162 self
163 }
164
165 pub fn with_human_verification(mut self, enabled: bool) -> Self {
167 self.human_verification = enabled;
168 self
169 }
170
171 pub async fn verify(&self, data: &[u8]) -> AnyaResult<bool> {
173 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 async fn calculate_confidence(&self, _data: &[u8]) -> AnyaResult<f64> {
188 Ok(0.98) }
192}
193
194impl Default for AiVerification {
195 fn default() -> Self {
196 Self::new()
197 }
198}
199
200pub 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 let mut watchdog = Watchdog::new(operation_name, timeout_duration);
211
212 match tokio::time::timeout(timeout_duration, operation).await {
214 Ok(result) => {
215 watchdog.stop();
217 result
218 }
219 Err(_) => {
220 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
230pub 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 let mut watchdog = Watchdog::new(
244 operation_name,
245 primary_timeout + recovery_timeout + Duration::from_secs(1),
246 );
247
248 match tokio::time::timeout(primary_timeout, primary_operation).await {
250 Ok(result) => {
251 watchdog.stop();
253 result
254 }
255 Err(_) => {
256 warn!(
258 "Operation '{operation_name}' timed out after {primary_timeout:?}, attempting recovery"
259 );
260
261 match tokio::time::timeout(recovery_timeout, recovery_operation).await {
263 Ok(result) => {
264 watchdog.stop();
266 info!("Recovery for '{operation_name}' succeeded");
267 result
268 }
269 Err(_) => {
270 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}