tensorlogic-oxirs-bridge 0.1.0

RDF/GraphQL/SHACL integration and provenance tracking for TensorLogic
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
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
//! Caching system for parsed RDF schemas and SymbolTables.
//!
//! This module provides two complementary caching mechanisms to optimize repeated RDF parsing:
//!
//! - [`SchemaCache`] - In-memory cache with TTL and LRU eviction
//! - [`PersistentCache`] - File-based cache that persists across process restarts
//!
//! # Performance Benefits
//!
//! Caching can provide **10-50x speedups** for repeated operations on the same RDF schemas.
//! Benchmarks show:
//! - Cold parse: ~2-5ms per schema
//! - Memory cache hit: ~0.1ms (20-50x faster)
//! - Disk cache hit: ~0.5ms (4-10x faster)
//!
//! # Examples
//!
//! ## In-Memory Caching
//!
//! ```
//! use tensorlogic_oxirs_bridge::SchemaCache;
//! use tensorlogic_adapters::SymbolTable;
//! use anyhow::Result;
//!
//! fn main() -> Result<()> {
//!     let mut cache = SchemaCache::new();
//!     let turtle = "@prefix ex: <http://example.org/> .";
//!
//!     // First access - cache miss
//!     if let Some(table) = cache.get_symbol_table(turtle) {
//!         println!("Cache hit!");
//!     } else {
//!         println!("Cache miss - parsing...");
//!         // ... parse and analyze ...
//!         let table = SymbolTable::new();
//!         cache.put_symbol_table(turtle, table);
//!     }
//!
//!     // Second access - cache hit
//!     assert!(cache.get_symbol_table(turtle).is_some());
//!
//!     // Check statistics
//!     let stats = cache.stats();
//!     println!("Hit rate: {:.1}%", stats.hit_rate * 100.0);
//!     Ok(())
//! }
//! ```
//!
//! ## File-Based Persistent Caching
//!
//! ```no_run
//! use tensorlogic_oxirs_bridge::PersistentCache;
//! use tensorlogic_adapters::SymbolTable;
//! use anyhow::Result;
//!
//! fn main() -> Result<()> {
//!     let cache_dir = std::env::temp_dir().join("my_cache");
//!     let mut cache = PersistentCache::new(&cache_dir)?;
//!
//!     let turtle = "@prefix ex: <http://example.org/> .";
//!
//!     // Try loading from disk
//!     if let Some(table) = cache.load_symbol_table(turtle)? {
//!         println!("Loaded from disk cache!");
//!     } else {
//!         println!("Not in cache - parsing...");
//!         // ... parse and analyze ...
//!         let table = SymbolTable::new();
//!         cache.save_symbol_table(turtle, &table)?;
//!     }
//!     Ok(())
//! }
//! ```
//!
//! # See Also
//!
//! - [`SchemaAnalyzer`](crate::SchemaAnalyzer) - The main schema parsing interface
//! - [Example 08](https://github.com/cool-japan/tensorlogic/blob/main/crates/tensorlogic-oxirs-bridge/examples/08_performance_features.rs) - Performance features demonstration

use anyhow::{Context, Result};
use serde::{Deserialize, Serialize};
use std::collections::hash_map::DefaultHasher;
use std::collections::HashMap;
use std::hash::{Hash, Hasher};
use std::path::{Path, PathBuf};
use std::time::{Duration, SystemTime};
use tensorlogic_adapters::SymbolTable;

use super::{ClassInfo, PropertyInfo};

/// Type alias for parsed schema data (classes and properties)
type ParsedSchema = (
    indexmap::IndexMap<String, ClassInfo>,
    indexmap::IndexMap<String, PropertyInfo>,
);

/// Cache entry with expiration tracking and access statistics.
///
/// Internal structure used by [`SchemaCache`] to track cached values with TTL and LRU metadata.
#[derive(Debug, Clone, Serialize, Deserialize)]
struct CacheEntry<T> {
    value: T,
    created_at: SystemTime,
    last_accessed: SystemTime,
    access_count: usize,
}

impl<T> CacheEntry<T> {
    fn new(value: T) -> Self {
        let now = SystemTime::now();
        Self {
            value,
            created_at: now,
            last_accessed: now,
            access_count: 0,
        }
    }

    fn access(&mut self) -> &T {
        self.last_accessed = SystemTime::now();
        self.access_count += 1;
        &self.value
    }

