#![allow(clippy::too_many_arguments, dead_code)] //! Crawler module for IntentForge v2 //! //! High-performance web crawler with robots.txt compliance, //! static-first fetching, adaptive rate limiting, and Trafilatura integration. pub mod extractor; use crate::crawler::extractor::FastExtractor; use anyhow::{Context, Result}; use reqwest::Client; use robotstxt::DefaultMatcher; use std::collections::HashMap; use std::sync::Arc; use std::time::{Duration, Instant}; use tokio::sync::{Mutex, Semaphore}; /// Pre-fetch information from HTTP HEAD request #[derive(Debug, Clone)] pub struct PreFetchInfo { pub content_type: String, pub content_length: u64, pub etag: Option, } /// Crawl result with extracted content #[derive(Debug, Clone)] pub struct CrawlResult { pub url: String, pub title: String, pub content: String, pub html: Option, pub status: u16, pub fetch_time_ms: u64, pub is_dynamic: bool, } /// Cached robots.txt entry #[derive(Debug, Clone)] struct RobotsEntry { body: String, fetched_at: Instant, } /// Robots.txt cache with TTL-based expiration pub struct RobotsCache { cache: HashMap, ttl: Duration, client: Client, } impl RobotsCache { pub fn new(ttl_secs: u64, client: Client) -> Self { Self { cache: HashMap::new(), ttl: Duration::from_secs(ttl_secs), client, } } /// Get robots.txt body for a domain, fetching if not cached or expired async fn get_robots_body(&mut self, domain: &str, scheme: &str) -> String { // Check cache validity if let Some(entry) = self.cache.get(domain) { if entry.fetched_at.elapsed() < self.ttl { return entry.body.clone(); } } // Fetch robots.txt let robots_url = format!("{}://{}/robots.txt", scheme, domain); let body = match self.client.get(&robots_url).send().await { Ok(resp) if resp.status().is_success() => resp.text().await.unwrap_or_default(), _ => String::new(), }; self.cache.insert( domain.to_string(), RobotsEntry { body: body.clone(), fetched_at: Instant::now(), }, ); body } /// Check if URL is allowed by robots.txt pub async fn is_allowed(&mut self, url: &str, user_agent: &str) -> Result { let parsed_url = url::Url::parse(url).with_context(|| format!("Invalid URL: {}", url))?; let domain = parsed_url.host_str().unwrap_or("").to_string(); let scheme = parsed_url.scheme(); if domain.is_empty() { return Ok(true); } let robots_body = self.get_robots_body(&domain, scheme).await; if robots_body.is_empty() { return Ok(true); } let mut matcher = DefaultMatcher::default(); Ok(matcher.one_agent_allowed_by_robots(&robots_body, user_agent, url)) } } /// Adaptive rate limiter using token bucket #[derive(Debug)] pub struct RateLimiter { tokens: f64, max_tokens: f64, refill_rate: f64, last_refill: Instant, } impl RateLimiter { pub fn new(requests_per_sec: u32) -> Self { let rate = requests_per_sec as f64; Self { tokens: rate, max_tokens: rate, refill_rate: rate, last_refill: Instant::now(), } } /// Acquire a token, waiting if necessary pub async fn acquire(&mut self) { loop { self.refill(); if self.tokens >= 1.0 { self.tokens -= 1.0; return; } let wait = Duration::from_secs_f64((1.0 - self.tokens) / self.refill_rate); tokio::time::sleep(wait).await; } } fn refill(&mut self) { let now = Instant::now(); let elapsed = now.duration_since(self.last_refill).as_secs_f64(); self.tokens = (self.tokens + elapsed * self.refill_rate).min(self.max_tokens); self.last_refill = now; } } /// Trafilatura microservice client #[derive(Debug, Clone)] pub struct TrafilaturaClient { client: Client, base_url: String, batch_size: usize, timeout: Duration, } /// Single extraction request #[derive(Debug, Clone, serde::Serialize)] pub struct ExtractRequest { pub url: String, pub html: String, } /// Single extraction response #[derive(Debug, Clone, serde::Deserialize)] pub struct ExtractResponse { pub url: String, pub title: Option, pub content: Option, pub success: bool, pub error: Option, } impl TrafilaturaClient { pub fn new(base_url: &str, batch_size: usize, timeout_secs: u64) -> Result { let client = Client::builder() .timeout(Duration::from_secs(timeout_secs)) .build() .with_context(|| "Failed to create Trafilatura HTTP client")?; Ok(Self { client, base_url: base_url.to_string(), batch_size, timeout: Duration::from_secs(timeout_secs), }) } /// Extract content from a batch of HTML documents pub async fn extract_batch( &self, requests: Vec, ) -> Result> { if requests.is_empty() { return Ok(Vec::new()); } let mut all_results = Vec::new(); // Process in chunks matching batch_size for chunk in requests.chunks(self.batch_size) { let url = format!("{}/extract-batch", self.base_url); let resp = self .client .post(&url) .json(chunk) .timeout(self.timeout) .send() .await .with_context(|| "Failed to send extraction request to Trafilatura")?; if !resp.status().is_success() { let status = resp.status(); let body = resp.text().await.unwrap_or_default(); tracing::warn!("Trafilatura returned {}: {}", status, body); // Return partial results with error info for req in chunk { all_results.push(ExtractResponse { url: req.url.clone(), title: None, content: None, success: false, error: Some(format!("HTTP {}: {}", status, body)), }); } continue; } let results: Vec = resp .json() .await .with_context(|| "Failed to parse Trafilatura response")?; all_results.extend(results); } Ok(all_results) } /// Health check for Trafilatura service pub async fn health_check(&self) -> bool { let url = format!("{}/health", self.base_url); self.client .get(&url) .send() .await .map(|r| r.status().is_success()) .unwrap_or(false) } } /// Web crawler with rate limiting, robots.txt, and Trafilatura integration #[derive(Clone)] pub struct Crawler { client: Client, robots_cache: Arc>, rate_limiter: Arc>, semaphore: Arc, user_agent: String, respect_robots: bool, static_first: bool, max_retries: u32, js_whitelist: Vec, trafilatura: Option, // Content deduplication cache (SHA-256 hashes) seen_content_hashes: Arc>, } impl Crawler { /// Create a new crawler instance pub fn new( rate_limit: u32, timeout_secs: u64, user_agent: String, respect_robots: bool, static_first: bool, max_concurrent: usize, max_retries: u32, robots_cache_ttl: u64, js_whitelist: Vec, trafilatura_url: Option<&str>, trafilatura_batch: usize, trafilatura_timeout: u64, ) -> Result { 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()); // Optimized HTTP client with connection pooling and HTTP/2 let client = Client::builder() .user_agent(&user_agent) .default_headers(headers) .timeout(Duration::from_secs(timeout_secs)) .pool_max_idle_per_host(max_concurrent * 4) // Increased pooling .pool_idle_timeout(Duration::from_secs(90)) .http2_keep_alive_interval(Duration::from_secs(30)) .http2_keep_alive_timeout(Duration::from_secs(20)) .http2_keep_alive_while_idle(true) .tcp_keepalive(Duration::from_secs(30)) .build() .with_context(|| "Failed to create HTTP client")?; let robots_cache = RobotsCache::new(robots_cache_ttl, client.clone()); let rate_limiter = RateLimiter::new(rate_limit); let semaphore = Arc::new(Semaphore::new(max_concurrent)); let trafilatura = trafilatura_url .map(|url| TrafilaturaClient::new(url, trafilatura_batch, trafilatura_timeout)) .transpose()?; Ok(Self { client, robots_cache: Arc::new(Mutex::new(robots_cache)), rate_limiter: Arc::new(Mutex::new(rate_limiter)), semaphore, user_agent, respect_robots, static_first, max_retries, js_whitelist, trafilatura, seen_content_hashes: Arc::new(dashmap::DashSet::new()), }) } /// Check if content type is fetchable (HTML or unknown) fn should_fetch_content_type(content_type: &str) -> bool { if content_type.is_empty() { return true; // Unknown, fetch and check } content_type.starts_with("text/html") || content_type.starts_with("application/xhtml") || content_type.starts_with("application/xml") } /// Pre-fetch check using HTTP HEAD request async fn pre_fetch_check(&self, url: &str) -> Result { let resp = self.client.head(url).send().await?; Ok(PreFetchInfo { content_type: resp .headers() .get("Content-Type") .and_then(|h| h.to_str().ok()) .unwrap_or("") .to_string(), content_length: resp .headers() .get("Content-Length") .and_then(|h| h.to_str().ok()) .and_then(|s| s.parse::().ok()) .unwrap_or(0), etag: resp .headers() .get("ETag") .and_then(|h| h.to_str().ok()) .map(|s| s.to_string()), }) } /// Check if content is a duplicate using SHA-256 hash fn is_duplicate_content(&self, html: &str) -> bool { use sha2::{Digest, Sha256}; let mut hasher = Sha256::new(); hasher.update(html.as_bytes()); let hash = format!("{:x}", hasher.finalize()); // Check if we've seen this hash before if self.seen_content_hashes.contains(&hash) { return true; } // Add to seen hashes self.seen_content_hashes.insert(hash); false } /// Check if a domain requires JS rendering fn requires_js(&self, url: &str) -> bool { if !self.static_first { return false; } for domain in &self.js_whitelist { if url.contains(domain) { return true; } } false } /// Fetch a URL with head-only peek for intent gating async fn fetch_head_only(&self, url: &str) -> Result { let resp = self .client .get(url) .header("Range", "bytes=0-10240") .send() .await?; let status = resp.status(); if !status.is_success() && status != reqwest::StatusCode::PARTIAL_CONTENT { return Err(anyhow::anyhow!("Head fetch failed with status: {}", status)); } Ok(resp.text().await?) } /// Fetch a single URL with full intent gating pub async fn fetch(&self, url: &str) -> Result { let start = Instant::now(); // Check robots.txt if self.respect_robots { let allowed = self .robots_cache .lock() .await .is_allowed(url, &self.user_agent) .await?; if !allowed { anyhow::bail!("Blocked by robots.txt: {}", url); } } // Phase 1: Pre-fetch check (HTTP HEAD) let pre_fetch = self.pre_fetch_check(url).await?; // Skip non-HTML content types if !Self::should_fetch_content_type(&pre_fetch.content_type) { anyhow::bail!("Skipping non-HTML content type: {}", pre_fetch.content_type); } let is_dynamic = self.requires_js(url); // Acquire rate limiter token and semaphore permit self.rate_limiter.lock().await.acquire().await; let _permit = self .semaphore .acquire() .await .with_context(|| "Semaphore closed")?; // Phase 2: Intent-Gated Peek with Enhanced Scoring // For non-whitelisted domains, peek at the first 10KB let is_technical = url.contains("github.com") || url.contains("arxiv.org") || url.contains("docs.") || url.contains("rust-lang.org"); let (status, html) = if !is_technical { let peek_html = self.fetch_head_only(url).await.unwrap_or_default(); // Enhanced intent scoring with URL boosting let _fast_result = FastExtractor::extract(&peek_html); let url_boosted_score = self.enhanced_intent_score(&peek_html, url); // Increased threshold from 0.2 to 0.35 for better noise filtering if url_boosted_score < 0.35 { tracing::debug!( "Aborting fetch for low-intent peek (score={:.3}): {}", url_boosted_score, url ); anyhow::bail!("Low intent score: {}", url_boosted_score); } else { self.fetch_with_retry(url).await? } } else { self.fetch_with_retry(url).await? }; // Phase 3: Content Deduplication Check if self.is_duplicate_content(&html) { tracing::debug!("Skipping duplicate content: {}", url); anyhow::bail!("Duplicate content"); } // Phase 4: Native Path Extraction (Rust-native) let fast_result = FastExtractor::extract(&html); // Phase 5: Trafilatura Fallback (only if low quality or explicit) let (title, content) = if fast_result.quality_score < 0.6 { if let Some(ref trafilatura) = self.trafilatura { let requests = vec![ExtractRequest { url: url.to_string(), html: html.clone(), }]; match trafilatura.extract_batch(requests).await { Ok(results) if results.len() == 1 && results[0].success => { let r = &results[0]; ( r.title.clone().unwrap_or(fast_result.title), r.content.clone().unwrap_or(fast_result.content), ) } _ => (fast_result.title, fast_result.content), } } else { (fast_result.title, fast_result.content) } } else { (fast_result.title, fast_result.content) }; let fetch_time_ms = start.elapsed().as_millis() as u64; Ok(CrawlResult { url: url.to_string(), title, content, html: Some(html), status, fetch_time_ms, is_dynamic, }) } /// Enhanced intent scoring with URL-based boosting fn enhanced_intent_score(&self, text: &str, url: &str) -> f32 { // Get base score from fast scorer let _base_score = self .trafilatura .as_ref() .map(|_| 0.5f32) // Placeholder - we'll use a dedicated scorer .unwrap_or(0.5f32); // Use the FastIntentScorer from inference module if available // For now, use simple keyword matching let text_lower = text.to_lowercase(); let mut keyword_score = 0.1f32; let high_signal_keywords = [ "tutorial", "guide", "how-to", "benchmark", "analysis", "framework", "library", "documentation", "api", "reference", ]; for keyword in &high_signal_keywords { if text_lower.contains(keyword) { keyword_score += 0.1; } } // URL-based boosting let mut url_boost = 1.0f32; if url.contains("github.com") || url.contains("arxiv.org") || url.contains(".edu") || url.contains("docs.") { url_boost = 1.5; // Technical content boost } else if url.contains("/tutorial/") || url.contains("/guide/") { url_boost = 1.3; } else if url.contains("news.") || url.contains("blog.") { url_boost = 0.8; // News penalty } (keyword_score.min(1.0) * url_boost).min(1.0) } /// Fetch with exponential backoff retry async fn fetch_with_retry(&self, url: &str) -> Result<(u16, String)> { let mut last_err = None; for attempt in 0..=self.max_retries { if attempt > 0 { let backoff = Duration::from_millis(100 * 2u64.pow(attempt - 1)); tokio::time::sleep(backoff).await; } match self.client.get(url).send().await { Ok(resp) => { let status = resp.status().as_u16(); if status == 429 || status >= 500 { last_err = Some(anyhow::anyhow!("HTTP {}", status)); continue; } let html = resp .text() .await .with_context(|| format!("Failed to read response: {}", url))?; return Ok((status, html)); } Err(e) => { last_err = Some(e.into()); } } } Err(last_err.unwrap_or_else(|| anyhow::anyhow!("Max retries exceeded"))) } /// Fetch multiple URLs concurrently with Trafilatura batch extraction pub async fn fetch_batch(&self, urls: Vec<&str>) -> Result> { // Phase 1: Fetch all HTML concurrently let fetch_tasks: Vec<_> = urls .iter() .map(|url| { let url = url.to_string(); async move { let result = self.fetch_raw(&url).await; (url, result) } }) .collect(); let fetch_results = futures::future::join_all(fetch_tasks).await; // Separate successful fetches for batch Trafilatura processing let mut raw_results: Vec<(String, u16, String)> = Vec::new(); let mut errors: Vec<(String, anyhow::Error)> = Vec::new(); for (url, result) in fetch_results { match result { Ok((status, html)) => raw_results.push((url, status, html)), Err(e) => errors.push((url, e)), } } // Phase 2: Native Fast Extraction let mut results = Vec::new(); let mut low_quality_indices = Vec::new(); for (idx, (url, status, html)) in raw_results.iter().enumerate() { let is_dynamic = self.requires_js(url); let fast_result = FastExtractor::extract(html); results.push(CrawlResult { url: url.clone(), title: fast_result.title, content: fast_result.content, html: Some(html.clone()), status: *status, fetch_time_ms: 0, is_dynamic, }); if fast_result.quality_score < 0.6 { low_quality_indices.push(idx); } } // Phase 3: Trafilatura Fallback (only for low-quality) if let Some(ref trafilatura) = self.trafilatura { if !low_quality_indices.is_empty() { let requests: Vec = low_quality_indices .iter() .map(|&idx| { let (url, _, html) = &raw_results[idx]; ExtractRequest { url: url.clone(), html: html.clone(), } }) .collect(); if let Ok(extract_results) = trafilatura.extract_batch(requests).await { for (&idx, extract) in low_quality_indices.iter().zip(extract_results.iter()) { if extract.success { if let Some(ref mut res) = results.get_mut(idx) { if let Some(title) = &extract.title { res.title = title.clone(); } if let Some(content) = &extract.content { res.content = content.clone(); } } } } } } } // Log errors for (url, e) in &errors { tracing::warn!("Failed to fetch {}: {}", url, e); } Ok(results) } /// Raw fetch without robots.txt or rate limiting (used internally by fetch_batch) async fn fetch_raw(&self, url: &str) -> Result<(u16, String)> { let _start = Instant::now(); if self.respect_robots { let allowed = self .robots_cache .lock() .await .is_allowed(url, &self.user_agent) .await?; if !allowed { anyhow::bail!("Blocked by robots.txt: {}", url); } } self.rate_limiter.lock().await.acquire().await; let _permit = self .semaphore .acquire() .await .with_context(|| "Semaphore closed")?; self.fetch_with_retry(url).await } /// Get reference to Trafilatura client pub fn trafilatura(&self) -> Option<&TrafilaturaClient> { self.trafilatura.as_ref() } } /// Extract outbound links from HTML pub fn find_links(html: &str, _base_url: &str) -> Vec { let mut links = Vec::new(); // Simple regex for absolute http/https links let re = match regex::Regex::new(r#"href=["'](https?://[^"']+)["']"#) { Ok(re) => re, Err(_) => return links, }; for cap in re.captures_iter(html) { if let Some(link) = cap.get(1) { let link_str = link.as_str(); // Filter out obvious noise if link_str.contains("javascript:") || link_str.contains("mailto:") || link_str.contains("/wp-json/") || link_str.contains("/login") || link_str.ends_with(".png") || link_str.ends_with(".jpg") || link_str.ends_with(".css") || link_str.ends_with(".js") { continue; } links.push(link_str.to_string()); } } links.sort(); links.dedup(); links } /// Extract title from HTML pub fn extract_title(html: &str) -> Option { let title_start = html.find("")?; let title_end = html[title_start..].find("")?; let title = html[title_start + 7..title_start + title_end].trim(); // Decode HTML entities let title = title .replace("&", "&") .replace("<", "<") .replace(">", ">") .replace(""", "\"") .replace("'", "'"); Some(title) } /// Strip HTML tags from content pub fn strip_html(html: &str) -> String { let mut result = String::with_capacity(html.len() / 2); let mut in_tag = false; let mut tag_buffer = String::new(); let mut skip_stack = Vec::new(); // Tags whose content we want to skip entirely let skip_tags = [ "script", "style", "head", "nav", "footer", "header", "aside", ]; for ch in html.chars() { if ch == '<' { in_tag = true; tag_buffer.clear(); continue; } if ch == '>' && in_tag { in_tag = false; let tag_content = tag_buffer.to_lowercase(); let is_closing = tag_content.starts_with('/'); let tag_name = if is_closing { &tag_content[1..] } else { tag_content.split_whitespace().next().unwrap_or("") }; if skip_tags.contains(&tag_name) { if is_closing { skip_stack.pop(); } else { skip_stack.push(tag_name.to_string()); } } // Add space for block-level elements to avoid merging words if [ "p", "div", "br", "h1", "h2", "h3", "h4", "h5", "h6", "li", "tr", ] .contains(&tag_name) { result.push(' '); } continue; } if in_tag { tag_buffer.push(ch); continue; } if skip_stack.is_empty() { result.push(ch); } } // Clean up whitespace and entities let cleaned = result .replace(" ", " ") .replace("&", "&") .replace("<", "<") .replace(">", ">") .replace(""", "\"") .replace("'", "'"); cleaned.split_whitespace().collect::>().join(" ") } #[cfg(test)] mod tests { use super::*; #[test] fn test_extract_title() { let html = "Test Page"; assert_eq!(extract_title(html), Some("Test Page".to_string())); } #[test] fn test_extract_title_with_entities() { let html = "Test & Page"; assert_eq!(extract_title(html), Some("Test & Page".to_string())); } #[test] fn test_extract_title_none() { let html = "No title"; assert_eq!(extract_title(html), None); } #[test] fn test_strip_html() { let html = "

