Skip to main content

hyprstream_core/archetypes/
domain.rs

1//! Domain trait and detection result types
2//!
3//! This module defines the `Domain` trait that replaces `RepoArchetype`,
4//! providing richer error handling and type-safe capability detection.
5
6use super::capabilities::CapabilitySet;
7use std::fmt;
8use std::path::{Path, PathBuf};
9
10/// Error that can occur during domain detection
11#[derive(Debug, Clone)]
12pub enum DetectionError {
13    /// I/O error accessing repository path
14    Io(String),
15    /// Path does not exist
16    PathNotFound(PathBuf),
17    /// Invalid repository structure (e.g., malformed config file)
18    InvalidStructure(String),
19}
20
21impl fmt::Display for DetectionError {
22    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
23        match self {
24            DetectionError::Io(msg) => write!(f, "I/O error: {msg}"),
25            DetectionError::PathNotFound(path) => write!(f, "Path not found: {}", path.display()),
26            DetectionError::InvalidStructure(msg) => write!(f, "Invalid structure: {msg}"),
27        }
28    }
29}
30
31impl std::error::Error for DetectionError {}
32
33impl From<std::io::Error> for DetectionError {
34    fn from(e: std::io::Error) -> Self {
35        DetectionError::Io(e.to_string())
36    }
37}
38
39/// Result of domain detection
40///
41/// Unlike the old boolean `detect()` method, this provides rich information
42/// about detection success, failure, or errors.
43#[derive(Debug, Clone)]
44pub enum DetectionResult {
45    /// Domain was detected with these capabilities
46    Detected(CapabilitySet),
47    /// Domain was not detected (normal case - not an error)
48    NotDetected,
49    /// Detection failed due to an error (should be logged)
50    Error(DetectionError),
51}
52
53impl DetectionResult {
54    /// Check if domain was detected
55    pub fn is_detected(&self) -> bool {
56        matches!(self, DetectionResult::Detected(_))
57    }
58
59    /// Check if detection resulted in error
60    pub fn is_error(&self) -> bool {
61        matches!(self, DetectionResult::Error(_))
62    }
63
64    /// Get capabilities if detected
65    pub fn capabilities(&self) -> Option<&CapabilitySet> {
66        match self {
67            DetectionResult::Detected(caps) => Some(caps),
68            _ => None,
69        }
70    }
71
72    /// Convert to Option, ignoring errors
73    pub fn into_option(self) -> Option<CapabilitySet> {
74        match self {
75            DetectionResult::Detected(caps) => Some(caps),
76            _ => None,
77        }
78    }
79}
80
81/// A domain that provides capabilities for repositories
82///
83/// Domains replace archetypes in the new capability system. Each domain:
84/// - Detects whether a repository belongs to it
85/// - Provides a set of capabilities for that repository
86/// - Can detect additional capabilities based on repository contents
87///
88/// # Example
89///
90/// ```ignore
91/// use hyprstream::archetypes::domain::{Domain, DetectionResult};
92/// use hyprstream::archetypes::capabilities::{CapabilitySet, Infer, Train, Serve};
93///
94/// struct HfModelDomain;
95///
96/// impl Domain for HfModelDomain {
97///     fn name(&self) -> &'static str { "HfModel" }
98///     fn description(&self) -> &'static str { "HuggingFace model" }
99///
100///     fn detect(&self, repo_path: &Path) -> DetectionResult {
101///         let config_path = repo_path.join("config.json");
102///         if !config_path.exists() {
103///             return DetectionResult::NotDetected;
104///         }
105///
106///         // Validate config and build capabilities
107///         let mut caps = CapabilitySet::model();
108///         if repo_path.join("adapters").is_dir() {
109///             caps.insert::<LoraSupport>();
110///         }
111///
112///         DetectionResult::Detected(caps)
113///     }
114/// }
115/// ```
116pub trait Domain: Send + Sync + 'static {
117    /// Domain identifier for Casbin (e.g., "HfModel")
118    ///
119    /// This is used in policy rules: `p, user, HfModel, model:*, infer`
120    fn name(&self) -> &'static str;
121
122    /// Human-readable description
123    fn description(&self) -> &'static str;
124
125    /// Detect if a repository belongs to this domain
126    ///
127    /// Returns:
128    /// - `Detected(caps)` if the repo matches with capabilities
129    /// - `NotDetected` if the repo doesn't match (not an error)
130    /// - `Error(e)` if detection failed (I/O error, invalid structure)
131    fn detect(&self, repo_path: &Path) -> DetectionResult;
132
133    /// Base capabilities this domain always provides when detected
134    ///
135    /// Override `detect()` for conditional capabilities.
136    fn base_capabilities(&self) -> CapabilitySet {
137        CapabilitySet::new()
138    }
139}
140
141/// Extension trait for domains with simple boolean detection
142///
143/// Implement this trait for domains where detection is a simple boolean check.
144/// The blanket implementation will automatically implement `Domain` for you,
145/// converting `matches()` to `DetectionResult`.
146pub trait SimpleDomain: Send + Sync + 'static {
147    /// Domain identifier for Casbin (e.g., "HfModel")
148    fn name(&self) -> &'static str;
149
150    /// Human-readable description
151    fn description(&self) -> &'static str;
152
153    /// Check if repository matches this domain (simple boolean check)
154    fn matches(&self, repo_path: &Path) -> bool;
155
156    /// Base capabilities this domain provides when detected
157    fn base_capabilities(&self) -> CapabilitySet {
158        CapabilitySet::new()
159    }
160}
161
162/// Blanket implementation that converts SimpleDomain::matches to DetectionResult
163impl<T: SimpleDomain> Domain for T {
164    fn name(&self) -> &'static str {
165        SimpleDomain::name(self)
166    }
167
168    fn description(&self) -> &'static str {
169        SimpleDomain::description(self)
170    }
171
172    fn detect(&self, repo_path: &Path) -> DetectionResult {
173        if self.matches(repo_path) {
174            DetectionResult::Detected(SimpleDomain::base_capabilities(self))
175        } else {
176            DetectionResult::NotDetected
177        }
178    }
179
180    fn base_capabilities(&self) -> CapabilitySet {
181        SimpleDomain::base_capabilities(self)
182    }
183}
184
185#[cfg(test)]
186#[allow(clippy::expect_used, clippy::unwrap_used, clippy::print_stdout)]
187mod tests {
188    use super::*;
189    use crate::archetypes::capabilities::{Infer, Serve, Train};
190
191    #[test]
192    fn test_detection_result_is_detected() {
193        let detected = DetectionResult::Detected(CapabilitySet::model());
194        assert!(detected.is_detected());
195
196        let not_detected = DetectionResult::NotDetected;
197        assert!(!not_detected.is_detected());
198
199        let error = DetectionResult::Error(DetectionError::Io("test".into()));
200        assert!(!error.is_detected());
201    }
202
203    #[test]
204    fn test_detection_result_capabilities() {
205        let caps = CapabilitySet::model();
206        let detected = DetectionResult::Detected(caps.clone());
207
208        let result_caps = detected.capabilities().expect("test: get capabilities");
209        assert!(result_caps.has::<Infer>());
210        assert!(result_caps.has::<Train>());
211        assert!(result_caps.has::<Serve>());
212    }
213
214    #[test]
215    fn test_detection_result_into_option() {
216        let caps = CapabilitySet::model();
217        let detected = DetectionResult::Detected(caps);
218        assert!(detected.into_option().is_some());
219
220        let not_detected = DetectionResult::NotDetected;
221        assert!(not_detected.into_option().is_none());
222
223        let error = DetectionResult::Error(DetectionError::Io("test".into()));
224        assert!(error.into_option().is_none());
225    }
226
227    #[test]
228    fn test_detection_error_display() {
229        let io_err = DetectionError::Io("permission denied".into());
230        assert!(io_err.to_string().contains("permission denied"));
231
232        let path_err = DetectionError::PathNotFound(PathBuf::from("/missing"));
233        assert!(path_err.to_string().contains("/missing"));
234
235        let struct_err = DetectionError::InvalidStructure("missing field".into());
236        assert!(struct_err.to_string().contains("missing field"));
237    }
238}