alef-component-runtime 0.134.7

Verified downloader and dynamic loader for Alef native components
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
use crate::identity::VerifiedFile;
use crate::loader::{decode_hash, validate_manifest};
use crate::manifest::COMPONENT_MANIFEST_SCHEMA;
use crate::stdio::{SidecarPolicy, SidecarProcess, SidecarRestartEvent, SidecarSessionSetup, SidecarVerifier};
use crate::{
    ArtifactCache, CachedArtifact, CachedObject, ComponentDeliveryMode, ComponentError, ComponentLock,
    ComponentLockEntry, ComponentRequirements, DownloadOptions, HostServices, LoadedComponent, RemovalReport, Retain,
    SignaturePolicy, TrustPolicy,
};
use alef_component_abi::AlefHostApiV1;
use std::collections::{HashMap, HashSet};
use std::path::{Path, PathBuf};
use std::sync::{Arc, Mutex, PoisonError};
use std::time::{Duration, SystemTime};

/// Where a configured component currently stands, independent of its on-disk location (see
/// [`ComponentManager::cache_path`] for that). Generated bindings expose this as both a
/// stable string tag and a numeric code (`alef_component_status`/`alef_component_status_code`
/// in `alef::backends::native_components`) so callers in any host language can branch on it
/// without parsing free-form text.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum ComponentStatus {
    /// Loaded and its contracts activated in this process.
    Ready,
    /// Downloaded and verified on disk, but not yet loaded in this process.
    Cached,
    /// Not yet present in the on-disk cache.
    NotDownloaded,
    /// Linked into the binding ahead of time for this target; never downloaded or loaded
    /// through this manager.
    Bundled,
    /// This host/target does not support downloading native components at all.
    Unsupported { reason: String },
}

pub struct ComponentManager {
    cache: ArtifactCache,
    target: String,
    entries: HashMap<String, ComponentLockEntry>,
    loaded: Mutex<HashMap<String, Arc<LoadedComponent>>>,
    stdio_components: HashSet<String>,
    sidecar_processes: Mutex<HashMap<String, Arc<SidecarProcess>>>,
    sidecar_timeout: Duration,
    /// Respawn knobs for stdio connections: the restart budget, the session setup replayed after
    /// every spawn and respawn, and the restart event handler. Applied to every stdio component
    /// this manager spawns; see the `with_sidecar_*` builders.
    sidecar_policy: SidecarPolicy,
    /// One lock per (component, contract) key, used to coalesce concurrent `ensure_contract`
    /// calls for the same key onto a single download-and-load instead of racing duplicates;
    /// a call for a different key gets its own lock and proceeds independently. See
    /// [`Self::contract_lock`].
    key_locks: Mutex<HashMap<String, Arc<Mutex<()>>>>,
    /// Artifacts this process has already installed and verified, keyed by the lock entry's
    /// own content-addressed `sha256` digest. A component that provides more than one
    /// contract shares one artifact across several `ensure_contract` calls; without this, each
    /// call would re-read and re-hash the same (potentially large) dylib. Each entry keeps the
    /// verified library open, and every later load goes through that descriptor or re-checks the
    /// path against it (see `identity`), so replacing the file after verification is refused
    /// rather than loaded.
    verified_artifacts: Mutex<HashMap<String, (CachedArtifact, VerifiedFile)>>,
    /// Whether the lock this manager was built from had zero artifacts *before* target
    /// filtering -- the shape `alef generate` bootstraps when a crate declares components but
    /// `alef component lock` has never run (see
    /// `alef::bin_cli::component_commands::bootstrap_missing_component_locks`). Distinguished
    /// from "no artifact for this particular target", which is a normal, populated lock that
    /// simply was not built for the requested target.
    lock_is_empty: bool,
    /// Archive digests of every artifact in the lock, across all targets; what
    /// [`Retain::referenced_by_lock`] keeps.
    locked_digests: HashSet<String>,
    host: AlefHostApiV1,
    host_services: Option<Arc<dyn HostServices>>,
}

