hyprstream_core/archetypes/
registry.rs1use super::capabilities::{Capability, CapabilitySet};
7use super::{builtin_archetypes, RepoArchetype};
8use dashmap::DashMap;
9use std::collections::HashMap;
10use std::path::{Path, PathBuf};
11use std::sync::Arc;
12use std::time::{Duration, Instant};
13
14#[derive(Debug, Clone)]
23pub struct DetectedDomains {
24 pub domains: Vec<&'static str>,
26 pub capabilities: CapabilitySet,
28 pub domain_capabilities: HashMap<&'static str, CapabilitySet>,
30 pub detected_at: Instant,
32}
33
34impl DetectedDomains {
35 pub fn empty() -> Self {
37 Self {
38 domains: Vec::new(),
39 capabilities: CapabilitySet::new(),
40 domain_capabilities: HashMap::new(),
41 detected_at: Instant::now(),
42 }
43 }
44
45 pub fn is_empty(&self) -> bool {
47 self.domains.is_empty()
48 }
49
50 pub fn has<C: Capability>(&self) -> bool {
59 self.capabilities.has::<C>()
60 }
61
62 pub fn has_str(&self, id: &str) -> bool {
64 self.capabilities.has_str(id)
65 }
66
67 pub fn has_in_domain<C: Capability>(&self, domain: &str) -> bool {
69 self.domain_capabilities
70 .get(domain)
71 .map(crate::archetypes::CapabilitySet::has::<C>)
72 .unwrap_or(false)
73 }
74
75 pub fn domains_for<C: Capability>(&self) -> Vec<&'static str> {
77 self.domain_capabilities
78 .iter()
79 .filter(|(_, caps)| caps.has::<C>())
80 .map(|(domain, _)| *domain)
81 .collect()
82 }
83
84 pub fn domains_for_str(&self, capability: &str) -> Vec<&'static str> {
86 self.domain_capabilities
87 .iter()
88 .filter(|(_, caps)| caps.has_str(capability))
89 .map(|(domain, _)| *domain)
90 .collect()
91 }
92
93 pub fn domains_display(&self) -> String {
95 self.domains.join(",")
96 }
97}
98
99impl Default for DetectedDomains {
100 fn default() -> Self {
101 Self::empty()
102 }
103}
104
105#[derive(Debug, Clone)]
111pub struct DetectedArchetypes {
112 pub archetypes: Vec<&'static str>,
114 pub capabilities: CapabilitySet,
116 pub detected_at: Instant,
118}
119
120impl DetectedArchetypes {
121 pub fn is_empty(&self) -> bool {
123 self.archetypes.is_empty()
124 }
125
126 pub fn has<C: Capability>(&self) -> bool {
128 self.capabilities.has::<C>()
129 }
130
131 pub fn has_str(&self, id: &str) -> bool {
133 self.capabilities.has_str(id)
134 }
135
136 pub fn archetypes_display(&self) -> String {
138 self.archetypes.join(",")
139 }
140
141 pub fn to_detected_domains(&self) -> DetectedDomains {
143 DetectedDomains {
144 domains: self.archetypes.clone(),
145 capabilities: self.capabilities.clone(),
146 domain_capabilities: HashMap::new(), detected_at: self.detected_at,
148 }
149 }
150}
151
152pub struct ArchetypeRegistry {
156 archetypes: Vec<Box<dyn RepoArchetype>>,
157 cache: DashMap<PathBuf, DetectedArchetypes>,
158 cache_ttl: Duration,
159}
160
161impl Default for ArchetypeRegistry {
162 fn default() -> Self {
163 Self::new()
164 }
165}
166
167impl ArchetypeRegistry {
168 pub fn new() -> Self {
170 Self {
171 archetypes: builtin_archetypes(),
172 cache: DashMap::new(),
173 cache_ttl: Duration::from_secs(60), }
175 }
176
177 pub fn with_ttl(ttl: Duration) -> Self {
179 Self {
180 archetypes: builtin_archetypes(),
181 cache: DashMap::new(),
182 cache_ttl: ttl,
183 }
184 }
185
186 pub fn detect(&self, repo_path: &Path) -> DetectedArchetypes {
190 let canonical = match repo_path.canonicalize() {
191 Ok(p) => p,
192 Err(_) => repo_path.to_path_buf(),
193 };
194
195 if let Some(cached) = self.cache.get(&canonical) {
197 if cached.detected_at.elapsed() < self.cache_ttl {
198 return cached.clone();
199 }
200 }
201
202 let mut detected = DetectedArchetypes {
204 archetypes: Vec::new(),
205 capabilities: CapabilitySet::new(),
206 detected_at: Instant::now(),
207 };
208
209 for archetype in &self.archetypes {
210 if archetype.detect(&canonical) {
211 detected.archetypes.push(archetype.name());
212 detected.capabilities = detected.capabilities.union(&archetype.capabilities());
213 }
214 }
215
216 self.cache.insert(canonical, detected.clone());
218
219 detected
220 }
221
222 pub fn capabilities(&self, repo_path: &Path) -> CapabilitySet {
226 self.detect(repo_path).capabilities
227 }
228
229 pub fn has<C: Capability>(&self, repo_path: &Path) -> bool {
231 self.capabilities(repo_path).has::<C>()
232 }
233
234 pub fn invalidate(&self, repo_path: &Path) {
236 if let Ok(canonical) = repo_path.canonicalize() {
237 self.cache.remove(&canonical);
238 }
239 self.cache.remove(&repo_path.to_path_buf());
240 }
241
242 pub fn invalidate_all(&self) {
244 self.cache.clear();
245 }
246
247 pub fn archetype_names(&self) -> Vec<&'static str> {
249 self.archetypes.iter().map(|a| a.name()).collect()
250 }
251}
252
253static REGISTRY: std::sync::OnceLock<Arc<ArchetypeRegistry>> = std::sync::OnceLock::new();
255
256pub fn global_registry() -> Arc<ArchetypeRegistry> {
258 REGISTRY
259 .get_or_init(|| Arc::new(ArchetypeRegistry::new()))
260 .clone()
261}
262
263#[cfg(test)]
264mod tests {
265 use super::*;
266 use crate::archetypes::{Context, Infer, Query, Serve, Train};
267 use std::fs;
268 use tempfile::TempDir;
269
270 #[test]
271 fn test_detect_model() -> std::io::Result<()> {
272 let temp = TempDir::new()?;
273 fs::write(
275 temp.path().join("config.json"),
276 r#"{"model_type": "llama"}"#,
277 )?;
278
279 let registry = ArchetypeRegistry::new();
280 let detected = registry.detect(temp.path());
281
282 assert!(detected.archetypes.contains(&"hf-model"));
283 assert!(detected.has::<Infer>());
284 Ok(())
285 }
286
287 #[test]
288 fn test_detect_dataset() -> std::io::Result<()> {
289 let temp = TempDir::new()?;
290 fs::write(temp.path().join("dataset_infos.json"), "{}")?;
291
292 let registry = ArchetypeRegistry::new();
293 let detected = registry.detect(temp.path());
294
295 assert!(detected.archetypes.contains(&"hf-dataset"));
296 assert!(detected.has::<Query>());
297 Ok(())
298 }
299
300 fn valid_duckdb_data() -> Vec<u8> {
302 vec![0u8; 4096]
303 }
304
305 #[test]
306 fn test_detect_duckdb() -> std::io::Result<()> {
307 let temp = TempDir::new()?;
308 fs::write(temp.path().join("metrics.duckdb"), valid_duckdb_data())?;
309
310 let registry = ArchetypeRegistry::new();
311 let detected = registry.detect(temp.path());
312
313 assert!(detected.archetypes.contains(&"duckdb"));
314 assert!(detected.has::<Query>());
315 Ok(())
316 }
317
318 #[test]
319 fn test_detect_multiple() -> std::io::Result<()> {
320 let temp = TempDir::new()?;
321 fs::write(
323 temp.path().join("config.json"),
324 r#"{"model_type": "llama"}"#,
325 )?;
326 fs::write(temp.path().join("metrics.duckdb"), valid_duckdb_data())?;
327
328 let registry = ArchetypeRegistry::new();
329 let detected = registry.detect(temp.path());
330
331 assert!(detected.archetypes.contains(&"hf-model"));
332 assert!(detected.archetypes.contains(&"duckdb"));
333 assert!(detected.has::<Infer>());
334 assert!(detected.has::<Query>());
335 Ok(())
336 }
337
338 #[test]
339 fn test_cache_invalidation() -> std::io::Result<()> {
340 let temp = TempDir::new()?;
341
342 let registry = ArchetypeRegistry::new();
343
344 let detected = registry.detect(temp.path());
346 assert!(detected.is_empty());
347
348 fs::write(
350 temp.path().join("config.json"),
351 r#"{"model_type": "llama"}"#,
352 )?;
353
354 let detected = registry.detect(temp.path());
356 assert!(detected.is_empty());
357
358 registry.invalidate(temp.path());
360 let detected = registry.detect(temp.path());
361 assert!(!detected.is_empty());
362 assert!(detected.archetypes.contains(&"hf-model"));
363 Ok(())
364 }
365
366 #[test]
367 fn test_detect_cag_context() -> std::io::Result<()> {
368 let temp = TempDir::new()?;
369 fs::write(
370 temp.path().join("context.json"),
371 r#"{"version": 1, "store": {"type": "duckdb", "path": "ctx.db"}, "embedding": {"dimension": 384, "model": "test"}}"#,
372 )?;
373
374 let registry = ArchetypeRegistry::new();
375 let detected = registry.detect(temp.path());
376
377 assert!(detected.archetypes.contains(&"cag-context"));
378 assert!(detected.has::<Context>());
379 Ok(())
380 }
381
382 #[test]
383 fn test_detect_model_with_cag() -> std::io::Result<()> {
384 let temp = TempDir::new()?;
385 fs::write(
387 temp.path().join("config.json"),
388 r#"{"model_type": "llama"}"#,
389 )?;
390 fs::write(
391 temp.path().join("context.json"),
392 r#"{"version": 1, "store": {"type": "duckdb", "path": "ctx.db"}, "embedding": {"dimension": 384, "model": "test"}}"#,
393 )?;
394
395 let registry = ArchetypeRegistry::new();
396 let detected = registry.detect(temp.path());
397
398 assert!(detected.archetypes.contains(&"hf-model"));
399 assert!(detected.archetypes.contains(&"cag-context"));
400 assert!(detected.has::<Infer>());
401 assert!(detected.has::<Context>());
402 assert!(detected.archetypes_display().contains("hf-model"));
404 assert!(detected.archetypes_display().contains("cag-context"));
405 Ok(())
406 }
407
408 #[test]
413 fn test_detected_domains_type_safe_has() -> std::io::Result<()> {
414 let temp = TempDir::new()?;
415 fs::write(
416 temp.path().join("config.json"),
417 r#"{"model_type": "llama"}"#,
418 )?;
419
420 let registry = ArchetypeRegistry::new();
421 let detected = registry.detect(temp.path());
422
423 let domains = detected.to_detected_domains();
425
426 assert!(domains.has::<Infer>());
428 assert!(domains.has::<Train>());
429 assert!(domains.has::<Serve>());
430 assert!(!domains.has::<Query>());
431 Ok(())
432 }
433
434 #[test]
435 fn test_detected_domains_string_has() -> std::io::Result<()> {
436 let temp = TempDir::new()?;
437 fs::write(
438 temp.path().join("config.json"),
439 r#"{"model_type": "llama"}"#,
440 )?;
441
442 let registry = ArchetypeRegistry::new();
443 let detected = registry.detect(temp.path()).to_detected_domains();
444
445 assert!(detected.has_str("infer"));
447 assert!(detected.has_str("train"));
448 assert!(!detected.has_str("query"));
449 assert!(!detected.has_str("unknown"));
450 Ok(())
451 }
452
453 #[test]
454 fn test_detected_domains_display() -> std::io::Result<()> {
455 let temp = TempDir::new()?;
456 fs::write(
457 temp.path().join("config.json"),
458 r#"{"model_type": "llama"}"#,
459 )?;
460 fs::write(
461 temp.path().join("context.json"),
462 r#"{"version": 1, "store": {"type": "duckdb", "path": "ctx.db"}, "embedding": {"dimension": 384, "model": "test"}}"#,
463 )?;
464
465 let registry = ArchetypeRegistry::new();
466 let domains = registry.detect(temp.path()).to_detected_domains();
467
468 assert!(domains.domains_display().contains("hf-model"));
470 assert!(domains.domains_display().contains("cag-context"));
471 Ok(())
472 }
473
474 #[test]
475 fn test_detected_domains_empty() {
476 let domains = DetectedDomains::empty();
477 assert!(domains.is_empty());
478 assert!(!domains.has::<Infer>());
479 assert_eq!(domains.domains_display(), "");
480 }
481}