Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(wasm): add support for the stable target wasm32-wasip2 #2453

Draft
wants to merge 4 commits into
base: master
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
target
Cargo.lock
*.swp
.idea
.idea
.vscode
3 changes: 3 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -195,6 +195,9 @@ wasm-bindgen = "0.2.89"
wasm-bindgen-futures = "0.4.18"
wasm-streams = { version = "0.4", optional = true }

[target.'cfg(all(target_os = "wasi", target_env = "p2"))'.dependencies]
wasi = "=0.13.3" # For compatibility, pin to [email protected] bindings

[target.'cfg(target_arch = "wasm32")'.dependencies.web-sys]
version = "0.3.28"
features = [
Expand Down
2 changes: 2 additions & 0 deletions examples/wasm_component/.cargo/config.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
[build]
target = "wasm32-wasip2"
20 changes: 20 additions & 0 deletions examples/wasm_component/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
[package]
name = "http-reqwest"
edition = "2021"
version = "0.1.0"

[workspace]

[lib]
crate-type = ["cdylib"]

[dependencies]
futures = "0.3.30"
reqwest = { version = "0.12.8", path = "../../", features = ["stream"] }
wasi = "=0.13.3" # For compatibility, pin to [email protected] bindings

[profile.release]
# Optimize for small code size
lto = true
opt-level = "s"
strip = true
34 changes: 34 additions & 0 deletions examples/wasm_component/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
# HTTP Reqwest

This is a simple Rust Wasm example that sends an outgoing http request using the `reqwest` library to [https://hyper.rs](https://hyper.rs).

## Prerequisites

- `cargo` 1.82+
- `rustup target add wasm32-wasip2`
- [wasmtime 23.0.0+](https://github.com/bytecodealliance/wasmtime)

## Building

```bash
# Build Wasm component
cargo build --target wasm32-wasip2
```

## Running with wasmtime

```bash
wasmtime serve -Scommon ./target/wasm32-wasip2/debug/http_reqwest.wasm
```

Then send a request to `localhost:8080`

```bash
> curl localhost:8080

<!doctype html>
<html>
<head>
<title>Example Domain</title>
....
```
34 changes: 34 additions & 0 deletions examples/wasm_component/src/lib.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
use wasi::http::types::{
Fields, IncomingBody, IncomingRequest, OutgoingBody, OutgoingResponse, ResponseOutparam,
};

#[allow(unused)]
struct ReqwestComponent;

impl wasi::exports::http::incoming_handler::Guest for ReqwestComponent {
fn handle(_request: IncomingRequest, response_out: ResponseOutparam) {
let response = OutgoingResponse::new(Fields::new());
response.set_status_code(200).unwrap();
let response_body = response
.body()
.expect("should be able to get response body");
ResponseOutparam::set(response_out, Ok(response));

let mut response = reqwest::get("https://hyper.rs").expect("should get response bytes");
let (mut body_stream, incoming_body) = response
.bytes_stream()
.expect("should be able to get response body stream");
std::io::copy(
&mut body_stream,
&mut response_body
.write()
.expect("should be able to write to response body"),
)
.expect("should be able to stream input to output");
drop(body_stream);
IncomingBody::finish(incoming_body);
OutgoingBody::finish(response_body, None).expect("failed to finish response body");
}
}

wasi::http::proxy::export!(ReqwestComponent);
34 changes: 33 additions & 1 deletion src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -306,10 +306,42 @@ pub use self::response::ResponseBuilderExt;
/// - supplied `Url` cannot be parsed
/// - there was an error while sending request
/// - redirect limit was exhausted
#[cfg(not(any(target_os = "wasi", target_env = "p2")))]
pub async fn get<T: IntoUrl>(url: T) -> crate::Result<Response> {
Client::builder().build()?.get(url).send().await
}

/// Shortcut method to quickly make a `GET` request.
///
/// See also the methods on the [`reqwest::Response`](./struct.Response.html)
/// type.
///
/// **NOTE**: This function creates a new internal `Client` on each call,
/// and so should not be used if making many requests. Create a
/// [`Client`](./struct.Client.html) instead.
///
/// # Examples
///
/// ```rust
/// # fn run() -> Result<(), reqwest::Error> {
/// let body = reqwest::get("https://www.rust-lang.org")?
/// .text()?;
/// # Ok(())
/// # }
/// ```
///
/// # Errors
///
/// This function fails if:
///
/// - supplied `Url` cannot be parsed
/// - there was an error while sending request
/// - redirect limit was exhausted
#[cfg(all(target_os = "wasi", target_env = "p2"))]
pub fn get<T: IntoUrl>(url: T) -> crate::Result<Response> {
Client::builder().build()?.get(url).send()
}

fn _assert_impls() {
fn assert_send<T: Send>() {}
fn assert_sync<T: Sync>() {}
Expand Down Expand Up @@ -372,6 +404,6 @@ if_wasm! {
mod util;

pub use self::wasm::{Body, Client, ClientBuilder, Request, RequestBuilder, Response};
#[cfg(feature = "multipart")]
#[cfg(all(not(all(target_os = "wasi", target_env = "p2")), feature = "multipart"))]
pub use self::wasm::multipart;
}
111 changes: 111 additions & 0 deletions src/wasm/component/body.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,111 @@
use bytes::Bytes;
use std::{borrow::Cow, fmt};

/// The body of a [`super::Request`].
pub struct Body {
inner: Inner,
}

enum Inner {
Single(Single),
}

#[derive(Clone)]
pub(crate) enum Single {
Bytes(Bytes),
Text(Cow<'static, str>),
}

impl Single {
fn as_bytes(&self) -> &[u8] {
match self {
Single::Bytes(bytes) => bytes.as_ref(),
Single::Text(text) => text.as_bytes(),
}
}

fn is_empty(&self) -> bool {
match self {
Single::Bytes(bytes) => bytes.is_empty(),
Single::Text(text) => text.is_empty(),
}
}
}

impl Body {
/// Returns a reference to the internal data of the `Body`.
///
/// `None` is returned, if the underlying data is a multipart form.
#[inline]
pub fn as_bytes(&self) -> Option<&[u8]> {
match &self.inner {
Inner::Single(single) => Some(single.as_bytes()),
}
}

#[allow(unused)]
pub(crate) fn is_empty(&self) -> bool {
match &self.inner {
Inner::Single(single) => single.is_empty(),
}
}

pub(crate) fn try_clone(&self) -> Option<Body> {
match &self.inner {
Inner::Single(single) => Some(Self {
inner: Inner::Single(single.clone()),
}),
}
}
}

impl From<Bytes> for Body {
#[inline]
fn from(bytes: Bytes) -> Body {
Body {
inner: Inner::Single(Single::Bytes(bytes)),
}
}
}

impl From<Vec<u8>> for Body {
#[inline]
fn from(vec: Vec<u8>) -> Body {
Body {
inner: Inner::Single(Single::Bytes(vec.into())),
}
}
}

impl From<&'static [u8]> for Body {
#[inline]
fn from(s: &'static [u8]) -> Body {
Body {
inner: Inner::Single(Single::Bytes(Bytes::from_static(s))),
}
}
}

impl From<String> for Body {
#[inline]
fn from(s: String) -> Body {
Body {
inner: Inner::Single(Single::Text(s.into())),
}
}
}

impl From<&'static str> for Body {
#[inline]
fn from(s: &'static str) -> Body {
Body {
inner: Inner::Single(Single::Text(s.into())),
}
}
}

impl fmt::Debug for Body {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.debug_struct("Body").finish()
}
}
Loading