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