alef_component_runtime/manager.rs
1use crate::identity::VerifiedFile;
2use crate::loader::{decode_hash, validate_manifest};
3use crate::manifest::COMPONENT_MANIFEST_SCHEMA;
4use crate::stdio::{SidecarPolicy, SidecarProcess, SidecarRestartEvent, SidecarSessionSetup, SidecarVerifier};
5use crate::{
6 ArtifactCache, CachedArtifact, CachedObject, ComponentDeliveryMode, ComponentError, ComponentLock,
7 ComponentLockEntry, ComponentRequirements, DownloadOptions, HostServices, LoadedComponent, RemovalReport, Retain,
8 SignaturePolicy, TrustPolicy,
9};
10use alef_component_abi::AlefHostApiV1;
11use std::collections::{HashMap, HashSet};
12use std::path::{Path, PathBuf};
13use std::sync::{Arc, Mutex, PoisonError};
14use std::time::{Duration, SystemTime};
15
16/// Where a configured component currently stands, independent of its on-disk location (see
17/// [`ComponentManager::cache_path`] for that). Generated bindings expose this as both a
18/// stable string tag and a numeric code (`alef_component_status`/`alef_component_status_code`
19/// in `alef::backends::native_components`) so callers in any host language can branch on it
20/// without parsing free-form text.
21#[derive(Clone, Debug, PartialEq, Eq)]
22pub enum ComponentStatus {
23 /// Loaded and its contracts activated in this process.
24 Ready,
25 /// Downloaded and verified on disk, but not yet loaded in this process.
26 Cached,
27 /// Not yet present in the on-disk cache.
28 NotDownloaded,
29 /// Linked into the binding ahead of time for this target; never downloaded or loaded
30 /// through this manager.
31 Bundled,
32 /// This host/target does not support downloading native components at all.
33 Unsupported { reason: String },
34}
35
36pub struct ComponentManager {
37 cache: ArtifactCache,
38 target: String,
39 entries: HashMap<String, ComponentLockEntry>,
40 loaded: Mutex<HashMap<String, Arc<LoadedComponent>>>,
41 stdio_components: HashSet<String>,
42 sidecar_processes: Mutex<HashMap<String, Arc<SidecarProcess>>>,
43 sidecar_timeout: Duration,
44 /// Respawn knobs for stdio connections: the restart budget, the session setup replayed after
45 /// every spawn and respawn, and the restart event handler. Applied to every stdio component
46 /// this manager spawns; see the `with_sidecar_*` builders.
47 sidecar_policy: SidecarPolicy,
48 /// One lock per (component, contract) key, used to coalesce concurrent `ensure_contract`
49 /// calls for the same key onto a single download-and-load instead of racing duplicates;
50 /// a call for a different key gets its own lock and proceeds independently. See
51 /// [`Self::contract_lock`].
52 key_locks: Mutex<HashMap<String, Arc<Mutex<()>>>>,
53 /// Artifacts this process has already installed and verified, keyed by the lock entry's
54 /// own content-addressed `sha256` digest. A component that provides more than one
55 /// contract shares one artifact across several `ensure_contract` calls; without this, each
56 /// call would re-read and re-hash the same (potentially large) dylib. Each entry keeps the
57 /// verified library open, and every later load goes through that descriptor or re-checks the
58 /// path against it (see `identity`), so replacing the file after verification is refused
59 /// rather than loaded.
60 verified_artifacts: Mutex<HashMap<String, (CachedArtifact, VerifiedFile)>>,
61 /// Whether the lock this manager was built from had zero artifacts *before* target
62 /// filtering -- the shape `alef generate` bootstraps when a crate declares components but
63 /// `alef component lock` has never run (see
64 /// `alef::bin_cli::component_commands::bootstrap_missing_component_locks`). Distinguished
65 /// from "no artifact for this particular target", which is a normal, populated lock that
66 /// simply was not built for the requested target.
67 lock_is_empty: bool,
68 /// Archive digests of every artifact in the lock, across all targets; what
69 /// [`Retain::referenced_by_lock`] keeps.
70 locked_digests: HashSet<String>,
71 host: AlefHostApiV1,
72 host_services: Option<Arc<dyn HostServices>>,
73}
74
75// SAFETY: `LoadedComponent` is thread-safe metadata and the host callback
76// context is required by the ABI to remain valid for calls from component
77// threads. Mutation is protected by the manager mutex. ~keep
78unsafe impl Send for ComponentManager {}
79// SAFETY: as for `Send` above: shared state is behind mutexes, and the host table is only
80// copied, never mutated, after construction.
81unsafe impl Sync for ComponentManager {}
82
83impl ComponentManager {
84 /// A manager for `lock` that accepts unsigned locks ([`SignaturePolicy::AllowUnsigned`]);
85 /// see [`Self::from_lock_with_signature_policy`] to require signatures.
86 pub fn from_lock(
87 lock: ComponentLock,
88 cache_root: impl Into<PathBuf>,
89 target: impl Into<String>,
90 host: AlefHostApiV1,
91 ) -> Result<Self, ComponentError> {
92 Self::from_lock_with_signature_policy(lock, cache_root, target, host, SignaturePolicy::AllowUnsigned)
93 }
94
95 /// Like [`Self::from_lock`]. With [`SignaturePolicy::Require`] the lock must embed at least
96 /// one public key and every artifact (for every target) must name one of them in `key_id`,
97 /// or this fails with [`ComponentError::UnsignedLock`]; every install then verifies the
98 /// manifest signature. Without it, a lock with no keys is checked by digest alone, so anyone
99 /// able to edit the lock can substitute an artifact.
100 pub fn from_lock_with_signature_policy(
101 lock: ComponentLock,
102 cache_root: impl Into<PathBuf>,
103 target: impl Into<String>,
104 host: AlefHostApiV1,
105 signatures: SignaturePolicy,
106 ) -> Result<Self, ComponentError> {
107 if lock.schema_version != COMPONENT_MANIFEST_SCHEMA {
108 return Err(ComponentError::UnsupportedLockSchema(lock.schema_version));
109 }
110 if signatures == SignaturePolicy::Require {
111 require_signed_lock(&lock)?;
112 }
113 let mut lock = lock;
114 for artifact in &mut lock.artifacts {
115 // One spelling per object, matching the cache's directory names (see `canonical_entry`).
116 artifact.sha256.make_ascii_lowercase();
117 }
118 let lock_is_empty = lock.artifacts.is_empty();
119 let locked_digests = lock.artifacts.iter().map(|artifact| artifact.sha256.clone()).collect();
120 let target = target.into();
121 let mut entries = HashMap::new();
122 for artifact in lock
123 .artifacts
124 .into_iter()
125 .filter(|artifact| artifact.identity.target == target)
126 {
127 let id = artifact.identity.component.clone();
128 if entries.insert(id.clone(), artifact).is_some() {
129 return Err(ComponentError::DuplicateLockEntry {
130 component_id: id,
131 target,
132 });
133 }
134 }
135 Ok(Self {
136 cache: ArtifactCache::new(cache_root, TrustPolicy::EmbeddedKeys(lock.public_keys))
137 .with_signature_policy(signatures),
138 target,
139 entries,
140 loaded: Mutex::new(HashMap::new()),
141 stdio_components: HashSet::new(),
142 sidecar_processes: Mutex::new(HashMap::new()),
143 sidecar_timeout: Duration::from_secs(30),
144 sidecar_policy: SidecarPolicy::default(),
145 key_locks: Mutex::new(HashMap::new()),
146 verified_artifacts: Mutex::new(HashMap::new()),
147 lock_is_empty,
148 locked_digests,
149 host,
150 host_services: None,
151 })
152 }
153
154 /// Select the framed stdio transport for an executable component before first use.
155 ///
156 /// The artifact, signature, lock and cache contract are identical to native components.
157 /// All contracts of this component share one long-lived process. Only bytes invocation
158 /// is supported; generated typed C tables and host callback services are unavailable.
159 #[must_use]
160 pub fn with_stdio_component(mut self, component_id: impl Into<String>) -> Self {
161 self.stdio_components.insert(component_id.into());
162 self
163 }
164
165 /// Set the response deadline for stdio handshakes and calls (default: 30 seconds). A timeout
166 /// terminates the child; the connection is then respawned from the verified executable on a
167 /// later call, within the restart budget (see [`Self::with_sidecar_restart_budget`]). On a
168 /// protocol-2 connection a call's timeout terminates the child only when the sidecar answered
169 /// nothing during the whole deadline; otherwise only that call fails and its late response is
170 /// dropped.
171 #[must_use]
172 pub fn with_sidecar_timeout(mut self, timeout: Duration) -> Self {
173 self.sidecar_timeout = timeout;
174 self
175 }
176
177 /// Set how many times a stdio connection may be respawned from its verified executable after a
178 /// fatal error (a timeout, a broken frame, a dead child: default 1). `0` restores the previous
179 /// behavior, where the first fatal error stops the connection for good. A respawn re-runs the
180 /// describe validation and replays the session setup before the connection serves calls again.
181 #[must_use]
182 pub fn with_sidecar_restart_budget(mut self, budget: u32) -> Self {
183 self.sidecar_policy.restart_budget = budget;
184 self
185 }
186
187 /// Replay `setup` after the first spawn of every stdio component and after every respawn of
188 /// its connection, where it re-sends whatever session the host had built on the previous
189 /// connection (an `Init` call, one `RegisterConfig` per engine config). A setup failure stops
190 /// the connection and fails the call that triggered the respawn. The setup must send its calls
191 /// through the [`SidecarSession`] it is given: calling back into the manager, or into a
192 /// component handle captured earlier, deadlocks.
193 #[must_use]
194 pub fn with_sidecar_session(mut self, setup: SidecarSessionSetup) -> Self {
195 self.sidecar_policy.session = Some(setup);
196 self
197 }
198
199 /// Call `handler` with the component id and the new restart count after each successful stdio
200 /// respawn, so hosts can log that a connection was rebuilt.
201 #[must_use]
202 pub fn with_sidecar_restart_event(mut self, handler: SidecarRestartEvent) -> Self {
203 self.sidecar_policy.on_restart = Some(handler);
204 self
205 }
206
207 /// Pass these host environment variables through to stdio sidecars, on top of the default
208 /// allowlist. A sidecar starts with a cleared environment holding only `PATH`, `HOME`, `USER`,
209 /// `LOGNAME`, `TMPDIR`/`TEMP`/`TMP`, `TZ`, `LANG`, `LANGUAGE` and `LC_*` (plus `SYSTEMROOT`,
210 /// `WINDIR`, `SYSTEMDRIVE`, `USERPROFILE`, `PATHEXT` and `COMSPEC`, which Windows processes
211 /// need) and the protocol variable the runtime sets, and runs in its component's cache
212 /// directory. A name ending in `*` passes every variable with that prefix; names compare
213 /// case-insensitively on Windows.
214 #[must_use]
215 pub fn with_sidecar_env_passthrough(mut self, names: impl IntoIterator<Item = impl Into<String>>) -> Self {
216 self.sidecar_policy
217 .env_passthrough
218 .extend(names.into_iter().map(Into::into));
219 self
220 }
221
222 /// How many times the stdio connection of `component_id` has been respawned, or `None` when it
223 /// was never spawned in this manager (or is not a stdio component).
224 #[must_use]
225 pub fn sidecar_restart_count(&self, component_id: &str) -> Option<u32> {
226 self.sidecar_processes
227 .lock()
228 .unwrap_or_else(PoisonError::into_inner)
229 .get(component_id)
230 .map(|process| process.restart_count())
231 }
232
233 /// Expose `services` to components loaded from now on, through the host table's
234 /// `service_call` / `service_notify` callbacks. Components already loaded keep the table
235 /// they were created with, so call this before [`Self::ensure_contract`].
236 #[must_use]
237 pub fn with_host_services(mut self, services: Arc<dyn HostServices>) -> Self {
238 self.host_services = Some(services);
239 self
240 }
241
242 /// Disable network downloads: [`Self::ensure_contract`] and [`Self::prefetch`] fail a
243 /// missing artifact with [`ComponentError::Offline`] instead of attempting a request, and a
244 /// damaged installed artifact with [`ComponentError::CachedObjectInvalid`]. An artifact
245 /// already verified on disk (or served via a `file://` URL) is unaffected. Generated
246 /// bindings call this when the crate-specific `{CRATE}_COMPONENT_OFFLINE` environment
247 /// variable is set.
248 #[must_use]
249 pub fn offline(mut self, offline: bool) -> Self {
250 self.cache = self.cache.offline(offline);
251 self
252 }
253
254 /// Tune downloads: timeouts, retry policy, progress reporting and cancellation. Applies to
255 /// [`Self::ensure_contract`] and [`Self::prefetch`].
256 #[must_use]
257 pub fn with_download_options(mut self, options: DownloadOptions) -> Self {
258 self.cache = self.cache.with_download_options(options);
259 self
260 }
261
262 /// Download from `resolve(entry)` instead of the lock entry's `url`, for mirrors and
263 /// air-gapped hosts. The archive size, SHA-256 and signature are still checked against the
264 /// lock, so a mirror cannot substitute different content. A `file://` URL reads from disk.
265 ///
266 /// ```ignore
267 /// let manager = manager.with_url_override(|entry| {
268 /// entry.url.replacen("https://github.com/", "https://mirror.corp.example/github/", 1)
269 /// });
270 /// ```
271 #[must_use]
272 pub fn with_url_override(
273 mut self,
274 resolve: impl Fn(&ComponentLockEntry) -> String + Send + Sync + 'static,
275 ) -> Self {
276 self.cache = self.cache.with_url_override(resolve);
277 self
278 }
279
280 /// Download every archive from `base` instead of the lock's URL, keeping only the archive
281 /// file name: `{base}/{file name}`. A trailing slash on `base` is ignored.
282 #[must_use]
283 pub fn with_mirror_base(self, base: impl Into<String>) -> Self {
284 let base = base.into();
285 self.with_url_override(move |entry| {
286 let name = entry.url.split(['?', '#']).next().unwrap_or_default();
287 let name = name.rsplit('/').next().unwrap_or_default();
288 format!("{}/{name}", base.trim_end_matches('/'))
289 })
290 }
291
292 /// Skip re-hashing installed libraries that match their verified stamp. See
293 /// [`ArtifactCache::with_verified_stamp`] for the threat model.
294 #[must_use]
295 pub fn with_verified_stamp(mut self, enabled: bool) -> Self {
296 self.cache = self.cache.with_verified_stamp(enabled);
297 self
298 }
299
300 /// The lock entry for `component_id` on this manager's target, whatever its delivery mode.
301 pub fn lock_entry(&self, component_id: &str) -> Result<&ComponentLockEntry, ComponentError> {
302 self.lookup(component_id)
303 }
304
305 /// Every lock entry for this manager's target, sorted by component id.
306 #[must_use]
307 pub fn lock_entries(&self) -> Vec<&ComponentLockEntry> {
308 let mut entries: Vec<_> = self.entries.values().collect();
309 entries.sort_by(|a, b| a.identity.component.cmp(&b.identity.component));
310 entries
311 }
312
313 /// Every object installed in the cache, including ones other host versions installed.
314 /// `component` names the lock entry referencing the object, when this lock has one.
315 pub fn list_cached(&self) -> Result<Vec<CachedObject>, ComponentError> {
316 let mut objects = self.cache.list_objects()?;
317 for object in &mut objects {
318 object.component = self
319 .entries
320 .values()
321 .find(|entry| entry.sha256 == object.sha256)
322 .map(|entry| entry.identity.component.clone());
323 }
324 Ok(objects)
325 }
326
327 /// Remove `component_id`'s cached object. It re-downloads on next use. On Windows an
328 /// object whose library is loaded cannot be deleted; it is reported under `skipped`.
329 pub fn remove(&self, component_id: &str) -> Result<RemovalReport, ComponentError> {
330 let entry = self.entry(component_id)?;
331 self.verified_artifacts
332 .lock()
333 .unwrap_or_else(PoisonError::into_inner)
334 .remove(&entry.sha256);
335 self.cache.remove_object(&entry.sha256)
336 }
337
338 /// Remove cached objects `retain` does not keep, plus orphaned `.install-*` staging
339 /// directories and stamps. Objects loaded in this process or being installed by another
340 /// thread or process are skipped, as are files Windows refuses to delete; all are listed in
341 /// the report.
342 pub fn prune(&self, retain: &Retain) -> Result<RemovalReport, ComponentError> {
343 let loaded = self.loaded.lock().unwrap_or_else(PoisonError::into_inner);
344 let protected: HashSet<String> = self
345 .entries
346 .values()
347 .filter(|entry| {
348 let prefix = format!("{}::", entry.identity.component);
349 loaded.keys().any(|key| key.starts_with(&prefix))
350 })
351 .map(|entry| entry.sha256.clone())
352 .collect();
353 drop(loaded);
354 let report = self
355 .cache
356 .prune_objects(retain, &self.locked_digests, &protected, SystemTime::now())?;
357 let mut verified = self.verified_artifacts.lock().unwrap_or_else(PoisonError::into_inner);
358 for path in &report.removed {
359 if let Some(name) = path.file_name().and_then(|name| name.to_str()) {
360 verified.remove(name);
361 }
362 }
363 Ok(report)
364 }
365
366 /// Load one contract a component provides.
367 ///
368 /// `entry_symbol` is that contract's NUL-terminated producer entry-point
369 /// symbol (`alef::codegen::component::entry_point_symbol`); the caller
370 /// supplies it because computing it requires the same identifier-casing
371 /// logic the producer used, which this crate does not depend on.
372 ///
373 /// Concurrent calls for the *same* `(component_id, contract_name)` coalesce onto one
374 /// download-and-load: a second caller waits behind the first instead of racing a
375 /// duplicate download or `dlopen`. A call for a different key is unaffected and proceeds
376 /// immediately -- the mutex guarding the loaded-component map is only ever held for a
377 /// map lookup or insert, never across I/O.
378 pub fn ensure_contract(
379 &self,
380 component_id: &str,
381 contract_name: &str,
382 entry_symbol: &[u8],
383 ) -> Result<Arc<LoadedComponent>, ComponentError> {
384 let cache_key = loaded_cache_key(component_id, contract_name);
385 if let Some(component) = self.loaded_component(&cache_key) {
386 component.ensure_active()?;
387 return Ok(component);
388 }
389
390 let key_lock = self.contract_lock(cache_key.clone());
391 let _guard = key_lock.lock().unwrap_or_else(PoisonError::into_inner);
392 // Re-check now that this call holds the per-key lock: a concurrent caller for the
393 // same key may have finished the work while this call was waiting for it.
394 if let Some(component) = self.loaded_component(&cache_key) {
395 component.ensure_active()?;
396 return Ok(component);
397 }
398
399 let entry = self.entry(component_id)?;
400 let requirements = contract_requirements(entry, contract_name)?;
401 let (cached, verified) = self.cached_artifact(entry)?;
402 validate_manifest(&cached.manifest, &requirements)?;
403 let component = Arc::new(if self.stdio_components.contains(component_id) {
404 let process = self.sidecar_process(entry, &cached, &verified)?;
405 LoadedComponent::from_sidecar(process, &cached.manifest, &requirements, self.host)?
406 } else {
407 LoadedComponent::load_with_services(
408 &verified,
409 entry_symbol,
410 &requirements,
411 self.host,
412 self.host_services.clone(),
413 )?
414 });
415 self.insert_loaded(cache_key, Arc::clone(&component));
416 Ok(component)
417 }
418
419 fn sidecar_process(
420 &self,
421 entry: &ComponentLockEntry,
422 cached: &CachedArtifact,
423 verified: &VerifiedFile,
424 ) -> Result<Arc<SidecarProcess>, ComponentError> {
425 let component_id = entry.identity.component.as_str();
426 let process_lock = self.contract_lock(format!("stdio:{component_id}"));
427 let _guard = process_lock.lock().unwrap_or_else(PoisonError::into_inner);
428 if let Some(process) = self
429 .sidecar_processes
430 .lock()
431 .unwrap_or_else(PoisonError::into_inner)
432 .get(component_id)
433 {
434 process.ensure_running()?;
435 return Ok(Arc::clone(process));
436 }
437 let verify: SidecarVerifier = {
438 let cache = self.cache.clone();
439 let entry = entry.clone();
440 Arc::new(move || cache.verify_cached_file(&entry).map(|(_, verified)| verified))
441 };
442 let process = Arc::new(SidecarProcess::spawn(
443 verified,
444 verify,
445 &cached.manifest,
446 self.sidecar_timeout,
447 self.sidecar_policy.clone(),
448 )?);
449 self.sidecar_processes
450 .lock()
451 .unwrap_or_else(PoisonError::into_inner)
452 .insert(component_id.to_owned(), Arc::clone(&process));
453 Ok(process)
454 }
455
456 pub fn prefetch(&self, component_ids: &[&str]) -> Result<Vec<CachedArtifact>, ComponentError> {
457 component_ids
458 .iter()
459 .map(|component_id| -> Result<CachedArtifact, ComponentError> {
460 Ok(self.cached_artifact(self.entry(component_id)?)?.0)
461 })
462 .collect()
463 }
464
465 fn loaded_component(&self, cache_key: &str) -> Option<Arc<LoadedComponent>> {
466 self.loaded
467 .lock()
468 .unwrap_or_else(PoisonError::into_inner)
469 .get(cache_key)
470 .cloned()
471 }
472
473 fn insert_loaded(&self, cache_key: String, component: Arc<LoadedComponent>) {
474 self.loaded
475 .lock()
476 .unwrap_or_else(PoisonError::into_inner)
477 .insert(cache_key, component);
478 }
479
480 /// The per-`cache_key` lock used to coalesce concurrent [`Self::ensure_contract`] calls.
481 /// The outer `key_locks` mutex is only ever held for the lookup-or-insert below, never
482 /// across the download/load work the returned lock guards.
483 fn contract_lock(&self, cache_key: String) -> Arc<Mutex<()>> {
484 Arc::clone(
485 self.key_locks
486 .lock()
487 .unwrap_or_else(PoisonError::into_inner)
488 .entry(cache_key)
489 .or_insert_with(|| Arc::new(Mutex::new(()))),
490 )
491 }
492
493 /// Install `entry`'s artifact, reusing an in-process-verified copy when this process has
494 /// already installed it (see [`Self::verified_artifacts`]).
495 fn cached_artifact(&self, entry: &ComponentLockEntry) -> Result<(CachedArtifact, VerifiedFile), ComponentError> {
496 if let Some(verified) = self
497 .verified_artifacts
498 .lock()
499 .unwrap_or_else(PoisonError::into_inner)
500 .get(&entry.sha256)
501 .cloned()
502 {
503 return Ok(verified);
504 }
505 let verified = self.cache.install_verified(entry)?;
506 self.verified_artifacts
507 .lock()
508 .unwrap_or_else(PoisonError::into_inner)
509 .insert(entry.sha256.clone(), verified.clone());
510 Ok(verified)
511 }
512
513 /// Report where `component_id` currently stands. Unlike [`Self::ensure_contract`],
514 /// [`Self::prefetch`], and [`Self::cache_path`], a `Bundled` entry is a legitimate answer
515 /// here rather than a failure: it is this manager's way of saying "linked in ahead of
516 /// time, never downloaded or loaded through me", not an error.
517 pub fn status(&self, component_id: &str) -> Result<ComponentStatus, ComponentError> {
518 let entry = self.lookup(component_id)?;
519 if entry.mode == ComponentDeliveryMode::Bundled {
520 return Ok(ComponentStatus::Bundled);
521 }
522 let loaded_prefix = format!("{component_id}::");
523 if self
524 .loaded
525 .lock()
526 .unwrap_or_else(PoisonError::into_inner)
527 .iter()
528 .any(|(key, component)| key.starts_with(&loaded_prefix) && component.is_active())
529 {
530 return Ok(ComponentStatus::Ready);
531 }
532 let root = self.cache.object_path(entry)?;
533 if root.join("component.json").is_file() {
534 Ok(ComponentStatus::Cached)
535 } else {
536 Ok(ComponentStatus::NotDownloaded)
537 }
538 }
539
540 pub fn cache_path(&self, component_id: &str) -> Result<PathBuf, ComponentError> {
541 self.cache.object_path(self.entry(component_id)?)
542 }
543
544 #[must_use]
545 pub fn cache_root(&self) -> &Path {
546 self.cache.root()
547 }
548
549 #[must_use]
550 pub fn target(&self) -> &str {
551 &self.target
552 }
553
554 /// Look up a component's lock entry for this manager's target, with no restriction on
555 /// its delivery mode. [`Self::status`] uses this directly since a `Bundled` entry is a
556 /// legitimate status to report, not a failure.
557 ///
558 /// A miss against a lock that was empty before target filtering reports
559 /// [`ComponentError::ComponentsNotLocked`] instead of the generic
560 /// [`ComponentError::ArtifactNotFound`]: `alef component lock` has never populated it, so
561 /// naming the fix is more useful than reporting a missing target.
562 fn lookup(&self, component_id: &str) -> Result<&ComponentLockEntry, ComponentError> {
563 self.entries.get(component_id).ok_or_else(|| {
564 if self.lock_is_empty {
565 ComponentError::ComponentsNotLocked {
566 component_id: component_id.to_owned(),
567 }
568 } else {
569 ComponentError::ArtifactNotFound {
570 component_id: component_id.to_owned(),
571 target: self.target.clone(),
572 }
573 }
574 })
575 }
576
577 /// Like [`Self::lookup`], but additionally rejects a `Bundled` entry -- one this manager
578 /// cannot download -- before any cache I/O runs. Every caller that actually needs to
579 /// touch the cache (`ensure_contract`, `prefetch`, `cache_path`) reaches it only through
580 /// this method.
581 fn entry(&self, component_id: &str) -> Result<&ComponentLockEntry, ComponentError> {
582 let entry = self.lookup(component_id)?;
583 if entry.mode == ComponentDeliveryMode::Bundled {
584 return Err(ComponentError::BundledComponentNotLoadable {
585 component: component_id.to_owned(),
586 });
587 }
588 Ok(entry)
589 }
590}
591
592/// Reject a lock that cannot be verified by signature: no embedded keys, or an artifact that
593/// names no key or a key the lock does not embed.
594fn require_signed_lock(lock: &ComponentLock) -> Result<(), ComponentError> {
595 if lock.public_keys.is_empty() {
596 return Err(ComponentError::UnsignedLock(
597 "the lock embeds no public keys".to_owned(),
598 ));
599 }
600 for artifact in &lock.artifacts {
601 if artifact.mode == ComponentDeliveryMode::Bundled {
602 // Linked into the binding ahead of time; never downloaded, so never verified here.
603 continue;
604 }
605 let name = || format!("`{}` for `{}`", artifact.identity.component, artifact.identity.target);
606 if artifact.key_id.is_empty() {
607 return Err(ComponentError::UnsignedLock(format!(
608 "artifact {} has no key_id",
609 name()
610 )));
611 }
612 if !lock.public_keys.contains_key(&artifact.key_id) {
613 return Err(ComponentError::UnsignedLock(format!(
614 "artifact {} names key `{}`, which the lock does not embed",
615 name(),
616 artifact.key_id
617 )));
618 }
619 }
620 Ok(())
621}
622
623fn loaded_cache_key(component_id: &str, contract_name: &str) -> String {
624 format!("{component_id}::{contract_name}")
625}
626
627fn contract_requirements(
628 entry: &ComponentLockEntry,
629 contract_name: &str,
630) -> Result<ComponentRequirements, ComponentError> {
631 let provided = entry
632 .provides
633 .iter()
634 .find(|provided| provided.contract == contract_name)
635 .ok_or_else(|| ComponentError::ContractNotProvided {
636 component_id: entry.identity.component.clone(),
637 contract: contract_name.to_owned(),
638 })?;
639 Ok(ComponentRequirements {
640 component_id: entry.identity.component.clone(),
641 contract_name: contract_name.to_owned(),
642 contract_hash: decode_hash(&provided.contract_hash)?,
643 feature_set_hash: Some(decode_hash(&entry.identity.feature_hash)?),
644 })
645}
646
647#[cfg(test)]
648mod tests;