#![allow(dead_code)] //! Redis integration for IntentForge v2 //! //! Provides deduplication via Bloom filters and SimHash, //! plus compressed storage for full document text. use anyhow::{Context, Result}; use redis::{aio::ConnectionManager, Client}; /// Redis wrapper for IntentForge operations pub struct RedisStore { client: Client, } impl RedisStore { /// Create a new Redis connection pub fn new(url: &str) -> Result { let client = Client::open(url).with_context(|| format!("Failed to connect to Redis: {}", url))?; Ok(Self { client }) } /// Get a connection manager for async operations pub async fn get_connection(&self) -> Result { let conn = self .client .get_connection_manager() .await .with_context(|| "Failed to get Redis connection manager")?; Ok(conn) } /// Check if URL has been seen (using Bloom filter) pub async fn is_duplicate(&self, url: &str) -> Result { let mut conn = self.get_connection().await?; // Use RedisBloom BF.EXISTS if available, otherwise fallback to SISMEMBER let exists: bool = match redis::cmd("BF.EXISTS") .arg("bloom:seen_urls") .arg(url) .query_async(&mut conn) .await { Ok(exists) => exists, Err(_) => { // Fallback to traditional set redis::cmd("SISMEMBER") .arg("seen_urls") .arg(url) .query_async(&mut conn) .await .unwrap_or(false) } }; Ok(exists) } /// Mark URL as seen pub async fn mark_seen(&self, url: &str) -> Result<()> { let mut conn = self.get_connection().await?; // Try BF.ADD first let _: Result<(), _> = redis::cmd("BF.ADD") .arg("bloom:seen_urls") .arg(url) .query_async(&mut conn) .await; // Also add to traditional set for safety/migration redis::cmd("SADD") .arg("seen_urls") .arg(url) .query_async::<()>(&mut conn) .await .with_context(|| "Failed to mark URL as seen")?; Ok(()) } /// Ensure Bloom filters are initialized with correct parameters pub async fn ensure_bloom_filters(&self) -> Result<()> { let mut conn = self.get_connection().await?; // Reserve 1M items with 1% error rate for URL seen filter let _: Result<(), _> = redis::cmd("BF.RESERVE") .arg("bloom:seen_urls") .arg("0.01") .arg("1000000") .query_async(&mut conn) .await; // Reserve 1M items for crawl seen filter let _: Result<(), _> = redis::cmd("BF.RESERVE") .arg("bloom:crawl:seen") .arg("0.01") .arg("1000000") .query_async(&mut conn) .await; Ok(()) } /// Store full document content (zstd compressed) pub async fn store_content(&self, id: &str, content: &str) -> Result<()> { let mut conn = self.get_connection().await?; // Compress content with zstd (level 3) let compressed = zstd::encode_all(content.as_bytes(), 3) .with_context(|| "Failed to compress content with zstd")?; redis::cmd("SET") .arg(format!("doc:{}", id)) .arg(compressed) .query_async::<()>(&mut conn) .await .with_context(|| "Failed to store document content")?; Ok(()) } /// Retrieve full document content (zstd decompressed) pub async fn get_content(&self, id: &str) -> Result> { let mut conn = self.get_connection().await?; let compressed: Option> = redis::cmd("GET") .arg(format!("doc:{}", id)) .query_async(&mut conn) .await .with_context(|| "Failed to retrieve document content")?; if let Some(bytes) = compressed { let decompressed = zstd::decode_all(&bytes[..]) .with_context(|| "Failed to decompress content with zstd")?; let content = String::from_utf8(decompressed) .with_context(|| "Decompressed content is not valid UTF-8")?; Ok(Some(content)) } else { Ok(None) } } /// Compute and store SimHash for deduplication pub async fn store_simhash(&self, id: &str, simhash: u64) -> Result<()> { let mut conn = self.get_connection().await?; redis::cmd("HSET") .arg("simhashes") .arg(id) .arg(simhash) .query_async::<()>(&mut conn) .await .with_context(|| "Failed to store SimHash")?; Ok(()) } /// Enqueue a URL for crawling pub async fn enqueue_url(&self, queued: &crate::discovery::QueuedUrl) -> Result { let mut conn = self.get_connection().await?; // 1. Check if seen using Bloom filter (BF.ADD returns 1 if new, 0 if exists) let is_new: bool = match redis::cmd("BF.ADD") .arg("bloom:crawl:seen") .arg(&queued.url) .query_async(&mut conn) .await { Ok(added) => added, Err(_) => { // Fallback to traditional set redis::cmd("SADD") .arg("crawl:seen") .arg(&queued.url) .query_async(&mut conn) .await .unwrap_or(false) } }; if !is_new { return Ok(false); } // Also add to traditional set for safety if using Bloom filter let _: Result<(), _> = redis::cmd("SADD") .arg("crawl:seen") .arg(&queued.url) .query_async(&mut conn) .await; // 2. Add to crawl queue (ZADD) // 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 = (queued.priority as i64 * 1000000) + (now % 1000000); let member = serde_json::to_string(queued).with_context(|| "Failed to serialize QueuedUrl")?; redis::cmd("ZADD") .arg("crawl:queue") .arg(score) .arg(member) .query_async::<()>(&mut conn) .await .with_context(|| "Failed to add URL to crawl:queue")?; Ok(true) } /// Store JSON data with TTL pub async fn store_json( &self, key: &str, data: &T, ttl_secs: u64, ) -> Result<()> { let mut conn = self.get_connection().await?; let json = serde_json::to_string(data)?; let compressed = zstd::encode_all(json.as_bytes(), 3)?; redis::cmd("SET") .arg(key) .arg(compressed) .arg("EX") .arg(ttl_secs) .query_async::<()>(&mut conn) .await?; Ok(()) } /// Retrieve and decompress JSON data pub async fn get_json(&self, key: &str) -> Result> { let mut conn = self.get_connection().await?; let compressed: Option> = redis::cmd("GET").arg(key).query_async(&mut conn).await?; if let Some(bytes) = compressed { let decompressed = zstd::decode_all(&bytes[..])?; let data = serde_json::from_slice(&decompressed)?; Ok(Some(data)) } else { Ok(None) } } /// Compress and store JSON data pub async fn set_json( &self, key: &str, value: &T, ttl_secs: u64, ) -> Result<()> { let mut conn = self.get_connection().await?; let json = serde_json::to_vec(value)?; let json_len = json.len(); let compressed = zstd::encode_all(&json[..], 3)?; let comp_len = compressed.len(); if ttl_secs > 0 { redis::cmd("SETEX") .arg(key) .arg(ttl_secs) .arg(compressed) .query_async::<()>(&mut conn) .await?; } else { redis::cmd("SET") .arg(key) .arg(compressed) .query_async::<()>(&mut conn) .await?; } tracing::info!( "Stored JSON in Redis: key={}, orig_size={}, comp_size={}, ttl={}s", key, json_len, comp_len, ttl_secs ); Ok(()) } } #[cfg(test)] mod tests { use super::*; use crate::utils::{compute_simhash, simhash_distance}; #[test] fn test_simhash_deterministic() { let text = "Hello world test"; let hash1 = compute_simhash(text); let hash2 = compute_simhash(text); assert_eq!(hash1, hash2); } #[test] fn test_simhash_different() { let hash1 = compute_simhash("Hello world"); let hash2 = compute_simhash("Goodbye world"); assert_ne!(hash1, hash2); } #[test] fn test_simhash_near_duplicates() { let hash1 = compute_simhash("The quick brown fox jumps over the lazy dog"); let hash2 = compute_simhash("The quick brown fox jumps over a lazy dog"); let dist = simhash_distance(hash1, hash2); assert!( dist < 16, "Near-duplicate texts should have low Hamming distance: {}", dist ); } #[test] fn test_simhash_different_content() { let hash1 = compute_simhash("Machine learning is transforming technology"); let hash2 = compute_simhash("Cooking recipes for dinner tonight"); let dist = simhash_distance(hash1, hash2); assert!( dist > 12, "Different content should have high Hamming distance: {}", dist ); } #[test] fn test_simhash_distance() { let a = 0u64; let b = u64::MAX; assert_eq!(simhash_distance(a, b), 64); assert_eq!(simhash_distance(a, a), 0); } #[test] fn test_zstd_compression_logic() { let content = "This is a test content that should be compressed and decompressed correctly."; let compressed = zstd::encode_all(content.as_bytes(), 3).unwrap(); assert!(!compressed.is_empty()); let decompressed = zstd::decode_all(&compressed[..]).unwrap(); let decompressed_str = String::from_utf8(decompressed).unwrap(); assert_eq!(content, decompressed_str); } }