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