// SAFETY: `LoadedComponent` is thread-safe metadata and the host callback
// context is required by the ABI to remain valid for calls from component
// threads. Mutation is protected by the manager mutex. ~keep
unsafe impl Send for ComponentManager {}
// SAFETY: as for `Send` above: shared state is behind mutexes, and the host table is only
// copied, never mutated, after construction.
unsafe impl Sync for ComponentManager {}

impl ComponentManager {
    /// A manager for `lock` that accepts unsigned locks ([`SignaturePolicy::AllowUnsigned`]);
    /// see [`Self::from_lock_with_signature_policy`] to require signatures.
    pub fn from_lock(
        lock: ComponentLock,
        cache_root: impl Into<PathBuf>,
        target: impl Into<String>,
        host: AlefHostApiV1,
    ) -> Result<Self, ComponentError> {
        Self::from_lock_with_signature_policy(lock, cache_root, target, host, SignaturePolicy::AllowUnsigned)
    }

    /// Like [`Self::from_lock`]. With [`SignaturePolicy::Require`] the lock must embed at least
    /// one public key and every artifact (for every target) must name one of them in `key_id`,
    /// or this fails with [`ComponentError::UnsignedLock`]; every install then verifies the
    /// manifest signature. Without it, a lock with no keys is checked by digest alone, so anyone
    /// able to edit the lock can substitute an artifact.
    pub fn from_lock_with_signature_policy(
        lock: ComponentLock,
        cache_root: impl Into<PathBuf>,
        target: impl Into<String>,
        host: AlefHostApiV1,
        signatures: SignaturePolicy,
    ) -> Result<Self, ComponentError> {
        if lock.schema_version != COMPONENT_MANIFEST_SCHEMA {
            return Err(ComponentError::UnsupportedLockSchema(lock.schema_version));
        }
        if signatures == SignaturePolicy::Require {
            require_signed_lock(&lock)?;
        }
        let mut lock = lock;
        for artifact in &mut lock.artifacts {
            // One spelling per object, matching the cache's directory names (see `canonical_entry`).
            artifact.sha256.make_ascii_lowercase();
        }
        let lock_is_empty = lock.artifacts.is_empty();
        let locked_digests = lock.artifacts.iter().map(|artifact| artifact.sha256.clone()).collect();
        let target = target.into();
        let mut entries = HashMap::new();
        for artifact in lock
            .artifacts
            .into_iter()
            .filter(|artifact| artifact.identity.target == target)
        {
            let id = artifact.identity.component.clone();
            if entries.insert(id.clone(), artifact).is_some() {
                return Err(ComponentError::DuplicateLockEntry {
                    component_id: id,
                    target,
                });
            }
        }
        Ok(Self {
            cache: ArtifactCache::new(cache_root, TrustPolicy::EmbeddedKeys(lock.public_keys))
                .with_signature_policy(signatures),
            target,
            entries,
            loaded: Mutex::new(HashMap::new()),
            stdio_components: HashSet::new(),
            sidecar_processes: Mutex::new(HashMap::new()),
            sidecar_timeout: Duration::from_secs(30),
            sidecar_policy: SidecarPolicy::default(),
            key_locks: Mutex::new(HashMap::new()),
            verified_artifacts: Mutex::new(HashMap::new()),
            lock_is_empty,
            locked_digests,
            host,
            host_services: None,
        })
    }

    /// Select the framed stdio transport for an executable component before first use.
    ///
    /// The artifact, signature, lock and cache contract are identical to native components.
    /// All contracts of this component share one long-lived process. Only bytes invocation
    /// is supported; generated typed C tables and host callback services are unavailable.
    #[must_use]
    pub fn with_stdio_component(mut self, component_id: impl Into<String>) -> Self {
        self.stdio_components.insert(component_id.into());
        self
    }

