stygian-graph 0.9.2

High-performance graph-based web scraping engine with AI extraction, multi-modal support, and anti-bot capabilities
Documentation
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
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
//! Cache adapters
//!
//! Three implementations available for different use-cases:
//!
//! | Adapter        | Eviction | TTL | Notes                        |
//! | ---------------- | ---------- | ----- | ------------------------------ |
//! | `MemoryCache`  | None     | No  | Dev/test                     |
//! | `DashMapCache` | None     | Yes | High-concurrency + background cleanup |
//! | `BoundedLruCache` | LRU  | Yes | Capacity-bounded; `LazyLock` singleton |

use crate::domain::error::Result;
use crate::ports::CachePort;
use async_trait::async_trait;
use dashmap::DashMap;
use parking_lot::RwLock;
use std::collections::HashMap;
use std::sync::{Arc, LazyLock};
use std::time::{Duration, Instant};

/// In-memory cache adapter for testing and development
///
/// Uses a simple `HashMap` with `RwLock` for thread-safe access.
/// Does not implement TTL expiration (all entries persist until explicitly invalidated).
///
/// # Example
///
/// ```
/// use stygian_graph::adapters::cache::MemoryCache;
/// use stygian_graph::ports::CachePort;
///
/// # tokio::runtime::Runtime::new().unwrap().block_on(async {
/// let cache = MemoryCache::new();
/// cache.set("key", "value".to_string(), None).await.unwrap();
/// let value = cache.get("key").await.unwrap();
/// assert_eq!(value, Some("value".to_string()));
/// # });
/// ```
pub struct MemoryCache {
    store: Arc<RwLock<HashMap<String, String>>>,
}

impl MemoryCache {
    /// Create a new memory cache
    pub fn new() -> Self {
        Self {
            store: Arc::new(RwLock::new(HashMap::new())),
        }
    }
}

impl Default for MemoryCache {
    fn default() -> Self {
        Self::new()
    }
}

#[async_trait]
impl CachePort for MemoryCache {
    async fn get(&self, key: &str) -> Result<Option<String>> {
        let value = {
            let store = self.store.read();
            store.get(key).cloned()
        };
        Ok(value)
    }

    async fn set(&self, key: &str, value: String, _ttl: Option<Duration>) -> Result<()> {
        {
            let mut store = self.store.write();
            store.insert(key.to_string(), value);
        }
        Ok(())
    }

    async fn invalidate(&self, key: &str) -> Result<()> {
        {
            let mut store = self.store.write();
            store.remove(key);
        }
        Ok(())
    }

    async fn exists(&self, key: &str) -> Result<bool> {
        let exists = {
            let store = self.store.read();
            store.contains_key(key)
        };
        Ok(exists)
    }
}

// ─── TTL entry ────────────────────────────────────────────────────────────────

#[derive(Clone)]
struct TtlEntry {
    value: String,
    expires_at: Option<Instant>,
}

impl TtlEntry {
    fn new(value: String, ttl: Option<Duration>) -> Self {
        Self {
            value,
            expires_at: ttl.map(|d| Instant::now() + d),
        }
    }

    fn is_expired(&self) -> bool {
        self.expires_at.is_some_and(|exp| Instant::now() > exp)
    }
}

// ─── DashMapCache ─────────────────────────────────────────────────────────────

/// High-concurrency in-memory cache using `DashMap` with TTL expiration.
///
/// Backed by [`dashmap::DashMap`] for lock-free concurrent access. A background
/// Tokio task sweeps expired entries at the configured interval.
///
/// # Example
///
/// ```
/// use stygian_graph::adapters::cache::DashMapCache;
/// use stygian_graph::ports::CachePort;
/// use std::time::Duration;
///
/// # tokio::runtime::Runtime::new().unwrap().block_on(async {
/// let cache = DashMapCache::new(Duration::from_secs(60));
/// cache.set("k", "v".to_string(), Some(Duration::from_secs(5))).await.unwrap();
/// assert_eq!(cache.get("k").await.unwrap(), Some("v".to_string()));
/// # });
/// ```
pub struct DashMapCache {
    store: Arc<DashMap<String, TtlEntry>>,
}

impl DashMapCache {
    /// Create a new `DashMapCache`.
    ///
    /// `cleanup_interval` controls how often a background task sweeps and
    /// removes expired entries. The task is spawned immediately.
    ///
    /// # Example
    ///
    /// ```no_run
    /// use stygian_graph::adapters::cache::DashMapCache;
    /// use std::time::Duration;
    ///
    /// let cache = DashMapCache::new(Duration::from_secs(30));
    /// ```
    pub fn new(cleanup_interval: Duration) -> Self {
        let store: Arc<DashMap<String, TtlEntry>> = Arc::new(DashMap::new());
        let weak = Arc::downgrade(&store);
        tokio::spawn(async move {
            let mut ticker = tokio::time::interval(cleanup_interval);
            ticker.tick().await; // skip the first immediate tick
            loop {
                ticker.tick().await;
                let Some(map) = weak.upgrade() else { break };
                map.retain(|_, v| !v.is_expired());
            }
        });
        Self { store }
    }

