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