    /// Set the response deadline for stdio handshakes and calls (default: 30 seconds). A timeout
    /// terminates the child; the connection is then respawned from the verified executable on a
    /// later call, within the restart budget (see [`Self::with_sidecar_restart_budget`]). On a
    /// protocol-2 connection a call's timeout terminates the child only when the sidecar answered
    /// nothing during the whole deadline; otherwise only that call fails and its late response is
    /// dropped.
    #[must_use]
    pub fn with_sidecar_timeout(mut self, timeout: Duration) -> Self {
        self.sidecar_timeout = timeout;
        self
    }

    /// Set how many times a stdio connection may be respawned from its verified executable after a
    /// fatal error (a timeout, a broken frame, a dead child: default 1). `0` restores the previous
    /// behavior, where the first fatal error stops the connection for good. A respawn re-runs the
    /// describe validation and replays the session setup before the connection serves calls again.
    #[must_use]
    pub fn with_sidecar_restart_budget(mut self, budget: u32) -> Self {
        self.sidecar_policy.restart_budget = budget;
        self
    }

    /// Replay `setup` after the first spawn of every stdio component and after every respawn of
    /// its connection, where it re-sends whatever session the host had built on the previous
    /// connection (an `Init` call, one `RegisterConfig` per engine config). A setup failure stops
    /// the connection and fails the call that triggered the respawn. The setup must send its calls
    /// through the [`SidecarSession`] it is given: calling back into the manager, or into a
    /// component handle captured earlier, deadlocks.
    #[must_use]
    pub fn with_sidecar_session(mut self, setup: SidecarSessionSetup) -> Self {
        self.sidecar_policy.session = Some(setup);
        self
    }

    /// Call `handler` with the component id and the new restart count after each successful stdio
    /// respawn, so hosts can log that a connection was rebuilt.
    #[must_use]
    pub fn with_sidecar_restart_event(mut self, handler: SidecarRestartEvent) -> Self {
        self.sidecar_policy.on_restart = Some(handler);
        self
    }

    /// Pass these host environment variables through to stdio sidecars, on top of the default
    /// allowlist. A sidecar starts with a cleared environment holding only `PATH`, `HOME`, `USER`,
    /// `LOGNAME`, `TMPDIR`/`TEMP`/`TMP`, `TZ`, `LANG`, `LANGUAGE` and `LC_*` (plus `SYSTEMROOT`,
    /// `WINDIR`, `SYSTEMDRIVE`, `USERPROFILE`, `PATHEXT` and `COMSPEC`, which Windows processes
    /// need) and the protocol variable the runtime sets, and runs in its component's cache
    /// directory. A name ending in `*` passes every variable with that prefix; names compare
    /// case-insensitively on Windows.
    #[must_use]
    pub fn with_sidecar_env_passthrough(mut self, names: impl IntoIterator<Item = impl Into<String>>) -> Self {
        self.sidecar_policy
            .env_passthrough
            .extend(names.into_iter().map(Into::into));
        self
    }

    /// How many times the stdio connection of `component_id` has been respawned, or `None` when it
    /// was never spawned in this manager (or is not a stdio component).
    #[must_use]
    pub fn sidecar_restart_count(&self, component_id: &str) -> Option<u32> {
        self.sidecar_processes
            .lock()
            .unwrap_or_else(PoisonError::into_inner)
            .get(component_id)
            .map(|process| process.restart_count())
    }

    /// Expose `services` to components loaded from now on, through the host table's
    /// `service_call` / `service_notify` callbacks. Components already loaded keep the table
    /// they were created with, so call this before [`Self::ensure_contract`].
    #[must_use]
    pub fn with_host_services(mut self, services: Arc<dyn HostServices>) -> Self {
        self.host_services = Some(services);
        self
    }

