//! Discovery service for IntentForge v2 //! //! Continuously discovers new content via sitemaps, RSS, and link following. pub mod enhanced; use anyhow::{Context, Result}; use async_recursion::async_recursion; use redis::aio::ConnectionManager; use redis::AsyncCommands; use serde::{Deserialize, Serialize}; use std::sync::Arc; use tokio::time::Duration; use tracing::{info, warn}; use crate::config::Config; use crate::inference::FastIntentScorer; use crate::trending::{DomainSource, SourcesConfig}; /// Results from sitemap parsing #[derive(Debug, Clone)] pub enum SitemapResult { Urls(Vec), Indices(Vec), Empty, } /// Redis keys for discovery const DISCOVERY_QUEUE: &str = "crawl:queue"; const DISCOVERY_SEEN: &str = "crawl:seen"; /// Discovery service pub struct DiscoveryService { config: Arc, sources: Arc, redis: ConnectionManager, client: reqwest::Client, meili: Option, last_cycle: std::sync::Mutex>, fast_scorer: FastIntentScorer, } impl DiscoveryService { /// Create a new discovery service pub async fn new( config: Arc, sources: Arc, fast_scorer: FastIntentScorer, ) -> Result { let client = redis::Client::open(config.redis.url.clone()) .with_context(|| "Failed to connect to Redis for DiscoveryService")?; let redis = ConnectionManager::new(client) .await .with_context(|| "Failed to create Redis ConnectionManager")?; let mut headers = reqwest::header::HeaderMap::new(); headers.insert("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7".parse().unwrap()); headers.insert("Accept-Language", "en-US,en;q=0.9".parse().unwrap()); headers.insert("Cache-Control", "max-age=0".parse().unwrap()); headers.insert( "Sec-Ch-Ua", "\"Not A(Brand\";v=\"99\", \"Google Chrome\";v=\"121\", \"Chromium\";v=\"121\"" .parse() .unwrap(), ); headers.insert("Sec-Ch-Ua-Mobile", "?0".parse().unwrap()); headers.insert("Sec-Ch-Ua-Platform", "\"Windows\"".parse().unwrap()); headers.insert("Sec-Fetch-Dest", "document".parse().unwrap()); headers.insert("Sec-Fetch-Mode", "navigate".parse().unwrap()); headers.insert("Sec-Fetch-Site", "none".parse().unwrap()); headers.insert("Sec-Fetch-User", "?1".parse().unwrap()); headers.insert("Upgrade-Insecure-Requests", "1".parse().unwrap()); let client = reqwest::Client::builder() .user_agent(&config.crawler.user_agent) .default_headers(headers) .timeout(Duration::from_secs(config.crawler.timeout_secs)) .build() .with_context(|| "Failed to create HTTP client for DiscoveryService")?; let meili = if config.meilisearch.enabled && !config.meilisearch.url.is_empty() && !config.meilisearch.master_key.is_empty() { let client = meilisearch_sdk::client::Client::new( &config.meilisearch.url, Some(&config.meilisearch.master_key), ) .with_context(|| "Failed to create Meilisearch client for DiscoveryService")?; Some(client) } else { tracing::info!("Meilisearch disabled in config - outbound link discovery will be disabled"); None }; Ok(Self { config, sources, redis, client, meili, last_cycle: std::sync::Mutex::new(None), fast_scorer, }) } /// Run the discovery loop pub async fn run(self: Arc) { info!("Starting DiscoveryService with aggressive continuous mode..."); let mut interval = tokio::time::interval(Duration::from_secs(self.config.discovery.interval_secs)); // Track consecutive successful cycles let mut success_count = 0usize; loop { interval.tick().await; // Adaptive interval: run more frequently when queue is empty // Clone redis connection manager for thread-safe access let mut redis_clone = self.redis.clone(); let queue_size: usize = redis_clone.zcard(DISCOVERY_QUEUE).await.unwrap_or_default(); // 0. Check backpressure: Pause if Redis queue is too large if queue_size > self.config.discovery.max_queue_size { info!( "Discovery paused: crawl queue size ({}) exceeds threshold ({}). Waiting for next cycle.", queue_size, self.config.discovery.max_queue_size ); // Reset interval to a longer wait when full to avoid frequent polling interval = tokio::time::interval(Duration::from_secs(300)); // Wait 5 mins interval.tick().await; // Consume the immediate tick continue; } // Adjust interval based on queue size if queue_size < 50 { // Queue is small, run more aggressively interval = tokio::time::interval(Duration::from_secs(30)); } else if queue_size < 200 { // Moderate queue interval = tokio::time::interval(Duration::from_secs(60)); } else { // Large queue, slow down interval = tokio::time::interval(Duration::from_secs(self.config.discovery.interval_secs)); } info!("Running discovery cycle (queue: {})...", queue_size); match self.run_cycle().await { Ok(_) => { success_count += 1; if success_count.is_multiple_of(10) { info!("Discovery: {} consecutive successful cycles", success_count); } } Err(e) => { success_count = 0; warn!("Discovery cycle failed: {}", e); } } } } /// Run a single discovery cycle async fn run_cycle(&self) -> Result<()> { // Record cycle start time { let mut last = self.last_cycle.lock().unwrap_or_else(|e| e.into_inner()); *last = Some(std::time::Instant::now()); } // 1. Process domain sitemaps for domain in &self.sources.domains { if let Err(e) = self.process_sitemap(domain).await { tracing::debug!("Could not process sitemap for {}: {}", domain.name, e); } } // 1b. Process additional sitemaps for more tech content for (name, sitemap_url, category) in enhanced::get_additional_sitemaps() { let domain = DomainSource { name: name.clone(), base_url: sitemap_url.clone(), category: category.clone(), priority: 7, sitemap: Some(sitemap_url.clone()), }; if let Err(e) = self.process_sitemap(&domain).await { tracing::debug!("Could not process additional sitemap for {}: {}", name, e); } } // 1c. Process additional domains with potential sitemaps for (name, base_url, category, sitemap) in enhanced::get_additional_domains() { let domain = DomainSource { name: name.clone(), base_url: base_url.clone(), category: category.clone(), priority: 6, sitemap, }; if let Err(e) = self.process_sitemap(&domain).await { tracing::debug!("Could not process additional domain for {}: {}", name, e); } } // 2. (Optional) Outbound link discovery from Meilisearch if self.config.discovery.follow_links { if let Err(e) = self.discover_outbound_links().await { warn!("Outbound link discovery failed: {}", e); } } Ok(()) } /// Process a domain's sitemap async fn process_sitemap(&self, domain: &DomainSource) -> Result<()> { let sitemap_url = domain .sitemap .clone() .unwrap_or_else(|| format!("{}/sitemap.xml", domain.base_url)); self.process_sitemap_recursive(domain, &sitemap_url, 0) .await } /// Recursively process sitemaps and indices #[async_recursion] async fn process_sitemap_recursive( &self, domain: &DomainSource, url: &str, depth: u32, ) -> Result<()> { if depth > 3 { return Ok(()); } info!("Fetching sitemap/feed for {}: {}", domain.name, url); let response = self.client.get(url).send().await?; if !response.status().is_success() { anyhow::bail!("Fetch failed for {} with status {}", url, response.status()); } let content_type = response .headers() .get(reqwest::header::CONTENT_TYPE) .and_then(|v| v.to_str().ok()) .unwrap_or("") .to_string(); let bytes = response.bytes().await?; // 1. Try parsing as RSS/Atom first if it looks like a feed or if it's a known feed URL if url.contains("/feed") || url.contains("rss.xml") || url.contains("atom.xml") || content_type.contains("xml") { if let Ok(urls) = self.parse_rss_as_sitemap(&bytes) { if !urls.is_empty() { info!( "Discovered {} URLs from feed of {}", urls.len(), domain.name ); let mut redis = self.redis.clone(); for u in urls { self.enqueue_url(&mut redis, &u, domain.priority, &domain.category) .await?; } return Ok(()); } } } // 2. Try parsing as Sitemap XML let body = String::from_utf8_lossy(&bytes); let result = self.parse_sitemap_advanced(&body)?; match result { SitemapResult::Urls(urls) => { info!( "Discovered {} URLs from sitemap of {}", urls.len(), domain.name ); let mut redis = self.redis.clone(); for u in urls { self.enqueue_url(&mut redis, &u, domain.priority, &domain.category) .await?; } } SitemapResult::Indices(indices) => { info!( "Found {} nested sitemaps in index for {}", indices.len(), domain.name ); for index_url in indices { // Avoid self-recursion if index points to itself if index_url != url { let _ = self .process_sitemap_recursive(domain, &index_url, depth + 1) .await; } } } SitemapResult::Empty => { info!("No URLs discovered from {}", url); } } Ok(()) } /// Parse RSS/Atom as a list of URLs fn parse_rss_as_sitemap(&self, bytes: &[u8]) -> Result> { let feed = feed_rs::parser::parse(bytes)?; let mut urls = Vec::new(); for entry in feed.entries { if let Some(link) = entry.links.first() { urls.push(link.href.clone()); } } Ok(urls) } /// Parse sitemap XML into URLs or Nested Indices fn parse_sitemap_advanced(&self, body: &str) -> Result { let is_index = body.contains("(.*?)")?; let mut urls = Vec::new(); let mut indices = Vec::new(); for cap in re.captures_iter(body) { if let Some(m) = cap.get(1) { let url = m.as_str().to_string(); if is_index || url.ends_with(".xml") || url.ends_with(".xml.gz") || url.contains("sitemap") { indices.push(url); } else { urls.push(url); } } } if !urls.is_empty() { Ok(SitemapResult::Urls(urls)) } else if !indices.is_empty() { Ok(SitemapResult::Indices(indices)) } else { Ok(SitemapResult::Empty) } } /// Enqueue a URL for crawling /// Returns true if URL is new, false if already seen async fn enqueue_url( &self, redis: &mut ConnectionManager, url: &str, priority: u32, category: &str, ) -> Result { // Fast Intent Scorer Pre-filter if !self.fast_scorer.passes(url) { tracing::debug!( "FastIntentScorer rejected URL (score={:.2} < {:.2}): {}", self.fast_scorer.score(url), self.fast_scorer.threshold(), url ); return Ok(false); } // Check if seen (using SADD as a set-based seen list) let is_new: bool = redis.sadd(DISCOVERY_SEEN, url).await?; if !is_new { return Ok(false); } // Add to sorted set queue // Score: priority * 1000000 + timestamp (wrapped to fit in score) // Using 1,000,000 for priority spacing to ensure it dominates the timestamp let now = chrono::Utc::now().timestamp(); let score = (priority as i64 * 1000000) + (now % 1000000); let member = serde_json::to_string(&QueuedUrl { url: url.to_string(), category: category.to_string(), priority, })?; redis .zadd::<_, _, _, ()>(DISCOVERY_QUEUE, member, score) .await?; Ok(true) } /// Extract outbound links from high-signal indexed pages async fn discover_outbound_links(&self) -> Result<()> { let meili = match &self.meili { Some(client) => client, None => { tracing::debug!("Outbound link discovery skipped: Meilisearch is disabled"); return Ok(()); } }; info!("Starting outbound link discovery..."); use crate::crawler::find_links; use crate::indexer::IntentDocument; // Query Meilisearch for high-quality pages let index = meili.index(&self.config.meilisearch.index_name); // Search for documents with relevance_score > threshold let threshold = self.config.discovery.link_threshold; let results = index .search() .with_filter(&format!("relevance_score > {}", threshold)) .with_limit(20) .execute::() .await?; info!( "Found {} high-quality pages for link extraction", results.hits.len() ); let mut conn = self.redis.clone(); for hit in results.hits { let doc = hit.result; // Re-fetch the page to get HTML for link extraction // (Budgeted by rate limiter in enqueue_url or if we added it here) let response = match self.client.get(&doc.url).send().await { Ok(res) if res.status().is_success() => res, _ => continue, }; let html = response.text().await.unwrap_or_default(); let links = find_links(&html, &doc.url); info!("Extracted {} links from {}", links.len(), doc.url); for link in links.iter().take(5) { // Be conservative with discovered links self.enqueue_url(&mut conn, link, 3, &doc.category).await?; } } Ok(()) } /// Pop the highest priority URL from the queue pub async fn pop_url(&self) -> Result> { let mut redis = self.redis.clone(); // ZPOPMIN/ZPOPMAX returns [member, score] // We use ZPOPMAX because higher score = higher priority let results: Vec<(String, f64)> = redis.zpopmax(DISCOVERY_QUEUE, 1).await?; if results.is_empty() { return Ok(None); } let (json, _) = &results[0]; let queued: QueuedUrl = serde_json::from_str(json) .with_context(|| "Failed to deserialize QueuedUrl from Redis")?; Ok(Some(queued)) } /// Get current queue size pub async fn queue_size(&self) -> Result { let mut redis = self.redis.clone(); let size: usize = redis.zcard(DISCOVERY_QUEUE).await?; Ok(size) } /// Get seconds since last discovery cycle, if any pub fn last_cycle_secs(&self) -> Option { let last = self.last_cycle.lock().unwrap_or_else(|e| e.into_inner()); last.map(|t| t.elapsed().as_secs()) } /// Enqueue a URL for crawling (public API for manual enqueue and CC delta) pub async fn enqueue_url_public( &self, url: &str, priority: u32, category: &str, ) -> Result { let mut redis = self.redis.clone(); self.enqueue_url(&mut redis, url, priority, category).await } /// Check if a URL has already been seen (without adding it) pub async fn is_url_seen(&self, url: &str) -> Result { let mut redis = self.redis.clone(); let seen: bool = redis.sismember(DISCOVERY_SEEN, url).await?; Ok(seen) } } /// URL in the crawl queue #[derive(Debug, Clone, Serialize, Deserialize)] pub struct QueuedUrl { pub url: String, pub category: String, pub priority: u32, }