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::{SidecarPolicy, SidecarProcess, SidecarRestartEvent, SidecarSessionSetup};
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    /// Respawn knobs for stdio connections: the restart budget, the session setup replayed after
44    /// every spawn and respawn, and the restart event handler. Applied to every stdio component
45    /// this manager spawns; see the `with_sidecar_*` builders.
46    sidecar_policy: SidecarPolicy,
47    /// One lock per (component, contract) key, used to coalesce concurrent `ensure_contract`
48    /// calls for the same key onto a single download-and-load instead of racing duplicates;
49    /// a call for a different key gets its own lock and proceeds independently. See
50    /// [`Self::contract_lock`].
51    key_locks: Mutex<HashMap<String, Arc<Mutex<()>>>>,
52    /// Artifacts this process has already installed and verified, keyed by the lock entry's
53    /// own content-addressed `sha256` digest. A component that provides more than one
54    /// contract shares one artifact across several `ensure_contract` calls; without this, each
55    /// call would re-read and re-hash the same (potentially large) dylib. On-disk tampering
56    /// with an artifact after this process has verified it once is out of scope: entries here
57    /// are trusted for the rest of the process, not re-checked against the disk.
58    verified_artifacts: Mutex<HashMap<String, CachedArtifact>>,
59    /// Whether the lock this manager was built from had zero artifacts *before* target
60    /// filtering -- the shape `alef generate` bootstraps when a crate declares components but
61    /// `alef component lock` has never run (see
62    /// `alef::bin_cli::component_commands::bootstrap_missing_component_locks`). Distinguished
63    /// from "no artifact for this particular target", which is a normal, populated lock that
64    /// simply was not built for the requested target.
65    lock_is_empty: bool,
66    /// Archive digests of every artifact in the lock, across all targets; what
67    /// [`Retain::referenced_by_lock`] keeps.
68    locked_digests: HashSet<String>,
69    host: AlefHostApiV1,
70    host_services: Option<Arc<dyn HostServices>>,
71}
72
73// SAFETY: `LoadedComponent` is thread-safe metadata and the host callback
74// context is required by the ABI to remain valid for calls from component
75// threads. Mutation is protected by the manager mutex. ~keep
76unsafe impl Send for ComponentManager {}
77unsafe impl Sync for ComponentManager {}
78
79impl ComponentManager {
80    pub fn from_lock(
81        lock: ComponentLock,
82        cache_root: impl Into<PathBuf>,
83        target: impl Into<String>,
84        host: AlefHostApiV1,
85    ) -> Result<Self, ComponentError> {
86        if lock.schema_version != COMPONENT_MANIFEST_SCHEMA {
87            return Err(ComponentError::UnsupportedLockSchema(lock.schema_version));
88        }
89        let lock_is_empty = lock.artifacts.is_empty();
90        let locked_digests = lock.artifacts.iter().map(|artifact| artifact.sha256.clone()).collect();
91        let target = target.into();
92        let mut entries = HashMap::new();
93        for artifact in lock
94            .artifacts
95            .into_iter()
96            .filter(|artifact| artifact.identity.target == target)
97        {
98            let id = artifact.identity.component.clone();
99            if entries.insert(id.clone(), artifact).is_some() {
100                return Err(ComponentError::DuplicateLockEntry {
101                    component_id: id,
102                    target,
103                });
104            }
105        }
106        Ok(Self {
107            cache: ArtifactCache::new(cache_root, TrustPolicy::EmbeddedKeys(lock.public_keys)),
108            target,
109            entries,
110            loaded: Mutex::new(HashMap::new()),
111            stdio_components: HashSet::new(),
112            sidecar_processes: Mutex::new(HashMap::new()),
113            sidecar_timeout: Duration::from_secs(30),
114            sidecar_policy: SidecarPolicy::default(),
115            key_locks: Mutex::new(HashMap::new()),
116            verified_artifacts: Mutex::new(HashMap::new()),
117            lock_is_empty,
118            locked_digests,
119            host,
120            host_services: None,
121        })
122    }
123
124    /// Select the framed stdio transport for an executable component before first use.
125    ///
126    /// The artifact, signature, lock and cache contract are identical to native components.
127    /// All contracts of this component share one long-lived process. Only bytes invocation
128    /// is supported; generated typed C tables and host callback services are unavailable.
129    #[must_use]
130    pub fn with_stdio_component(mut self, component_id: impl Into<String>) -> Self {
131        self.stdio_components.insert(component_id.into());
132        self
133    }
134
135    /// Set the response deadline for stdio handshakes and calls (default: 30 seconds). A timeout
136    /// terminates the child; the connection is then respawned from the verified executable on a
137    /// later call, within the restart budget (see [`Self::with_sidecar_restart_budget`]).
138    #[must_use]
139    pub fn with_sidecar_timeout(mut self, timeout: Duration) -> Self {
140        self.sidecar_timeout = timeout;
141        self
142    }
143
144    /// Set how many times a stdio connection may be respawned from its verified executable after a
145    /// fatal error (a timeout, a broken frame, a dead child: default 1). `0` restores the previous
146    /// behavior, where the first fatal error stops the connection for good. A respawn re-runs the
147    /// describe validation and replays the session setup before the connection serves calls again.
148    #[must_use]
149    pub fn with_sidecar_restart_budget(mut self, budget: u32) -> Self {
150        self.sidecar_policy.restart_budget = budget;
151        self
152    }
153
154    /// Replay `setup` after the first spawn of every stdio component and after every respawn of
155    /// its connection, where it re-sends whatever session the host had built on the previous
156    /// connection (an `Init` call, one `RegisterConfig` per engine config). A setup failure stops
157    /// the connection and fails the call that triggered the respawn. The setup must send its calls
158    /// through the [`SidecarSession`] it is given: calling back into the manager, or into a
159    /// component handle captured earlier, deadlocks.
160    #[must_use]
161    pub fn with_sidecar_session(mut self, setup: SidecarSessionSetup) -> Self {
162        self.sidecar_policy.session = Some(setup);
163        self
164    }
165
166    /// Call `handler` with the component id and the new restart count after each successful stdio
167    /// respawn, so hosts can log that a connection was rebuilt.
168    #[must_use]
169    pub fn with_sidecar_restart_event(mut self, handler: SidecarRestartEvent) -> Self {
170        self.sidecar_policy.on_restart = Some(handler);
171        self
172    }
173
174    /// How many times the stdio connection of `component_id` has been respawned, or `None` when it
175    /// was never spawned in this manager (or is not a stdio component).
176    #[must_use]
177    pub fn sidecar_restart_count(&self, component_id: &str) -> Option<u32> {
178        self.sidecar_processes
179            .lock()
180            .unwrap_or_else(PoisonError::into_inner)
181            .get(component_id)
182            .map(|process| process.restart_count())
183    }
184
185    /// Expose `services` to components loaded from now on, through the host table's
186    /// `service_call` / `service_notify` callbacks. Components already loaded keep the table
187    /// they were created with, so call this before [`Self::ensure_contract`].
188    #[must_use]
189    pub fn with_host_services(mut self, services: Arc<dyn HostServices>) -> Self {
190        self.host_services = Some(services);
191        self
192    }
193
194    /// Disable network downloads: [`Self::ensure_contract`] and [`Self::prefetch`] fail a
195    /// missing artifact with [`ComponentError::Offline`] instead of attempting a request, and a
196    /// damaged installed artifact with [`ComponentError::CachedObjectInvalid`]. An artifact
197    /// already verified on disk (or served via a `file://` URL) is unaffected. Generated
198    /// bindings call this when the crate-specific `{CRATE}_COMPONENT_OFFLINE` environment
199    /// variable is set.
200    #[must_use]
201    pub fn offline(mut self, offline: bool) -> Self {
202        self.cache = self.cache.offline(offline);
203        self
204    }
205
206    /// Tune downloads: timeouts, retry policy, progress reporting and cancellation. Applies to
207    /// [`Self::ensure_contract`] and [`Self::prefetch`].
208    #[must_use]
209    pub fn with_download_options(mut self, options: DownloadOptions) -> Self {
210        self.cache = self.cache.with_download_options(options);
211        self
212    }
213
214    /// Download from `resolve(entry)` instead of the lock entry's `url`, for mirrors and
215    /// air-gapped hosts. The archive size, SHA-256 and signature are still checked against the
216    /// lock, so a mirror cannot substitute different content. A `file://` URL reads from disk.
217    ///
218    /// ```ignore
219    /// let manager = manager.with_url_override(|entry| {
220    ///     entry.url.replacen("https://github.com/", "https://mirror.corp.example/github/", 1)
221    /// });
222    /// ```
223    #[must_use]
224    pub fn with_url_override(
225        mut self,
226        resolve: impl Fn(&ComponentLockEntry) -> String + Send + Sync + 'static,
227    ) -> Self {
228        self.cache = self.cache.with_url_override(resolve);
229        self
230    }
231
232    /// Download every archive from `base` instead of the lock's URL, keeping only the archive
233    /// file name: `{base}/{file name}`. A trailing slash on `base` is ignored.
234    #[must_use]
235    pub fn with_mirror_base(self, base: impl Into<String>) -> Self {
236        let base = base.into();
237        self.with_url_override(move |entry| {
238            let name = entry.url.split(['?', '#']).next().unwrap_or_default();
239            let name = name.rsplit('/').next().unwrap_or_default();
240            format!("{}/{name}", base.trim_end_matches('/'))
241        })
242    }
243
244    /// Skip re-hashing installed libraries that match their verified stamp. See
245    /// [`ArtifactCache::with_verified_stamp`] for the threat model.
246    #[must_use]
247    pub fn with_verified_stamp(mut self, enabled: bool) -> Self {
248        self.cache = self.cache.with_verified_stamp(enabled);
249        self
250    }
251
252    /// The lock entry for `component_id` on this manager's target, whatever its delivery mode.
253    pub fn lock_entry(&self, component_id: &str) -> Result<&ComponentLockEntry, ComponentError> {
254        self.lookup(component_id)
255    }
256
257    /// Every lock entry for this manager's target, sorted by component id.
258    #[must_use]
259    pub fn lock_entries(&self) -> Vec<&ComponentLockEntry> {
260        let mut entries: Vec<_> = self.entries.values().collect();
261        entries.sort_by(|a, b| a.identity.component.cmp(&b.identity.component));
262        entries
263    }
264
265    /// Every object installed in the cache, including ones other host versions installed.
266    /// `component` names the lock entry referencing the object, when this lock has one.
267    pub fn list_cached(&self) -> Result<Vec<CachedObject>, ComponentError> {
268        let mut objects = self.cache.list_objects()?;
269        for object in &mut objects {
270            object.component = self
271                .entries
272                .values()
273                .find(|entry| entry.sha256 == object.sha256)
274                .map(|entry| entry.identity.component.clone());
275        }
276        Ok(objects)
277    }
278
279    /// Remove `component_id`'s cached object. It re-downloads on next use. On Windows an
280    /// object whose library is loaded cannot be deleted; it is reported under `skipped`.
281    pub fn remove(&self, component_id: &str) -> Result<RemovalReport, ComponentError> {
282        let entry = self.entry(component_id)?;
283        self.verified_artifacts
284            .lock()
285            .unwrap_or_else(PoisonError::into_inner)
286            .remove(&entry.sha256);
287        self.cache.remove_object(&entry.sha256)
288    }
289
290    /// Remove cached objects `retain` does not keep, plus orphaned `.install-*` staging
291    /// directories and stale `.lock` files. Objects loaded in this process are skipped, as are
292    /// files Windows refuses to delete; both are listed in the report.
293    pub fn prune(&self, retain: &Retain) -> Result<RemovalReport, ComponentError> {
294        let loaded = self.loaded.lock().unwrap_or_else(PoisonError::into_inner);
295        let protected: HashSet<String> = self
296            .entries
297            .values()
298            .filter(|entry| {
299                let prefix = format!("{}::", entry.identity.component);
300                loaded.keys().any(|key| key.starts_with(&prefix))
301            })
302            .map(|entry| entry.sha256.clone())
303            .collect();
304        drop(loaded);
305        let report = self
306            .cache
307            .prune_objects(retain, &self.locked_digests, &protected, SystemTime::now())?;
308        let mut verified = self.verified_artifacts.lock().unwrap_or_else(PoisonError::into_inner);
309        for path in &report.removed {
310            if let Some(name) = path.file_name().and_then(|name| name.to_str()) {
311                verified.remove(name);
312            }
313        }
314        Ok(report)
315    }
316
317    /// Load one contract a component provides.
318    ///
319    /// `entry_symbol` is that contract's NUL-terminated producer entry-point
320    /// symbol (`alef::codegen::component::entry_point_symbol`); the caller
321    /// supplies it because computing it requires the same identifier-casing
322    /// logic the producer used, which this crate does not depend on.
323    ///
324    /// Concurrent calls for the *same* `(component_id, contract_name)` coalesce onto one
325    /// download-and-load: a second caller waits behind the first instead of racing a
326    /// duplicate download or `dlopen`. A call for a different key is unaffected and proceeds
327    /// immediately -- the mutex guarding the loaded-component map is only ever held for a
328    /// map lookup or insert, never across I/O.
329    pub fn ensure_contract(
330        &self,
331        component_id: &str,
332        contract_name: &str,
333        entry_symbol: &[u8],
334    ) -> Result<Arc<LoadedComponent>, ComponentError> {
335        let cache_key = loaded_cache_key(component_id, contract_name);
336        if let Some(component) = self.loaded_component(&cache_key) {
337            component.ensure_active()?;
338            return Ok(component);
339        }
340
341        let key_lock = self.contract_lock(cache_key.clone());
342        let _guard = key_lock.lock().unwrap_or_else(PoisonError::into_inner);
343        // Re-check now that this call holds the per-key lock: a concurrent caller for the
344        // same key may have finished the work while this call was waiting for it.
345        if let Some(component) = self.loaded_component(&cache_key) {
346            component.ensure_active()?;
347            return Ok(component);
348        }
349
350        let entry = self.entry(component_id)?;
351        let requirements = contract_requirements(entry, contract_name)?;
352        let cached = self.cached_artifact(entry)?;
353        validate_manifest(&cached.manifest, &requirements)?;
354        let component = Arc::new(if self.stdio_components.contains(component_id) {
355            let process = self.sidecar_process(component_id, &cached)?;
356            LoadedComponent::from_sidecar(process, &cached.manifest, &requirements, self.host)?
357        } else {
358            LoadedComponent::load_with_services(
359                cached.library,
360                entry_symbol,
361                &requirements,
362                self.host,
363                self.host_services.clone(),
364            )?
365        });
366        self.insert_loaded(cache_key, Arc::clone(&component));
367        Ok(component)
368    }
369
370    fn sidecar_process(
371        &self,
372        component_id: &str,
373        cached: &CachedArtifact,
374    ) -> Result<Arc<SidecarProcess>, ComponentError> {
375        let process_lock = self.contract_lock(format!("stdio:{component_id}"));
376        let _guard = process_lock.lock().unwrap_or_else(PoisonError::into_inner);
377        if let Some(process) = self
378            .sidecar_processes
379            .lock()
380            .unwrap_or_else(PoisonError::into_inner)
381            .get(component_id)
382        {
383            process.ensure_running()?;
384            return Ok(Arc::clone(process));
385        }
386        let process = Arc::new(SidecarProcess::spawn(
387            &cached.library,
388            &cached.manifest,
389            self.sidecar_timeout,
390            self.sidecar_policy.clone(),
391        )?);
392        self.sidecar_processes
393            .lock()
394            .unwrap_or_else(PoisonError::into_inner)
395            .insert(component_id.to_owned(), Arc::clone(&process));
396        Ok(process)
397    }
398
399    pub fn prefetch(&self, component_ids: &[&str]) -> Result<Vec<CachedArtifact>, ComponentError> {
400        component_ids
401            .iter()
402            .map(|component_id| self.cached_artifact(self.entry(component_id)?))
403            .collect()
404    }
405
406    fn loaded_component(&self, cache_key: &str) -> Option<Arc<LoadedComponent>> {
407        self.loaded
408            .lock()
409            .unwrap_or_else(PoisonError::into_inner)
410            .get(cache_key)
411            .cloned()
412    }
413
414    fn insert_loaded(&self, cache_key: String, component: Arc<LoadedComponent>) {
415        self.loaded
416            .lock()
417            .unwrap_or_else(PoisonError::into_inner)
418            .insert(cache_key, component);
419    }
420
421    /// The per-`cache_key` lock used to coalesce concurrent [`Self::ensure_contract`] calls.
422    /// The outer `key_locks` mutex is only ever held for the lookup-or-insert below, never
423    /// across the download/load work the returned lock guards.
424    fn contract_lock(&self, cache_key: String) -> Arc<Mutex<()>> {
425        Arc::clone(
426            self.key_locks
427                .lock()
428                .unwrap_or_else(PoisonError::into_inner)
429                .entry(cache_key)
430                .or_insert_with(|| Arc::new(Mutex::new(()))),
431        )
432    }
433
434    /// Install `entry`'s artifact, reusing an in-process-verified copy when this process has
435    /// already installed it (see [`Self::verified_artifacts`]).
436    fn cached_artifact(&self, entry: &ComponentLockEntry) -> Result<CachedArtifact, ComponentError> {
437        if let Some(cached) = self
438            .verified_artifacts
439            .lock()
440            .unwrap_or_else(PoisonError::into_inner)
441            .get(&entry.sha256)
442            .cloned()
443        {
444            return Ok(cached);
445        }
446        let cached = self.cache.install(entry)?;
447        self.verified_artifacts
448            .lock()
449            .unwrap_or_else(PoisonError::into_inner)
450            .insert(entry.sha256.clone(), cached.clone());
451        Ok(cached)
452    }
453
454    /// Report where `component_id` currently stands. Unlike [`Self::ensure_contract`],
455    /// [`Self::prefetch`], and [`Self::cache_path`], a `Bundled` entry is a legitimate answer
456    /// here rather than a failure: it is this manager's way of saying "linked in ahead of
457    /// time, never downloaded or loaded through me", not an error.
458    pub fn status(&self, component_id: &str) -> Result<ComponentStatus, ComponentError> {
459        let entry = self.lookup(component_id)?;
460        if entry.mode == ComponentDeliveryMode::Bundled {
461            return Ok(ComponentStatus::Bundled);
462        }
463        let loaded_prefix = format!("{component_id}::");
464        if self
465            .loaded
466            .lock()
467            .unwrap_or_else(PoisonError::into_inner)
468            .iter()
469            .any(|(key, component)| key.starts_with(&loaded_prefix) && component.is_active())
470        {
471            return Ok(ComponentStatus::Ready);
472        }
473        let root = self.cache.object_path(entry)?;
474        if root.join("component.json").is_file() {
475            Ok(ComponentStatus::Cached)
476        } else {
477            Ok(ComponentStatus::NotDownloaded)
478        }
479    }
480
481    pub fn cache_path(&self, component_id: &str) -> Result<PathBuf, ComponentError> {
482        self.cache.object_path(self.entry(component_id)?)
483    }
484
485    #[must_use]
486    pub fn cache_root(&self) -> &Path {
487        self.cache.root()
488    }
489
490    #[must_use]
491    pub fn target(&self) -> &str {
492        &self.target
493    }
494
495    /// Look up a component's lock entry for this manager's target, with no restriction on
496    /// its delivery mode. [`Self::status`] uses this directly since a `Bundled` entry is a
497    /// legitimate status to report, not a failure.
498    ///
499    /// A miss against a lock that was empty before target filtering reports
500    /// [`ComponentError::ComponentsNotLocked`] instead of the generic
501    /// [`ComponentError::ArtifactNotFound`]: `alef component lock` has never populated it, so
502    /// naming the fix is more useful than reporting a missing target.
503    fn lookup(&self, component_id: &str) -> Result<&ComponentLockEntry, ComponentError> {
504        self.entries.get(component_id).ok_or_else(|| {
505            if self.lock_is_empty {
506                ComponentError::ComponentsNotLocked {
507                    component_id: component_id.to_owned(),
508                }
509            } else {
510                ComponentError::ArtifactNotFound {
511                    component_id: component_id.to_owned(),
512                    target: self.target.clone(),
513                }
514            }
515        })
516    }
517
518    /// Like [`Self::lookup`], but additionally rejects a `Bundled` entry -- one this manager
519    /// cannot download -- before any cache I/O runs. Every caller that actually needs to
520    /// touch the cache (`ensure_contract`, `prefetch`, `cache_path`) reaches it only through
521    /// this method.
522    fn entry(&self, component_id: &str) -> Result<&ComponentLockEntry, ComponentError> {
523        let entry = self.lookup(component_id)?;
524        if entry.mode == ComponentDeliveryMode::Bundled {
525            return Err(ComponentError::BundledComponentNotLoadable {
526                component: component_id.to_owned(),
527            });
528        }
529        Ok(entry)
530    }
531}
532
533fn loaded_cache_key(component_id: &str, contract_name: &str) -> String {
534    format!("{component_id}::{contract_name}")
535}
536
537fn contract_requirements(
538    entry: &ComponentLockEntry,
539    contract_name: &str,
540) -> Result<ComponentRequirements, ComponentError> {
541    let provided = entry
542        .provides
543        .iter()
544        .find(|provided| provided.contract == contract_name)
545        .ok_or_else(|| ComponentError::ContractNotProvided {
546            component_id: entry.identity.component.clone(),
547            contract: contract_name.to_owned(),
548        })?;
549    Ok(ComponentRequirements {
550        component_id: entry.identity.component.clone(),
551        contract_name: contract_name.to_owned(),
552        contract_hash: decode_hash(&provided.contract_hash)?,
553        feature_set_hash: Some(decode_hash(&entry.identity.feature_hash)?),
554    })
555}
556
557#[cfg(test)]
558mod tests {
559    use super::*;
560    use crate::ComponentIdentity;
561    use std::collections::BTreeMap;
562
563    fn host() -> AlefHostApiV1 {
564        AlefHostApiV1 {
565            struct_size: 0,
566            abi_major: 0,
567            abi_minor: 0,
568            ..AlefHostApiV1::EMPTY
569        }
570    }
571
572    fn lock(target: &str) -> ComponentLock {
573        lock_with_mode(target, ComponentDeliveryMode::Download)
574    }
575
576    fn lock_with_mode(target: &str, mode: ComponentDeliveryMode) -> ComponentLock {
577        ComponentLock {
578            schema_version: COMPONENT_MANIFEST_SCHEMA,
579            public_keys: BTreeMap::new(),
580            artifacts: vec![ComponentLockEntry {
581                identity: ComponentIdentity {
582                    crate_name: "demo-core".into(),
583                    component: "demo".into(),
584                    version: "1.0.0".into(),
585                    target: target.into(),
586                    feature_hash: hex::encode([2; 32]),
587                    contract_hash: hex::encode([1; 32]),
588                },
589                provides: vec![crate::ComponentProvidedContract {
590                    contract: "engine".into(),
591                    interface_version: 1,
592                    contract_hash: hex::encode([1; 32]),
593                    implementation: "demo::Demo".into(),
594                }],
595                mode,
596                url: "file:///does/not/exist".into(),
597                sha256: hex::encode([3; 32]),
598                size: 0,
599                manifest_sha256: hex::encode([4; 32]),
600                key_id: String::new(),
601                input_hash: None,
602            }],
603        }
604    }
605
606    #[test]
607    fn bootstrap_empty_lock_reports_components_not_locked_instead_of_artifact_not_found() {
608        let dir = tempfile::tempdir().unwrap();
609        let empty = ComponentLock {
610            schema_version: COMPONENT_MANIFEST_SCHEMA,
611            public_keys: BTreeMap::new(),
612            artifacts: Vec::new(),
613        };
614        let manager = ComponentManager::from_lock(empty, dir.path(), "target-a", host()).unwrap();
615
616        assert!(matches!(
617            manager.status("demo"),
618            Err(ComponentError::ComponentsNotLocked { .. })
619        ));
620        assert!(matches!(
621            manager.ensure_contract("demo", "engine", b"irrelevant\0"),
622            Err(ComponentError::ComponentsNotLocked { .. })
623        ));
624        assert!(matches!(
625            manager.prefetch(&["demo"]),
626            Err(ComponentError::ComponentsNotLocked { .. })
627        ));
628        assert!(matches!(
629            manager.cache_path("demo"),
630            Err(ComponentError::ComponentsNotLocked { .. })
631        ));
632    }
633
634    #[test]
635    fn manager_filters_lock_to_exact_target() {
636        let dir = tempfile::tempdir().unwrap();
637        let manager = ComponentManager::from_lock(lock("target-a"), dir.path(), "target-b", host()).unwrap();
638        assert!(matches!(
639            manager.status("demo"),
640            Err(ComponentError::ArtifactNotFound { .. })
641        ));
642    }
643
644    #[test]
645    fn manager_reports_content_address_before_download() {
646        let dir = tempfile::tempdir().unwrap();
647        let manager = ComponentManager::from_lock(lock("target-a"), dir.path(), "target-a", host()).unwrap();
648        assert_eq!(manager.status("demo").unwrap(), ComponentStatus::NotDownloaded);
649        assert!(
650            manager
651                .cache_path("demo")
652                .unwrap()
653                .ends_with(format!("sha256/{}", hex::encode([3; 32])))
654        );
655    }
656
657    #[test]
658    fn duplicate_target_entry_is_rejected() {
659        let dir = tempfile::tempdir().unwrap();
660        let mut lock = lock("target-a");
661        lock.artifacts.push(lock.artifacts[0].clone());
662        assert!(matches!(
663            ComponentManager::from_lock(lock, dir.path(), "target-a", host()),
664            Err(ComponentError::DuplicateLockEntry { .. })
665        ));
666    }
667
668    #[test]
669    fn ensure_contract_rejects_a_contract_the_component_does_not_provide() {
670        let dir = tempfile::tempdir().unwrap();
671        let manager = ComponentManager::from_lock(lock("target-a"), dir.path(), "target-a", host()).unwrap();
672        assert!(matches!(
673            manager.ensure_contract("demo", "missing-contract", b"irrelevant\0"),
674            Err(ComponentError::ContractNotProvided { .. })
675        ));
676    }
677
678    #[test]
679    fn ensure_contract_reaches_the_download_step_for_a_provided_contract() {
680        let dir = tempfile::tempdir().unwrap();
681        let mut two_contracts = lock("target-a");
682        two_contracts.artifacts[0]
683            .provides
684            .push(crate::ComponentProvidedContract {
685                contract: "second".into(),
686                interface_version: 1,
687                contract_hash: hex::encode([9; 32]),
688                implementation: "demo::Second".into(),
689            });
690        let manager = ComponentManager::from_lock(two_contracts, dir.path(), "target-a", host()).unwrap();
691        // Fails to find the library at the fake `file://` URL -- proving contract resolution
692        // for "second" succeeded and the manager reached the download step, not that the
693        // download itself succeeded.
694        assert!(matches!(
695            manager.ensure_contract("demo", "second", b"alef_component_entry_v1_second\0"),
696            Err(ComponentError::Io(_))
697        ));
698    }
699
700    #[test]
701    fn bundled_component_is_rejected_before_touching_the_cache() {
702        let dir = tempfile::tempdir().unwrap();
703        let manager = ComponentManager::from_lock(
704            lock_with_mode("target-a", ComponentDeliveryMode::Bundled),
705            dir.path(),
706            "target-a",
707            host(),
708        )
709        .unwrap();
710
711        assert!(matches!(
712            manager.ensure_contract("demo", "engine", b"alef_component_entry_v1_engine\0"),
713            Err(ComponentError::BundledComponentNotLoadable { .. })
714        ));
715        // Unlike `ensure_contract`/`prefetch`/`cache_path`, `status` reports `Bundled` as a
716        // legitimate answer rather than failing: this manager genuinely cannot download or
717        // load the component, and that is exactly what the status says.
718        assert_eq!(manager.status("demo").unwrap(), ComponentStatus::Bundled);
719        assert!(matches!(
720            manager.prefetch(&["demo"]),
721            Err(ComponentError::BundledComponentNotLoadable { .. })
722        ));
723        assert!(matches!(
724            manager.cache_path("demo"),
725            Err(ComponentError::BundledComponentNotLoadable { .. })
726        ));
727        assert!(
728            std::fs::read_dir(dir.path()).unwrap().next().is_none(),
729            "a bundled component must never touch the cache directory"
730        );
731    }
732
733    #[test]
734    fn prefetch_reuses_an_already_verified_artifact_without_reinstalling() {
735        let dir = tempfile::tempdir().unwrap();
736        let manager = ComponentManager::from_lock(lock("target-a"), dir.path(), "target-a", host()).unwrap();
737        let entry = manager.entries.get("demo").unwrap().clone();
738
739        let fake = CachedArtifact {
740            root: dir.path().join("fake-root"),
741            library: dir.path().join("fake-root/libdemo.so"),
742            manifest: crate::ComponentManifest {
743                schema_version: COMPONENT_MANIFEST_SCHEMA,
744                abi_version: 1,
745                identity: entry.identity.clone(),
746                provides: entry.provides.clone(),
747                features: Vec::new(),
748                default_features: false,
749                library: crate::ComponentLibrary {
750                    file: "libdemo.so".into(),
751                    sha256: hex::encode([0; 32]),
752                    size: 0,
753                },
754            },
755        };
756        manager
757            .verified_artifacts
758            .lock()
759            .unwrap()
760            .insert(entry.sha256.clone(), fake.clone());
761
762        // The lock entry's URL points nowhere real (`file:///does/not/exist`, see `lock()`),
763        // so this call would fail if it attempted to actually install/verify the artifact;
764        // succeeding proves it reused the in-process cache instead.
765        let prefetched = manager.prefetch(&["demo"]).unwrap();
766        assert_eq!(prefetched, vec![fake]);
767    }
768
769    #[test]
770    fn lock_entry_exposes_version_digest_and_size() {
771        let dir = tempfile::tempdir().unwrap();
772        let manager = ComponentManager::from_lock(lock("target-a"), dir.path(), "target-a", host()).unwrap();
773        let entry = manager.lock_entry("demo").unwrap();
774        assert_eq!(entry.identity.version, "1.0.0");
775        assert_eq!(entry.sha256, hex::encode([3; 32]));
776        assert_eq!(manager.lock_entries().len(), 1);
777        assert!(matches!(
778            manager.lock_entry("missing"),
779            Err(ComponentError::ArtifactNotFound { .. })
780        ));
781    }
782
783    #[test]
784    fn list_remove_and_prune_operate_on_the_cache() {
785        let dir = tempfile::tempdir().unwrap();
786        let manager = ComponentManager::from_lock(lock("target-a"), dir.path(), "target-a", host()).unwrap();
787        let ours = dir.path().join("sha256").join(hex::encode([3; 32]));
788        let foreign = dir.path().join("sha256").join(hex::encode([7; 32]));
789        for path in [&ours, &foreign] {
790            std::fs::create_dir_all(path).unwrap();
791            std::fs::write(path.join("component.json"), b"{}").unwrap();
792        }
793
794        let listed = manager.list_cached().unwrap();
795        assert_eq!(listed.len(), 2);
796        let named: Vec<_> = listed.iter().filter_map(|object| object.component.as_deref()).collect();
797        assert_eq!(named, vec!["demo"]);
798
799        let report = manager.prune(&Retain::new().referenced_by_lock()).unwrap();
800        assert_eq!(report.removed, vec![foreign.clone()]);
801        assert!(ours.exists() && !foreign.exists());
802
803        let report = manager.remove("demo").unwrap();
804        assert_eq!(report.removed, vec![ours.clone()]);
805        assert_eq!(manager.status("demo").unwrap(), ComponentStatus::NotDownloaded);
806    }
807
808    #[test]
809    fn mirror_base_keeps_only_the_archive_file_name() {
810        let dir = tempfile::tempdir().unwrap();
811        let mut remote = lock("target-a");
812        remote.artifacts[0].url = "https://origin.example/dl/demo-1.0.0.tar.gz?token=1".into();
813        let manager = ComponentManager::from_lock(remote, dir.path(), "target-a", host())
814            .unwrap()
815            .offline(true)
816            .with_mirror_base("https://mirror.example/components/");
817
818        let error = manager.prefetch(&["demo"]).unwrap_err();
819
820        assert!(matches!(
821            error,
822            ComponentError::Offline { ref url, .. }
823                if url == "https://mirror.example/components/demo-1.0.0.tar.gz"
824        ));
825    }
826
827    #[test]
828    fn contract_lock_coalesces_the_same_key_and_separates_different_keys() {
829        let dir = tempfile::tempdir().unwrap();
830        let manager = ComponentManager::from_lock(lock("target-a"), dir.path(), "target-a", host()).unwrap();
831
832        let first = manager.contract_lock("demo::engine".to_string());
833        let second = manager.contract_lock("demo::engine".to_string());
834        assert!(
835            Arc::ptr_eq(&first, &second),
836            "the same (component, contract) key must coalesce onto one lock"
837        );
838
839        let unrelated = manager.contract_lock("other::engine".to_string());
840        assert!(
841            !Arc::ptr_eq(&first, &unrelated),
842            "an unrelated key must get its own lock so it is never blocked by a different key"
843        );
844    }
845
846    #[test]
847    fn concurrent_calls_for_the_same_key_serialize_on_the_coalescing_lock() {
848        use std::sync::Barrier;
849        use std::thread;
850
851        let dir = tempfile::tempdir().unwrap();
852        let manager = Arc::new(ComponentManager::from_lock(lock("target-a"), dir.path(), "target-a", host()).unwrap());
853        let order = Arc::new(Mutex::new(Vec::new()));
854        let ready = Arc::new(Barrier::new(2));
855
856        // Hold the coalescing lock as a stand-in for an in-progress download, then prove a
857        // concurrent request for the *same* key really does wait for it: `order` only ever
858        // records the second entry-point-symbol lookup after the first thread has both run
859        // and released the lock, never interleaved with it.
860        let held = manager.contract_lock("demo::engine".to_string());
861        let guard = held.lock().unwrap();
862
863        let waiter = {
864            let manager = Arc::clone(&manager);
865            let order = Arc::clone(&order);
866            let ready = Arc::clone(&ready);
867            thread::spawn(move || {
868                ready.wait();
869                let _ = manager.ensure_contract("demo", "engine", b"alef_component_entry_v1_engine\0");
870                order.lock().unwrap().push("waiter");
871            })
872        };
873
874        ready.wait();
875        thread::sleep(std::time::Duration::from_millis(50));
876        assert!(
877            order.lock().unwrap().is_empty(),
878            "a concurrent call for the same key must not proceed while the lock is held"
879        );
880        order.lock().unwrap().push("holder");
881        drop(guard);
882
883        waiter.join().unwrap();
884        assert_eq!(*order.lock().unwrap(), vec!["holder", "waiter"]);
885    }
886}