    /// Disable network downloads: [`Self::ensure_contract`] and [`Self::prefetch`] fail a
    /// missing artifact with [`ComponentError::Offline`] instead of attempting a request, and a
    /// damaged installed artifact with [`ComponentError::CachedObjectInvalid`]. An artifact
    /// already verified on disk (or served via a `file://` URL) is unaffected. Generated
    /// bindings call this when the crate-specific `{CRATE}_COMPONENT_OFFLINE` environment
    /// variable is set.
    #[must_use]
    pub fn offline(mut self, offline: bool) -> Self {
        self.cache = self.cache.offline(offline);
        self
    }

    /// Tune downloads: timeouts, retry policy, progress reporting and cancellation. Applies to
    /// [`Self::ensure_contract`] and [`Self::prefetch`].
    #[must_use]
    pub fn with_download_options(mut self, options: DownloadOptions) -> Self {
        self.cache = self.cache.with_download_options(options);
        self
    }

    /// Download from `resolve(entry)` instead of the lock entry's `url`, for mirrors and
    /// air-gapped hosts. The archive size, SHA-256 and signature are still checked against the
    /// lock, so a mirror cannot substitute different content. A `file://` URL reads from disk.
    ///
    /// ```ignore
    /// let manager = manager.with_url_override(|entry| {
    ///     entry.url.replacen("https://github.com/", "https://mirror.corp.example/github/", 1)
    /// });
    /// ```
    #[must_use]
    pub fn with_url_override(
        mut self,
        resolve: impl Fn(&ComponentLockEntry) -> String + Send + Sync + 'static,
    ) -> Self {
        self.cache = self.cache.with_url_override(resolve);
        self
    }

    /// Download every archive from `base` instead of the lock's URL, keeping only the archive
    /// file name: `{base}/{file name}`. A trailing slash on `base` is ignored.
    #[must_use]
    pub fn with_mirror_base(self, base: impl Into<String>) -> Self {
        let base = base.into();
        self.with_url_override(move |entry| {
            let name = entry.url.split(['?', '#']).next().unwrap_or_default();
            let name = name.rsplit('/').next().unwrap_or_default();
            format!("{}/{name}", base.trim_end_matches('/'))
        })
    }

    /// Skip re-hashing installed libraries that match their verified stamp. See
    /// [`ArtifactCache::with_verified_stamp`] for the threat model.
    #[must_use]
    pub fn with_verified_stamp(mut self, enabled: bool) -> Self {
        self.cache = self.cache.with_verified_stamp(enabled);
        self
    }

    /// The lock entry for `component_id` on this manager's target, whatever its delivery mode.
    pub fn lock_entry(&self, component_id: &str) -> Result<&ComponentLockEntry, ComponentError> {
        self.lookup(component_id)
    }

    /// Every lock entry for this manager's target, sorted by component id.
    #[must_use]
    pub fn lock_entries(&self) -> Vec<&ComponentLockEntry> {
        let mut entries: Vec<_> = self.entries.values().collect();
        entries.sort_by(|a, b| a.identity.component.cmp(&b.identity.component));
        entries
    }

    /// Every object installed in the cache, including ones other host versions installed.
    /// `component` names the lock entry referencing the object, when this lock has one.
    pub fn list_cached(&self) -> Result<Vec<CachedObject>, ComponentError> {
        let mut objects = self.cache.list_objects()?;
        for object in &mut objects {
            object.component = self
                .entries
                .values()
                .find(|entry| entry.sha256 == object.sha256)
                .map(|entry| entry.identity.component.clone());
        }
        Ok(objects)
    }

    /// Remove `component_id`'s cached object. It re-downloads on next use. On Windows an
    /// object whose library is loaded cannot be deleted; it is reported under `skipped`.
    pub fn remove(&self, component_id: &str) -> Result<RemovalReport, ComponentError> {
        let entry = self.entry(component_id)?;
        self.verified_artifacts
            .lock()
            .unwrap_or_else(PoisonError::into_inner)
            .remove(&entry.sha256);
        self.cache.remove_object(&entry.sha256)
    }