    /// Return the number of live (non-expired) entries.
    pub fn len(&self) -> usize {
        self.store.iter().filter(|e| !e.is_expired()).count()
    }

    /// Returns `true` if the cache contains no live entries.
    pub fn is_empty(&self) -> bool {
        self.len() == 0
    }
}

#[async_trait]
impl CachePort for DashMapCache {
    async fn get(&self, key: &str) -> Result<Option<String>> {
        match self.store.get(key) {
            None => Ok(None),
            Some(entry) if entry.is_expired() => {
                drop(entry);
                self.store.remove(key);
                Ok(None)
            }
            Some(entry) => Ok(Some(entry.value.clone())),
        }
    }

    async fn set(&self, key: &str, value: String, ttl: Option<Duration>) -> Result<()> {
        self.store
            .insert(key.to_string(), TtlEntry::new(value, ttl));
        Ok(())
    }

    async fn invalidate(&self, key: &str) -> Result<()> {
        self.store.remove(key);
        Ok(())
    }

    async fn exists(&self, key: &str) -> Result<bool> {
        match self.store.get(key) {
            None => Ok(false),
            Some(entry) if entry.is_expired() => {
                drop(entry);
                self.store.remove(key);
                Ok(false)
            }
            Some(_) => Ok(true),
        }
    }
}

// ─── BoundedLruCache ──────────────────────────────────────────────────────────

/// Capacity-bounded LRU cache with optional TTL per entry.
///
/// Wraps [`lru::LruCache`] behind a `Mutex` for thread safety. When the cache
/// reaches `capacity`, the least-recently-used entry is evicted automatically.
/// TTL is enforced on read: expired entries are treated as misses.
///
/// # Example
///
/// ```
/// use stygian_graph::adapters::cache::BoundedLruCache;
/// use stygian_graph::ports::CachePort;
/// use std::num::NonZeroUsize;
/// use std::time::Duration;
///
/// # tokio::runtime::Runtime::new().unwrap().block_on(async {
/// let cache = BoundedLruCache::new(NonZeroUsize::new(128).unwrap());
/// cache.set("k", "v".to_string(), Some(Duration::from_secs(60))).await.unwrap();
/// assert_eq!(cache.get("k").await.unwrap(), Some("v".to_string()));
/// # });
/// ```
pub struct BoundedLruCache {
    inner: tokio::sync::Mutex<lru::LruCache<String, TtlEntry>>,
}

impl BoundedLruCache {
    /// Create a new bounded LRU cache with the given `capacity`.
    ///
    /// # Example
    ///
    /// ```
    /// use stygian_graph::adapters::cache::BoundedLruCache;
    /// use std::num::NonZeroUsize;
    ///
    /// let cache = BoundedLruCache::new(NonZeroUsize::new(256).unwrap());
    /// ```
    pub fn new(capacity: std::num::NonZeroUsize) -> Self {
        Self {
            inner: tokio::sync::Mutex::new(lru::LruCache::new(capacity)),
        }
    }
}

#[async_trait]
impl CachePort for BoundedLruCache {
    async fn get(&self, key: &str) -> Result<Option<String>> {
        let result = {
            let mut cache = self.inner.lock().await;
            match cache.get(key) {
                None => None,
                Some(entry) if entry.is_expired() => {
                    cache.pop(key);
                    None
                }
                Some(entry) => Some(entry.value.clone()),
            }
        };
        Ok(result)
    }

    async fn set(&self, key: &str, value: String, ttl: Option<Duration>) -> Result<()> {
        {
            let mut cache = self.inner.lock().await;
            cache.put(key.to_string(), TtlEntry::new(value, ttl));
        }
        Ok(())
    }

    async fn invalidate(&self, key: &str) -> Result<()> {
        {
            let mut cache = self.inner.lock().await;
            cache.pop(key);
        }
        Ok(())
    }

    async fn exists(&self, key: &str) -> Result<bool> {
        let result = {
            let mut cache = self.inner.lock().await;
            match cache.get(key) {
                None => false,
                Some(entry) if entry.is_expired() => {
                    cache.pop(key);
                    false
                }
                Some(_) => true,
            }
        };
        Ok(result)
    }
}

// ─── Global singleton ─────────────────────────────────────────────────────────

