Path: blob/main/crates/misc/component-async-tests/tests/scenario/common.rs
1693 views
use std::sync::{Arc, Mutex, Once};1use std::time::Duration;23use anyhow::Result;4use tokio::fs;5use wasm_compose::composer::ComponentComposer;6use wasmtime::component::{Component, Linker, PromisesUnordered, ResourceTable};7use wasmtime::{Config, Engine, Store};8use wasmtime_wasi::WasiCtxBuilder;910use component_async_tests::Ctx;1112pub fn annotate<T, F>(val: F) -> F13where14F: Fn(&mut T) -> &mut T,15{16val17}1819pub fn init_logger() {20static ONCE: Once = Once::new();21ONCE.call_once(pretty_env_logger::init);22}2324/// Compose two components25///26/// a is the "root" component, and b is composed into it27#[allow(unused)]28pub async fn compose(a: &[u8], b: &[u8]) -> Result<Vec<u8>> {29let dir = tempfile::tempdir()?;3031let a_file = dir.path().join("a.wasm");32fs::write(&a_file, a).await?;3334let b_file = dir.path().join("b.wasm");35fs::write(&b_file, b).await?;3637ComponentComposer::new(38&a_file,39&wasm_compose::config::Config {40dir: dir.path().to_owned(),41definitions: vec![b_file.to_owned()],42..Default::default()43},44)45.compose()46}4748#[allow(unused)]49pub async fn test_run(component: &[u8]) -> Result<()> {50let mut config = config();51// As of this writing, miri/pulley/epochs is a problematic combination, so52// we don't test it.53if env::var_os("MIRI_TEST_CWASM_DIR").is_none() {54config.epoch_interruption(true);55}5657let engine = Engine::new(&config)?;5859let component = Component::new(&engine, component)?;6061let mut linker = Linker::new(&engine);6263wasmtime_wasi::add_to_linker_async(&mut linker)?;64component_async_tests::yield_host::bindings::local::local::continue_::add_to_linker_get_host(65&mut linker,66annotate(|ctx| ctx),67)?;68component_async_tests::yield_host::bindings::local::local::ready::add_to_linker_get_host(69&mut linker,70annotate(|ctx| ctx),71)?;72component_async_tests::resource_stream::bindings::local::local::resource_stream::add_to_linker_get_host(73&mut linker,74annotate(|ctx| ctx),75)?;7677let mut store = Store::new(78&engine,79Ctx {80wasi: WasiCtxBuilder::new().inherit_stdio().build(),81table: ResourceTable::default(),82continue_: false,83wakers: Arc::new(Mutex::new(None)),84},85);8687if env::var_os("MIRI_TEST_CWASM_DIR").is_none() {88store.set_epoch_deadline(1);8990std::thread::spawn(move || {91std::thread::sleep(Duration::from_secs(10));92engine.increment_epoch();93});94}9596let yield_host = component_async_tests::yield_host::bindings::YieldHost::instantiate_async(97&mut store, &component, &linker,98)99.await?;100101// Start three concurrent calls and then join them all:102let mut promises = PromisesUnordered::new();103for _ in 0..3 {104promises.push(yield_host.local_local_run().call_run(&mut store).await?);105}106107while let Some(()) = promises.next(&mut store).await? {108// continue109}110111Ok(())112}113114115