    /// Remove cached objects `retain` does not keep, plus orphaned `.install-*` staging
    /// directories and stamps. Objects loaded in this process or being installed by another
    /// thread or process are skipped, as are files Windows refuses to delete; all are listed in
    /// the report.
    pub fn prune(&self, retain: &Retain) -> Result<RemovalReport, ComponentError> {
        let loaded = self.loaded.lock().unwrap_or_else(PoisonError::into_inner);
        let protected: HashSet<String> = self
            .entries
            .values()
            .filter(|entry| {
                let prefix = format!("{}::", entry.identity.component);
                loaded.keys().any(|key| key.starts_with(&prefix))
            })
            .map(|entry| entry.sha256.clone())
            .collect();
        drop(loaded);
        let report = self
            .cache
            .prune_objects(retain, &self.locked_digests, &protected, SystemTime::now())?;
        let mut verified = self.verified_artifacts.lock().unwrap_or_else(PoisonError::into_inner);
        for path in &report.removed {
            if let Some(name) = path.file_name().and_then(|name| name.to_str()) {
                verified.remove(name);
            }
        }
        Ok(report)
    }

    /// Load one contract a component provides.
    ///
    /// `entry_symbol` is that contract's NUL-terminated producer entry-point
    /// symbol (`alef::codegen::component::entry_point_symbol`); the caller
    /// supplies it because computing it requires the same identifier-casing
    /// logic the producer used, which this crate does not depend on.
    ///
    /// Concurrent calls for the *same* `(component_id, contract_name)` coalesce onto one
    /// download-and-load: a second caller waits behind the first instead of racing a
    /// duplicate download or `dlopen`. A call for a different key is unaffected and proceeds
    /// immediately -- the mutex guarding the loaded-component map is only ever held for a
    /// map lookup or insert, never across I/O.
    pub fn ensure_contract(
        &self,
        component_id: &str,
        contract_name: &str,
        entry_symbol: &[u8],
    ) -> Result<Arc<LoadedComponent>, ComponentError> {
        let cache_key = loaded_cache_key(component_id, contract_name);
        if let Some(component) = self.loaded_component(&cache_key) {
            component.ensure_active()?;
            return Ok(component);
        }

        let key_lock = self.contract_lock(cache_key.clone());
        let _guard = key_lock.lock().unwrap_or_else(PoisonError::into_inner);
        // Re-check now that this call holds the per-key lock: a concurrent caller for the
        // same key may have finished the work while this call was waiting for it.
        if let Some(component) = self.loaded_component(&cache_key) {
            component.ensure_active()?;
            return Ok(component);
        }

        let entry = self.entry(component_id)?;
        let requirements = contract_requirements(entry, contract_name)?;
        let (cached, verified) = self.cached_artifact(entry)?;
        validate_manifest(&cached.manifest, &requirements)?;
        let component = Arc::new(if self.stdio_components.contains(component_id) {
            let process = self.sidecar_process(entry, &cached, &verified)?;
            LoadedComponent::from_sidecar(process, &cached.manifest, &requirements, self.host)?
        } else {
            LoadedComponent::load_with_services(
                &verified,
                entry_symbol,
                &requirements,
                self.host,
                self.host_services.clone(),
            )?
        });
        self.insert_loaded(cache_key, Arc::clone(&component));
        Ok(component)
    }

