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