Likhith Sai Seemala
Deploy IntentForge v2 to HF Spaces
0ca462b
Raw History Blame Contribute Delete
17.5 kB
#![allow(dead_code)]
//! Common Crawl module for IntentForge v2
//!
//! Implements CDX-based URL discovery with live verification, deduplication,
//! and quality scoring. Supports persistent state for restart detection.
use anyhow::{Context, Result};
use serde::{Deserialize, Serialize};
use std::io::{BufRead, BufReader, Read};
use std::path::Path;
use std::time::{Duration, Instant};
/// CDX API response entry
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CdxEntry {
pub urlkey: String,
pub timestamp: String,
pub url: String,
pub mime: String,
pub status: String,
pub digest: String,
pub length: String,
}
/// A single WET record (extracted text)
#[derive(Debug, Clone)]
pub struct WetRecord {
pub url: String,
pub date: String,
pub content: String,
pub content_length: usize,
}
/// Persistent state for CC delta to detect restarts
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CrawlState {
pub crawl_id: String,
pub completed_at: String,
pub urls_enqueued: u64,
pub urls_verified: u64,
pub urls_total: u64,
}
impl CrawlState {
/// Load state from disk, returns None if not found
pub fn load(data_dir: &str) -> Option<Self> {
let path = Path::new(data_dir).join("delta_state.json");
if !path.exists() {
return None;
}
let content = std::fs::read_to_string(path).ok()?;
serde_json::from_str(&content).ok()
}
/// Save state to disk
pub fn save(&self, data_dir: &str) -> Result<()> {
let path = Path::new(data_dir).join("delta_state.json");
std::fs::create_dir_all(data_dir)
.with_context(|| format!("Failed to create data dir: {}", data_dir))?;
let content = serde_json::to_string_pretty(self)?;
std::fs::write(path, content).with_context(|| "Failed to write delta state")?;
Ok(())
}
}
/// Quality score result for a URL
#[derive(Debug, Clone)]
pub struct UrlQuality {
pub url: String,
pub score: f32,
pub is_live: bool,
pub status_code: u16,
}
/// Compute a quality score for a URL based on domain heuristics
pub fn compute_url_quality(url: &str) -> f32 {
let mut score: f32 = 0.5;
let Ok(parsed) = url::Url::parse(url) else {
return 0.1;
};
// HTTPS bonus
if parsed.scheme() == "https" {
score += 0.1;
}
let host = parsed.host_str().unwrap_or_default().to_lowercase();
// Trusted TLD bonus
let trusted_tlds = [".edu", ".gov", ".org"];
for tld in &trusted_tlds {
if host.ends_with(tld) {
score += 0.2;
break;
}
}
// Known high-quality domains
let quality_domains = [
"github.com",
"arxiv.org",
"stackoverflow.com",
"medium.com",
"wikipedia.org",
"arstechnica.com",
"wired.com",
"techcrunch.com",
"theverge.com",
"news.ycombinator.com",
"reddit.com",
"dev.to",
"docs.rs",
];
for domain in &quality_domains {
if host == *domain || host.ends_with(&format!(".{}", domain)) {
score += 0.2;
break;
}
}
// Spam penalties
let path = parsed.path().to_lowercase();
let spam_signals = [
"click",
"offer",
"promo",
"deal",
"coupon",
"casino",
"viagra",
"buy-now",
"free-trial",
"signup?ref=",
"/ads/",
];
for signal in &spam_signals {
if path.contains(signal) {
score -= 0.3;
break;
}
}
// Short clean paths bonus
let segment_count = path.split('/').filter(|s| !s.is_empty()).count();
if segment_count <= 2 {
score += 0.05;
}
score.clamp(0.0, 1.0)
}
/// CDX API client for domain-filtered content discovery
pub struct CdxClient {
client: reqwest::Client,
base_url: String,
}
impl CdxClient {
pub fn new() -> Self {
let client = reqwest::Client::builder()
.timeout(Duration::from_secs(30))
.build()
.expect("Failed to create CDX HTTP client");
Self {
client,
base_url: "https://index.commoncrawl.org".to_string(),
}
}
/// Query CDX index for URLs matching a domain pattern
pub async fn query_domain(
&self,
domain: &str,
crawl_id: Option<&str>,
limit: usize,
) -> Result<Vec<CdxEntry>> {
let index = crawl_id.unwrap_or("CC-MAIN-2024-51");
let url = format!(
"{}/{}-index?url={}&output=json&limit={}",
self.base_url, index, domain, limit
);
tracing::info!("Querying CDX index: {}", url);
let response = self
.client
.get(&url)
.send()
.await
.with_context(|| format!("Failed to query CDX index for domain: {}", domain))?;
if !response.status().is_success() {
anyhow::bail!("CDX API returned status: {}", response.status());
}
let text = response.text().await?;
let mut entries = Vec::new();
for line in text.lines() {
if let Ok(entry) = serde_json::from_str::<CdxEntry>(line) {
entries.push(entry);
}
}
Ok(entries)
}
/// Query CDX for multiple domains
pub async fn query_domains(
&self,
domains: &[&str],
crawl_id: Option<&str>,
limit_per_domain: usize,
) -> Result<Vec<CdxEntry>> {
let mut all_entries = Vec::new();
for domain in domains {
match self.query_domain(domain, crawl_id, limit_per_domain).await {
Ok(entries) => {
tracing::info!("Found {} entries for {}", entries.len(), domain);
all_entries.extend(entries);
}
Err(e) => {
tracing::warn!("Failed to query CDX for {}: {}", domain, e);
}
}
}
Ok(all_entries)
}
}
/// WET file downloader and parser
pub struct WetProcessor {
client: reqwest::Client,
base_url: String,
}
impl WetProcessor {
pub fn new() -> Self {
let client = reqwest::Client::builder()
.timeout(Duration::from_secs(120))
.build()
.expect("Failed to create WET HTTP client");
Self {
client,
base_url: "https://data.commoncrawl.org".to_string(),
}
}
/// Download and parse a WET file by its path
pub async fn process_wet_file(&self, wet_path: &str) -> Result<Vec<WetRecord>> {
let url = format!("{}/{}", self.base_url, wet_path);
tracing::info!("Downloading WET file: {}", url);
let response = self
.client
.get(&url)
.send()
.await
.with_context(|| format!("Failed to download WET file: {}", url))?;
if !response.status().is_success() {
anyhow::bail!("WET download failed with status: {}", response.status());
}
let bytes = response
.bytes()
.await
.with_context(|| "Failed to read WET file body")?;
self.parse_wet_gzipped(&bytes)
}
/// Parse gzipped WET content
fn parse_wet_gzipped(&self, gzipped: &[u8]) -> Result<Vec<WetRecord>> {
use std::io::Cursor;
let cursor = Cursor::new(gzipped);
let decoder = flate2::read::GzDecoder::new(cursor);
let reader = BufReader::new(decoder);
self.parse_wet_records(reader)
}
/// Parse WET format records from a reader
fn parse_wet_records<R: Read>(&self, reader: BufReader<R>) -> Result<Vec<WetRecord>> {
let mut records = Vec::new();
let mut lines = reader.lines();
let mut current_url = String::new();
let mut current_date = String::new();
let mut current_length: usize = 0;
let mut in_record = false;
let mut content_buffer = String::new();
while let Some(Ok(line)) = lines.next() {
if line.starts_with("WARC/1.0") {
// Save previous record if exists
if in_record && !content_buffer.is_empty() {
records.push(WetRecord {
url: current_url.clone(),
date: current_date.clone(),
content: content_buffer.clone(),
content_length: current_length,
});
}
// Reset for new record
in_record = false;
content_buffer.clear();
current_url.clear();
current_date.clear();
current_length = 0;
} else if line.starts_with("WARC-Type: conversion") {
in_record = true;
} else if let Some(stripped) = line.strip_prefix("WARC-Target-URI:") {
current_url = stripped.trim().to_string();
} else if let Some(stripped) = line.strip_prefix("WARC-Date:") {
current_date = stripped.trim().to_string();
} else if let Some(stripped) = line.strip_prefix("Content-Length:") {
current_length = stripped.trim().parse().unwrap_or(0);
} else if in_record && !line.is_empty() {
content_buffer.push_str(&line);
content_buffer.push('\n');
}
}
// Don't forget the last record
if in_record && !content_buffer.is_empty() {
records.push(WetRecord {
url: current_url,
date: current_date,
content: content_buffer,
content_length: current_length,
});
}
Ok(records)
}
/// List available WET file paths for a crawl
pub async fn list_wet_files(&self, crawl_id: &str) -> Result<Vec<String>> {
let url = format!("{}/crawl-data/{}/wat.paths.gz", self.base_url, crawl_id);
tracing::info!("Listing WET files for crawl: {}", crawl_id);
let response = self.client.get(&url).send().await;
match response {
Ok(resp) if resp.status().is_success() => {
// This is a gzipped file listing - parse it
let bytes = resp.bytes().await?;
let mut decoder = flate2::read::GzDecoder::new(&bytes[..]);
let mut content = String::new();
decoder.read_to_string(&mut content)?;
// Convert WAT paths to WET paths
let wet_paths: Vec<String> = content
.lines()
.filter(|l| !l.is_empty())
.map(|l| {
l.replace("/wat/", "/wet/")
.replace(".wat.gz", ".warc.wet.gz")
})
.collect();
Ok(wet_paths)
}
_ => {
tracing::warn!("Could not list WET files, returning empty list");
Ok(Vec::new())
}
}
}
}
/// Configuration for Common Crawl processing
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CommonCrawlConfig {
pub crawl_id: String,
pub domains: Vec<String>,
pub max_entries_per_domain: usize,
pub max_wet_files: usize,
pub min_content_length: usize,
}
impl Default for CommonCrawlConfig {
fn default() -> Self {
Self {
crawl_id: "CC-MAIN-2024-51".to_string(),
domains: vec![
"github.com".to_string(),
"arxiv.org".to_string(),
"news.ycombinator.com".to_string(),
"stackoverflow.com".to_string(),
],
max_entries_per_domain: 100,
max_wet_files: 5,
min_content_length: 200,
}
}
}
/// Main Common Crawl pipeline
pub struct CommonCrawlPipeline {
config: CommonCrawlConfig,
cdx_client: CdxClient,
wet_processor: WetProcessor,
}
impl CommonCrawlPipeline {
pub fn new(config: CommonCrawlConfig) -> Self {
Self {
config,
cdx_client: CdxClient::new(),
wet_processor: WetProcessor::new(),
}
}
/// Run the full pipeline: CDX query -> WET download -> parse
pub async fn run(&self) -> Result<Vec<WetRecord>> {
let start = Instant::now();
tracing::info!(
"Starting Common Crawl pipeline for {} domains",
self.config.domains.len()
);
// Step 1: Query CDX for domain-filtered entries
let domain_refs: Vec<&str> = self.config.domains.iter().map(|s| s.as_str()).collect();
let cdx_entries = self
.cdx_client
.query_domains(
&domain_refs,
Some(&self.config.crawl_id),
self.config.max_entries_per_domain,
)
.await?;
tracing::info!("Found {} CDX entries", cdx_entries.len());
// Step 2: Filter by content type
let html_entries: Vec<_> = cdx_entries
.into_iter()
.filter(|e| e.mime.contains("html") || e.mime.contains("text"))
.collect();
tracing::info!("Filtered to {} HTML/text entries", html_entries.len());
// Step 3: Filter by minimum content length
let filtered_entries: Vec<_> = html_entries
.into_iter()
.filter(|e| {
e.length
.parse::<usize>()
.unwrap_or(0)
.ge(&self.config.min_content_length)
})
.collect();
tracing::info!("After length filter: {} entries", filtered_entries.len());
// For now, return CDX metadata as WetRecord summaries
// Full WET processing would be done in a background job
let records: Vec<WetRecord> = filtered_entries
.into_iter()
.map(|e| WetRecord {
url: e.url,
date: e.timestamp,
content: String::new(),
content_length: e.length.parse().unwrap_or(0),
})
.take(self.config.max_entries_per_domain * self.config.domains.len())
.collect();
tracing::info!(
"Common Crawl pipeline completed in {:.2}s, {} records",
start.elapsed().as_secs_f64(),
records.len()
);
Ok(records)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_common_crawl_config_default() {
let config = CommonCrawlConfig::default();
assert!(!config.domains.is_empty());
assert!(config.max_entries_per_domain > 0);
assert!(config.min_content_length > 0);
}
#[test]
fn test_cdx_client_creation() {
let client = CdxClient::new();
assert!(!client.base_url.is_empty());
}
#[test]
fn test_wet_processor_creation() {
let processor = WetProcessor::new();
assert!(!processor.base_url.is_empty());
}
#[test]
fn test_pipeline_creation() {
let config = CommonCrawlConfig::default();
let pipeline = CommonCrawlPipeline::new(config);
assert_eq!(pipeline.config.domains.len(), 4);
}
#[test]
fn test_url_quality_https_bonus() {
let https_score = compute_url_quality("https://example.com/page");
let http_score = compute_url_quality("http://example.com/page");
assert!(https_score > http_score);
}
#[test]
fn test_url_quality_trusted_tld() {
let org_score = compute_url_quality("https://example.org/article");
let com_score = compute_url_quality("https://example.com/article");
assert!(org_score > com_score);
}
#[test]
fn test_url_quality_known_domain() {
let gh_score = compute_url_quality("https://github.com/user/repo");
let random_score = compute_url_quality("https://random-site.com/page");
assert!(gh_score > random_score);
}
#[test]
fn test_url_quality_spam_penalty() {
let normal = compute_url_quality("https://example.com/article");
let spam = compute_url_quality("https://example.com/click-here-casino");
assert!(normal > spam);
}
#[test]
fn test_url_quality_invalid_url() {
let score = compute_url_quality("not-a-url");
assert_eq!(score, 0.1);
}
#[test]
fn test_url_quality_clamped() {
let score = compute_url_quality("https://github.com/org/repo");
assert!((0.0..=1.0).contains(&score));
}
#[test]
fn test_crawl_state_roundtrip() {
let state = CrawlState {
crawl_id: "CC-MAIN-2025-08".to_string(),
completed_at: "2025-03-26T00:00:00Z".to_string(),
urls_enqueued: 42,
urls_verified: 100,
urls_total: 200,
};
let dir = std::env::temp_dir().join("intentforge_test_cc");
let dir_str = dir.to_str().unwrap();
state.save(dir_str).unwrap();
let loaded = CrawlState::load(dir_str).unwrap();
assert_eq!(loaded.crawl_id, "CC-MAIN-2025-08");
assert_eq!(loaded.urls_enqueued, 42);
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn test_crawl_state_missing() {
let loaded = CrawlState::load("/nonexistent/path");
assert!(loaded.is_none());
}
}