    fn is_expired(&self, ttl: Duration) -> bool {
        self.created_at
            .elapsed()
            .map(|age| age > ttl)
            .unwrap_or(false)
    }
}

/// Serializable schema cache data.
///
/// Internal structure for storing parsed RDF schemas before conversion to symbol tables.
#[derive(Debug, Clone, Serialize, Deserialize)]
struct SchemaCacheData {
    classes: indexmap::IndexMap<String, ClassInfo>,
    properties: indexmap::IndexMap<String, PropertyInfo>,
}

/// In-memory cache for parsed RDF schemas and symbol tables.
///
/// Provides fast caching with content-based hashing, TTL expiration, and LRU eviction.
/// Ideal for repeated parsing of the same RDF schemas during a single session.
///
/// # Features
///
/// - **Content-based hashing**: Automatically deduplicates identical schemas
/// - **TTL expiration**: Configurable time-to-live (default: 1 hour)
/// - **LRU eviction**: Automatic removal of least-recently-used entries when full
/// - **Hit/miss tracking**: Built-in statistics for cache performance monitoring
/// - **Dual storage**: Caches both raw parsed schemas and symbol tables
///
/// # Performance
///
/// - **Lookup**: O(1) average case (HashMap-based)
/// - **Insertion**: O(1) average case
/// - **Space overhead**: ~2-3x original schema size (includes metadata)
///
/// # Examples
///
/// ## Basic Usage
///
/// ```
/// use tensorlogic_oxirs_bridge::{SchemaCache, SchemaAnalyzer};
/// use anyhow::Result;
///
/// fn main() -> Result<()> {
///     let mut cache = SchemaCache::new();
///     let turtle = r#"
///         @prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> .
///         @prefix ex: <http://example.org/> .
///         ex:Person a rdfs:Class .
///     "#;
///
///     // First parse - cache miss
///     let table1 = if let Some(cached) = cache.get_symbol_table(turtle) {
///         cached
///     } else {
///         let mut analyzer = SchemaAnalyzer::new();
///         analyzer.load_turtle(turtle)?;
///         analyzer.analyze()?;
///         let table = analyzer.to_symbol_table()?;
///         cache.put_symbol_table(turtle, table.clone());
///         table
///     };
///
///     // Second access - cache hit (much faster)
///     let table2 = cache.get_symbol_table(turtle).expect("should be cached");
///
///     // Statistics
///     let stats = cache.stats();
///     assert_eq!(stats.total_hits, 1);
///     assert_eq!(stats.total_misses, 1);
///     assert_eq!(stats.hit_rate, 0.5);
///     Ok(())
/// }
/// ```
///
/// ## Custom TTL and Size
///
/// ```
/// use tensorlogic_oxirs_bridge::SchemaCache;
/// use std::time::Duration;
///
/// // Cache with 30-minute TTL and max 50 entries
/// let cache = SchemaCache::with_settings(
///     Duration::from_secs(30 * 60),  // TTL: 30 minutes
///     50                              // Max size: 50 entries
/// );
/// ```
///
/// ## Cleanup
///
/// ```
/// use tensorlogic_oxirs_bridge::SchemaCache;
///
/// let mut cache = SchemaCache::new();
/// // ... use cache ...
///
/// // Remove expired entries
/// cache.cleanup_expired();
///
/// // Clear everything
/// cache.clear();
/// ```
///
/// # See Also
///
/// - [`PersistentCache`] - File-based caching for cross-session persistence
/// - [`CacheStats`] - Cache performance statistics
#[derive(Debug)]
pub struct SchemaCache {
    /// Content hash → Parsed schema
    schemas: HashMap<u64, CacheEntry<SchemaCacheData>>,

    /// Content hash → SymbolTable
    symbol_tables: HashMap<u64, CacheEntry<SymbolTable>>,

    /// Time-to-live for cache entries
    ttl: Duration,

    /// Maximum cache size (number of entries)
    max_size: usize,

    /// Cache statistics
    hits: usize,
    misses: usize,
}

impl SchemaCache {
    /// Creates a new cache with default settings.
    ///
    /// Default configuration:
    /// - **TTL**: 1 hour (3600 seconds)
    /// - **Max entries**: 100
    ///
    /// # Examples
    ///
    /// ```
    /// use tensorlogic_oxirs_bridge::SchemaCache;
    ///
    /// let cache = SchemaCache::new();
    /// ```
    pub fn new() -> Self {
        Self::with_settings(Duration::from_secs(3600), 100)
    }

