File size: 10,915 Bytes
0ca462b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
#![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<Self> {
        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<ConnectionManager> {
        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<bool> {
        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<Option<String>> {
        let mut conn = self.get_connection().await?;

        let compressed: Option<Vec<u8>> = 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<bool> {
        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<T: serde::Serialize>(
        &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<T: serde::de::DeserializeOwned>(&self, key: &str) -> Result<Option<T>> {
        let mut conn = self.get_connection().await?;
        let compressed: Option<Vec<u8>> = 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<T: serde::Serialize>(
        &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);
    }
}