forked from bytecodealliance/wasip3-prototyping
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathasync_http_echo.rs
More file actions
76 lines (66 loc) · 2.44 KB
/
async_http_echo.rs
File metadata and controls
76 lines (66 loc) · 2.44 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
mod bindings {
wit_bindgen::generate!({
path: "../misc/component-async-tests/wit",
world: "wasi:http/proxy",
async: {
imports: [
"wasi:http/handler@0.3.0-draft#handle",
],
exports: [
"wasi:http/handler@0.3.0-draft#handle",
]
}
});
use super::Component;
export!(Component);
}
use {
bindings::{
exports::wasi::http::handler::Guest as Handler,
wasi::http::types::{Body, ErrorCode, Request, Response},
wit_future, wit_stream,
},
wit_bindgen_rt::async_support::{self, StreamResult},
};
struct Component;
impl Handler for Component {
/// Return a response which echoes the request headers, body, and trailers.
async fn handle(request: Request) -> Result<Response, ErrorCode> {
let (headers, body) = Request::into_parts(request);
if false {
// This is the easy and efficient way to do it...
Ok(Response::new(headers, body))
} else {
// ...but we do it the more difficult, less efficient way here to exercise various component model
// features (e.g. `future`s, `stream`s, and post-return asynchronous execution):
let (trailers_tx, trailers_rx) = wit_future::new();
let (mut pipe_tx, pipe_rx) = wit_stream::new();
async_support::spawn(async move {
let mut body_rx = body.stream().unwrap();
let mut chunk = Vec::with_capacity(1024);
loop {
let (status, buf) = body_rx.read(chunk).await;
chunk = buf;
match status {
StreamResult::Complete(_) => {
chunk = pipe_tx.write_all(chunk).await;
assert!(chunk.is_empty());
}
StreamResult::Closed => break,
StreamResult::Cancelled => unreachable!(),
}
}
drop(pipe_tx);
if let Some(trailers) = Body::finish(body).await {
trailers_tx.write(trailers).await.unwrap();
}
});
Ok(Response::new(
headers,
Body::new_with_trailers(pipe_rx, trailers_rx),
))
}
}
}
// Unused function; required since this file is built as a `bin`:
fn main() {}