1use std::{
2 collections::{BTreeMap, HashMap, HashSet},
3 fmt::Debug,
4 path::{Path, PathBuf},
5 sync::Arc,
6};
7
8use anyhow::{Context, Error};
9use futures::{StreamExt, TryStreamExt, future::BoxFuture};
10use once_cell::sync::OnceCell;
11use petgraph::visit::EdgeRef;
12use virtual_fs::{FileSystem, OverlayFileSystem, UnionFileSystem, WebcVolumeFileSystem};
13use wasmer_config::package::{PackageId, SuggestedCompilerOptimizations};
14use wasmer_package::utils::wasm_annotations_to_features;
15use webc::metadata::annotations::Atom as AtomAnnotation;
16use webc::{Container, Volume};
17
18use crate::{
19 bin_factory::{BinaryPackage, BinaryPackageCommand},
20 runtime::{
21 package_loader::PackageLoader,
22 resolver::{
23 DependencyGraph, ItemLocation, PackageSummary, Resolution, ResolvedFileSystemMapping,
24 ResolvedPackage,
25 },
26 },
27};
28
29use super::to_module_hash;
30
31fn wasm_annotation_to_features(
33 wasm_annotation: &webc::metadata::annotations::Wasm,
34) -> Option<wasmer_types::Features> {
35 Some(wasm_annotations_to_features(&wasm_annotation.features))
36}
37
38fn extract_features_from_atom_metadata(
40 atom_metadata: &webc::metadata::Atom,
41) -> Option<wasmer_types::Features> {
42 if let Ok(Some(wasm_annotation)) = atom_metadata
43 .annotation::<webc::metadata::annotations::Wasm>(webc::metadata::annotations::Wasm::KEY)
44 {
45 wasm_annotation_to_features(&wasm_annotation)
46 } else {
47 None
48 }
49}
50
51const MAX_PARALLEL_DOWNLOADS: usize = 32;
53
54#[tracing::instrument(level = "debug", skip_all)]
56pub async fn load_package_tree(
57 root: &Container,
58 loader: &dyn PackageLoader,
59 resolution: &Resolution,
60 root_is_local_dir: bool,
61) -> Result<BinaryPackage, Error> {
62 let mut containers = fetch_dependencies(loader, &resolution.package, &resolution.graph).await?;
63 containers.insert(resolution.package.root_package.clone(), root.clone());
64 let package_ids = containers.keys().cloned().collect();
65 let fs = filesystem(&containers, &resolution.package, root_is_local_dir)?;
66
67 let root = &resolution.package.root_package;
68 let commands: Vec<BinaryPackageCommand> =
69 commands(&resolution.package.commands, &containers, resolution)?;
70
71 let file_system_memory_footprint = count_file_system(&fs, Path::new("/"));
72
73 let loaded = BinaryPackage {
74 id: root.clone(),
75 package_ids,
76 when_cached: crate::syscalls::platform_clock_time_get(
77 wasmer_wasix_types::wasi::Snapshot0Clockid::Monotonic,
78 1_000_000,
79 )
80 .ok()
81 .map(|ts| ts as u128),
82 hash: OnceCell::new(),
83 entrypoint_cmd: resolution.package.entrypoint.clone(),
84 webc_fs: Arc::new(fs),
85 commands,
86 uses: Vec::new(),
87 file_system_memory_footprint,
88
89 additional_host_mapped_directories: vec![],
90 };
91
92 Ok(loaded)
93}
94
95fn commands(
96 commands: &BTreeMap<String, ItemLocation>,
97 containers: &HashMap<PackageId, Container>,
98 resolution: &Resolution,
99) -> Result<Vec<BinaryPackageCommand>, Error> {
100 let mut pkg_commands = Vec::new();
101
102 for (
103 name,
104 ItemLocation {
105 name: original_name,
106 package,
107 },
108 ) in commands
109 {
110 let webc = &containers[package];
111 let manifest = webc.manifest();
112 let command_metadata = &manifest.commands[original_name];
113
114 if let Some(cmd) =
115 load_binary_command(package, name, command_metadata, containers, resolution)?
116 {
117 pkg_commands.push(cmd);
118 }
119 }
120
121 Ok(pkg_commands)
122}
123
124#[tracing::instrument(skip_all, fields(%package_id, %command_name))]
127fn load_binary_command(
128 package_id: &PackageId,
129 command_name: &str,
130 cmd: &webc::metadata::Command,
131 containers: &HashMap<PackageId, Container>,
132 resolution: &Resolution,
133) -> Result<Option<BinaryPackageCommand>, anyhow::Error> {
134 let AtomAnnotation {
135 name: atom_name,
136 dependency,
137 ..
138 } = match atom_name_for_command(command_name, cmd)? {
139 Some(name) => name,
140 None => {
141 tracing::warn!(
142 cmd.name=command_name,
143 cmd.runner=%cmd.runner,
144 "Skipping unsupported command",
145 );
146 return Ok(None);
147 }
148 };
149
150 let package = &containers[package_id];
151
152 let (webc, resolved_package_id) = match dependency {
153 Some(dep) => {
154 let ix = resolution
155 .graph
156 .packages()
157 .get(package_id)
158 .copied()
159 .unwrap();
160 let graph = resolution.graph.graph();
161 let edge_reference = graph
162 .edges_directed(ix, petgraph::Direction::Outgoing)
163 .find(|edge| edge.weight().alias == dep)
164 .with_context(|| format!("Unable to find the \"{dep}\" dependency for the \"{command_name}\" command in \"{package_id}\""))?;
165
166 let other_package = graph.node_weight(edge_reference.target()).unwrap();
167 let id = &other_package.id;
168
169 tracing::debug!(
170 dependency=%dep,
171 resolved_package_id=%id,
172 "command atom resolution: resolved dependency",
173 );
174 (&containers[id], id)
175 }
176 None => (package, package_id),
177 };
178
179 let atom = webc.get_atom(&atom_name);
180
181 if atom.is_none() && cmd.annotations.is_empty() {
182 tracing::info!("applying legacy atom hack");
183 return legacy_atom_hack(webc, command_name, cmd);
184 }
185
186 let hash = to_module_hash(webc.manifest().atom_signature(&atom_name)?);
187
188 let atom = atom.with_context(|| {
189
190 let available_atoms = webc.atoms().keys().map(|x| x.as_str()).collect::<Vec<_>>().join(",");
191
192 tracing::warn!(
193 %atom_name,
194 %resolved_package_id,
195 %available_atoms,
196 "invalid command: could not find atom in package",
197 );
198
199 format!(
200 "The '{command_name}' command uses the '{atom_name}' atom, but it isn't present in the package: {resolved_package_id})"
201 )
202 })?;
203
204 let features = if let Some(atom_metadata) = webc.manifest().atoms.get(&atom_name) {
206 extract_features_from_atom_metadata(atom_metadata)
207 } else {
208 None
209 };
210
211 let suggested_compiler_optimizations =
212 if let Some(atom_metadata) = webc.manifest().atoms.get(&atom_name) {
213 extract_suggested_compiler_opts_from_atom_metadata(atom_metadata)
214 } else {
215 wasmer_config::package::SuggestedCompilerOptimizations::default()
216 };
217
218 let cmd = BinaryPackageCommand::new(
219 command_name.to_string(),
220 cmd.clone(),
221 atom,
222 hash,
223 features,
224 suggested_compiler_optimizations,
225 );
226
227 Ok(Some(cmd))
228}
229
230fn extract_suggested_compiler_opts_from_atom_metadata(
231 atom_metadata: &webc::metadata::Atom,
232) -> wasmer_config::package::SuggestedCompilerOptimizations {
233 let mut ret = SuggestedCompilerOptimizations::default();
234
235 if let Some(sco) = atom_metadata
236 .annotations
237 .get(SuggestedCompilerOptimizations::KEY)
238 && let Some((_, v)) = sco.as_map().and_then(|v| {
239 v.iter().find(|(k, _)| {
240 k.as_text()
241 .is_some_and(|v| v == SuggestedCompilerOptimizations::PASS_PARAMS_KEY)
242 })
243 })
244 {
245 ret.pass_params = v.as_bool()
246 }
247
248 ret
249}
250
251fn atom_name_for_command(
252 command_name: &str,
253 cmd: &webc::metadata::Command,
254) -> Result<Option<AtomAnnotation>, anyhow::Error> {
255 use webc::metadata::annotations::{WASI_RUNNER_URI, WCGI_RUNNER_URI};
256
257 if let Some(atom) = cmd
258 .atom()
259 .context("Unable to deserialize atom annotations")?
260 {
261 return Ok(Some(atom));
262 }
263
264 if [WASI_RUNNER_URI, WCGI_RUNNER_URI]
265 .iter()
266 .any(|uri| cmd.runner.starts_with(uri))
267 {
268 tracing::debug!(
272 command = command_name,
273 "No annotations specifying the atom name found. Falling back to the command name"
274 );
275 return Ok(Some(AtomAnnotation::new(command_name, None)));
276 }
277
278 Ok(None)
279}
280
281fn legacy_atom_hack(
292 webc: &Container,
293 command_name: &str,
294 metadata: &webc::metadata::Command,
295) -> Result<Option<BinaryPackageCommand>, anyhow::Error> {
296 let (name, atom) = webc
297 .atoms()
298 .into_iter()
299 .next()
300 .ok_or_else(|| anyhow::Error::msg("container does not have any atom"))?;
301
302 tracing::debug!(
303 command_name,
304 atom.name = name.as_str(),
305 atom.len = atom.len(),
306 "(hack) The command metadata is malformed. Falling back to the first atom in the WEBC file",
307 );
308
309 let hash = to_module_hash(webc.manifest().atom_signature(&name)?);
310
311 let features = if let Some(atom_metadata) = webc.manifest().atoms.get(&name) {
313 extract_features_from_atom_metadata(atom_metadata)
314 } else {
315 None
316 };
317
318 let suggested_opts_from_manifest = if let Some(atom_metadata) = webc.manifest().atoms.get(&name)
320 {
321 extract_suggested_compiler_opts_from_atom_metadata(atom_metadata)
322 } else {
323 SuggestedCompilerOptimizations::default()
324 };
325
326 Ok(Some(BinaryPackageCommand::new(
327 command_name.to_string(),
328 metadata.clone(),
329 atom,
330 hash,
331 features,
332 suggested_opts_from_manifest,
333 )))
334}
335
336async fn fetch_dependencies(
337 loader: &dyn PackageLoader,
338 pkg: &ResolvedPackage,
339 graph: &DependencyGraph,
340) -> Result<HashMap<PackageId, Container>, Error> {
341 let mut packages = HashSet::new();
342
343 for loc in pkg.commands.values() {
344 packages.insert(loc.package.clone());
345 }
346
347 for mapping in &pkg.filesystem {
348 packages.insert(mapping.package.clone());
349 }
350
351 packages.remove(&pkg.root_package);
353
354 let packages = packages.into_iter().filter_map(|id| {
355 let crate::runtime::resolver::Node { pkg, dist, .. } = &graph[&id];
356 let summary = PackageSummary {
357 pkg: pkg.clone(),
358 dist: dist.clone()?,
359 };
360 Some((id, summary))
361 });
362 let packages: HashMap<PackageId, Container> = futures::stream::iter(packages)
363 .map(|(id, s)| async move {
364 match loader.load(&s).await {
365 Ok(webc) => Ok((id, webc)),
366 Err(e) => Err(e),
367 }
368 })
369 .buffer_unordered(MAX_PARALLEL_DOWNLOADS)
370 .try_collect()
371 .await?;
372
373 Ok(packages)
374}
375
376fn count_file_system(fs: &dyn FileSystem, path: &Path) -> u64 {
378 let mut total = 0;
379
380 let dir = match fs.read_dir(path) {
381 Ok(d) => d,
382 Err(_err) => {
383 return 0;
384 }
385 };
386
387 for entry in dir.flatten() {
388 if let Ok(meta) = entry.metadata() {
389 total += meta.len();
390 if meta.is_dir() {
391 total += count_file_system(fs, entry.path.as_path());
392 }
393 }
394 }
395
396 total
397}
398
399fn filesystem(
402 packages: &HashMap<PackageId, Container>,
403 pkg: &ResolvedPackage,
404 root_is_local_dir: bool,
405) -> Result<Box<dyn FileSystem + Send + Sync>, Error> {
406 if pkg.filesystem.is_empty() {
407 return Ok(Box::new(OverlayFileSystem::<
408 virtual_fs::EmptyFileSystem,
409 Vec<WebcVolumeFileSystem>,
410 >::new(
411 virtual_fs::EmptyFileSystem::default(), vec![]
412 )));
413 }
414
415 let mut found_v2 = None;
416 let mut found_v3 = None;
417
418 for ResolvedFileSystemMapping { package, .. } in &pkg.filesystem {
419 let container = packages.get(package).with_context(|| {
420 format!(
421 "\"{}\" wants to use the \"{}\" package, but it isn't in the dependency tree",
422 pkg.root_package, package,
423 )
424 })?;
425
426 if container.version() == webc::Version::V2 && found_v2.is_none() {
427 found_v2 = Some(package.clone());
428 }
429 if container.version() == webc::Version::V3 && found_v3.is_none() {
430 found_v3 = Some(package.clone());
431 }
432 }
433
434 match (found_v2, found_v3) {
435 (None, Some(_)) => filesystem_v3(packages, pkg, root_is_local_dir),
436 (Some(_), None) => filesystem_v2(packages, pkg, root_is_local_dir),
437 (Some(v2), Some(v3)) => {
438 anyhow::bail!(
439 "Mix of webc v2 and v3 in the same dependency tree is not supported; v2: {v2}, v3: {v3}"
440 )
441 }
442 (None, None) => anyhow::bail!("Internal error: no packages found in tree"),
443 }
444}
445
446fn filesystem_v3(
448 packages: &HashMap<PackageId, Container>,
449 pkg: &ResolvedPackage,
450 root_is_local_dir: bool,
451) -> Result<Box<dyn FileSystem + Send + Sync>, Error> {
452 let mut volumes: HashMap<&PackageId, BTreeMap<String, Volume>> = HashMap::new();
453
454 let mut mountings: Vec<_> = pkg.filesystem.iter().collect();
455 mountings.sort_by_key(|m| std::cmp::Reverse(m.mount_path.as_path()));
456
457 let union_fs = UnionFileSystem::new();
458
459 for ResolvedFileSystemMapping {
460 mount_path,
461 volume_name,
462 package,
463 ..
464 } in &pkg.filesystem
465 {
466 if *package == pkg.root_package && root_is_local_dir {
467 continue;
468 }
469
470 let container = packages.get(package).with_context(|| {
475 format!(
476 "\"{}\" wants to use the \"{}\" package, but it isn't in the dependency tree",
477 pkg.root_package, package,
478 )
479 })?;
480 let container_volumes = match volumes.entry(package) {
481 std::collections::hash_map::Entry::Occupied(entry) => &*entry.into_mut(),
482 std::collections::hash_map::Entry::Vacant(entry) => &*entry.insert(container.volumes()),
483 };
484
485 let volume = container_volumes.get(volume_name).with_context(|| {
486 format!("The \"{package}\" package doesn't have a \"{volume_name}\" volume")
487 })?;
488
489 let webc_vol = WebcVolumeFileSystem::new(volume.clone());
490 union_fs.mount(volume_name.clone(), mount_path, Box::new(webc_vol))?;
491 }
492
493 let fs = OverlayFileSystem::new(virtual_fs::EmptyFileSystem::default(), [union_fs]);
494
495 Ok(Box::new(fs))
496}
497
498fn filesystem_v2(
522 packages: &HashMap<PackageId, Container>,
523 pkg: &ResolvedPackage,
524 root_is_local_dir: bool,
525) -> Result<Box<dyn FileSystem + Send + Sync>, Error> {
526 let mut filesystems = Vec::new();
527 let mut volumes: HashMap<&PackageId, BTreeMap<String, Volume>> = HashMap::new();
528
529 let mut mountings: Vec<_> = pkg.filesystem.iter().collect();
530 mountings.sort_by_key(|m| std::cmp::Reverse(m.mount_path.as_path()));
531
532 for ResolvedFileSystemMapping {
533 mount_path,
534 volume_name,
535 package,
536 original_path,
537 } in &pkg.filesystem
538 {
539 if *package == pkg.root_package && root_is_local_dir {
540 continue;
541 }
542
543 let container_volumes = match volumes.entry(package) {
547 std::collections::hash_map::Entry::Occupied(entry) => &*entry.into_mut(),
548 std::collections::hash_map::Entry::Vacant(entry) => {
549 let container = packages.get(package)
551 .with_context(|| format!(
552 "\"{}\" wants to use the \"{}\" package, but it isn't in the dependency tree",
553 pkg.root_package,
554 package,
555 ))?;
556 &*entry.insert(container.volumes())
557 }
558 };
559
560 let volume = container_volumes.get(volume_name).with_context(|| {
561 format!("The \"{package}\" package doesn't have a \"{volume_name}\" volume")
562 })?;
563
564 let mount_path = mount_path.clone();
565 let fs = if let Some(original) = original_path {
568 let original = PathBuf::from(original);
569
570 MappedPathFileSystem::new(
571 WebcVolumeFileSystem::new(volume.clone()),
572 Box::new(move |path: &Path| {
573 let without_mount_dir = path
574 .strip_prefix(&mount_path)
575 .map_err(|_| virtual_fs::FsError::BaseNotDirectory)?;
576 Ok(original.join(without_mount_dir))
577 }) as DynPathMapper,
578 )
579 } else {
580 MappedPathFileSystem::new(
581 WebcVolumeFileSystem::new(volume.clone()),
582 Box::new(move |path: &Path| {
583 let without_mount_dir = path
584 .strip_prefix(&mount_path)
585 .map_err(|_| virtual_fs::FsError::BaseNotDirectory)?;
586 Ok(without_mount_dir.to_owned())
587 }) as DynPathMapper,
588 )
589 };
590
591 filesystems.push(fs);
592 }
593
594 let fs = OverlayFileSystem::new(virtual_fs::EmptyFileSystem::default(), filesystems);
595
596 Ok(Box::new(fs))
597}
598
599type DynPathMapper = Box<dyn Fn(&Path) -> Result<PathBuf, virtual_fs::FsError> + Send + Sync>;
600
601#[derive(Clone, PartialEq)]
604struct MappedPathFileSystem<F, M> {
605 inner: F,
606 map: M,
607}
608
609impl<F, M> MappedPathFileSystem<F, M>
610where
611 M: Fn(&Path) -> Result<PathBuf, virtual_fs::FsError> + Send + Sync + 'static,
612{
613 fn new(inner: F, map: M) -> Self {
614 MappedPathFileSystem { inner, map }
615 }
616
617 fn path(&self, path: &Path) -> Result<PathBuf, virtual_fs::FsError> {
618 let path = (self.map)(path)?;
619
620 Ok(Path::new("/").join(path))
622 }
623}
624
625impl<M, F> FileSystem for MappedPathFileSystem<F, M>
626where
627 F: FileSystem,
628 M: Fn(&Path) -> Result<PathBuf, virtual_fs::FsError> + Send + Sync + 'static,
629{
630 fn readlink(&self, path: &Path) -> virtual_fs::Result<PathBuf> {
631 let path = self.path(path)?;
632 self.inner.readlink(&path)
633 }
634
635 fn read_dir(&self, path: &Path) -> virtual_fs::Result<virtual_fs::ReadDir> {
636 let path = self.path(path)?;
637 self.inner.read_dir(&path)
638 }
639
640 fn create_dir(&self, path: &Path) -> virtual_fs::Result<()> {
641 let path = self.path(path)?;
642 self.inner.create_dir(&path)
643 }
644
645 fn remove_dir(&self, path: &Path) -> virtual_fs::Result<()> {
646 let path = self.path(path)?;
647 self.inner.remove_dir(&path)
648 }
649
650 fn rename<'a>(&'a self, from: &Path, to: &Path) -> BoxFuture<'a, virtual_fs::Result<()>> {
651 let from = from.to_owned();
652 let to = to.to_owned();
653 Box::pin(async move {
654 let from = self.path(&from)?;
655 let to = self.path(&to)?;
656 self.inner.rename(&from, &to).await
657 })
658 }
659
660 fn metadata(&self, path: &Path) -> virtual_fs::Result<virtual_fs::Metadata> {
661 let path = self.path(path)?;
662 self.inner.metadata(&path)
663 }
664
665 fn symlink_metadata(&self, path: &Path) -> virtual_fs::Result<virtual_fs::Metadata> {
666 let path = self.path(path)?;
667 self.inner.symlink_metadata(&path)
668 }
669
670 fn remove_file(&self, path: &Path) -> virtual_fs::Result<()> {
671 let path = self.path(path)?;
672 self.inner.remove_file(&path)
673 }
674
675 fn new_open_options(&self) -> virtual_fs::OpenOptions<'_> {
676 virtual_fs::OpenOptions::new(self)
677 }
678
679 fn mount(
680 &self,
681 name: String,
682 path: &Path,
683 fs: Box<dyn FileSystem + Send + Sync>,
684 ) -> virtual_fs::Result<()> {
685 let path = self.path(path)?;
686 self.inner.mount(name, path.as_path(), fs)
687 }
688}
689
690impl<F, M> virtual_fs::FileOpener for MappedPathFileSystem<F, M>
691where
692 F: FileSystem,
693 M: Fn(&Path) -> Result<PathBuf, virtual_fs::FsError> + Send + Sync + 'static,
694{
695 fn open(
696 &self,
697 path: &Path,
698 conf: &virtual_fs::OpenOptionsConfig,
699 ) -> virtual_fs::Result<Box<dyn virtual_fs::VirtualFile + Send + Sync + 'static>> {
700 let path = self.path(path)?;
701 self.inner
702 .new_open_options()
703 .options(conf.clone())
704 .open(path)
705 }
706}
707
708impl<F, M> Debug for MappedPathFileSystem<F, M>
709where
710 F: Debug,
711{
712 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
713 f.debug_struct("MappedPathFileSystem")
714 .field("inner", &self.inner)
715 .field("map", &std::any::type_name::<M>())
716 .finish()
717 }
718}