Hello World

"; let text = strip_html(html); assert_eq!(text, "Hello World"); } #[test] fn test_strip_html_removes_scripts() { let html = "

Visible

Also visible

"; let text = strip_html(html); assert!(!text.contains("alert")); assert!(text.contains("Visible")); assert!(text.contains("Also visible")); } #[test] fn test_strip_html_removes_styles() { let html = "

Text

More

"; let text = strip_html(html); assert!(!text.contains("color")); assert!(text.contains("Text")); assert!(text.contains("More")); } #[tokio::test] async fn test_rate_limiter() { let mut limiter = RateLimiter::new(100); let start = Instant::now(); for _ in 0..5 { limiter.acquire().await; } // Should be fast since we have tokens assert!(start.elapsed() < Duration::from_millis(100)); } #[test] fn test_js_whitelist_detection() { let crawler = Crawler::new( 10, 30, "test".to_string(), false, true, 8, 3, 3600, vec!["producthunt.com".to_string()], None, 16, 60, ) .unwrap(); assert!(crawler.requires_js("https://producthunt.com/posts/test")); assert!(!crawler.requires_js("https://example.com/page")); } #[test] fn test_trafilatura_request_serialization() { let req = ExtractRequest { url: "https://example.com".to_string(), html: "Test".to_string(), }; let json = serde_json::to_string(&req).unwrap(); assert!(json.contains("example.com")); assert!(json.contains("Test")); } #[test] fn test_trafilatura_response_deserialization() { let json = r#"{"url":"https://example.com","title":"Test","content":"Hello","success":true}"#; let resp: ExtractResponse = serde_json::from_str(json).unwrap(); assert!(resp.success); assert_eq!(resp.title, Some("Test".to_string())); assert_eq!(resp.content, Some("Hello".to_string())); } #[test] fn test_trafilatura_response_with_error() { let json = r#"{"url":"https://example.com","title":null,"content":null,"success":false,"error":"timeout"}"#; let resp: ExtractResponse = serde_json::from_str(json).unwrap(); assert!(!resp.success); assert_eq!(resp.error, Some("timeout".to_string())); } #[tokio::test] async fn test_robots_cache_creation() { let client = Client::builder().user_agent("test").build().unwrap(); let cache = RobotsCache::new(3600, client); assert!(cache.cache.is_empty()); } }