-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlib.rs
160 lines (134 loc) · 5.86 KB
/
lib.rs
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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
#![deny(warnings)]
mod bindings {
wit_bindgen::generate!({
path: "../wit",
world: "wasi:http/proxy",
async: {
imports: [
"wasi:http/[email protected]#[static]body.finish",
"wasi:http/[email protected]#handle",
],
exports: [
"wasi:http/[email protected]#handle",
]
}
});
use super::Component;
export!(Component);
}
use {
bindings::{
exports::wasi::http::handler::Guest as Handler,
stream_and_future_support,
wasi::http::{
handler,
types::{Body, ErrorCode, Headers, Request, Response},
},
},
flate2::{
write::{DeflateDecoder, DeflateEncoder},
Compression,
},
futures::{SinkExt, StreamExt},
std::{io::Write, mem},
wit_bindgen_rt::async_support,
};
struct Component;
impl Handler for Component {
/// Forward the specified request to the imported `wasi:http/handler`, transparently decoding the request body
/// if it is `deflate`d and then encoding the response body if the client has provided an `accept-encoding:
/// deflate` header.
async fn handle(request: Request) -> Result<Response, ErrorCode> {
// First, extract the parts of the request and check for (and remove) headers pertaining to body encodings.
let method = request.method();
let scheme = request.scheme();
let path_with_query = request.path_with_query();
let authority = request.authority();
let mut accept_deflated = false;
let mut content_deflated = false;
let (headers, body) = Request::into_parts(request);
let mut headers = headers.entries();
headers.retain(|(k, v)| match (k.as_str(), v.as_slice()) {
("accept-encoding", b"deflate") => {
accept_deflated = true;
false
}
("content-encoding", b"deflate") => {
content_deflated = true;
false
}
_ => true,
});
let body = if content_deflated {
// Next, spawn a task to pipe and decode the original request body and trailers into a new request
// we'll create below. This will run concurrently with any code in the imported `wasi:http/handler`.
let (trailers_tx, trailers_rx) = stream_and_future_support::new_future();
let (mut pipe_tx, pipe_rx) = stream_and_future_support::new_stream();
async_support::spawn(async move {
{
let mut body_rx = body.stream().unwrap();
let mut decoder = DeflateDecoder::new(Vec::new());
while let Some(chunk) = body_rx.next().await {
decoder.write_all(&chunk).unwrap();
pipe_tx.send(mem::take(decoder.get_mut())).await.unwrap();
}
pipe_tx.send(decoder.finish().unwrap()).await.unwrap();
drop(pipe_tx);
}
if let Some(trailers) = Body::finish(body).await.unwrap() {
trailers_tx.write(trailers).await;
}
});
Body::new(pipe_rx, Some(trailers_rx))
} else {
body
};
// While the above task (if any) is running, synthesize a request from the parts collected above and pass
// it to the imported `wasi:http/handler`.
let my_request = Request::new(Headers::from_list(&headers).unwrap(), body, None);
my_request.set_method(&method).unwrap();
my_request.set_scheme(scheme.as_ref()).unwrap();
my_request
.set_path_with_query(path_with_query.as_deref())
.unwrap();
my_request.set_authority(authority.as_deref()).unwrap();
let response = handler::handle(my_request).await?;
// Now that we have the response, extract the parts, adding an extra header if we'll be encoding the body.
let status_code = response.status_code();
let (headers, body) = Response::into_parts(response);
let mut headers = headers.entries();
if accept_deflated {
headers.push(("content-encoding".into(), b"deflate".into()));
}
let body = if accept_deflated {
// Spawn another task; this one is to pipe and encode the original response body and trailers into a
// new response we'll create below. This will run concurrently with the caller's code (i.e. it won't
// necessarily complete before we return a value).
let (trailers_tx, trailers_rx) = stream_and_future_support::new_future();
let (mut pipe_tx, pipe_rx) = stream_and_future_support::new_stream();
async_support::spawn(async move {
{
let mut body_rx = body.stream().unwrap();
let mut encoder = DeflateEncoder::new(Vec::new(), Compression::fast());
while let Some(chunk) = body_rx.next().await {
encoder.write_all(&chunk).unwrap();
pipe_tx.send(mem::take(encoder.get_mut())).await.unwrap();
}
pipe_tx.send(encoder.finish().unwrap()).await.unwrap();
drop(pipe_tx);
}
if let Some(trailers) = Body::finish(body).await.unwrap() {
trailers_tx.write(trailers).await;
}
});
Body::new(pipe_rx, Some(trailers_rx))
} else {
body
};
// While the above tasks (if any) are running, synthesize a response from the parts collected above and
// return it.
let my_response = Response::new(Headers::from_list(&headers).unwrap(), body);
my_response.set_status_code(status_code).unwrap();
Ok(my_response)
}
}