    fn sidecar_process(
        &self,
        entry: &ComponentLockEntry,
        cached: &CachedArtifact,
        verified: &VerifiedFile,
    ) -> Result<Arc<SidecarProcess>, ComponentError> {
        let component_id = entry.identity.component.as_str();
        let process_lock = self.contract_lock(format!("stdio:{component_id}"));
        let _guard = process_lock.lock().unwrap_or_else(PoisonError::into_inner);
        if let Some(process) = self
            .sidecar_processes
            .lock()
            .unwrap_or_else(PoisonError::into_inner)
            .get(component_id)
        {
            process.ensure_running()?;
            return Ok(Arc::clone(process));
        }
        let verify: SidecarVerifier = {
            let cache = self.cache.clone();
            let entry = entry.clone();
            Arc::new(move || cache.verify_cached_file(&entry).map(|(_, verified)| verified))
        };
        let process = Arc::new(SidecarProcess::spawn(
            verified,
            verify,
            &cached.manifest,
            self.sidecar_timeout,
            self.sidecar_policy.clone(),
        )?);
        self.sidecar_processes
            .lock()
            .unwrap_or_else(PoisonError::into_inner)
            .insert(component_id.to_owned(), Arc::clone(&process));
        Ok(process)
    }

    pub fn prefetch(&self, component_ids: &[&str]) -> Result<Vec<CachedArtifact>, ComponentError> {
        component_ids
            .iter()
            .map(|component_id| -> Result<CachedArtifact, ComponentError> {
                Ok(self.cached_artifact(self.entry(component_id)?)?.0)
            })
            .collect()
    }

    fn loaded_component(&self, cache_key: &str) -> Option<Arc<LoadedComponent>> {
        self.loaded
            .lock()
            .unwrap_or_else(PoisonError::into_inner)
            .get(cache_key)
            .cloned()
    }

    fn insert_loaded(&self, cache_key: String, component: Arc<LoadedComponent>) {
        self.loaded
            .lock()
            .unwrap_or_else(PoisonError::into_inner)
            .insert(cache_key, component);
    }

    /// The per-`cache_key` lock used to coalesce concurrent [`Self::ensure_contract`] calls.
    /// The outer `key_locks` mutex is only ever held for the lookup-or-insert below, never
    /// across the download/load work the returned lock guards.
    fn contract_lock(&self, cache_key: String) -> Arc<Mutex<()>> {
        Arc::clone(
            self.key_locks
                .lock()
                .unwrap_or_else(PoisonError::into_inner)
                .entry(cache_key)
                .or_insert_with(|| Arc::new(Mutex::new(()))),
        )
    }

    /// Install `entry`'s artifact, reusing an in-process-verified copy when this process has
    /// already installed it (see [`Self::verified_artifacts`]).
    fn cached_artifact(&self, entry: &ComponentLockEntry) -> Result<(CachedArtifact, VerifiedFile), ComponentError> {
        if let Some(verified) = self
            .verified_artifacts
            .lock()
            .unwrap_or_else(PoisonError::into_inner)
            .get(&entry.sha256)
            .cloned()
        {
            return Ok(verified);
        }
        let verified = self.cache.install_verified(entry)?;
        self.verified_artifacts
            .lock()
            .unwrap_or_else(PoisonError::into_inner)
            .insert(entry.sha256.clone(), verified.clone());
        Ok(verified)
    }

    /// Report where `component_id` currently stands. Unlike [`Self::ensure_contract`],
    /// [`Self::prefetch`], and [`Self::cache_path`], a `Bundled` entry is a legitimate answer
    /// here rather than a failure: it is this manager's way of saying "linked in ahead of
    /// time, never downloaded or loaded through me", not an error.
    pub fn status(&self, component_id: &str) -> Result<ComponentStatus, ComponentError> {
        let entry = self.lookup(component_id)?;
        if entry.mode == ComponentDeliveryMode::Bundled {
            return Ok(ComponentStatus::Bundled);
        }
        let loaded_prefix = format!("{component_id}::");
        if self
            .loaded
            .lock()
            .unwrap_or_else(PoisonError::into_inner)
            .iter()
            .any(|(key, component)| key.starts_with(&loaded_prefix) && component.is_active())
        {
            return Ok(ComponentStatus::Ready);
        }
        let root = self.cache.object_path(entry)?;
        if root.join("component.json").is_file() {
            Ok(ComponentStatus::Cached)
        } else {
            Ok(ComponentStatus::NotDownloaded)
        }
    }