    /// Creates a cache with custom TTL and maximum size.
    ///
    /// # Arguments
    ///
    /// * `ttl` - Time-to-live for cache entries
    /// * `max_size` - Maximum number of entries before LRU eviction kicks in
    ///
    /// # Examples
    ///
    /// ```
    /// use tensorlogic_oxirs_bridge::SchemaCache;
    /// use std::time::Duration;
    ///
    /// // 5-minute TTL, max 25 entries
    /// let cache = SchemaCache::with_settings(Duration::from_secs(300), 25);
    /// ```
    pub fn with_settings(ttl: Duration, max_size: usize) -> Self {
        Self {
            schemas: HashMap::new(),
            symbol_tables: HashMap::new(),
            ttl,
            max_size,
            hits: 0,
            misses: 0,
        }
    }

    /// Calculate hash of content
    fn hash_content(content: &str) -> u64 {
        let mut hasher = DefaultHasher::new();
        content.hash(&mut hasher);
        hasher.finish()
    }

    /// Get cached schema by content hash
    pub fn get_schema(&mut self, content: &str) -> Option<ParsedSchema> {
        let hash = Self::hash_content(content);

        if let Some(entry) = self.schemas.get_mut(&hash) {
            if !entry.is_expired(self.ttl) {
                self.hits += 1;
                let data = entry.access();
                return Some((data.classes.clone(), data.properties.clone()));
            } else {
                // Remove expired entry
                self.schemas.remove(&hash);
            }
        }

        self.misses += 1;
        None
    }

    /// Cache a parsed schema
    pub fn put_schema(
        &mut self,
        content: &str,
        classes: indexmap::IndexMap<String, ClassInfo>,
        properties: indexmap::IndexMap<String, PropertyInfo>,
    ) {
        let hash = Self::hash_content(content);

        // Evict oldest if at capacity
        if self.schemas.len() >= self.max_size {
            if let Some(oldest_key) = self.find_oldest_schema() {
                self.schemas.remove(&oldest_key);
            }
        }

        self.schemas.insert(
            hash,
            CacheEntry::new(SchemaCacheData {
                classes,
                properties,
            }),
        );
    }

    /// Get cached SymbolTable by content hash
    pub fn get_symbol_table(&mut self, content: &str) -> Option<SymbolTable> {
        let hash = Self::hash_content(content);

        if let Some(entry) = self.symbol_tables.get_mut(&hash) {
            if !entry.is_expired(self.ttl) {
                self.hits += 1;
                return Some(entry.access().clone());
            } else {
                // Remove expired entry
                self.symbol_tables.remove(&hash);
            }
        }

        self.misses += 1;
        None
    }

    /// Cache a SymbolTable
    pub fn put_symbol_table(&mut self, content: &str, table: SymbolTable) {
        let hash = Self::hash_content(content);

        // Evict oldest if at capacity
        if self.symbol_tables.len() >= self.max_size {
            if let Some(oldest_key) = self.find_oldest_symbol_table() {
                self.symbol_tables.remove(&oldest_key);
            }
        }

        self.symbol_tables.insert(hash, CacheEntry::new(table));
    }

    /// Find oldest schema entry for eviction
    fn find_oldest_schema(&self) -> Option<u64> {
        self.schemas
            .iter()
            .min_by_key(|(_, entry)| entry.last_accessed)
            .map(|(k, _)| *k)
    }

    /// Find oldest symbol table entry for eviction
    fn find_oldest_symbol_table(&self) -> Option<u64> {
        self.symbol_tables
            .iter()
            .min_by_key(|(_, entry)| entry.last_accessed)
            .map(|(k, _)| *k)
    }

    /// Clear all expired entries
    pub fn cleanup_expired(&mut self) {
        self.schemas.retain(|_, entry| !entry.is_expired(self.ttl));
        self.symbol_tables
            .retain(|_, entry| !entry.is_expired(self.ttl));
    }

    /// Clear all cache entries
    pub fn clear(&mut self) {
        self.schemas.clear();
        self.symbol_tables.clear();
        self.hits = 0;
        self.misses = 0;
    }

