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(http): add http crate integration #90

Draft
wants to merge 6 commits into
base: main
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
33 changes: 31 additions & 2 deletions .github/workflows/main.yml
Original file line number Diff line number Diff line change
Expand Up @@ -26,17 +26,46 @@ jobs:
uses: bytecodealliance/actions/wasm-tools/setup@v1
with:
version: "1.202.0"
- run: cargo build --examples --target wasm32-wasi
- run: curl -LO https://github.com/bytecodealliance/wasmtime/releases/download/v19.0.0/wasi_snapshot_preview1.command.wasm

- run: cargo build --examples --target wasm32-wasi --no-default-features

- run: wasm-tools component new ./target/wasm32-wasi/debug/examples/hello-world-no_std.wasm --adapt ./wasi_snapshot_preview1.command.wasm -o component.wasm
- run: wasmtime run component.wasm

- run: cargo build --examples --target wasm32-unknown-unknown --no-default-features

- run: wasm-tools component new ./target/wasm32-unknown-unknown/debug/examples/cli_command_no_std.wasm -o component.wasm
- run: wasmtime run component.wasm

- run: wasm-tools component new ./target/wasm32-unknown-unknown/debug/examples/http_proxy_no_std.wasm -o component.wasm
- run: wasm-tools component targets wit component.wasm -w wasi:http/proxy

- run: cargo build --examples --target wasm32-wasi

- run: wasm-tools component new ./target/wasm32-wasi/debug/examples/hello-world.wasm --adapt ./wasi_snapshot_preview1.command.wasm -o component.wasm
- run: wasmtime run component.wasm

- run: cargo build --examples --target wasm32-unknown-unknown

- run: wasm-tools component new ./target/wasm32-unknown-unknown/debug/examples/cli_command.wasm -o component.wasm
- run: wasmtime run component.wasm

- run: cargo build --examples --target wasm32-wasi --no-default-features --features rand

- run: wasm-tools component new ./target/wasm32-wasi/debug/examples/rand-no_std.wasm --adapt ./wasi_snapshot_preview1.command.wasm -o component.wasm
- run: wasmtime run component.wasm

- run: cargo build --examples --target wasm32-wasi --features rand

- run: wasm-tools component new ./target/wasm32-wasi/debug/examples/rand.wasm --adapt ./wasi_snapshot_preview1.command.wasm -o component.wasm
- run: wasmtime run component.wasm

- run: cargo build --examples --target wasm32-unknown-unknown --features http

- run: wasm-tools component new ./target/wasm32-unknown-unknown/debug/examples/http_proxy.wasm -o component.wasm
- run: wasm-tools component targets wit component.wasm -w wasi:http/proxy


rustfmt:
name: Rustfmt
runs-on: ubuntu-latest
Expand Down
29 changes: 29 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -19,16 +19,45 @@ compiler_builtins = { version = "0.1", optional = true }
core = { version = "1.0", optional = true, package = "rustc-std-workspace-core" }
rustc-std-workspace-alloc = { version = "1.0", optional = true }

# When built with `http` crate integration
http = { version = "1.1", default-features = false, optional = true }

# When built with `rand` crate integration
rand = { version = "0.8.5", default-features = false, optional = true }

[features]
default = ["std"]
std = []
http = ["dep:http", "http/std", "std"]
# Unstable feature to support being a libstd dependency
rustc-dep-of-std = ["compiler_builtins", "core", "rustc-std-workspace-alloc"]

[[example]]
name = "cli-command-no_std"
crate-type = ["cdylib"]

[[example]]
name = "cli-command"
crate-type = ["cdylib"]
required-features = ["std"]

[[example]]
name = "hello-world"
required-features = ["std"]

[[example]]
name = "http-proxy-no_std"
crate-type = ["cdylib"]

[[example]]
name = "http-proxy"
crate-type = ["cdylib"]
required-features = ["http", "std"]

[[example]]
name = "rand-no_std"
required-features = ["rand"]

[[example]]
name = "rand"
required-features = ["std", "rand"]
11 changes: 11 additions & 0 deletions examples/cli-command-no_std.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
wasi::cli::command::export!(Example);

struct Example;

impl wasi::exports::cli::run::Guest for Example {
fn run() -> Result<(), ()> {
let stdout = wasi::cli::stdout::get_stdout();
stdout.blocking_write_and_flush(b"Hello, WASI!").unwrap();
Ok(())
}
}
7 changes: 5 additions & 2 deletions examples/cli-command.rs
Original file line number Diff line number Diff line change
@@ -1,11 +1,14 @@
use std::io::Write as _;

wasi::cli::command::export!(Example);

struct Example;