    pub fn cache_path(&self, component_id: &str) -> Result<PathBuf, ComponentError> {
        self.cache.object_path(self.entry(component_id)?)
    }

    #[must_use]
    pub fn cache_root(&self) -> &Path {
        self.cache.root()
    }

    #[must_use]
    pub fn target(&self) -> &str {
        &self.target
    }

    /// Look up a component's lock entry for this manager's target, with no restriction on
    /// its delivery mode. [`Self::status`] uses this directly since a `Bundled` entry is a
    /// legitimate status to report, not a failure.
    ///
    /// A miss against a lock that was empty before target filtering reports
    /// [`ComponentError::ComponentsNotLocked`] instead of the generic
    /// [`ComponentError::ArtifactNotFound`]: `alef component lock` has never populated it, so
    /// naming the fix is more useful than reporting a missing target.
    fn lookup(&self, component_id: &str) -> Result<&ComponentLockEntry, ComponentError> {
        self.entries.get(component_id).ok_or_else(|| {
            if self.lock_is_empty {
                ComponentError::ComponentsNotLocked {
                    component_id: component_id.to_owned(),
                }
            } else {
                ComponentError::ArtifactNotFound {
                    component_id: component_id.to_owned(),
                    target: self.target.clone(),
                }
            }
        })
    }

    /// Like [`Self::lookup`], but additionally rejects a `Bundled` entry -- one this manager
    /// cannot download -- before any cache I/O runs. Every caller that actually needs to
    /// touch the cache (`ensure_contract`, `prefetch`, `cache_path`) reaches it only through
    /// this method.
    fn entry(&self, component_id: &str) -> Result<&ComponentLockEntry, ComponentError> {
        let entry = self.lookup(component_id)?;
        if entry.mode == ComponentDeliveryMode::Bundled {
            return Err(ComponentError::BundledComponentNotLoadable {
                component: component_id.to_owned(),
            });
        }
        Ok(entry)
    }
}

/// Reject a lock that cannot be verified by signature: no embedded keys, or an artifact that
/// names no key or a key the lock does not embed.
fn require_signed_lock(lock: &ComponentLock) -> Result<(), ComponentError> {
    if lock.public_keys.is_empty() {
        return Err(ComponentError::UnsignedLock(
            "the lock embeds no public keys".to_owned(),
        ));
    }
    for artifact in &lock.artifacts {
        if artifact.mode == ComponentDeliveryMode::Bundled {
            // Linked into the binding ahead of time; never downloaded, so never verified here.
            continue;
        }
        let name = || format!("`{}` for `{}`", artifact.identity.component, artifact.identity.target);
        if artifact.key_id.is_empty() {
            return Err(ComponentError::UnsignedLock(format!(
                "artifact {} has no key_id",
                name()
            )));
        }
        if !lock.public_keys.contains_key(&artifact.key_id) {
            return Err(ComponentError::UnsignedLock(format!(
                "artifact {} names key `{}`, which the lock does not embed",
                name(),
                artifact.key_id
            )));
        }
    }
    Ok(())
}

fn loaded_cache_key(component_id: &str, contract_name: &str) -> String {
    format!("{component_id}::{contract_name}")
}

fn contract_requirements(
    entry: &ComponentLockEntry,
    contract_name: &str,
) -> Result<ComponentRequirements, ComponentError> {
    let provided = entry
        .provides
        .iter()
        .find(|provided| provided.contract == contract_name)
        .ok_or_else(|| ComponentError::ContractNotProvided {
            component_id: entry.identity.component.clone(),
            contract: contract_name.to_owned(),
        })?;
    Ok(ComponentRequirements {
        component_id: entry.identity.component.clone(),
        contract_name: contract_name.to_owned(),
        contract_hash: decode_hash(&provided.contract_hash)?,
        feature_set_hash: Some(decode_hash(&entry.identity.feature_hash)?),
    })
}

#[cfg(test)]
mod tests;