//! Experimental, unstable and incomplete implementation of wasip3 version of WASI.1//!2//! This module is under heavy development.3//! It is not compliant with semver and is not ready4//! for production use.5//!6//! Bug and security fixes limited to wasip3 will not be given patch releases.7//!8//! Documentation of this module may be incorrect or out-of-sync with the implementation.910pub mod bindings;11pub mod cli;12pub mod clocks;13pub mod filesystem;14pub mod random;15pub mod sockets;1617use crate::WasiView;18use crate::p3::bindings::LinkOptions;19use core::pin::Pin;20use core::task::{Context, Poll};21use tokio::sync::oneshot;22use wasmtime::StoreContextMut;23use wasmtime::component::{Destination, Linker, StreamProducer, StreamResult, VecBuffer};2425// Default buffer capacity to use for reads of byte-sized values.26const DEFAULT_BUFFER_CAPACITY: usize = 8192;2728/// Helper structure to convert an iterator of `Result<T, E>` into a `stream<T>`29/// plus a `future<result<_, T>>` in WIT.30///31/// This will drain the iterator on calls to `poll_produce` and place as many32/// items as the input buffer has capacity for into the result. This will avoid33/// doing anything if the async read is cancelled.34///35/// Note that this does not actually do anything async, it's assuming that the36/// internal `iter` is either fast or intended to block.37struct FallibleIteratorProducer<I, E> {38iter: I,39result: Option<oneshot::Sender<Result<(), E>>>,40}4142impl<I, T, E, D> StreamProducer<D> for FallibleIteratorProducer<I, E>43where44I: Iterator<Item = Result<T, E>> + Send + Unpin + 'static,45T: Send + Sync + 'static,46E: Send + 'static,47{48type Item = T;49type Buffer = VecBuffer<T>;5051fn poll_produce<'a>(52mut self: Pin<&mut Self>,53_: &mut Context<'_>,54mut store: StoreContextMut<'a, D>,55mut dst: Destination<'a, Self::Item, Self::Buffer>,56// Explicitly ignore `_finish` because this implementation never57// returns `Poll::Pending` anyway meaning that it never "blocks" in the58// async sense.59_finish: bool,60) -> Poll<wasmtime::Result<StreamResult>> {61// Take up to `count` items as requested by the guest, or pick some62// reasonable-ish number for the host.63let count = dst.remaining(&mut store).unwrap_or(32);6465// Handle 0-length reads which test for readiness as saying "we're66// always ready" since, in theory, this is.67if count == 0 {68return Poll::Ready(Ok(StreamResult::Completed));69}7071// Drain `self.iter`. Successful results go into `buf`. Any errors make72// their way to the `oneshot` result inside this structure. Otherwise73// this only gets dropped if `None` is seen or an error. Also this'll74// terminate once `buf` grows too large.75let mut buf = Vec::new();76let result = loop {77match self.iter.next() {78Some(Ok(item)) => buf.push(item),79Some(Err(e)) => {80self.close(Err(e));81break StreamResult::Dropped;82}8384None => {85self.close(Ok(()));86break StreamResult::Dropped;87}88}89if buf.len() >= count {90break StreamResult::Completed;91}92};9394dst.set_buffer(buf.into());95return Poll::Ready(Ok(result));96}97}9899impl<I, E> FallibleIteratorProducer<I, E> {100fn new(iter: I, result: oneshot::Sender<Result<(), E>>) -> Self {101Self {102iter,103result: Some(result),104}105}106107fn close(&mut self, result: Result<(), E>) {108// Ignore send failures because it means the other end wasn't interested109// in the final error, if any.110let _ = self.result.take().unwrap().send(result);111}112}113114impl<I, E> Drop for FallibleIteratorProducer<I, E> {115fn drop(&mut self) {116if self.result.is_some() {117self.close(Ok(()));118}119}120}121122/// Add all WASI interfaces from this module into the `linker` provided.123///124/// This function will add all interfaces implemented by this module to the125/// [`Linker`], which corresponds to the `wasi:cli/imports` world supported by126/// this module.127///128/// # Example129///130/// ```131/// use wasmtime::{Engine, Result, Store, Config};132/// use wasmtime::component::{Linker, ResourceTable};133/// use wasmtime_wasi::{WasiCtx, WasiCtxView, WasiView};134///135/// fn main() -> Result<()> {136/// let mut config = Config::new();137/// config.wasm_component_model_async(true);138/// let engine = Engine::new(&config)?;139///140/// let mut linker = Linker::<MyState>::new(&engine);141/// wasmtime_wasi::p3::add_to_linker(&mut linker)?;142/// // ... add any further functionality to `linker` if desired ...143///144/// let mut store = Store::new(145/// &engine,146/// MyState::default(),147/// );148///149/// // ... use `linker` to instantiate within `store` ...150///151/// Ok(())152/// }153///154/// #[derive(Default)]155/// struct MyState {156/// ctx: WasiCtx,157/// table: ResourceTable,158/// }159///160/// impl WasiView for MyState {161/// fn ctx(&mut self) -> WasiCtxView<'_> {162/// WasiCtxView{163/// ctx: &mut self.ctx,164/// table: &mut self.table,165/// }166/// }167/// }168/// ```169pub fn add_to_linker<T>(linker: &mut Linker<T>) -> wasmtime::Result<()>170where171T: WasiView + 'static,172{173let options = LinkOptions::default();174add_to_linker_with_options(linker, &options)175}176177/// Similar to [`add_to_linker`], but with the ability to enable unstable features.178pub fn add_to_linker_with_options<T>(179linker: &mut Linker<T>,180options: &LinkOptions,181) -> wasmtime::Result<()>182where183T: WasiView + 'static,184{185cli::add_to_linker_with_options(linker, &options.into())?;186clocks::add_to_linker(linker)?;187filesystem::add_to_linker(linker)?;188random::add_to_linker(linker)?;189sockets::add_to_linker(linker)?;190Ok(())191}192193194