impl wasi::exports::cli::run::Guest for Example {
fn run() -> Result<(), ()> {
let stdout = wasi::cli::stdout::get_stdout();
stdout.blocking_write_and_flush(b"Hello, WASI!").unwrap();
let mut stdout = wasi::cli::stdout::get_stdout();
stdout.write_all(b"Hello, WASI!").unwrap();
stdout.flush().unwrap();
Ok(())
}
}
4 changes: 4 additions & 0 deletions examples/hello-world-no_std.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
fn main() {
let stdout = wasi::cli::stdout::get_stdout();
stdout.blocking_write_and_flush(b"Hello, world!\n").unwrap();
}
7 changes: 5 additions & 2 deletions examples/hello-world.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,7 @@
use std::io::Write as _;

fn main() {
let stdout = wasi::cli::stdout::get_stdout();
stdout.blocking_write_and_flush(b"Hello, world!\n").unwrap();
let mut stdout = wasi::cli::stdout::get_stdout();
stdout.write_all(b"Hello, world!\n").unwrap();
stdout.flush().unwrap();
}
22 changes: 22 additions & 0 deletions examples/http-proxy-no_std.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
use wasi::http::types::{
Fields, IncomingRequest, OutgoingBody, OutgoingResponse, ResponseOutparam,
};

wasi::http::proxy::export!(Example);

struct Example;

impl wasi::exports::http::incoming_handler::Guest for Example {
fn handle(_request: IncomingRequest, response_out: ResponseOutparam) {
let resp = OutgoingResponse::new(Fields::new());
let body = resp.body().unwrap();

ResponseOutparam::set(response_out, Ok(resp));

let out = body.write().unwrap();
out.blocking_write_and_flush(b"Hello, WASI!").unwrap();
drop(out);

OutgoingBody::finish(body, None).unwrap();
}
}
34 changes: 27 additions & 7 deletions examples/http-proxy.rs
Original file line number Diff line number Diff line change
@@ -1,20 +1,40 @@
use wasi::http::types::{
Fields, IncomingRequest, OutgoingBody, OutgoingResponse, ResponseOutparam,
};
use std::io::Write as _;

use wasi::http::types::{IncomingRequest, OutgoingBody, OutgoingResponse, ResponseOutparam};

wasi::http::proxy::export!(Example);

struct Example;

