1use crate::loader::{decode_hash, validate_manifest};
2use crate::manifest::COMPONENT_MANIFEST_SCHEMA;
3use crate::{
4 ArtifactCache, CachedArtifact, CachedObject, ComponentDeliveryMode, ComponentError, ComponentLock,
5 ComponentLockEntry, ComponentRequirements, DownloadOptions, HostServices, LoadedComponent, RemovalReport, Retain,
6 TrustPolicy,
7};
8use alef_component_abi::AlefHostApiV1;
9use std::collections::{HashMap, HashSet};
10use std::path::{Path, PathBuf};
11use std::sync::{Arc, Mutex, PoisonError};
12use std::time::SystemTime;
13
14#[derive(Clone, Debug, PartialEq, Eq)]
20pub enum ComponentStatus {
21 Ready,
23 Cached,
25 NotDownloaded,
27 Bundled,
30 Unsupported { reason: String },
32}
33
34pub struct ComponentManager {
35 cache: ArtifactCache,
36 target: String,
37 entries: HashMap<String, ComponentLockEntry>,
38 loaded: Mutex<HashMap<String, Arc<LoadedComponent>>>,
39 key_locks: Mutex<HashMap<String, Arc<Mutex<()>>>>,
44 verified_artifacts: Mutex<HashMap<String, CachedArtifact>>,
51 lock_is_empty: bool,
58 locked_digests: HashSet<String>,
61 host: AlefHostApiV1,
62 host_services: Option<Arc<dyn HostServices>>,
63}
64
65unsafe impl Send for ComponentManager {}
69unsafe impl Sync for ComponentManager {}
70
71impl ComponentManager {
72 pub fn from_lock(
73 lock: ComponentLock,
74 cache_root: impl Into<PathBuf>,
75 target: impl Into<String>,
76 host: AlefHostApiV1,
77 ) -> Result<Self, ComponentError> {
78 if lock.schema_version != COMPONENT_MANIFEST_SCHEMA {
79 return Err(ComponentError::UnsupportedLockSchema(lock.schema_version));
80 }
81 let lock_is_empty = lock.artifacts.is_empty();
82 let locked_digests = lock.artifacts.iter().map(|artifact| artifact.sha256.clone()).collect();
83 let target = target.into();
84 let mut entries = HashMap::new();
85 for artifact in lock
86 .artifacts
87 .into_iter()
88 .filter(|artifact| artifact.identity.target == target)
89 {
90 let id = artifact.identity.component.clone();
91 if entries.insert(id.clone(), artifact).is_some() {
92 return Err(ComponentError::DuplicateLockEntry {
93 component_id: id,
94 target,
95 });
96 }
97 }
98 Ok(Self {
99 cache: ArtifactCache::new(cache_root, TrustPolicy::EmbeddedKeys(lock.public_keys)),
100 target,
101 entries,
102 loaded: Mutex::new(HashMap::new()),
103 key_locks: Mutex::new(HashMap::new()),
104 verified_artifacts: Mutex::new(HashMap::new()),
105 lock_is_empty,
106 locked_digests,
107 host,
108 host_services: None,
109 })
110 }
111
112 #[must_use]
116 pub fn with_host_services(mut self, services: Arc<dyn HostServices>) -> Self {
117 self.host_services = Some(services);
118 self
119 }
120
121 #[must_use]
126 pub fn offline(mut self, offline: bool) -> Self {
127 self.cache = self.cache.offline(offline);
128 self
129 }
130
131 #[must_use]
134 pub fn with_download_options(mut self, options: DownloadOptions) -> Self {
135 self.cache = self.cache.with_download_options(options);
136 self
137 }
138
139 #[must_use]
149 pub fn with_url_override(
150 mut self,
151 resolve: impl Fn(&ComponentLockEntry) -> String + Send + Sync + 'static,
152 ) -> Self {
153 self.cache = self.cache.with_url_override(resolve);
154 self
155 }
156
157 #[must_use]
160 pub fn with_mirror_base(self, base: impl Into<String>) -> Self {
161 let base = base.into();
162 self.with_url_override(move |entry| {
163 let name = entry.url.split(['?', '#']).next().unwrap_or_default();
164 let name = name.rsplit('/').next().unwrap_or_default();
165 format!("{}/{name}", base.trim_end_matches('/'))
166 })
167 }
168
169 #[must_use]
172 pub fn with_verified_stamp(mut self, enabled: bool) -> Self {
173 self.cache = self.cache.with_verified_stamp(enabled);
174 self
175 }
176
177 pub fn lock_entry(&self, component_id: &str) -> Result<&ComponentLockEntry, ComponentError> {
179 self.lookup(component_id)
180 }
181
182 #[must_use]
184 pub fn lock_entries(&self) -> Vec<&ComponentLockEntry> {
185 let mut entries: Vec<_> = self.entries.values().collect();
186 entries.sort_by(|a, b| a.identity.component.cmp(&b.identity.component));
187 entries
188 }
189
190 pub fn list_cached(&self) -> Result<Vec<CachedObject>, ComponentError> {
193 let mut objects = self.cache.list_objects()?;
194 for object in &mut objects {
195 object.component = self
196 .entries
197 .values()
198 .find(|entry| entry.sha256 == object.sha256)
199 .map(|entry| entry.identity.component.clone());
200 }
201 Ok(objects)
202 }
203
204 pub fn remove(&self, component_id: &str) -> Result<RemovalReport, ComponentError> {
207 let entry = self.entry(component_id)?;
208 self.verified_artifacts
209 .lock()
210 .unwrap_or_else(PoisonError::into_inner)
211 .remove(&entry.sha256);
212 self.cache.remove_object(&entry.sha256)
213 }
214
215 pub fn prune(&self, retain: &Retain) -> Result<RemovalReport, ComponentError> {
219 let loaded = self.loaded.lock().unwrap_or_else(PoisonError::into_inner);
220 let protected: HashSet<String> = self
221 .entries
222 .values()
223 .filter(|entry| {
224 let prefix = format!("{}::", entry.identity.component);
225 loaded.keys().any(|key| key.starts_with(&prefix))
226 })
227 .map(|entry| entry.sha256.clone())
228 .collect();
229 drop(loaded);
230 let report = self
231 .cache
232 .prune_objects(retain, &self.locked_digests, &protected, SystemTime::now())?;
233 let mut verified = self.verified_artifacts.lock().unwrap_or_else(PoisonError::into_inner);
234 for path in &report.removed {
235 if let Some(name) = path.file_name().and_then(|name| name.to_str()) {
236 verified.remove(name);
237 }
238 }
239 Ok(report)
240 }
241
242 pub fn ensure_contract(
255 &self,
256 component_id: &str,
257 contract_name: &str,
258 entry_symbol: &[u8],
259 ) -> Result<Arc<LoadedComponent>, ComponentError> {
260 let cache_key = loaded_cache_key(component_id, contract_name);
261 if let Some(component) = self.loaded_component(&cache_key) {
262 return Ok(component);
263 }
264
265 let key_lock = self.contract_lock(cache_key.clone());
266 let _guard = key_lock.lock().unwrap_or_else(PoisonError::into_inner);
267 if let Some(component) = self.loaded_component(&cache_key) {
270 return Ok(component);
271 }
272
273 let entry = self.entry(component_id)?;
274 let requirements = contract_requirements(entry, contract_name)?;
275 let cached = self.cached_artifact(entry)?;
276 validate_manifest(&cached.manifest, &requirements)?;
277 let component = Arc::new(LoadedComponent::load_with_services(
278 cached.library,
279 entry_symbol,
280 &requirements,
281 self.host,
282 self.host_services.clone(),
283 )?);
284 self.insert_loaded(cache_key, Arc::clone(&component));
285 Ok(component)
286 }
287
288 pub fn prefetch(&self, component_ids: &[&str]) -> Result<Vec<CachedArtifact>, ComponentError> {
289 component_ids
290 .iter()
291 .map(|component_id| self.cached_artifact(self.entry(component_id)?))
292 .collect()
293 }
294
295 fn loaded_component(&self, cache_key: &str) -> Option<Arc<LoadedComponent>> {
296 self.loaded
297 .lock()
298 .unwrap_or_else(PoisonError::into_inner)
299 .get(cache_key)
300 .cloned()
301 }
302
303 fn insert_loaded(&self, cache_key: String, component: Arc<LoadedComponent>) {
304 self.loaded
305 .lock()
306 .unwrap_or_else(PoisonError::into_inner)
307 .insert(cache_key, component);
308 }
309
310 fn contract_lock(&self, cache_key: String) -> Arc<Mutex<()>> {
314 Arc::clone(
315 self.key_locks
316 .lock()
317 .unwrap_or_else(PoisonError::into_inner)
318 .entry(cache_key)
319 .or_insert_with(|| Arc::new(Mutex::new(()))),
320 )
321 }
322
323 fn cached_artifact(&self, entry: &ComponentLockEntry) -> Result<CachedArtifact, ComponentError> {
326 if let Some(cached) = self
327 .verified_artifacts
328 .lock()
329 .unwrap_or_else(PoisonError::into_inner)
330 .get(&entry.sha256)
331 .cloned()
332 {
333 return Ok(cached);
334 }
335 let cached = self.cache.install(entry)?;
336 self.verified_artifacts
337 .lock()
338 .unwrap_or_else(PoisonError::into_inner)
339 .insert(entry.sha256.clone(), cached.clone());
340 Ok(cached)
341 }
342
343 pub fn status(&self, component_id: &str) -> Result<ComponentStatus, ComponentError> {
348 let entry = self.lookup(component_id)?;
349 if entry.mode == ComponentDeliveryMode::Bundled {
350 return Ok(ComponentStatus::Bundled);
351 }
352 let loaded_prefix = format!("{component_id}::");
353 if self
354 .loaded
355 .lock()
356 .unwrap_or_else(PoisonError::into_inner)
357 .keys()
358 .any(|key| key.starts_with(&loaded_prefix))
359 {
360 return Ok(ComponentStatus::Ready);
361 }
362 let root = self.cache.object_path(entry)?;
363 if root.join("component.json").is_file() {
364 Ok(ComponentStatus::Cached)
365 } else {
366 Ok(ComponentStatus::NotDownloaded)
367 }
368 }
369
370 pub fn cache_path(&self, component_id: &str) -> Result<PathBuf, ComponentError> {
371 self.cache.object_path(self.entry(component_id)?)
372 }
373
374 #[must_use]
375 pub fn cache_root(&self) -> &Path {
376 self.cache.root()
377 }
378
379 #[must_use]
380 pub fn target(&self) -> &str {
381 &self.target
382 }
383
384 fn lookup(&self, component_id: &str) -> Result<&ComponentLockEntry, ComponentError> {
393 self.entries.get(component_id).ok_or_else(|| {
394 if self.lock_is_empty {
395 ComponentError::ComponentsNotLocked {
396 component_id: component_id.to_owned(),
397 }
398 } else {
399 ComponentError::ArtifactNotFound {
400 component_id: component_id.to_owned(),
401 target: self.target.clone(),
402 }
403 }
404 })
405 }
406
407 fn entry(&self, component_id: &str) -> Result<&ComponentLockEntry, ComponentError> {
412 let entry = self.lookup(component_id)?;
413 if entry.mode == ComponentDeliveryMode::Bundled {
414 return Err(ComponentError::BundledComponentNotLoadable {
415 component: component_id.to_owned(),
416 });
417 }
418 Ok(entry)
419 }
420}
421
422fn loaded_cache_key(component_id: &str, contract_name: &str) -> String {
423 format!("{component_id}::{contract_name}")
424}
425
426fn contract_requirements(
427 entry: &ComponentLockEntry,
428 contract_name: &str,
429) -> Result<ComponentRequirements, ComponentError> {
430 let provided = entry
431 .provides
432 .iter()
433 .find(|provided| provided.contract == contract_name)
434 .ok_or_else(|| ComponentError::ContractNotProvided {
435 component_id: entry.identity.component.clone(),
436 contract: contract_name.to_owned(),
437 })?;
438 Ok(ComponentRequirements {
439 component_id: entry.identity.component.clone(),
440 contract_name: contract_name.to_owned(),
441 contract_hash: decode_hash(&provided.contract_hash)?,
442 feature_set_hash: Some(decode_hash(&entry.identity.feature_hash)?),
443 })
444}
445
446#[cfg(test)]
447mod tests {
448 use super::*;
449 use crate::ComponentIdentity;
450 use std::collections::BTreeMap;
451
452 fn host() -> AlefHostApiV1 {
453 AlefHostApiV1 {
454 struct_size: 0,
455 abi_major: 0,
456 abi_minor: 0,
457 ..AlefHostApiV1::EMPTY
458 }
459 }
460
461 fn lock(target: &str) -> ComponentLock {
462 lock_with_mode(target, ComponentDeliveryMode::Download)
463 }
464
465 fn lock_with_mode(target: &str, mode: ComponentDeliveryMode) -> ComponentLock {
466 ComponentLock {
467 schema_version: COMPONENT_MANIFEST_SCHEMA,
468 public_keys: BTreeMap::new(),
469 artifacts: vec![ComponentLockEntry {
470 identity: ComponentIdentity {
471 crate_name: "demo-core".into(),
472 component: "demo".into(),
473 version: "1.0.0".into(),
474 target: target.into(),
475 feature_hash: hex::encode([2; 32]),
476 contract_hash: hex::encode([1; 32]),
477 },
478 provides: vec![crate::ComponentProvidedContract {
479 contract: "engine".into(),
480 interface_version: 1,
481 contract_hash: hex::encode([1; 32]),
482 implementation: "demo::Demo".into(),
483 }],
484 mode,
485 url: "file:///does/not/exist".into(),
486 sha256: hex::encode([3; 32]),
487 size: 0,
488 manifest_sha256: hex::encode([4; 32]),
489 key_id: String::new(),
490 }],
491 }
492 }
493
494 #[test]
495 fn bootstrap_empty_lock_reports_components_not_locked_instead_of_artifact_not_found() {
496 let dir = tempfile::tempdir().unwrap();
497 let empty = ComponentLock {
498 schema_version: COMPONENT_MANIFEST_SCHEMA,
499 public_keys: BTreeMap::new(),
500 artifacts: Vec::new(),
501 };
502 let manager = ComponentManager::from_lock(empty, dir.path(), "target-a", host()).unwrap();
503
504 assert!(matches!(
505 manager.status("demo"),
506 Err(ComponentError::ComponentsNotLocked { .. })
507 ));
508 assert!(matches!(
509 manager.ensure_contract("demo", "engine", b"irrelevant\0"),
510 Err(ComponentError::ComponentsNotLocked { .. })
511 ));
512 assert!(matches!(
513 manager.prefetch(&["demo"]),
514 Err(ComponentError::ComponentsNotLocked { .. })
515 ));
516 assert!(matches!(
517 manager.cache_path("demo"),
518 Err(ComponentError::ComponentsNotLocked { .. })
519 ));
520 }
521
522 #[test]
523 fn manager_filters_lock_to_exact_target() {
524 let dir = tempfile::tempdir().unwrap();
525 let manager = ComponentManager::from_lock(lock("target-a"), dir.path(), "target-b", host()).unwrap();
526 assert!(matches!(
527 manager.status("demo"),
528 Err(ComponentError::ArtifactNotFound { .. })
529 ));
530 }
531
532 #[test]
533 fn manager_reports_content_address_before_download() {
534 let dir = tempfile::tempdir().unwrap();
535 let manager = ComponentManager::from_lock(lock("target-a"), dir.path(), "target-a", host()).unwrap();
536 assert_eq!(manager.status("demo").unwrap(), ComponentStatus::NotDownloaded);
537 assert!(
538 manager
539 .cache_path("demo")
540 .unwrap()
541 .ends_with(format!("sha256/{}", hex::encode([3; 32])))
542 );
543 }
544
545 #[test]
546 fn duplicate_target_entry_is_rejected() {
547 let dir = tempfile::tempdir().unwrap();
548 let mut lock = lock("target-a");
549 lock.artifacts.push(lock.artifacts[0].clone());
550 assert!(matches!(
551 ComponentManager::from_lock(lock, dir.path(), "target-a", host()),
552 Err(ComponentError::DuplicateLockEntry { .. })
553 ));
554 }
555
556 #[test]
557 fn ensure_contract_rejects_a_contract_the_component_does_not_provide() {
558 let dir = tempfile::tempdir().unwrap();
559 let manager = ComponentManager::from_lock(lock("target-a"), dir.path(), "target-a", host()).unwrap();
560 assert!(matches!(
561 manager.ensure_contract("demo", "missing-contract", b"irrelevant\0"),
562 Err(ComponentError::ContractNotProvided { .. })
563 ));
564 }
565
566 #[test]
567 fn ensure_contract_reaches_the_download_step_for_a_provided_contract() {
568 let dir = tempfile::tempdir().unwrap();
569 let mut two_contracts = lock("target-a");
570 two_contracts.artifacts[0]
571 .provides
572 .push(crate::ComponentProvidedContract {
573 contract: "second".into(),
574 interface_version: 1,
575 contract_hash: hex::encode([9; 32]),
576 implementation: "demo::Second".into(),
577 });
578 let manager = ComponentManager::from_lock(two_contracts, dir.path(), "target-a", host()).unwrap();
579 assert!(matches!(
583 manager.ensure_contract("demo", "second", b"alef_component_entry_v1_second\0"),
584 Err(ComponentError::Io(_))
585 ));
586 }
587
588 #[test]
589 fn bundled_component_is_rejected_before_touching_the_cache() {
590 let dir = tempfile::tempdir().unwrap();
591 let manager = ComponentManager::from_lock(
592 lock_with_mode("target-a", ComponentDeliveryMode::Bundled),
593 dir.path(),
594 "target-a",
595 host(),
596 )
597 .unwrap();
598
599 assert!(matches!(
600 manager.ensure_contract("demo", "engine", b"alef_component_entry_v1_engine\0"),
601 Err(ComponentError::BundledComponentNotLoadable { .. })
602 ));
603 assert_eq!(manager.status("demo").unwrap(), ComponentStatus::Bundled);
607 assert!(matches!(
608 manager.prefetch(&["demo"]),
609 Err(ComponentError::BundledComponentNotLoadable { .. })
610 ));
611 assert!(matches!(
612 manager.cache_path("demo"),
613 Err(ComponentError::BundledComponentNotLoadable { .. })
614 ));
615 assert!(
616 std::fs::read_dir(dir.path()).unwrap().next().is_none(),
617 "a bundled component must never touch the cache directory"
618 );
619 }
620
621 #[test]
622 fn prefetch_reuses_an_already_verified_artifact_without_reinstalling() {
623 let dir = tempfile::tempdir().unwrap();
624 let manager = ComponentManager::from_lock(lock("target-a"), dir.path(), "target-a", host()).unwrap();
625 let entry = manager.entries.get("demo").unwrap().clone();
626
627 let fake = CachedArtifact {
628 root: dir.path().join("fake-root"),
629 library: dir.path().join("fake-root/libdemo.so"),
630 manifest: crate::ComponentManifest {
631 schema_version: COMPONENT_MANIFEST_SCHEMA,
632 abi_version: 1,
633 identity: entry.identity.clone(),
634 provides: entry.provides.clone(),
635 features: Vec::new(),
636 default_features: false,
637 library: crate::ComponentLibrary {
638 file: "libdemo.so".into(),
639 sha256: hex::encode([0; 32]),
640 size: 0,
641 },
642 },
643 };
644 manager
645 .verified_artifacts
646 .lock()
647 .unwrap()
648 .insert(entry.sha256.clone(), fake.clone());
649
650 let prefetched = manager.prefetch(&["demo"]).unwrap();
654 assert_eq!(prefetched, vec![fake]);
655 }
656
657 #[test]
658 fn lock_entry_exposes_version_digest_and_size() {
659 let dir = tempfile::tempdir().unwrap();
660 let manager = ComponentManager::from_lock(lock("target-a"), dir.path(), "target-a", host()).unwrap();
661 let entry = manager.lock_entry("demo").unwrap();
662 assert_eq!(entry.identity.version, "1.0.0");
663 assert_eq!(entry.sha256, hex::encode([3; 32]));
664 assert_eq!(manager.lock_entries().len(), 1);
665 assert!(matches!(
666 manager.lock_entry("missing"),
667 Err(ComponentError::ArtifactNotFound { .. })
668 ));
669 }
670
671 #[test]
672 fn list_remove_and_prune_operate_on_the_cache() {
673 let dir = tempfile::tempdir().unwrap();
674 let manager = ComponentManager::from_lock(lock("target-a"), dir.path(), "target-a", host()).unwrap();
675 let ours = dir.path().join("sha256").join(hex::encode([3; 32]));
676 let foreign = dir.path().join("sha256").join(hex::encode([7; 32]));
677 for path in [&ours, &foreign] {
678 std::fs::create_dir_all(path).unwrap();
679 std::fs::write(path.join("component.json"), b"{}").unwrap();
680 }
681
682 let listed = manager.list_cached().unwrap();
683 assert_eq!(listed.len(), 2);
684 let named: Vec<_> = listed.iter().filter_map(|object| object.component.as_deref()).collect();
685 assert_eq!(named, vec!["demo"]);
686
687 let report = manager.prune(&Retain::new().referenced_by_lock()).unwrap();
688 assert_eq!(report.removed, vec![foreign.clone()]);
689 assert!(ours.exists() && !foreign.exists());
690
691 let report = manager.remove("demo").unwrap();
692 assert_eq!(report.removed, vec![ours.clone()]);
693 assert_eq!(manager.status("demo").unwrap(), ComponentStatus::NotDownloaded);
694 }
695
696 #[test]
697 fn mirror_base_keeps_only_the_archive_file_name() {
698 let dir = tempfile::tempdir().unwrap();
699 let mut remote = lock("target-a");
700 remote.artifacts[0].url = "https://origin.example/dl/demo-1.0.0.tar.gz?token=1".into();
701 let manager = ComponentManager::from_lock(remote, dir.path(), "target-a", host())
702 .unwrap()
703 .offline(true)
704 .with_mirror_base("https://mirror.example/components/");
705
706 let error = manager.prefetch(&["demo"]).unwrap_err();
707
708 assert!(matches!(
709 error,
710 ComponentError::Offline { ref url, .. }
711 if url == "https://mirror.example/components/demo-1.0.0.tar.gz"
712 ));
713 }
714
715 #[test]
716 fn contract_lock_coalesces_the_same_key_and_separates_different_keys() {
717 let dir = tempfile::tempdir().unwrap();
718 let manager = ComponentManager::from_lock(lock("target-a"), dir.path(), "target-a", host()).unwrap();
719
720 let first = manager.contract_lock("demo::engine".to_string());
721 let second = manager.contract_lock("demo::engine".to_string());
722 assert!(
723 Arc::ptr_eq(&first, &second),
724 "the same (component, contract) key must coalesce onto one lock"
725 );
726
727 let unrelated = manager.contract_lock("other::engine".to_string());
728 assert!(
729 !Arc::ptr_eq(&first, &unrelated),
730 "an unrelated key must get its own lock so it is never blocked by a different key"
731 );
732 }
733
734 #[test]
735 fn concurrent_calls_for_the_same_key_serialize_on_the_coalescing_lock() {
736 use std::sync::Barrier;
737 use std::thread;
738
739 let dir = tempfile::tempdir().unwrap();
740 let manager = Arc::new(ComponentManager::from_lock(lock("target-a"), dir.path(), "target-a", host()).unwrap());
741 let order = Arc::new(Mutex::new(Vec::new()));
742 let ready = Arc::new(Barrier::new(2));
743
744 let held = manager.contract_lock("demo::engine".to_string());
749 let guard = held.lock().unwrap();
750
751 let waiter = {
752 let manager = Arc::clone(&manager);
753 let order = Arc::clone(&order);
754 let ready = Arc::clone(&ready);
755 thread::spawn(move || {
756 ready.wait();
757 let _ = manager.ensure_contract("demo", "engine", b"alef_component_entry_v1_engine\0");
758 order.lock().unwrap().push("waiter");
759 })
760 };
761
762 ready.wait();
763 thread::sleep(std::time::Duration::from_millis(50));
764 assert!(
765 order.lock().unwrap().is_empty(),
766 "a concurrent call for the same key must not proceed while the lock is held"
767 );
768 order.lock().unwrap().push("holder");
769 drop(guard);
770
771 waiter.join().unwrap();
772 assert_eq!(*order.lock().unwrap(), vec!["holder", "waiter"]);
773 }
774}