Spaces:
Build error
Build error
Download src/domain_manager/mod.rs from LuckyMod/intentforge: direct link, hf CLI and curl.
- Browser
- Download file 24.6 kB
-
https://huggingface.co/spaces/LuckyMod/intentforge/resolve/main/src/domain_manager/mod.rs
- Command line
-
hf download hf://spaces/LuckyMod/intentforge/src/domain_manager/mod.rs
-
curl -L -o mod.rs https://huggingface.co/spaces/LuckyMod/intentforge/resolve/main/src/domain_manager/mod.rs
24.6 kB
| //! Domain Manager Module for IntentForge v2 | |
| //! | |
| //! Manages domains with automatic source discovery, validation, and performance tracking. | |
| //! Provides reliable, always-updated sources for each domain. | |
| use anyhow::Result; | |
| use serde::{Deserialize, Serialize}; | |
| use std::collections::HashMap; | |
| use std::sync::Arc; | |
| use tokio::sync::RwLock; | |
| use crate::redis_store::RedisStore; | |
| const DOMAIN_STATS_KEY: &str = "domain_manager:stats"; | |
| const SOURCE_HEALTH_KEY: &str = "domain_manager:source_health"; | |
| const DOMAIN_SOURCES_KEY: &str = "domain_manager:domain_sources"; | |
| /// Source type enumeration | |
| pub enum SourceType { | |
| RssFeed, | |
| AtomFeed, | |
| Sitemap, | |
| Api, | |
| Html, | |
| Json, | |
| } | |
| /// Source health status | |
| pub enum HealthStatus { | |
| Healthy, | |
| Degraded, | |
| Unhealthy, | |
| Unknown, | |
| } | |
| /// Source performance metrics | |
| pub struct SourceMetrics { | |
| pub total_requests: u64, | |
| pub successful_requests: u64, | |
| pub failed_requests: u64, | |
| pub avg_response_time_ms: f64, | |
| pub last_success_at: Option<i64>, | |
| pub last_failure_at: Option<i64>, | |
| pub consecutive_failures: u32, | |
| pub items_fetched: u64, | |
| pub quality_score: f32, | |
| } | |
| impl Default for SourceMetrics { | |
| fn default() -> Self { | |
| Self { | |
| total_requests: 0, | |
| successful_requests: 0, | |
| failed_requests: 0, | |
| avg_response_time_ms: 0.0, | |
| last_success_at: None, | |
| last_failure_at: None, | |
| consecutive_failures: 0, | |
| items_fetched: 0, | |
| quality_score: 0.5, | |
| } | |
| } | |
| } | |
| impl SourceMetrics { | |
| /// Calculate success rate | |
| pub fn success_rate(&self) -> f32 { | |
| if self.total_requests == 0 { | |
| return 0.0; | |
| } | |
| self.successful_requests as f32 / self.total_requests as f32 | |
| } | |
| /// Calculate health status based on metrics | |
| pub fn health_status(&self) -> HealthStatus { | |
| if self.total_requests == 0 { | |
| return HealthStatus::Unknown; | |
| } | |
| let success_rate = self.success_rate(); | |
| if success_rate >= 0.9 && self.consecutive_failures < 3 { | |
| HealthStatus::Healthy | |
| } else if success_rate >= 0.5 && self.consecutive_failures < 5 { | |
| HealthStatus::Degraded | |
| } else { | |
| HealthStatus::Unhealthy | |
| } | |
| } | |
| /// Update metrics after a request | |
| pub fn record_success(&mut self, response_time_ms: f64, items_count: usize) { | |
| self.total_requests += 1; | |
| self.successful_requests += 1; | |
| self.consecutive_failures = 0; | |
| self.last_success_at = Some(chrono::Utc::now().timestamp()); | |
| self.items_fetched += items_count as u64; | |
| // Update rolling average response time | |
| let n = self.successful_requests as f64; | |
| self.avg_response_time_ms = (self.avg_response_time_ms * (n - 1.0) + response_time_ms) / n; | |
| } | |
| pub fn record_failure(&mut self) { | |
| self.total_requests += 1; | |
| self.failed_requests += 1; | |
| self.consecutive_failures += 1; | |
| self.last_failure_at = Some(chrono::Utc::now().timestamp()); | |
| } | |
| } | |
| /// Source configuration with metadata | |
| pub struct ManagedSource { | |
| pub id: String, | |
| pub domain: String, | |
| pub name: String, | |
| pub url: String, | |
| pub source_type: SourceType, | |
| pub category: String, | |
| pub priority: u32, | |
| pub enabled: bool, | |
| pub discovered_at: i64, | |
| pub last_checked_at: Option<i64>, | |
| pub check_interval_secs: u64, | |
| pub metrics: SourceMetrics, | |
| } | |
| impl ManagedSource { | |
| pub fn new( | |
| domain: String, | |
| name: String, | |
| url: String, | |
| source_type: SourceType, | |
| category: String, | |
| priority: u32, | |
| ) -> Self { | |
| Self { | |
| id: format!("{}-{}", domain, uuid::Uuid::new_v4()), | |
| domain, | |
| name, | |
| url, | |
| source_type, | |
| category, | |
| priority, | |
| enabled: true, | |
| discovered_at: chrono::Utc::now().timestamp(), | |
| last_checked_at: None, | |
| check_interval_secs: 3600, // 1 hour default | |
| metrics: SourceMetrics::default(), | |
| } | |
| } | |
| /// Calculate effective priority based on metrics | |
| pub fn effective_priority(&self) -> f32 { | |
| let base_priority = self.priority as f32; | |
| let health_multiplier = match self.metrics.health_status() { | |
| HealthStatus::Healthy => 1.0, | |
| HealthStatus::Degraded => 0.7, | |
| HealthStatus::Unhealthy => 0.3, | |
| HealthStatus::Unknown => 0.5, | |
| }; | |
| let quality_multiplier = self.metrics.quality_score; | |
| base_priority * health_multiplier * quality_multiplier | |
| } | |
| } | |
| /// Domain configuration | |
| pub struct Domain { | |
| pub name: String, | |
| pub base_url: String, | |
| pub category: String, | |
| pub priority: u32, | |
| pub enabled: bool, | |
| pub sources: Vec<String>, // Source IDs | |
| pub discovered_sources: Vec<String>, | |
| pub last_discovery_at: Option<i64>, | |
| pub discovery_interval_secs: u64, | |
| } | |
| impl Domain { | |
| pub fn new(name: String, base_url: String, category: String, priority: u32) -> Self { | |
| Self { | |
| name, | |
| base_url, | |
| category, | |
| priority, | |
| enabled: true, | |
| sources: Vec::new(), | |
| discovered_sources: Vec::new(), | |
| last_discovery_at: None, | |
| discovery_interval_secs: 86400, // 24 hours default | |
| } | |
| } | |
| } | |
| /// Domain Manager - manages domains and their sources | |
| pub struct DomainManager { | |
| redis: Arc<RedisStore>, | |
| domains: Arc<RwLock<HashMap<String, Domain>>>, | |
| sources: Arc<RwLock<HashMap<String, ManagedSource>>>, | |
| client: reqwest::Client, | |
| } | |
| impl DomainManager { | |
| /// Create a new domain manager | |
| pub fn new(redis: Arc<RedisStore>) -> Self { | |
| let client = reqwest::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(std::time::Duration::from_secs(30)) | |
| .build() | |
| .unwrap_or_default(); | |
| Self { | |
| redis, | |
| domains: Arc::new(RwLock::new(HashMap::new())), | |
| sources: Arc::new(RwLock::new(HashMap::new())), | |
| client, | |
| } | |
| } | |
| /// Initialize from sources.yaml | |
| pub async fn init_from_config(&self, config: &crate::trending::SourcesConfig) -> Result<()> { | |
| { | |
| let mut domains = self.domains.write().await; | |
| let mut sources = self.sources.write().await; | |
| // Add domains from config | |
| for domain_source in &config.domains { | |
| let domain = Domain::new( | |
| domain_source.name.clone(), | |
| domain_source.base_url.clone(), | |
| domain_source.category.clone(), | |
| domain_source.priority, | |
| ); | |
| domains.insert(domain.name.clone(), domain); | |
| } | |
| // Add RSS feeds as sources | |
| for feed in &config.sources { | |
| let source = ManagedSource::new( | |
| feed.name.clone(), // Use name as domain for feeds | |
| feed.name.clone(), | |
| feed.url.clone(), | |
| SourceType::RssFeed, | |
| feed.category.clone(), | |
| feed.priority, | |
| ); | |
| sources.insert(source.id.clone(), source); | |
| } | |
| } | |
| // Load persisted state from Redis | |
| self.load_state().await?; | |
| let domains_len = self.domains.read().await.len(); | |
| let sources_len = self.sources.read().await.len(); | |
| tracing::info!( | |
| "Domain manager initialized with {} domains and {} sources", | |
| domains_len, | |
| sources_len | |
| ); | |
| Ok(()) | |
| } | |
| /// Load state from Redis | |
| async fn load_state(&self) -> Result<()> { | |
| let mut conn = self.redis.get_connection().await?; | |
| // Load domain sources mapping | |
| let domain_sources_json: Option<String> = redis::cmd("GET") | |
| .arg(DOMAIN_SOURCES_KEY) | |
| .query_async(&mut conn) | |
| .await?; | |
| if let Some(json) = domain_sources_json { | |
| if let Ok(domain_sources) = serde_json::from_str::<HashMap<String, Vec<String>>>(&json) | |
| { | |
| let mut domains = self.domains.write().await; | |
| for (domain_name, source_ids) in domain_sources { | |
| if let Some(domain) = domains.get_mut(&domain_name) { | |
| domain.discovered_sources = source_ids; | |
| } | |
| } | |
| } | |
| } | |
| // Load source health data | |
| let source_health_json: Option<String> = redis::cmd("GET") | |
| .arg(SOURCE_HEALTH_KEY) | |
| .query_async(&mut conn) | |
| .await?; | |
| if let Some(json) = source_health_json { | |
| if let Ok(source_health) = serde_json::from_str::<HashMap<String, SourceMetrics>>(&json) | |
| { | |
| let mut sources = self.sources.write().await; | |
| for (source_id, metrics) in source_health { | |
| if let Some(source) = sources.get_mut(&source_id) { | |
| source.metrics = metrics; | |
| } | |
| } | |
| } | |
| } | |
| Ok(()) | |
| } | |
| /// Save state to Redis | |
| pub async fn save_state(&self) -> Result<()> { | |
| let mut conn = self.redis.get_connection().await?; | |
| // Save domain sources mapping | |
| let domains = self.domains.read().await; | |
| let domain_sources: HashMap<String, Vec<String>> = domains | |
| .iter() | |
| .map(|(name, domain)| { | |
| ( | |
| name.clone(), | |
| domain | |
| .sources | |
| .iter() | |
| .chain(domain.discovered_sources.iter()) | |
| .cloned() | |
| .collect(), | |
| ) | |
| }) | |
| .collect(); | |
| let domain_sources_json = serde_json::to_string(&domain_sources)?; | |
| redis::cmd("SET") | |
| .arg(DOMAIN_SOURCES_KEY) | |
| .arg(&domain_sources_json) | |
| .arg("EX") | |
| .arg(86400) | |
| .query_async::<()>(&mut conn) | |
| .await?; | |
| // Save source health data | |
| let sources = self.sources.read().await; | |
| let source_health: HashMap<String, SourceMetrics> = sources | |
| .iter() | |
| .map(|(id, source)| (id.clone(), source.metrics.clone())) | |
| .collect(); | |
| let source_health_json = serde_json::to_string(&source_health)?; | |
| redis::cmd("SET") | |
| .arg(SOURCE_HEALTH_KEY) | |
| .arg(&source_health_json) | |
| .arg("EX") | |
| .arg(86400) | |
| .query_async::<()>(&mut conn) | |
| .await?; | |
| Ok(()) | |
| } | |
| /// Discover sources for a domain | |
| pub async fn discover_sources(&self, domain_name: &str) -> Result<Vec<ManagedSource>> { | |
| let domain = { | |
| let domains = self.domains.read().await; | |
| domains.get(domain_name).cloned() | |
| }; | |
| let domain = match domain { | |
| Some(d) => d, | |
| None => return Ok(Vec::new()), | |
| }; | |
| let mut discovered = Vec::new(); | |
| // Try common RSS/Atom feed locations | |
| let feed_paths = vec![ | |
| "/feed", | |
| "/feed/", | |
| "/rss", | |
| "/rss/", | |
| "/atom.xml", | |
| "/feed.xml", | |
| "/rss.xml", | |
| "/blog/feed", | |
| "/blog/rss", | |
| "/blog/feed.xml", | |
| "/blog/rss.xml", | |
| "/index.xml", | |
| ]; | |
| for path in feed_paths { | |
| let url = format!("{}{}", domain.base_url.trim_end_matches('/'), path); | |
| if let Ok(Some(source)) = self.check_feed_url(&url, &domain).await { | |
| discovered.push(source); | |
| } | |
| } | |
| // Check for sitemap | |
| let sitemap_url = format!("{}/sitemap.xml", domain.base_url.trim_end_matches('/')); | |
| if let Ok(Some(source)) = self.check_sitemap_url(&sitemap_url, &domain).await { | |
| discovered.push(source); | |
| } | |
| // Check robots.txt for sitemap | |
| let robots_url = format!("{}/robots.txt", domain.base_url.trim_end_matches('/')); | |
| if let Ok(sitemaps) = self.extract_sitemaps_from_robots(&robots_url).await { | |
| for sitemap_url in sitemaps { | |
| if let Ok(Some(source)) = self.check_sitemap_url(&sitemap_url, &domain).await { | |
| discovered.push(source); | |
| } | |
| } | |
| } | |
| // Update domain with discovered sources | |
| { | |
| let mut domains = self.domains.write().await; | |
| if let Some(domain) = domains.get_mut(domain_name) { | |
| domain.last_discovery_at = Some(chrono::Utc::now().timestamp()); | |
| domain.discovered_sources = discovered.iter().map(|s| s.id.clone()).collect(); | |
| } | |
| } | |
| // Add sources to manager | |
| { | |
| let mut sources = self.sources.write().await; | |
| for source in &discovered { | |
| sources.insert(source.id.clone(), source.clone()); | |
| } | |
| } | |
| tracing::info!( | |
| "Discovered {} sources for domain '{}'", | |
| discovered.len(), | |
| domain_name | |
| ); | |
| Ok(discovered) | |
| } | |
| /// Check if a URL is a valid feed | |
| async fn check_feed_url(&self, url: &str, domain: &Domain) -> Result<Option<ManagedSource>> { | |
| let start = std::time::Instant::now(); | |
| match self.client.get(url).send().await { | |
| Ok(resp) if resp.status().is_success() => { | |
| let content_type = resp | |
| .headers() | |
| .get("content-type") | |
| .and_then(|v| v.to_str().ok()) | |
| .unwrap_or("") | |
| .to_lowercase(); | |
| let body = resp.text().await?; | |
| // Check if it's a feed | |
| let is_feed = content_type.contains("xml") | |
| || content_type.contains("rss") | |
| || content_type.contains("atom") | |
| || body.contains("<rss") | |
| || body.contains("<feed") | |
| || body.contains("<channel>"); | |
| if is_feed { | |
| let source_type = if body.contains("<feed") { | |
| SourceType::AtomFeed | |
| } else { | |
| SourceType::RssFeed | |
| }; | |
| let name = format!("{} Feed", domain.name); | |
| let mut source = ManagedSource::new( | |
| domain.name.clone(), | |
| name, | |
| url.to_string(), | |
| source_type, | |
| domain.category.clone(), | |
| domain.priority, | |
| ); | |
| let elapsed = start.elapsed().as_millis() as f64; | |
| source.metrics.record_success(elapsed, 0); | |
| source.last_checked_at = Some(chrono::Utc::now().timestamp()); | |
| return Ok(Some(source)); | |
| } | |
| } | |
| _ => {} | |
| } | |
| Ok(None) | |
| } | |
| /// Check if a sitemap URL is valid | |
| async fn check_sitemap_url(&self, url: &str, domain: &Domain) -> Result<Option<ManagedSource>> { | |
| let start = std::time::Instant::now(); | |
| match self.client.get(url).send().await { | |
| Ok(resp) if resp.status().is_success() => { | |
| let body = resp.text().await?; | |
| if body.contains("<sitemapindex") || body.contains("<urlset") { | |
| let name = format!("{} Sitemap", domain.name); | |
| let mut source = ManagedSource::new( | |
| domain.name.clone(), | |
| name, | |
| url.to_string(), | |
| SourceType::Sitemap, | |
| domain.category.clone(), | |
| domain.priority, | |
| ); | |
| let elapsed = start.elapsed().as_millis() as f64; | |
| source.metrics.record_success(elapsed, 0); | |
| source.last_checked_at = Some(chrono::Utc::now().timestamp()); | |
| return Ok(Some(source)); | |
| } | |
| } | |
| _ => {} | |
| } | |
| Ok(None) | |
| } | |
| /// Extract sitemap URLs from robots.txt | |
| async fn extract_sitemaps_from_robots(&self, robots_url: &str) -> Result<Vec<String>> { | |
| let mut sitemaps = Vec::new(); | |
| if let Ok(resp) = self.client.get(robots_url).send().await { | |
| if resp.status().is_success() { | |
| let body = resp.text().await?; | |
| for line in body.lines() { | |
| let line = line.trim(); | |
| if line.to_lowercase().starts_with("sitemap:") { | |
| let sitemap_url = line["sitemap:".len()..].trim().to_string(); | |
| if !sitemap_url.is_empty() { | |
| sitemaps.push(sitemap_url); | |
| } | |
| } | |
| } | |
| } | |
| } | |
| Ok(sitemaps) | |
| } | |
| /// Get best sources for a category | |
| pub async fn get_best_sources(&self, category: &str, limit: usize) -> Vec<ManagedSource> { | |
| let sources = self.sources.read().await; | |
| let mut category_sources: Vec<&ManagedSource> = sources | |
| .values() | |
| .filter(|s| s.category == category && s.enabled) | |
| .collect(); | |
| // Sort by effective priority | |
| category_sources.sort_by(|a, b| { | |
| b.effective_priority() | |
| .partial_cmp(&a.effective_priority()) | |
| .unwrap_or(std::cmp::Ordering::Equal) | |
| }); | |
| category_sources.into_iter().take(limit).cloned().collect() | |
| } | |
| /// Get sources for a domain | |
| pub async fn get_domain_sources(&self, domain_name: &str) -> Vec<ManagedSource> { | |
| let domains = self.domains.read().await; | |
| let sources = self.sources.read().await; | |
| if let Some(domain) = domains.get(domain_name) { | |
| domain | |
| .sources | |
| .iter() | |
| .chain(domain.discovered_sources.iter()) | |
| .filter_map(|id| sources.get(id).cloned()) | |
| .collect() | |
| } else { | |
| Vec::new() | |
| } | |
| } | |
| /// Update source metrics | |
| pub async fn update_source_metrics( | |
| &self, | |
| source_id: &str, | |
| success: bool, | |
| response_time_ms: f64, | |
| items_count: usize, | |
| ) -> Result<()> { | |
| let mut sources = self.sources.write().await; | |
| if let Some(source) = sources.get_mut(source_id) { | |
| if success { | |
| source.metrics.record_success(response_time_ms, items_count); | |
| } else { | |
| source.metrics.record_failure(); | |
| } | |
| source.last_checked_at = Some(chrono::Utc::now().timestamp()); | |
| } | |
| // Persist to Redis periodically | |
| static COUNTER: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); | |
| let count = COUNTER.fetch_add(1, std::sync::atomic::Ordering::Relaxed); | |
| if count.is_multiple_of(100) { | |
| self.save_state().await?; | |
| } | |
| Ok(()) | |
| } | |
| /// Run discovery for all domains | |
| pub async fn run_discovery(&self) -> Result<usize> { | |
| let domain_names: Vec<String> = { | |
| let domains = self.domains.read().await; | |
| domains.keys().cloned().collect() | |
| }; | |
| let mut total_discovered = 0; | |
| for domain_name in domain_names { | |
| // Check if discovery is needed | |
| let needs_discovery = { | |
| let domains = self.domains.read().await; | |
| if let Some(domain) = domains.get(&domain_name) { | |
| if !domain.enabled { | |
| continue; | |
| } | |
| match domain.last_discovery_at { | |
| Some(last) => { | |
| let elapsed = chrono::Utc::now().timestamp() - last; | |
| elapsed as u64 >= domain.discovery_interval_secs | |
| } | |
| None => true, | |
| } | |
| } else { | |
| false | |
| } | |
| }; | |
| if needs_discovery { | |
| match self.discover_sources(&domain_name).await { | |
| Ok(sources) => { | |
| total_discovered += sources.len(); | |
| } | |
| Err(e) => { | |
| tracing::warn!( | |
| "Failed to discover sources for domain '{}': {}", | |
| domain_name, | |
| e | |
| ); | |
| } | |
| } | |
| } | |
| } | |
| if total_discovered > 0 { | |
| self.save_state().await?; | |
| } | |
| Ok(total_discovered) | |
| } | |
| /// Get domain statistics | |
| pub async fn get_stats(&self) -> DomainManagerStats { | |
| let domains = self.domains.read().await; | |
| let sources = self.sources.read().await; | |
| let total_domains = domains.len(); | |
| let enabled_domains = domains.values().filter(|d| d.enabled).count(); | |
| let total_sources = sources.len(); | |
| let healthy_sources = sources | |
| .values() | |
| .filter(|s| s.metrics.health_status() == HealthStatus::Healthy) | |
| .count(); | |
| let sources_by_category: HashMap<String, usize> = | |
| sources.values().fold(HashMap::new(), |mut acc, s| { | |
| *acc.entry(s.category.clone()).or_insert(0) += 1; | |
| acc | |
| }); | |
| DomainManagerStats { | |
| total_domains, | |
| enabled_domains, | |
| total_sources, | |
| healthy_sources, | |
| sources_by_category, | |
| } | |
| } | |
| } | |
| /// Domain manager statistics | |
| pub struct DomainManagerStats { | |
| pub total_domains: usize, | |
| pub enabled_domains: usize, | |
| pub total_sources: usize, | |
| pub healthy_sources: usize, | |
| pub sources_by_category: HashMap<String, usize>, | |
| } | |
| mod tests { | |
| use super::*; | |
| fn test_source_metrics_default() { | |
| let metrics = SourceMetrics::default(); | |
| assert_eq!(metrics.total_requests, 0); | |
| assert_eq!(metrics.success_rate(), 0.0); | |
| assert_eq!(metrics.health_status(), HealthStatus::Unknown); | |
| } | |
| fn test_source_metrics_success_rate() { | |
| let mut metrics = SourceMetrics::default(); | |
| metrics.total_requests = 100; | |
| metrics.successful_requests = 95; | |
| assert_eq!(metrics.success_rate(), 0.95); | |
| } | |
| fn test_source_metrics_health_status() { | |
| let mut metrics = SourceMetrics::default(); | |
| // Healthy | |
| metrics.total_requests = 100; | |
| metrics.successful_requests = 95; | |
| metrics.consecutive_failures = 1; | |
| assert_eq!(metrics.health_status(), HealthStatus::Healthy); | |
| // Degraded | |
| metrics.successful_requests = 70; | |
| metrics.consecutive_failures = 3; | |
| assert_eq!(metrics.health_status(), HealthStatus::Degraded); | |
| // Unhealthy | |
| metrics.successful_requests = 30; | |
| metrics.consecutive_failures = 10; | |
| assert_eq!(metrics.health_status(), HealthStatus::Unhealthy); | |
| } | |
| fn test_managed_source_effective_priority() { | |
| let mut source = ManagedSource::new( | |
| "example.com".to_string(), | |
| "Example".to_string(), | |
| "https://example.com/feed".to_string(), | |
| SourceType::RssFeed, | |
| "tech".to_string(), | |
| 10, | |
| ); | |
| // Unknown health | |
| assert!(source.effective_priority() > 0.0); | |
| // Healthy with good quality | |
| source.metrics.total_requests = 100; | |
| source.metrics.successful_requests = 95; | |
| source.metrics.quality_score = 0.9; | |
| let priority = source.effective_priority(); | |
| assert!(priority > 5.0); | |
| } | |
| } | |