impl wasi::exports::http::incoming_handler::Guest for Example {
fn handle(_request: IncomingRequest, response_out: ResponseOutparam) {
let resp = OutgoingResponse::new(Fields::new());
fn handle(request: IncomingRequest, response_out: ResponseOutparam) {
let req_headers =
http::HeaderMap::try_from(request.headers()).expect("failed to parse headers");
let mut resp_headers = http::HeaderMap::new();
for (name, value) in req_headers.iter() {
// Append `-orig` to all request headers and send them back to the client
resp_headers.append(
http::HeaderName::try_from(format!("{name}-orig")).unwrap(),
value.clone(),
);
}
let resp = OutgoingResponse::new(resp_headers.into());
let body = resp.body().unwrap();

ResponseOutparam::set(response_out, Ok(resp));

let out = body.write().unwrap();
out.blocking_write_and_flush(b"Hello, WASI!").unwrap();
let mut out = body.write().unwrap();

let method = http::Method::try_from(request.method()).unwrap();
writeln!(out, "method: {method}").unwrap();

if let Some(scheme) = request.scheme() {
let scheme = http::uri::Scheme::try_from(scheme).unwrap();
writeln!(out, "scheme: {scheme}").unwrap();
}

out.write_all(b"Hello, WASI!").unwrap();
out.flush().unwrap();
drop(out);

OutgoingBody::finish(body, None).unwrap();
Expand Down
19 changes: 19 additions & 0 deletions examples/rand-no_std.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
use wasi::ext::rand::rand::Rng as _;
use wasi::ext::rand::{HostInsecureRng, HostRng};

fn main() {
let stdout = wasi::cli::stdout::get_stdout();

let r: u64 = HostRng.gen();

stdout
.blocking_write_and_flush(
format!("Cryptographically-secure random u64 is {r}\n").as_bytes(),
)
.unwrap();

let r: u64 = HostInsecureRng.gen();
stdout
.blocking_write_and_flush(format!("Pseudo-random u64 is {r}\n").as_bytes())
.unwrap();
}
16 changes: 16 additions & 0 deletions examples/rand.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
use std::io::Write as _;

use wasi::ext::rand::rand::Rng as _;
use wasi::ext::rand::{HostInsecureRng, HostRng};

fn main() {
let mut stdout = wasi::cli::stdout::get_stdout();

let r: u64 = HostRng.gen();
writeln!(stdout, "Cryptographically-secure random u64 is {r}").unwrap();

let r: u64 = HostInsecureRng.gen();
writeln!(stdout, "Pseudo-random u64 is {r}").unwrap();

stdout.flush().unwrap();
}
119 changes: 119 additions & 0 deletions src/ext/http.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,119 @@
pub use http;

use core::fmt::Display;

impl From<http::Method> for crate::http::types::Method {
fn from(method: http::Method) -> Self {
use std::string::ToString;

match method.as_str() {
"GET" => Self::Get,
"HEAD" => Self::Head,
"POST" => Self::Post,
"PUT" => Self::Put,
"DELETE" => Self::Delete,
"CONNECT" => Self::Connect,
"OPTIONS" => Self::Options,
"TRACE" => Self::Trace,
"PATCH" => Self::Patch,
_ => Self::Other(method.to_string()),
}
}
}

impl TryFrom<crate::http::types::Method> for http::Method {
type Error = http::method::InvalidMethod;

fn try_from(method: crate::http::types::Method) -> Result<Self, Self::Error> {
match method {
crate::http::types::Method::Get => Ok(Self::GET),
crate::http::types::Method::Head => Ok(Self::HEAD),
crate::http::types::Method::Post => Ok(Self::POST),
crate::http::types::Method::Put => Ok(Self::PUT),
crate::http::types::Method::Delete => Ok(Self::DELETE),
crate::http::types::Method::Connect => Ok(Self::CONNECT),
crate::http::types::Method::Options => Ok(Self::OPTIONS),
crate::http::types::Method::Trace => Ok(Self::TRACE),
crate::http::types::Method::Patch => Ok(Self::PATCH),
crate::http::types::Method::Other(method) => method.parse(),
}
}
}

impl From<http::uri::Scheme> for crate::http::types::Scheme {
fn from(scheme: http::uri::Scheme) -> Self {
use std::string::ToString;

match scheme.as_str() {
"http" => Self::Http,
"https" => Self::Https,
_ => Self::Other(scheme.to_string()),
}
}
}

impl TryFrom<crate::http::types::Scheme> for http::uri::Scheme {
type Error = http::uri::InvalidUri;

fn try_from(scheme: crate::http::types::Scheme) -> Result<Self, Self::Error> {
match scheme {
crate::http::types::Scheme::Http => Ok(Self::HTTP),
crate::http::types::Scheme::Https => Ok(Self::HTTPS),
crate::http::types::Scheme::Other(scheme) => scheme.parse(),
}
}
}

#[derive(Debug)]
pub enum FieldsToHeaderMapError {
InvalidHeaderName(http::header::InvalidHeaderName),
InvalidHeaderValue(http::header::InvalidHeaderValue),
}

impl Display for FieldsToHeaderMapError {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
match self {
FieldsToHeaderMapError::InvalidHeaderName(e) => write!(f, "invalid header name: {e}"),
FieldsToHeaderMapError::InvalidHeaderValue(e) => write!(f, "invalid header value: {e}"),
}
}
}

impl std::error::Error for FieldsToHeaderMapError {}

impl TryFrom<crate::http::types::Fields> for http::HeaderMap {
type Error = FieldsToHeaderMapError;

fn try_from(fields: crate::http::types::Fields) -> Result<Self, Self::Error> {
let mut headers = http::HeaderMap::new();
for (name, value) in fields.entries() {
let name = http::HeaderName::try_from(name)
.map_err(FieldsToHeaderMapError::InvalidHeaderName)?;
let value = http::HeaderValue::try_from(value)
.map_err(FieldsToHeaderMapError::InvalidHeaderValue)?;
match headers.entry(name) {
http::header::Entry::Vacant(entry) => {
entry.insert(value);
}
http::header::Entry::Occupied(mut entry) => {
entry.append(value);
}
};
}
Ok(headers)
}
}

impl From<http::HeaderMap> for crate::http::types::Fields {
fn from(headers: http::HeaderMap) -> Self {
use std::string::ToString;

let fields = crate::http::types::Fields::new();
for (name, value) in headers.iter() {
fields
.append(&name.to_string(), &value.as_bytes().to_vec())
.expect("failed to append header")
}
fields
}
}
12 changes: 9 additions & 3 deletions src/errors.rs → src/ext/mod.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,14 @@
#[cfg(feature = "std")]
mod std;

#[cfg(feature = "http")]
pub mod http;

#[cfg(feature = "rand")]
pub mod rand;

impl core::fmt::Display for crate::io::error::Error {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
f.write_str(&self.to_debug_string())
}
}

#[cfg(feature = "std")]
impl std::error::Error for crate::io::error::Error {}
Loading