use crate::intent_classifier::QueryIntent; use crate::meta_search::models::{SearchResponse, SearchResult}; use crate::meta_search::providers::{SearchContext, SearchProvider}; use crate::meta_search::proxy_manager::ProxyManager; use crate::meta_search::tor::TorManager; use anyhow::Result; use futures::stream::{FuturesUnordered, StreamExt}; use reqwest::Client; use std::collections::HashMap; use std::sync::atomic::{AtomicU64, Ordering}; use std::sync::Arc; use tokio::time::{timeout, Duration}; use tracing::info; struct ProviderHealth { successes: AtomicU64, failures: AtomicU64, consecutive_failures: AtomicU64, last_success_epoch: AtomicU64, } impl ProviderHealth { fn new() -> Self { let now = std::time::SystemTime::now() .duration_since(std::time::UNIX_EPOCH) .unwrap_or_default() .as_secs(); Self { successes: AtomicU64::new(0), failures: AtomicU64::new(0), consecutive_failures: AtomicU64::new(0), last_success_epoch: AtomicU64::new(now), } } fn record_success(&self) { self.successes.fetch_add(1, Ordering::Relaxed); self.consecutive_failures.store(0, Ordering::Relaxed); let now = std::time::SystemTime::now() .duration_since(std::time::UNIX_EPOCH) .unwrap_or_default() .as_secs(); self.last_success_epoch.store(now, Ordering::Relaxed); } fn record_failure(&self) { self.failures.fetch_add(1, Ordering::Relaxed); self.consecutive_failures.fetch_add(1, Ordering::Relaxed); } fn is_healthy(&self) -> bool { let consec = self.consecutive_failures.load(Ordering::Relaxed); if consec < 3 { return true; } let now = std::time::SystemTime::now() .duration_since(std::time::UNIX_EPOCH) .unwrap_or_default() .as_secs(); let last = self.last_success_epoch.load(Ordering::Relaxed); now.saturating_sub(last) > 60 } } fn freshness_boost(published_at: &Option) -> f32 { let Some(date_str) = published_at else { return 0.0; }; let trimmed = date_str.trim(); if trimmed.len() < 10 { return 0.0; } let date_part = match trimmed.get(..10) { Some(s) => s, None => return 0.0, }; let parts: Vec<&str> = date_part.split('-').collect(); if parts.len() != 3 { return 0.0; } let year: u64 = parts[0].parse().unwrap_or(0); let month: u64 = parts[1].parse().unwrap_or(6); let day: u64 = parts[2].parse().unwrap_or(15); if !(2000..=2035).contains(&year) { return 0.0; } let pub_days = (year - 1970) * 365 + (year - 1970) / 4 + (month - 1) * 30 + day; let now_days = std::time::SystemTime::now() .duration_since(std::time::UNIX_EPOCH) .unwrap_or_default() .as_secs() / 86400; let days_ago = now_days.saturating_sub(pub_days) as f64; (0.2 * (-days_ago / 120.0).exp()) as f32 } pub struct MetaSearchAggregator { pub providers: Vec>, pub news_providers: Vec>, pub timeout_ms: u64, pub proxy_manager: Arc, pub tor_manager: Option>, pub client: Arc, provider_health: HashMap>, } impl MetaSearchAggregator { pub fn new( proxy_manager: Arc, tor_manager: Option>, _whoogle_url: Option<&str>, _librex_url: Option<&str>, searxng_url: Option<&str>, ) -> Self { let client = Arc::new( Client::builder() .user_agent("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/122.0.0.0 Safari/537.36 IntentForge/0.1") .timeout(Duration::from_secs(10)) .tcp_keepalive(Duration::from_secs(60)) .pool_idle_timeout(Duration::from_secs(90)) .build() .unwrap_or_default(), ); let mut providers: Vec> = vec![ // Tier 1: Self-hosted SearXNG (70+ engines via Tor - highest priority) // Tier 2: Direct engine providers (API-based, reliable via Tor) Arc::new(crate::meta_search::providers::duckduckgo::DuckDuckGoProvider), Arc::new(crate::meta_search::providers::bing::BingProvider), // Tier 3: Domain-specific providers (all work through Tor) Arc::new(crate::meta_search::providers::github::GitHubProvider), Arc::new(crate::meta_search::providers::arxiv::ArxivProvider), Arc::new(crate::meta_search::providers::reddit::RedditProvider), Arc::new(crate::meta_search::providers::gdelt::GDELTProvider), Arc::new(crate::meta_search::providers::invidious::InvidiousProvider), ]; // Add self-hosted SearXNG at front for highest priority (works through Tor) if let Some(url) = searxng_url { if !url.is_empty() { providers.insert( 0, Arc::new(crate::meta_search::providers::searx::SearxProvider::new( client.clone(), url, )), ); } } // Skip Whoogle and LibreX - they don't work through Tor (Google CAPTCHAs Tor exit nodes) let news_providers: Vec> = vec![ Arc::new(crate::meta_search::providers::google_news::GoogleNewsProvider), Arc::new(crate::meta_search::providers::ddg_news::DuckDuckGoNewsProvider), Arc::new(crate::meta_search::providers::gdelt::GDELTProvider), ]; let mut provider_health: HashMap> = HashMap::new(); for p in &providers { provider_health .entry(p.name().to_string()) .or_insert_with(|| Arc::new(ProviderHealth::new())); } for p in &news_providers { provider_health .entry(p.name().to_string()) .or_insert_with(|| Arc::new(ProviderHealth::new())); } Self { providers, news_providers, timeout_ms: 10000, proxy_manager, tor_manager, client, provider_health, } } pub async fn search(&self, query: &str) -> SearchResponse { self.search_with_providers_weighted(query, &self.providers, None) .await } pub async fn search_news(&self, query: &str) -> SearchResponse { self.search_with_providers_weighted(query, &self.news_providers, None) .await } pub async fn search_news_geo(&self, query: &str, location: &str) -> SearchResponse { let start = std::time::Instant::now(); let mut all_results = Vec::new(); let news_resp = self.search_news(query).await; all_results.push(news_resp.results); let enriched_query = format!("{} {}", query, location); let enriched_resp = self.search_news(&enriched_query).await; all_results.push(enriched_resp.results); let ctx = Arc::new(SearchContext { proxy_manager: self.proxy_manager.clone(), tor_manager: self.tor_manager.clone(), }); for provider in &self.news_providers { if provider.name() == "google_news" { if let Some(gn_provider) = provider.as_any().downcast_ref::() { if let Ok(res) = gn_provider.get_geo_news(location, "en-US", "US", "US:en", ctx.clone()).await { all_results.push(res); } } } } let merged = self.merge_results(all_results); let unique = self.deduplicate_results(merged); SearchResponse { query: query.to_string(), results: unique.into_iter().take(100).collect(), took_ms: start.elapsed().as_millis() as u64, } } fn merge_results(&self, all_results: Vec>) -> Vec { let mut rrf_scores: HashMap = HashMap::new(); let k = 60.0; for engine_results in all_results { for (rank, result) in engine_results.into_iter().enumerate() { let fresh = freshness_boost(&result.published_at); let entry = rrf_scores .entry(result.url.clone()) .or_insert((0.0, result.clone())); entry.0 += (1.0 / (k + rank as f32)) * (1.0 + fresh); } } let mut merged: Vec = rrf_scores .into_iter() .map(|(_, (s, mut r))| { r.score = s; r }) .collect(); merged.sort_by(|a, b| { b.score .partial_cmp(&a.score) .unwrap_or(std::cmp::Ordering::Equal) }); merged } fn deduplicate_results(&self, results: Vec) -> Vec { let mut unique: Vec = Vec::with_capacity(results.len()); for result in results { let hash = crate::utils::compute_simhash(&format!("{} {}", result.title, result.description)); if !unique.iter().any(|e| { crate::utils::simhash_distance( hash, crate::utils::compute_simhash(&format!("{} {}", e.title, e.description)), ) <= 3 }) { unique.push(result); } } unique } pub async fn search_with_intent( &self, query: &str, intent: Option<&QueryIntent>, ) -> SearchResponse { self.search_with_providers_weighted(query, &self.providers, intent) .await } fn get_provider_weight(&self, provider_name: &str, intent: Option<&QueryIntent>) -> f32 { let intent = match intent { Some(i) => i, None => return 1.0, }; // Base weight for all providers let mut weight = 1.0; match intent { QueryIntent::Programming | QueryIntent::DevOps | QueryIntent::WebDevelopment | QueryIntent::Database => match provider_name { "github" => weight = 2.5, "stackoverflow" | "searxng" => weight = 2.0, "reddit" => weight = 1.5, "arxiv" => weight = 1.3, "medium" => weight = 1.2, _ => {} }, QueryIntent::AIML | QueryIntent::DataScience | QueryIntent::Academic => { match provider_name { "arxiv" => weight = 3.0, "github" => weight = 2.0, "searxng" => weight = 1.5, "reddit" => weight = 1.2, _ => {} } } QueryIntent::Cooking | QueryIntent::Travel | QueryIntent::Fitness | QueryIntent::Gardening => match provider_name { "searxng" => weight = 2.5, "reddit" => weight = 2.0, "duckduckgo" | "bing" => weight = 1.3, _ => {} }, QueryIntent::News | QueryIntent::Sports | QueryIntent::Finance => match provider_name { "gdelt" => weight = 2.5, "searxng" => weight = 2.0, "bing" => weight = 1.5, "reddit" => weight = 1.3, _ => {} }, QueryIntent::Gaming => match provider_name { "reddit" => weight = 2.5, "searxng" => weight = 2.0, _ => {} }, _ => { // For other intents, boost general-purpose providers match provider_name { "searxng" => weight = 1.5, "duckduckgo" => weight = 1.2, _ => {} } } } weight } pub async fn search_with_providers_weighted( &self, query: &str, providers: &[Arc], intent: Option<&QueryIntent>, ) -> SearchResponse { let start = std::time::Instant::now(); let query_owned = query.to_string(); let query_lower = query.to_lowercase(); let is_code = query_lower.contains("repo") || query_lower.contains("github") || query_lower.contains("rust"); let is_news = query_lower.contains("news") || query_lower.contains("breaking"); let is_video = query_lower.contains("video") || query_lower.contains("watch"); let ctx = Arc::new(SearchContext { proxy_manager: self.proxy_manager.clone(), tor_manager: self.tor_manager.clone(), }); let mut futures = FuturesUnordered::new(); for provider in providers { let name = provider.name(); let health = self.provider_health.get(name).cloned(); if let Some(ref h) = health { if !h.is_healthy() { info!( "Provider {} skipped (unhealthy — {} consecutive failures)", name, h.consecutive_failures.load(Ordering::Relaxed) ); continue; } } let provider = provider.clone(); let query = query_owned.clone(); let ctx = ctx.clone(); let mut priority_boost = 0.0; if is_code && name == "github" { priority_boost = 0.5; } if is_news && (name == "gdelt" || name.contains("news")) { priority_boost = 0.8; } if is_video && name == "invidious" { priority_boost = 0.8; } let weight = self.get_provider_weight(name, intent); futures.push(async move { let name = provider.name(); // Dynamic timeout: Meta-engines get more time, direct engines are faster let provider_timeout = match name { "searxng" => 10000, "whoogle" | "librex" => 8000, "duckduckgo" | "bing" | "reddit" | "github" | "arxiv" | "gdelt" => 8000, _ => 6000, }; match timeout( Duration::from_millis(provider_timeout), provider.search(&query, ctx), ) .await { Ok(Ok(mut results)) => { if let Some(h) = &health { h.record_success(); } info!( "Provider {} returned {} results (weight={})", name, results.len(), weight ); for r in &mut results { r.score += priority_boost; } (name, results, weight) } Ok(Err(e)) => { if let Some(h) = &health { h.record_failure(); } info!("Provider {} error: {}", name, e); (name, vec![], weight) } Err(_) => { if let Some(h) = &health { h.record_failure(); } info!("Provider {} timed out", name); (name, vec![], weight) } } }); } let mut all_results: Vec<(Vec, f32)> = Vec::new(); let mut total_count = 0; let mut high_quality_engines_responded = 0; let target_count = 20; let fast_threshold = 8; let fast_deadline_ms = 1200; let deadline = tokio::time::sleep(Duration::from_millis(self.timeout_ms)); let fast_deadline = tokio::time::sleep(Duration::from_millis(fast_deadline_ms)); tokio::pin!(deadline); tokio::pin!(fast_deadline); loop { tokio::select! { res = futures.next() => { match res { Some((name, results, weight)) => { let is_hq = name == "searxng" || name == "whoogle" || name == "librex"; // If an HQ engine returned zero results (likely blocked), we don't increment HQ count // but we keep going to allow other providers to fill the gap. if is_hq && !results.is_empty() { high_quality_engines_responded += 1; } if !results.is_empty() { total_count += results.len(); all_results.push((results, weight)); } // Dynamic Early Exit Strategy: // 1. If we have at least one HQ engine and met the target count if high_quality_engines_responded >= 1 && total_count >= target_count { info!("Target reached with HQ engine ({}): Early exit in {}ms", total_count, start.elapsed().as_millis()); break; } // 2. If we have results from multiple engines and it's taking too long if total_count >= 50 { info!("High result count ({}): Early exit in {}ms", total_count, start.elapsed().as_millis()); break; } } None => break, } } _ = &mut fast_deadline => { // If we already have a decent number of results after the fast deadline, don't wait for slow ones if total_count >= fast_threshold && high_quality_engines_responded >= 1 { info!("Fast deadline hit with results ({}): Early exit in {}ms", total_count, start.elapsed().as_millis()); break; } } _ = &mut deadline => { info!("Global timeout hit ({}ms). Returning {} results, HQ_engines={}", self.timeout_ms, total_count, high_quality_engines_responded); break; } } } let query_clone = query.to_string(); let unique = tokio::task::spawn_blocking(move || { let mut rrf_scores: HashMap = HashMap::new(); let k = 60.0; for (engine_results, weight) in all_results { for (rank, result) in engine_results.into_iter().enumerate() { let fresh = freshness_boost(&result.published_at); let entry = rrf_scores .entry(result.url.clone()) .or_insert((0.0, result.clone())); entry.0 += (weight / (k + rank as f32)) * (1.0 + fresh); } } let mut merged: Vec = rrf_scores .into_iter() .map(|(_, (s, mut r))| { r.score = s; r }) .collect(); merged.sort_by(|a, b| { b.score .partial_cmp(&a.score) .unwrap_or(std::cmp::Ordering::Equal) }); let mut unique: Vec = Vec::with_capacity(merged.len()); for result in merged { let text = format!("{} {}", result.title, result.description); let hash = crate::utils::compute_simhash(&text); let mut is_dup = false; for u in &unique { let utext = format!("{} {}", u.title, u.description); let uhash = crate::utils::compute_simhash(&utext); if crate::utils::simhash_distance(hash, uhash) <= 3 { is_dup = true; break; } } if !is_dup { unique.push(result); } } unique }) .await .unwrap_or_default(); SearchResponse { query: query_clone, results: unique.into_iter().take(100).collect(), took_ms: start.elapsed().as_millis() as u64, } } pub async fn search_results(&self, query: &str) -> Result> { let response = self.search(query).await; Ok(response.results) } pub async fn fast_search_results( &self, query: &str, timeout_ms: u64, ) -> Result> { let start = std::time::Instant::now(); let results = match timeout( Duration::from_millis(timeout_ms), self.search_results(query), ) .await { Ok(Ok(res)) => res, _ => vec![], }; tracing::info!( "Fast meta-search for '{}' took {}ms", query, start.elapsed().as_millis() ); Ok(results) } }