use crate::{AnyaError, AnyaResult};
use log::{error, info, warn};
use std::future::Future;
use std::time::{Duration, Instant};
#[derive(Debug, Clone)]
pub struct ConfidenceAssessment<T> {
pub output: AnyaResult<T>,
pub confidence: f64,
pub verification_steps: Vec<String>,
pub reasoning: String,
}
#[derive(Debug, Clone)]
pub struct Watchdog {
name: String,
timeout: Duration,
start_time: Instant,
is_active: bool,
}
impl Watchdog {
pub fn new(name: &str, timeout: Duration) -> Self {
Self {
name: name.to_string(),
timeout,
start_time: Instant::now(),
is_active: true,
}
}
pub fn stop(&mut self) {
self.is_active = false;
}
pub fn trigger_alert(&self) {
error!(
"Watchdog '{}' triggered alert after {:?}",
self.name, self.timeout
);
}
pub fn has_timed_out(&self) -> bool {
self.is_active && self.start_time.elapsed() > self.timeout
}
}
#[derive(Debug, Clone)]
pub struct ProgressTracker {
name: String,
timeout: Duration,
verbose: bool,
start_time: Instant,
}
impl ProgressTracker {
pub fn new(name: &str) -> Self {
Self {
name: name.to_string(),
timeout: Duration::from_secs(300), verbose: false,
start_time: Instant::now(),
}
}
pub fn with_timeout(mut self, timeout: Duration) -> Self {
self.timeout = timeout;
self
}
pub fn with_verbosity(mut self, verbose: bool) -> Self {
self.verbose = verbose;
self
}
pub fn log_progress(&self, message: &str) {
if self.verbose {
info!("[{}] {}", self.name, message);
}
}
pub fn elapsed(&self) -> Duration {
self.start_time.elapsed()
}
pub fn update(&self, progress: f64) -> AnyaResult<()> {
if !(0.0..=1.0).contains(&progress) {
return Err(AnyaError::InvalidInput(
"Progress must be between 0.0 and 1.0".to_string(),
));
}
if self.verbose {
info!("[{}] Progress: {:.1}%", self.name, progress * 100.0);
}
Ok(())
}
pub fn complete(&self) {
if self.verbose {
info!(
"[{}] Operation completed in {:?}",
self.name,
self.elapsed()
);
}
}
}
#[derive(Debug, Clone)]
pub struct AiVerification {
min_confidence: f64,
blockchain_verification: bool,
external_data_verification: bool,
human_verification: bool,
}
impl AiVerification {
pub fn new() -> Self {
Self {
min_confidence: 0.95,
blockchain_verification: true,
external_data_verification: true,
human_verification: false,
}
}
pub fn with_min_confidence(mut self, confidence: f64) -> Self {
self.min_confidence = confidence;
self
}
pub fn with_blockchain_verification(mut self, enabled: bool) -> Self {
self.blockchain_verification = enabled;
self
}
pub fn with_external_data_verification(mut self, enabled: bool) -> Self {
self.external_data_verification = enabled;
self
}
pub fn with_human_verification(mut self, enabled: bool) -> Self {
self.human_verification = enabled;
self
}
pub async fn verify(&self, data: &[u8]) -> AnyaResult<bool> {
let confidence = self.calculate_confidence(data).await?;
if confidence >= self.min_confidence {
Ok(true)
} else {
Err(AnyaError::LowConfidence(format!(
"Verification confidence {} below threshold {}",
confidence, self.min_confidence
)))
}
}
async fn calculate_confidence(&self, _data: &[u8]) -> AnyaResult<f64> {
Ok(0.98) }
}
impl Default for AiVerification {
fn default() -> Self {
Self::new()
}
}
pub async fn execute_with_monitoring<T, F>(
operation_name: &str,
timeout_duration: Duration,
operation: F,
) -> AnyaResult<T>
where
F: Future<Output = AnyaResult<T>>,
{
let mut watchdog = Watchdog::new(operation_name, timeout_duration);
match tokio::time::timeout(timeout_duration, operation).await {
Ok(result) => {
watchdog.stop();
result
}
Err(_) => {
watchdog.trigger_alert();
let error_msg =
format!("Operation '{operation_name}' timed out after {timeout_duration:?}");
error!("{error_msg}");
Err(AnyaError::Timeout(error_msg))
}
}
}
pub async fn execute_with_recovery<T, F, R>(
operation_name: &str,
primary_timeout: Duration,
recovery_timeout: Duration,
primary_operation: F,
recovery_operation: R,
) -> AnyaResult<T>
where
F: Future<Output = AnyaResult<T>>,
R: Future<Output = AnyaResult<T>>,
{
let mut watchdog = Watchdog::new(
operation_name,
primary_timeout + recovery_timeout + Duration::from_secs(1),
);
match tokio::time::timeout(primary_timeout, primary_operation).await {
Ok(result) => {
watchdog.stop();
result
}
Err(_) => {
warn!(
"Operation '{operation_name}' timed out after {primary_timeout:?}, attempting recovery"
);
match tokio::time::timeout(recovery_timeout, recovery_operation).await {
Ok(result) => {
watchdog.stop();
info!("Recovery for '{operation_name}' succeeded");
result
}
Err(_) => {
watchdog.trigger_alert();
let error_msg = format!(
"Operation '{operation_name}' and recovery both timed out (after {primary_timeout:?} and {recovery_timeout:?})"
);
error!("{error_msg}");
Err(AnyaError::Timeout(error_msg))
}
}
}
}
}