    /// Get cache statistics
    pub fn stats(&self) -> CacheStats {
        CacheStats {
            schema_entries: self.schemas.len(),
            symbol_table_entries: self.symbol_tables.len(),
            total_hits: self.hits,
            total_misses: self.misses,
            hit_rate: if self.hits + self.misses > 0 {
                (self.hits as f64) / ((self.hits + self.misses) as f64)
            } else {
                0.0
            },
        }
    }
}

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

/// Cache statistics
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CacheStats {
    pub schema_entries: usize,
    pub symbol_table_entries: usize,
    pub total_hits: usize,
    pub total_misses: usize,
    pub hit_rate: f64,
}

impl std::fmt::Display for CacheStats {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        writeln!(f, "Cache Statistics:")?;
        writeln!(f, "  Schema entries: {}", self.schema_entries)?;
        writeln!(f, "  Symbol table entries: {}", self.symbol_table_entries)?;
        writeln!(f, "  Total hits: {}", self.total_hits)?;
        writeln!(f, "  Total misses: {}", self.total_misses)?;
        writeln!(f, "  Hit rate: {:.2}%", self.hit_rate * 100.0)?;
        Ok(())
    }
}

/// File-based persistent cache
pub struct PersistentCache {
    cache_dir: PathBuf,
    in_memory: SchemaCache,
}

impl PersistentCache {
    /// Create a new persistent cache with a directory
    pub fn new(cache_dir: impl AsRef<Path>) -> Result<Self> {
        let cache_dir = cache_dir.as_ref().to_path_buf();
        std::fs::create_dir_all(&cache_dir).context("Failed to create cache directory")?;

        Ok(Self {
            cache_dir,
            in_memory: SchemaCache::new(),
        })
    }

    /// Get cache file path for content
    fn cache_path(&self, content: &str, suffix: &str) -> PathBuf {
        let hash = SchemaCache::hash_content(content);
        self.cache_dir.join(format!("{:016x}.{}", hash, suffix))
    }

    /// Load SymbolTable from cache (memory or disk)
    pub fn load_symbol_table(&mut self, content: &str) -> Result<Option<SymbolTable>> {
        // Try memory first
        if let Some(table) = self.in_memory.get_symbol_table(content) {
            return Ok(Some(table));
        }

        // Try disk
        let path = self.cache_path(content, "symboltable.json");
        if path.exists() {
            let json = std::fs::read_to_string(&path).context("Failed to read cache file")?;
            let table: SymbolTable =
                serde_json::from_str(&json).context("Failed to deserialize SymbolTable")?;

            // Store in memory for future access
            self.in_memory.put_symbol_table(content, table.clone());

            return Ok(Some(table));
        }

        Ok(None)
    }

    /// Save SymbolTable to cache (memory and disk)
    pub fn save_symbol_table(&mut self, content: &str, table: &SymbolTable) -> Result<()> {
        // Save to memory
        self.in_memory.put_symbol_table(content, table.clone());

        // Save to disk
        let path = self.cache_path(content, "symboltable.json");
        let json =
            serde_json::to_string_pretty(table).context("Failed to serialize SymbolTable")?;
        std::fs::write(&path, json).context("Failed to write cache file")?;

        Ok(())
    }

    /// Load schema from cache (memory or disk)
    pub fn load_schema(&mut self, content: &str) -> Result<Option<ParsedSchema>> {
        // Try memory first
        if let Some(result) = self.in_memory.get_schema(content) {
            return Ok(Some(result));
        }

        // Try disk
        let path = self.cache_path(content, "schema.json");
        if path.exists() {
            let json = std::fs::read_to_string(&path).context("Failed to read cache file")?;
            let data: SchemaCacheData =
                serde_json::from_str(&json).context("Failed to deserialize schema")?;

            // Store in memory for future access
            self.in_memory
                .put_schema(content, data.classes.clone(), data.properties.clone());

            return Ok(Some((data.classes, data.properties)));
        }

        Ok(None)
    }

    /// Save schema to cache (memory and disk)
    pub fn save_schema(
        &mut self,
        content: &str,
        classes: &indexmap::IndexMap<String, ClassInfo>,
        properties: &indexmap::IndexMap<String, PropertyInfo>,
    ) -> Result<()> {
        // Save to memory
        self.in_memory
            .put_schema(content, classes.clone(), properties.clone());

        // Save to disk
        let path = self.cache_path(content, "schema.json");
        let data = SchemaCacheData {
            classes: classes.clone(),
            properties: properties.clone(),
        };
        let json = serde_json::to_string_pretty(&data).context("Failed to serialize schema")?;
        std::fs::write(&path, json).context("Failed to write cache file")?;

        Ok(())
    }