/// Process-wide default cache singleton backed by `DashMapCache`.
///
/// Initialized once on first access via [`LazyLock`]. Suitable for lightweight
/// shared caching where a dedicated instance is unnecessary.
///
/// # Example
///
/// ```no_run
/// use stygian_graph::adapters::cache::global_cache;
/// # use stygian_graph::ports::CachePort;
///
/// # tokio::runtime::Runtime::new().unwrap().block_on(async {
/// global_cache().set("session", "abc".to_string(), None).await.unwrap();
/// let v = global_cache().get("session").await.unwrap();
/// assert_eq!(v, Some("abc".to_string()));
/// # });
/// ```
pub fn global_cache() -> &'static DashMapCache {
    static INSTANCE: LazyLock<DashMapCache> =
        LazyLock::new(|| DashMapCache::new(Duration::from_secs(300)));
    &INSTANCE
}

// ─── Tests ────────────────────────────────────────────────────────────────────

#[cfg(test)]
mod tests {
    use super::*;

    // --- DashMapCache ---

    #[tokio::test]
    async fn dashmap_set_get() -> Result<()> {
        let c = DashMapCache::new(Duration::from_secs(60));
        c.set("a", "1".to_string(), None).await?;
        assert_eq!(c.get("a").await?, Some("1".to_string()));
        Ok(())
    }

    #[tokio::test]
    async fn dashmap_miss_returns_none() -> Result<()> {
        let c = DashMapCache::new(Duration::from_secs(60));
        assert_eq!(c.get("missing").await?, None);
        Ok(())
    }

    #[tokio::test]
    async fn dashmap_invalidate() -> Result<()> {
        let c = DashMapCache::new(Duration::from_secs(60));
        c.set("b", "2".to_string(), None).await?;
        c.invalidate("b").await?;
        assert_eq!(c.get("b").await?, None);
        Ok(())
    }

    #[tokio::test]
    async fn dashmap_ttl_expires() -> Result<()> {
        let c = DashMapCache::new(Duration::from_secs(60));
        // 1ns TTL — effectively already expired after one tokio yield
        c.set("x", "y".to_string(), Some(Duration::from_nanos(1)))
            .await?;
        tokio::time::sleep(Duration::from_millis(10)).await;
        assert_eq!(c.get("x").await?, None);
        Ok(())
    }

    #[tokio::test]
    async fn dashmap_exists() -> Result<()> {
        let c = DashMapCache::new(Duration::from_secs(60));
        c.set("e", "z".to_string(), None).await?;
        assert!(c.exists("e").await?);
        assert!(!c.exists("nope").await?);
        Ok(())
    }

    // --- BoundedLruCache ---

    #[tokio::test]
    async fn lru_set_get() -> Result<()> {
        let c = BoundedLruCache::new(std::num::NonZeroUsize::MIN.saturating_add(3));
        c.set("a", "1".to_string(), None).await?;
        assert_eq!(c.get("a").await?, Some("1".to_string()));
        Ok(())
    }

    #[tokio::test]
    async fn lru_evicts_on_capacity() -> Result<()> {
        let c = BoundedLruCache::new(std::num::NonZeroUsize::MIN.saturating_add(1));
        c.set("k1", "v1".to_string(), None).await?;
        c.set("k2", "v2".to_string(), None).await?;
        // Access k1 to make it recently used
        c.get("k1").await?;
        // Insert k3 — k2 is LRU and should be evicted
        c.set("k3", "v3".to_string(), None).await?;
        assert_eq!(c.get("k2").await?, None);
        assert_eq!(c.get("k1").await?, Some("v1".to_string()));
        assert_eq!(c.get("k3").await?, Some("v3".to_string()));
        Ok(())
    }

    #[tokio::test]
    async fn lru_ttl_expires() -> Result<()> {
        let c = BoundedLruCache::new(std::num::NonZeroUsize::MIN.saturating_add(7));
        c.set("t", "val".to_string(), Some(Duration::from_nanos(1)))
            .await?;
        tokio::time::sleep(Duration::from_millis(10)).await;
        assert_eq!(c.get("t").await?, None);
        Ok(())
    }

    #[tokio::test]
    async fn lru_invalidate() -> Result<()> {
        let c = BoundedLruCache::new(std::num::NonZeroUsize::MIN.saturating_add(3));
        c.set("x", "y".to_string(), None).await?;
        c.invalidate("x").await?;
        assert!(!c.exists("x").await?);
        Ok(())
    }

    // --- global_cache ---

    #[tokio::test]
    async fn global_cache_roundtrip() -> Result<()> {
        global_cache()
            .set("gc_test", "hello".to_string(), None)
            .await?;
        let v = global_cache().get("gc_test").await?;
        assert_eq!(v, Some("hello".to_string()));
        global_cache().invalidate("gc_test").await?;
        Ok(())
    }
}