1use anyhow::Result;
4use wasmtime::component::{Component, Linker};
5use wasmtime::{Config, Engine};
6
7use crate::store::HostState;
8use crate::{credentials, fs_policy};
9
10pub fn create_engine() -> Result<Engine> {
12 let mut config = Config::new();
13 config.wasm_component_model(true);
14 config.wasm_component_model_async(true);
15 config.wasm_exceptions(true);
19 config.wasm_function_references(true);
21 config.wasm_gc(true);
22 let engine = Engine::new(&config)
23 .map_err(|e| anyhow::anyhow!("failed to create wasmtime engine: {e}"))?;
24 Ok(engine)
25}
26pub fn load_component(engine: &Engine, path: &std::path::Path) -> Result<(Component, String)> {
33 let bytes = std::fs::read(path)
34 .map_err(|e| anyhow::anyhow!("failed to read component {}: {e}", path.display()))?;
35 let digest = crate::audit::sha256_hex(&bytes);
36 let component = Component::from_binary(engine, &bytes)
37 .map_err(|e| anyhow::anyhow!("failed to load component from {}: {e}", path.display()))?;
38 Ok((component, digest))
39}
40pub fn create_linker(engine: &Engine) -> Result<Linker<HostState>> {
42 let mut linker = Linker::new(engine);
43 wasmtime_wasi::p2::add_to_linker_async(&mut linker)
45 .map_err(|e| anyhow::anyhow!("failed to add WASI P2 to linker: {e}"))?;
46 linker.allow_shadowing(true);
50 wasmtime_wasi::p2::bindings::filesystem::types::add_to_linker::<
51 HostState,
52 fs_policy::PolicyFilesystem,
53 >(&mut linker, super::store::HostState::policy_fs_view)
54 .map_err(|e| anyhow::anyhow!("failed to add policy wasi:filesystem/types: {e}"))?;
55 wasmtime_wasi::p2::bindings::filesystem::preopens::add_to_linker::<
56 HostState,
57 fs_policy::PolicyFilesystem,
58 >(&mut linker, super::store::HostState::policy_fs_view)
59 .map_err(|e| anyhow::anyhow!("failed to add policy wasi:filesystem/preopens: {e}"))?;
60 linker.allow_shadowing(false);
61 wasmtime_wasi::p3::add_to_linker(&mut linker)
63 .map_err(|e| anyhow::anyhow!("failed to add WASI P3 to linker: {e}"))?;
64 linker.allow_shadowing(true);
70 wasmtime_wasi::p3::bindings::filesystem::preopens::add_to_linker::<
71 HostState,
72 fs_policy::PolicyFilesystem,
73 >(&mut linker, super::store::HostState::policy_fs_view)
74 .map_err(|e| anyhow::anyhow!("failed to add policy wasi:filesystem/preopens (p3): {e}"))?;
75 linker.allow_shadowing(false);
76 wasmtime_wasi_http::p2::add_only_http_to_linker_async(&mut linker)
78 .map_err(|e| anyhow::anyhow!("failed to add WASI HTTP P2 to linker: {e}"))?;
79 wasmtime_wasi_http::p3::add_to_linker(&mut linker)
80 .map_err(|e| anyhow::anyhow!("failed to add WASI HTTP P3 to linker: {e}"))?;
81 credentials::add_to_linker(&mut linker)?;
85 crate::consent::gate::add_to_linker(&mut linker)?;
89 Ok(linker)
90}