Skip to main content

alef_component_runtime/
manager.rs

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/// Where a configured component currently stands, independent of its on-disk location (see
16/// [`ComponentManager::cache_path`] for that). Generated bindings expose this as both a
17/// stable string tag and a numeric code (`alef_component_status`/`alef_component_status_code`
18/// in `alef::backends::native_components`) so callers in any host language can branch on it
19/// without parsing free-form text.
20#[derive(Clone, Debug, PartialEq, Eq)]
21pub enum ComponentStatus {
22    /// Loaded and its contracts activated in this process.
23    Ready,
24    /// Downloaded and verified on disk, but not yet loaded in this process.
25    Cached,
26    /// Not yet present in the on-disk cache.
27    NotDownloaded,
28    /// Linked into the binding ahead of time for this target; never downloaded or loaded
29    /// through this manager.
30    Bundled,
31    /// This host/target does not support downloading native components at all.
32    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    /// One lock per (component, contract) key, used to coalesce concurrent `ensure_contract`
44    /// calls for the same key onto a single download-and-load instead of racing duplicates;
45    /// a call for a different key gets its own lock and proceeds independently. See
46    /// [`Self::contract_lock`].
47    key_locks: Mutex<HashMap<String, Arc<Mutex<()>>>>,
48    /// Artifacts this process has already installed and verified, keyed by the lock entry's
49    /// own content-addressed `sha256` digest. A component that provides more than one
50    /// contract shares one artifact across several `ensure_contract` calls; without this, each
51    /// call would re-read and re-hash the same (potentially large) dylib. On-disk tampering
52    /// with an artifact after this process has verified it once is out of scope: entries here
53    /// are trusted for the rest of the process, not re-checked against the disk.
54    verified_artifacts: Mutex<HashMap<String, CachedArtifact>>,
55    /// Whether the lock this manager was built from had zero artifacts *before* target
56    /// filtering -- the shape `alef generate` bootstraps when a crate declares components but
57    /// `alef component lock` has never run (see
58    /// `alef::bin_cli::component_commands::bootstrap_missing_component_locks`). Distinguished
59    /// from "no artifact for this particular target", which is a normal, populated lock that
60    /// simply was not built for the requested target.
61    lock_is_empty: bool,
62    /// Archive digests of every artifact in the lock, across all targets; what
63    /// [`Retain::referenced_by_lock`] keeps.
64    locked_digests: HashSet<String>,
65    host: AlefHostApiV1,
66    host_services: Option<Arc<dyn HostServices>>,
67}
68
69// SAFETY: `LoadedComponent` is thread-safe metadata and the host callback
70// context is required by the ABI to remain valid for calls from component
71// threads. Mutation is protected by the manager mutex. ~keep
72unsafe 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    /// Select the framed stdio transport for an executable component before first use.
120    ///
121    /// The artifact, signature, lock and cache contract are identical to native components.
122    /// All contracts of this component share one long-lived process. Only bytes invocation
123    /// is supported; generated typed C tables and host callback services are unavailable.
124    #[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    /// Set the response deadline for stdio handshakes and calls (default: 30 seconds).
131    /// A timeout terminates the child and permanently invalidates that connection.
132    #[must_use]
133    pub fn with_sidecar_timeout(mut self, timeout: Duration) -> Self {
134        self.sidecar_timeout = timeout;
135        self
136    }
137
138    /// Expose `services` to components loaded from now on, through the host table's
139    /// `service_call` / `service_notify` callbacks. Components already loaded keep the table
140    /// they were created with, so call this before [`Self::ensure_contract`].
141    #[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    /// Disable network downloads: [`Self::ensure_contract`] and [`Self::prefetch`] fail a
148    /// missing artifact with [`ComponentError::Offline`] instead of attempting a request. An
149    /// artifact already cached on disk is unaffected. Generated bindings call this when the
150    /// crate-specific `{CRATE}_COMPONENT_OFFLINE` environment variable is set.
151    #[must_use]
152    pub fn offline(mut self, offline: bool) -> Self {
153        self.cache = self.cache.offline(offline);
154        self
155    }
156
157    /// Tune downloads: timeouts, retry policy, progress reporting and cancellation. Applies to
158    /// [`Self::ensure_contract`] and [`Self::prefetch`].
159    #[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    /// Download from `resolve(entry)` instead of the lock entry's `url`, for mirrors and
166    /// air-gapped hosts. The archive size, SHA-256 and signature are still checked against the
167    /// lock, so a mirror cannot substitute different content. A `file://` URL reads from disk.
168    ///
169    /// ```ignore
170    /// let manager = manager.with_url_override(|entry| {
171    ///     entry.url.replacen("https://github.com/", "https://mirror.corp.example/github/", 1)
172    /// });
173    /// ```
174    #[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    /// Download every archive from `base` instead of the lock's URL, keeping only the archive
184    /// file name: `{base}/{file name}`. A trailing slash on `base` is ignored.
185    #[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    /// Skip re-hashing installed libraries that match their verified stamp. See
196    /// [`ArtifactCache::with_verified_stamp`] for the threat model.
197    #[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    /// The lock entry for `component_id` on this manager's target, whatever its delivery mode.
204    pub fn lock_entry(&self, component_id: &str) -> Result<&ComponentLockEntry, ComponentError> {
205        self.lookup(component_id)
206    }
207
208    /// Every lock entry for this manager's target, sorted by component id.
209    #[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    /// Every object installed in the cache, including ones other host versions installed.
217    /// `component` names the lock entry referencing the object, when this lock has one.
218    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    /// Remove `component_id`'s cached object. It re-downloads on next use. On Windows an
231    /// object whose library is loaded cannot be deleted; it is reported under `skipped`.
232    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    /// Remove cached objects `retain` does not keep, plus orphaned `.install-*` staging
242    /// directories and stale `.lock` files. Objects loaded in this process are skipped, as are
243    /// files Windows refuses to delete; both are listed in the report.
244    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    /// Load one contract a component provides.
269    ///
270    /// `entry_symbol` is that contract's NUL-terminated producer entry-point
271    /// symbol (`alef::codegen::component::entry_point_symbol`); the caller
272    /// supplies it because computing it requires the same identifier-casing
273    /// logic the producer used, which this crate does not depend on.
274    ///
275    /// Concurrent calls for the *same* `(component_id, contract_name)` coalesce onto one
276    /// download-and-load: a second caller waits behind the first instead of racing a
277    /// duplicate download or `dlopen`. A call for a different key is unaffected and proceeds
278    /// immediately -- the mutex guarding the loaded-component map is only ever held for a
279    /// map lookup or insert, never across I/O.
280    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        // Re-check now that this call holds the per-key lock: a concurrent caller for the
295        // same key may have finished the work while this call was waiting for it.
296        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    /// The per-`cache_key` lock used to coalesce concurrent [`Self::ensure_contract`] calls.
372    /// The outer `key_locks` mutex is only ever held for the lookup-or-insert below, never
373    /// across the download/load work the returned lock guards.
374    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    /// Install `entry`'s artifact, reusing an in-process-verified copy when this process has
385    /// already installed it (see [`Self::verified_artifacts`]).
386    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    /// Report where `component_id` currently stands. Unlike [`Self::ensure_contract`],
405    /// [`Self::prefetch`], and [`Self::cache_path`], a `Bundled` entry is a legitimate answer
406    /// here rather than a failure: it is this manager's way of saying "linked in ahead of
407    /// time, never downloaded or loaded through me", not an error.
408    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    /// Look up a component's lock entry for this manager's target, with no restriction on
446    /// its delivery mode. [`Self::status`] uses this directly since a `Bundled` entry is a
447    /// legitimate status to report, not a failure.
448    ///
449    /// A miss against a lock that was empty before target filtering reports
450    /// [`ComponentError::ComponentsNotLocked`] instead of the generic
451    /// [`ComponentError::ArtifactNotFound`]: `alef component lock` has never populated it, so
452    /// naming the fix is more useful than reporting a missing target.
453    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    /// Like [`Self::lookup`], but additionally rejects a `Bundled` entry -- one this manager
469    /// cannot download -- before any cache I/O runs. Every caller that actually needs to
470    /// touch the cache (`ensure_contract`, `prefetch`, `cache_path`) reaches it only through
471    /// this method.
472    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                input_hash: None,
552            }],
553        }
554    }
555
556    #[test]
557    fn bootstrap_empty_lock_reports_components_not_locked_instead_of_artifact_not_found() {
558        let dir = tempfile::tempdir().unwrap();
559        let empty = ComponentLock {
560            schema_version: COMPONENT_MANIFEST_SCHEMA,
561            public_keys: BTreeMap::new(),
562            artifacts: Vec::new(),
563        };
564        let manager = ComponentManager::from_lock(empty, dir.path(), "target-a", host()).unwrap();
565
566        assert!(matches!(
567            manager.status("demo"),
568            Err(ComponentError::ComponentsNotLocked { .. })
569        ));
570        assert!(matches!(
571            manager.ensure_contract("demo", "engine", b"irrelevant\0"),
572            Err(ComponentError::ComponentsNotLocked { .. })
573        ));
574        assert!(matches!(
575            manager.prefetch(&["demo"]),
576            Err(ComponentError::ComponentsNotLocked { .. })
577        ));
578        assert!(matches!(
579            manager.cache_path("demo"),
580            Err(ComponentError::ComponentsNotLocked { .. })
581        ));
582    }
583
584    #[test]
585    fn manager_filters_lock_to_exact_target() {
586        let dir = tempfile::tempdir().unwrap();
587        let manager = ComponentManager::from_lock(lock("target-a"), dir.path(), "target-b", host()).unwrap();
588        assert!(matches!(
589            manager.status("demo"),
590            Err(ComponentError::ArtifactNotFound { .. })
591        ));
592    }
593
594    #[test]
595    fn manager_reports_content_address_before_download() {
596        let dir = tempfile::tempdir().unwrap();
597        let manager = ComponentManager::from_lock(lock("target-a"), dir.path(), "target-a", host()).unwrap();
598        assert_eq!(manager.status("demo").unwrap(), ComponentStatus::NotDownloaded);
599        assert!(
600            manager
601                .cache_path("demo")
602                .unwrap()
603                .ends_with(format!("sha256/{}", hex::encode([3; 32])))
604        );
605    }
606
607    #[test]
608    fn duplicate_target_entry_is_rejected() {
609        let dir = tempfile::tempdir().unwrap();
610        let mut lock = lock("target-a");
611        lock.artifacts.push(lock.artifacts[0].clone());
612        assert!(matches!(
613            ComponentManager::from_lock(lock, dir.path(), "target-a", host()),
614            Err(ComponentError::DuplicateLockEntry { .. })
615        ));
616    }
617
618    #[test]
619    fn ensure_contract_rejects_a_contract_the_component_does_not_provide() {
620        let dir = tempfile::tempdir().unwrap();
621        let manager = ComponentManager::from_lock(lock("target-a"), dir.path(), "target-a", host()).unwrap();
622        assert!(matches!(
623            manager.ensure_contract("demo", "missing-contract", b"irrelevant\0"),
624            Err(ComponentError::ContractNotProvided { .. })
625        ));
626    }
627
628    #[test]
629    fn ensure_contract_reaches_the_download_step_for_a_provided_contract() {
630        let dir = tempfile::tempdir().unwrap();
631        let mut two_contracts = lock("target-a");
632        two_contracts.artifacts[0]
633            .provides
634            .push(crate::ComponentProvidedContract {
635                contract: "second".into(),
636                interface_version: 1,
637                contract_hash: hex::encode([9; 32]),
638                implementation: "demo::Second".into(),
639            });
640        let manager = ComponentManager::from_lock(two_contracts, dir.path(), "target-a", host()).unwrap();
641        // Fails to find the library at the fake `file://` URL -- proving contract resolution
642        // for "second" succeeded and the manager reached the download step, not that the
643        // download itself succeeded.
644        assert!(matches!(
645            manager.ensure_contract("demo", "second", b"alef_component_entry_v1_second\0"),
646            Err(ComponentError::Io(_))
647        ));
648    }
649
650    #[test]
651    fn bundled_component_is_rejected_before_touching_the_cache() {
652        let dir = tempfile::tempdir().unwrap();
653        let manager = ComponentManager::from_lock(
654            lock_with_mode("target-a", ComponentDeliveryMode::Bundled),
655            dir.path(),
656            "target-a",
657            host(),
658        )
659        .unwrap();
660
661        assert!(matches!(
662            manager.ensure_contract("demo", "engine", b"alef_component_entry_v1_engine\0"),
663            Err(ComponentError::BundledComponentNotLoadable { .. })
664        ));
665        // Unlike `ensure_contract`/`prefetch`/`cache_path`, `status` reports `Bundled` as a
666        // legitimate answer rather than failing: this manager genuinely cannot download or
667        // load the component, and that is exactly what the status says.
668        assert_eq!(manager.status("demo").unwrap(), ComponentStatus::Bundled);
669        assert!(matches!(
670            manager.prefetch(&["demo"]),
671            Err(ComponentError::BundledComponentNotLoadable { .. })
672        ));
673        assert!(matches!(
674            manager.cache_path("demo"),
675            Err(ComponentError::BundledComponentNotLoadable { .. })
676        ));
677        assert!(
678            std::fs::read_dir(dir.path()).unwrap().next().is_none(),
679            "a bundled component must never touch the cache directory"
680        );
681    }
682
683    #[test]
684    fn prefetch_reuses_an_already_verified_artifact_without_reinstalling() {
685        let dir = tempfile::tempdir().unwrap();
686        let manager = ComponentManager::from_lock(lock("target-a"), dir.path(), "target-a", host()).unwrap();
687        let entry = manager.entries.get("demo").unwrap().clone();
688
689        let fake = CachedArtifact {
690            root: dir.path().join("fake-root"),
691            library: dir.path().join("fake-root/libdemo.so"),
692            manifest: crate::ComponentManifest {
693                schema_version: COMPONENT_MANIFEST_SCHEMA,
694                abi_version: 1,
695                identity: entry.identity.clone(),
696                provides: entry.provides.clone(),
697                features: Vec::new(),
698                default_features: false,
699                library: crate::ComponentLibrary {
700                    file: "libdemo.so".into(),
701                    sha256: hex::encode([0; 32]),
702                    size: 0,
703                },
704            },
705        };
706        manager
707            .verified_artifacts
708            .lock()
709            .unwrap()
710            .insert(entry.sha256.clone(), fake.clone());
711
712        // The lock entry's URL points nowhere real (`file:///does/not/exist`, see `lock()`),
713        // so this call would fail if it attempted to actually install/verify the artifact;
714        // succeeding proves it reused the in-process cache instead.
715        let prefetched = manager.prefetch(&["demo"]).unwrap();
716        assert_eq!(prefetched, vec![fake]);
717    }
718
719    #[test]
720    fn lock_entry_exposes_version_digest_and_size() {
721        let dir = tempfile::tempdir().unwrap();
722        let manager = ComponentManager::from_lock(lock("target-a"), dir.path(), "target-a", host()).unwrap();
723        let entry = manager.lock_entry("demo").unwrap();
724        assert_eq!(entry.identity.version, "1.0.0");
725        assert_eq!(entry.sha256, hex::encode([3; 32]));
726        assert_eq!(manager.lock_entries().len(), 1);
727        assert!(matches!(
728            manager.lock_entry("missing"),
729            Err(ComponentError::ArtifactNotFound { .. })
730        ));
731    }
732
733    #[test]
734    fn list_remove_and_prune_operate_on_the_cache() {
735        let dir = tempfile::tempdir().unwrap();
736        let manager = ComponentManager::from_lock(lock("target-a"), dir.path(), "target-a", host()).unwrap();
737        let ours = dir.path().join("sha256").join(hex::encode([3; 32]));
738        let foreign = dir.path().join("sha256").join(hex::encode([7; 32]));
739        for path in [&ours, &foreign] {
740            std::fs::create_dir_all(path).unwrap();
741            std::fs::write(path.join("component.json"), b"{}").unwrap();
742        }
743
744        let listed = manager.list_cached().unwrap();
745        assert_eq!(listed.len(), 2);
746        let named: Vec<_> = listed.iter().filter_map(|object| object.component.as_deref()).collect();
747        assert_eq!(named, vec!["demo"]);
748
749        let report = manager.prune(&Retain::new().referenced_by_lock()).unwrap();
750        assert_eq!(report.removed, vec![foreign.clone()]);
751        assert!(ours.exists() && !foreign.exists());
752
753        let report = manager.remove("demo").unwrap();
754        assert_eq!(report.removed, vec![ours.clone()]);
755        assert_eq!(manager.status("demo").unwrap(), ComponentStatus::NotDownloaded);
756    }
757
758    #[test]
759    fn mirror_base_keeps_only_the_archive_file_name() {
760        let dir = tempfile::tempdir().unwrap();
761        let mut remote = lock("target-a");
762        remote.artifacts[0].url = "https://origin.example/dl/demo-1.0.0.tar.gz?token=1".into();
763        let manager = ComponentManager::from_lock(remote, dir.path(), "target-a", host())
764            .unwrap()
765            .offline(true)
766            .with_mirror_base("https://mirror.example/components/");
767
768        let error = manager.prefetch(&["demo"]).unwrap_err();
769
770        assert!(matches!(
771            error,
772            ComponentError::Offline { ref url, .. }
773                if url == "https://mirror.example/components/demo-1.0.0.tar.gz"
774        ));
775    }
776
777    #[test]
778    fn contract_lock_coalesces_the_same_key_and_separates_different_keys() {
779        let dir = tempfile::tempdir().unwrap();
780        let manager = ComponentManager::from_lock(lock("target-a"), dir.path(), "target-a", host()).unwrap();
781
782        let first = manager.contract_lock("demo::engine".to_string());
783        let second = manager.contract_lock("demo::engine".to_string());
784        assert!(
785            Arc::ptr_eq(&first, &second),
786            "the same (component, contract) key must coalesce onto one lock"
787        );
788
789        let unrelated = manager.contract_lock("other::engine".to_string());
790        assert!(
791            !Arc::ptr_eq(&first, &unrelated),
792            "an unrelated key must get its own lock so it is never blocked by a different key"
793        );
794    }
795
796    #[test]
797    fn concurrent_calls_for_the_same_key_serialize_on_the_coalescing_lock() {
798        use std::sync::Barrier;
799        use std::thread;
800
801        let dir = tempfile::tempdir().unwrap();
802        let manager = Arc::new(ComponentManager::from_lock(lock("target-a"), dir.path(), "target-a", host()).unwrap());
803        let order = Arc::new(Mutex::new(Vec::new()));
804        let ready = Arc::new(Barrier::new(2));
805
806        // Hold the coalescing lock as a stand-in for an in-progress download, then prove a
807        // concurrent request for the *same* key really does wait for it: `order` only ever
808        // records the second entry-point-symbol lookup after the first thread has both run
809        // and released the lock, never interleaved with it.
810        let held = manager.contract_lock("demo::engine".to_string());
811        let guard = held.lock().unwrap();
812
813        let waiter = {
814            let manager = Arc::clone(&manager);
815            let order = Arc::clone(&order);
816            let ready = Arc::clone(&ready);
817            thread::spawn(move || {
818                ready.wait();
819                let _ = manager.ensure_contract("demo", "engine", b"alef_component_entry_v1_engine\0");
820                order.lock().unwrap().push("waiter");
821            })
822        };
823
824        ready.wait();
825        thread::sleep(std::time::Duration::from_millis(50));
826        assert!(
827            order.lock().unwrap().is_empty(),
828            "a concurrent call for the same key must not proceed while the lock is held"
829        );
830        order.lock().unwrap().push("holder");
831        drop(guard);
832
833        waiter.join().unwrap();
834        assert_eq!(*order.lock().unwrap(), vec!["holder", "waiter"]);
835    }
836}