Skip to main content

alef_component_runtime/
manager.rs

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/// Where a configured component currently stands, independent of its on-disk location (see
15/// [`ComponentManager::cache_path`] for that). Generated bindings expose this as both a
16/// stable string tag and a numeric code (`alef_component_status`/`alef_component_status_code`
17/// in `alef::backends::native_components`) so callers in any host language can branch on it
18/// without parsing free-form text.
19#[derive(Clone, Debug, PartialEq, Eq)]
20pub enum ComponentStatus {
21    /// Loaded and its contracts activated in this process.
22    Ready,
23    /// Downloaded and verified on disk, but not yet loaded in this process.
24    Cached,
25    /// Not yet present in the on-disk cache.
26    NotDownloaded,
27    /// Linked into the binding ahead of time for this target; never downloaded or loaded
28    /// through this manager.
29    Bundled,
30    /// This host/target does not support downloading native components at all.
31    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    /// One lock per (component, contract) key, used to coalesce concurrent `ensure_contract`
40    /// calls for the same key onto a single download-and-load instead of racing duplicates;
41    /// a call for a different key gets its own lock and proceeds independently. See
42    /// [`Self::contract_lock`].
43    key_locks: Mutex<HashMap<String, Arc<Mutex<()>>>>,
44    /// Artifacts this process has already installed and verified, keyed by the lock entry's
45    /// own content-addressed `sha256` digest. A component that provides more than one
46    /// contract shares one artifact across several `ensure_contract` calls; without this, each
47    /// call would re-read and re-hash the same (potentially large) dylib. On-disk tampering
48    /// with an artifact after this process has verified it once is out of scope: entries here
49    /// are trusted for the rest of the process, not re-checked against the disk.
50    verified_artifacts: Mutex<HashMap<String, CachedArtifact>>,
51    /// Whether the lock this manager was built from had zero artifacts *before* target
52    /// filtering -- the shape `alef generate` bootstraps when a crate declares components but
53    /// `alef component lock` has never run (see
54    /// `alef::bin_cli::component_commands::bootstrap_missing_component_locks`). Distinguished
55    /// from "no artifact for this particular target", which is a normal, populated lock that
56    /// simply was not built for the requested target.
57    lock_is_empty: bool,
58    /// Archive digests of every artifact in the lock, across all targets; what
59    /// [`Retain::referenced_by_lock`] keeps.
60    locked_digests: HashSet<String>,
61    host: AlefHostApiV1,
62    host_services: Option<Arc<dyn HostServices>>,
63}
64
65// SAFETY: `LoadedComponent` is thread-safe metadata and the host callback
66// context is required by the ABI to remain valid for calls from component
67// threads. Mutation is protected by the manager mutex. ~keep
68unsafe 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    /// Expose `services` to components loaded from now on, through the host table's
113    /// `service_call` / `service_notify` callbacks. Components already loaded keep the table
114    /// they were created with, so call this before [`Self::ensure_contract`].
115    #[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    /// Disable network downloads: [`Self::ensure_contract`] and [`Self::prefetch`] fail a
122    /// missing artifact with [`ComponentError::Offline`] instead of attempting a request. An
123    /// artifact already cached on disk is unaffected. Generated bindings call this when the
124    /// crate-specific `{CRATE}_COMPONENT_OFFLINE` environment variable is set.
125    #[must_use]
126    pub fn offline(mut self, offline: bool) -> Self {
127        self.cache = self.cache.offline(offline);
128        self
129    }
130
131    /// Tune downloads: timeouts, retry policy, progress reporting and cancellation. Applies to
132    /// [`Self::ensure_contract`] and [`Self::prefetch`].
133    #[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    /// Download from `resolve(entry)` instead of the lock entry's `url`, for mirrors and
140    /// air-gapped hosts. The archive size, SHA-256 and signature are still checked against the
141    /// lock, so a mirror cannot substitute different content. A `file://` URL reads from disk.
142    ///
143    /// ```ignore
144    /// let manager = manager.with_url_override(|entry| {
145    ///     entry.url.replacen("https://github.com/", "https://mirror.corp.example/github/", 1)
146    /// });
147    /// ```
148    #[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    /// Download every archive from `base` instead of the lock's URL, keeping only the archive
158    /// file name: `{base}/{file name}`. A trailing slash on `base` is ignored.
159    #[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    /// Skip re-hashing installed libraries that match their verified stamp. See
170    /// [`ArtifactCache::with_verified_stamp`] for the threat model.
171    #[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    /// The lock entry for `component_id` on this manager's target, whatever its delivery mode.
178    pub fn lock_entry(&self, component_id: &str) -> Result<&ComponentLockEntry, ComponentError> {
179        self.lookup(component_id)
180    }
181
182    /// Every lock entry for this manager's target, sorted by component id.
183    #[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    /// Every object installed in the cache, including ones other host versions installed.
191    /// `component` names the lock entry referencing the object, when this lock has one.
192    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    /// Remove `component_id`'s cached object. It re-downloads on next use. On Windows an
205    /// object whose library is loaded cannot be deleted; it is reported under `skipped`.
206    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    /// Remove cached objects `retain` does not keep, plus orphaned `.install-*` staging
216    /// directories and stale `.lock` files. Objects loaded in this process are skipped, as are
217    /// files Windows refuses to delete; both are listed in the report.
218    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    /// Load one contract a component provides.
243    ///
244    /// `entry_symbol` is that contract's NUL-terminated producer entry-point
245    /// symbol (`alef::codegen::component::entry_point_symbol`); the caller
246    /// supplies it because computing it requires the same identifier-casing
247    /// logic the producer used, which this crate does not depend on.
248    ///
249    /// Concurrent calls for the *same* `(component_id, contract_name)` coalesce onto one
250    /// download-and-load: a second caller waits behind the first instead of racing a
251    /// duplicate download or `dlopen`. A call for a different key is unaffected and proceeds
252    /// immediately -- the mutex guarding the loaded-component map is only ever held for a
253    /// map lookup or insert, never across I/O.
254    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        // Re-check now that this call holds the per-key lock: a concurrent caller for the
268        // same key may have finished the work while this call was waiting for it.
269        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    /// The per-`cache_key` lock used to coalesce concurrent [`Self::ensure_contract`] calls.
311    /// The outer `key_locks` mutex is only ever held for the lookup-or-insert below, never
312    /// across the download/load work the returned lock guards.
313    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    /// Install `entry`'s artifact, reusing an in-process-verified copy when this process has
324    /// already installed it (see [`Self::verified_artifacts`]).
325    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    /// Report where `component_id` currently stands. Unlike [`Self::ensure_contract`],
344    /// [`Self::prefetch`], and [`Self::cache_path`], a `Bundled` entry is a legitimate answer
345    /// here rather than a failure: it is this manager's way of saying "linked in ahead of
346    /// time, never downloaded or loaded through me", not an error.
347    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    /// Look up a component's lock entry for this manager's target, with no restriction on
385    /// its delivery mode. [`Self::status`] uses this directly since a `Bundled` entry is a
386    /// legitimate status to report, not a failure.
387    ///
388    /// A miss against a lock that was empty before target filtering reports
389    /// [`ComponentError::ComponentsNotLocked`] instead of the generic
390    /// [`ComponentError::ArtifactNotFound`]: `alef component lock` has never populated it, so
391    /// naming the fix is more useful than reporting a missing target.
392    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    /// Like [`Self::lookup`], but additionally rejects a `Bundled` entry -- one this manager
408    /// cannot download -- before any cache I/O runs. Every caller that actually needs to
409    /// touch the cache (`ensure_contract`, `prefetch`, `cache_path`) reaches it only through
410    /// this method.
411    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        // Fails to find the library at the fake `file://` URL -- proving contract resolution
580        // for "second" succeeded and the manager reached the download step, not that the
581        // download itself succeeded.
582        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        // Unlike `ensure_contract`/`prefetch`/`cache_path`, `status` reports `Bundled` as a
604        // legitimate answer rather than failing: this manager genuinely cannot download or
605        // load the component, and that is exactly what the status says.
606        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        // The lock entry's URL points nowhere real (`file:///does/not/exist`, see `lock()`),
651        // so this call would fail if it attempted to actually install/verify the artifact;
652        // succeeding proves it reused the in-process cache instead.
653        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        // Hold the coalescing lock as a stand-in for an in-progress download, then prove a
745        // concurrent request for the *same* key really does wait for it: `order` only ever
746        // records the second entry-point-symbol lookup after the first thread has both run
747        // and released the lock, never interleaved with it.
748        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}