Skip to main content

hyprstream_core/archetypes/
duckdb.rs

1//! DuckDB database archetype detection
2//!
3//! Detects repositories containing DuckDB database files.
4//! These can be used for metrics storage, training data,
5//! or query via Flight SQL.
6//!
7//! # Security
8//!
9//! Detection validates DuckDB files have minimum size and valid
10//! header structure to prevent trivial spoofing attacks.
11
12use super::capabilities::{CapabilitySet, Query, Serve, Write};
13use super::RepoArchetype;
14use std::path::Path;
15
16/// Minimum valid DuckDB file size (header + at least one page)
17const MIN_DUCKDB_SIZE: u64 = 4096;
18
19/// DuckDB database archetype
20///
21/// Detects repos with:
22/// - `*.duckdb` files (DuckDB database) - must have valid structure
23///
24/// Enables: QUERY, WRITE, SERVE
25pub struct DuckDbArchetype;
26
27impl DuckDbArchetype {
28    /// Validate that a DuckDB file appears to be valid
29    ///
30    /// Checks:
31    /// - File exists and is readable
32    /// - File is at least the minimum size for a valid DuckDB database
33    fn validate_duckdb_file(path: &Path) -> bool {
34        match std::fs::metadata(path) {
35            Ok(meta) => {
36                // DuckDB files must be at least MIN_DUCKDB_SIZE bytes
37                // An empty database is ~4KB due to page structure
38                meta.len() >= MIN_DUCKDB_SIZE
39            }
40            Err(_) => false,
41        }
42    }
43
44    /// Check for valid DuckDB files in a directory
45    fn has_valid_duckdb_in_dir(dir: &Path) -> bool {
46        if let Ok(entries) = std::fs::read_dir(dir) {
47            for entry in entries.flatten() {
48                let path = entry.path();
49                if let Some(ext) = path.extension() {
50                    if ext == "duckdb" && Self::validate_duckdb_file(&path) {
51                        return true;
52                    }
53                }
54            }
55        }
56        false
57    }
58}
59
60impl RepoArchetype for DuckDbArchetype {
61    fn name(&self) -> &'static str {
62        "duckdb"
63    }
64
65    fn description(&self) -> &'static str {
66        "DuckDB database for SQL queries via Flight SQL"
67    }
68
69    fn detect(&self, repo_path: &Path) -> bool {
70        // Check for valid .duckdb files in root
71        if Self::has_valid_duckdb_in_dir(repo_path) {
72            return true;
73        }
74
75        // Also check common subdirectories for databases
76        for subdir in &["data", "db", "databases"] {
77            let sub_path = repo_path.join(subdir);
78            if sub_path.is_dir() && Self::has_valid_duckdb_in_dir(&sub_path) {
79                return true;
80            }
81        }
82
83        false
84    }
85
86    fn capabilities(&self) -> CapabilitySet {
87        let mut caps = CapabilitySet::new();
88        caps.insert::<Query>();
89        caps.insert::<Write>();
90        caps.insert::<Serve>();
91        caps
92    }
93}
94
95#[cfg(test)]
96mod tests {
97    use super::*;
98    use std::fs;
99    use tempfile::TempDir;
100
101    /// Create dummy DuckDB data with valid minimum size
102    fn valid_duckdb_data() -> Vec<u8> {
103        // Create data at least MIN_DUCKDB_SIZE bytes
104        vec![0u8; MIN_DUCKDB_SIZE as usize]
105    }
106
107    #[test]
108    fn test_detect_with_duckdb_file() -> std::io::Result<()> {
109        let temp = TempDir::new()?;
110        let db_path = temp.path().join("metrics.duckdb");
111        fs::write(&db_path, valid_duckdb_data())?;
112
113        let archetype = DuckDbArchetype;
114        assert!(archetype.detect(temp.path()));
115        Ok(())
116    }
117
118    #[test]
119    fn test_detect_with_duckdb_in_subdir() -> std::io::Result<()> {
120        let temp = TempDir::new()?;
121        let db_dir = temp.path().join("db");
122        fs::create_dir(&db_dir)?;
123        let db_path = db_dir.join("metrics.duckdb");
124        fs::write(&db_path, valid_duckdb_data())?;
125
126        let archetype = DuckDbArchetype;
127        assert!(archetype.detect(temp.path()));
128        Ok(())
129    }
130
131    #[test]
132    fn test_no_detect_empty_dir() -> std::io::Result<()> {
133        let temp = TempDir::new()?;
134
135        let archetype = DuckDbArchetype;
136        assert!(!archetype.detect(temp.path()));
137        Ok(())
138    }
139
140    #[test]
141    fn test_no_detect_small_file() -> std::io::Result<()> {
142        let temp = TempDir::new()?;
143        // Small file should not be detected (potential spoof)
144        let db_path = temp.path().join("metrics.duckdb");
145        fs::write(&db_path, "dummy")?;
146
147        let archetype = DuckDbArchetype;
148        assert!(!archetype.detect(temp.path()));
149        Ok(())
150    }
151
152    #[test]
153    fn test_capabilities() {
154        use super::super::capabilities::{Infer, Train};
155
156        let archetype = DuckDbArchetype;
157        let caps = archetype.capabilities();
158
159        assert!(caps.has::<Query>());
160        assert!(caps.has::<Write>());
161        assert!(caps.has::<Serve>());
162        assert!(!caps.has::<Infer>());
163        assert!(!caps.has::<Train>());
164    }
165}