    /// Clear all cache files
    pub fn clear_all(&mut self) -> Result<()> {
        self.in_memory.clear();

        for entry in std::fs::read_dir(&self.cache_dir)? {
            let entry = entry?;
            if entry.path().is_file() {
                std::fs::remove_file(entry.path())?;
            }
        }

        Ok(())
    }

    /// Get cache statistics
    pub fn stats(&self) -> CacheStats {
        self.in_memory.stats()
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::thread;
    use std::time::Duration;

    #[test]
    fn test_schema_cache_basic() {
        let mut cache = SchemaCache::new();

        let content = "@prefix ex: <http://example.org/> .";
        let classes = indexmap::IndexMap::new();
        let properties = indexmap::IndexMap::new();

        // First access - miss
        assert!(cache.get_schema(content).is_none());
        assert_eq!(cache.stats().total_misses, 1);

        // Store
        cache.put_schema(content, classes.clone(), properties.clone());

        // Second access - hit
        assert!(cache.get_schema(content).is_some());
        assert_eq!(cache.stats().total_hits, 1);
    }

    #[test]
    fn test_symbol_table_cache() {
        let mut cache = SchemaCache::new();

        let content = "@prefix ex: <http://example.org/> .";
        let table = SymbolTable::new();

        // First access - miss
        assert!(cache.get_symbol_table(content).is_none());

        // Store
        cache.put_symbol_table(content, table.clone());

        // Second access - hit
        assert!(cache.get_symbol_table(content).is_some());
    }

    #[test]
    fn test_cache_expiration() {
        let mut cache = SchemaCache::with_settings(Duration::from_millis(100), 10);

        let content = "@prefix ex: <http://example.org/> .";
        let table = SymbolTable::new();

        cache.put_symbol_table(content, table);

        // Should hit immediately
        assert!(cache.get_symbol_table(content).is_some());

        // Wait for expiration
        thread::sleep(Duration::from_millis(150));

        // Should miss after expiration
        assert!(cache.get_symbol_table(content).is_none());
    }

    #[test]
    fn test_cache_eviction() {
        let mut cache = SchemaCache::with_settings(Duration::from_secs(3600), 2);

        let table = SymbolTable::new();

        // Fill cache
        cache.put_symbol_table("content1", table.clone());
        cache.put_symbol_table("content2", table.clone());

        // Add third item - should evict oldest
        cache.put_symbol_table("content3", table.clone());

        // Cache should still have 2 entries
        assert_eq!(cache.stats().symbol_table_entries, 2);
    }

    #[test]
    fn test_cache_stats() {
        let mut cache = SchemaCache::new();

        let content = "@prefix ex: <http://example.org/> .";
        let table = SymbolTable::new();

        cache.get_symbol_table(content); // Miss
        cache.put_symbol_table(content, table);
        cache.get_symbol_table(content); // Hit
        cache.get_symbol_table(content); // Hit

        let stats = cache.stats();
        assert_eq!(stats.total_hits, 2);
        assert_eq!(stats.total_misses, 1);
        assert!((stats.hit_rate - 0.666).abs() < 0.01);
    }

    #[test]
    fn test_cache_clear() {
        let mut cache = SchemaCache::new();

        let content = "@prefix ex: <http://example.org/> .";
        let table = SymbolTable::new();

        cache.put_symbol_table(content, table);
        assert_eq!(cache.stats().symbol_table_entries, 1);

        cache.clear();
        assert_eq!(cache.stats().symbol_table_entries, 0);
        assert_eq!(cache.stats().total_hits, 0);
    }

    #[test]
    fn test_persistent_cache() -> Result<()> {
        let temp_dir = std::env::temp_dir().join("tensorlogic_oxirs_test_cache");
        std::fs::create_dir_all(&temp_dir)?;

        let mut cache = PersistentCache::new(&temp_dir)?;

        let content = "@prefix ex: <http://example.org/> .";
        let table = SymbolTable::new();

        // Save
        cache.save_symbol_table(content, &table)?;

        // Load
        let loaded = cache.load_symbol_table(content)?;
        assert!(loaded.is_some());

        // Clean up
        cache.clear_all()?;
        std::fs::remove_dir_all(temp_dir)?;

        Ok(())
    }
}