Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
bytecodealliance
GitHub Repository: bytecodealliance/wasmtime
Path: blob/main/crates/wasi/src/p3/mod.rs
3076 views
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
11
pub mod bindings;
12
pub mod cli;
13
pub mod clocks;
14
pub mod filesystem;
15
pub mod random;
16
pub mod sockets;
17
18
use crate::WasiView;
19
use crate::p3::bindings::LinkOptions;
20
use core::pin::Pin;
21
use core::task::{Context, Poll};
22
use tokio::sync::oneshot;
23
use wasmtime::StoreContextMut;
24
use wasmtime::component::{Destination, Linker, StreamProducer, StreamResult, VecBuffer};
25
26
// Default buffer capacity to use for reads of byte-sized values.
27
const 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.
38
struct FallibleIteratorProducer<I, E> {
39
iter: I,
40
result: Option<oneshot::Sender<Result<(), E>>>,
41
}
42
43
impl<I, T, E, D> StreamProducer<D> for FallibleIteratorProducer<I, E>
44
where
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
100
impl<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
115
impl<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.wasm_component_model_async(true);
139
/// let engine = Engine::new(&config)?;
140
///
141
/// let mut linker = Linker::<MyState>::new(&engine);
142
/// wasmtime_wasi::p3::add_to_linker(&mut linker)?;
143
/// // ... add any further functionality to `linker` if desired ...
144
///
145
/// let mut store = Store::new(
146
/// &engine,
147
/// MyState::default(),
148
/// );
149
///
150
/// // ... use `linker` to instantiate within `store` ...
151
///
152
/// Ok(())
153
/// }
154
///
155
/// #[derive(Default)]
156
/// struct MyState {
157
/// ctx: WasiCtx,
158
/// table: ResourceTable,
159
/// }
160
///
161
/// impl WasiView for MyState {
162
/// fn ctx(&mut self) -> WasiCtxView<'_> {
163
/// WasiCtxView{
164
/// ctx: &mut self.ctx,
165
/// table: &mut self.table,
166
/// }
167
/// }
168
/// }
169
/// ```
170
pub fn add_to_linker<T>(linker: &mut Linker<T>) -> wasmtime::Result<()>
171
where
172
T: WasiView + 'static,
173
{
174
let options = LinkOptions::default();
175
add_to_linker_with_options(linker, &options)
176
}
177
178
/// Similar to [`add_to_linker`], but with the ability to enable unstable features.
179
pub fn add_to_linker_with_options<T>(
180
linker: &mut Linker<T>,
181
options: &LinkOptions,
182
) -> wasmtime::Result<()>
183
where
184
T: WasiView + 'static,
185
{
186
cli::add_to_linker_with_options(linker, &options.into())?;
187
clocks::add_to_linker(linker)?;
188
filesystem::add_to_linker(linker)?;
189
random::add_to_linker(linker)?;
190
sockets::add_to_linker(linker)?;
191
Ok(())
192
}
193
194