Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
bytecodealliance
GitHub Repository: bytecodealliance/wasmtime
Path: blob/main/crates/wasi-nn/tests/exec/wit.rs
1693 views
1
use super::PREOPENED_DIR_NAME;
2
use crate::check::artifacts_dir;
3
use anyhow::{Result, anyhow};
4
use std::path::Path;
5
use wasmtime::component::{Component, Linker, ResourceTable};
6
use wasmtime::{Config, Engine, Store};
7
use wasmtime_wasi::p2::bindings::sync::Command;
8
use wasmtime_wasi::{DirPerms, FilePerms, WasiCtx, WasiCtxView};
9
use wasmtime_wasi_nn::wit::WasiNnView;
10
use wasmtime_wasi_nn::{Backend, InMemoryRegistry, wit::WasiNnCtx};
11
12
/// Run a wasi-nn test program. This is modeled after
13
/// `crates/wasi/tests/all/main.rs` but still uses the older p1 API for
14
/// file reads.
15
pub fn run(path: &str, backend: Backend, preload_model: bool) -> Result<()> {
16
let path = Path::new(path);
17
let engine = Engine::new(&Config::new())?;
18
let mut linker = Linker::new(&engine);
19
wasmtime_wasi_nn::wit::add_to_linker(&mut linker, |c: &mut Ctx| {
20
WasiNnView::new(&mut c.table, &mut c.wasi_nn)
21
})?;
22
wasmtime_wasi::p2::add_to_linker_sync(&mut linker)?;
23
let module = Component::from_file(&engine, path)?;
24
let mut store = Store::new(&engine, Ctx::new(&artifacts_dir(), preload_model, backend)?);
25
let command = Command::instantiate(&mut store, &module, &linker)?;
26
let result = command.wasi_cli_run().call_run(&mut store)?;
27
result.map_err(|_| anyhow!("failed to run command"))
28
}
29
30
/// The host state for running wasi-nn component tests.
31
struct Ctx {
32
wasi: WasiCtx,
33
wasi_nn: WasiNnCtx,
34
table: ResourceTable,
35
}
36
37
impl Ctx {
38
fn new(preopen_dir: &Path, preload_model: bool, mut backend: Backend) -> Result<Self> {
39
let mut builder = WasiCtx::builder();
40
builder.inherit_stdio().preopened_dir(
41
preopen_dir,
42
PREOPENED_DIR_NAME,
43
DirPerms::READ,
44
FilePerms::READ,
45
)?;
46
let wasi = builder.build();
47
48
let mut registry = InMemoryRegistry::new();
49
let mobilenet_dir = artifacts_dir();
50
if preload_model {
51
registry.load((backend).as_dir_loadable().unwrap(), &mobilenet_dir)?;
52
}
53
let wasi_nn = WasiNnCtx::new([backend], registry.into());
54
55
let table = ResourceTable::new();
56
57
Ok(Self {
58
wasi,
59
wasi_nn,
60
table,
61
})
62
}
63
}
64
65
impl wasmtime_wasi::WasiView for Ctx {
66
fn ctx(&mut self) -> WasiCtxView<'_> {
67
WasiCtxView {
68
ctx: &mut self.wasi,
69
table: &mut self.table,
70
}
71
}
72
}
73
74