-
Notifications
You must be signed in to change notification settings - Fork 758
/
web_http_client.rs
341 lines (296 loc) 路 10.8 KB
/
web_http_client.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
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
use std::sync::Arc;
use anyhow::{Context, Error};
use futures::{channel::oneshot, future::BoxFuture};
use http::header::{HeaderMap, HeaderValue, IntoHeaderName};
use wasm_bindgen::{JsCast, JsValue};
use wasm_bindgen_futures::JsFuture;
use web_sys::{RequestInit, RequestMode, Window, WorkerGlobalScope};
use crate::{
http::{HttpClient, HttpRequest, HttpRequestOptions, HttpResponse},
utils::web::js_error,
VirtualTaskManager, WasiThreadError,
};
#[derive(Debug, Default, Clone)]
#[non_exhaustive]
pub struct WebHttpClient {
default_headers: HeaderMap,
tasks: Option<Arc<dyn VirtualTaskManager + Send + Sync>>,
}
impl WebHttpClient {
pub fn new() -> Self {
WebHttpClient {
default_headers: HeaderMap::new(),
tasks: None,
}
}
pub fn with_task_manager(
&mut self,
tasks: Arc<dyn VirtualTaskManager + Send + Sync>,
) -> &mut Self {
self.tasks = Some(tasks);
self
}
pub fn with_default_header(
&mut self,
name: impl IntoHeaderName,
value: HeaderValue,
) -> &mut Self {
self.default_headers.insert(name, value);
self
}
pub fn extend_default_headers(&mut self, map: HeaderMap) -> &mut Self {
self.default_headers.extend(map);
self
}
/// Execute a `fetch()` request.
///
/// # Hack
///
/// This function is here to work around issues that are associated with the
/// promises we get when calling into JavaScript.
///
/// Under most conditions it's perfectly fine to call
/// [`wasm_bindgen_futures::spawn_local()`] directly from the
/// [`WebHttpClient::request()`] method, however there is a pretty nasty
/// gotcha when it comes to syscalls.
///
/// - The Wasmer VM doesn't support `async` host functions, so all
/// syscalls must block
/// - Some syscalls need to run asynchronous operations
/// - To call async code from a sync function, we use
/// [`crate::syscalls::__asyncify_light()`] which uses
/// [`futures::executor::block_on()`] to poll the future on the current
/// thread until it resolves
/// - In order for a [`wasm_bindgen_futures::spawn_local()`] future (i.e.
/// `fetch()`) to run to completion, you need to return control to the
/// JavaScript event loop
///
/// This causes a nasty deadlock where the syscall won't return until the
/// `fetch()` promise resolves, but the `fetch()` promise can't resolve
/// until the syscall returns.
///
/// We saw one example of this when a WASIX program uses the `wasmer run
/// ...` virtual command and the [`crate::Runtime`] needs to load a package
/// from the registry.
///
/// The workaround is use a [`VirtualTaskManager`] to run `fetch()` on a
/// background thread and hope *that* thread doesn't get stuck in a
/// deadlock. Otherwise if no [`VirtualTaskManager`] was provided, we'll run
/// the `fetch()` request on the current event loop and hope for the best.
fn spawn_js(
&self,
request: HttpRequest,
) -> Result<oneshot::Receiver<Result<HttpResponse, Error>>, WasiThreadError> {
let (sender, receiver) = oneshot::channel();
fn spawn_fetch(request: HttpRequest, sender: oneshot::Sender<Result<HttpResponse, Error>>) {
wasm_bindgen_futures::spawn_local(async move {
let result = fetch(request).await;
let _ = sender.send(result);
});
}
match self.tasks.as_deref() {
Some(tasks) => {
tasks.task_shared(Box::new(|| {
Box::pin(async move {
spawn_fetch(request, sender);
})
}))?;
}
None => {
spawn_fetch(request, sender);
}
}
Ok(receiver)
}
}
impl HttpClient for WebHttpClient {
fn request(&self, mut request: HttpRequest) -> BoxFuture<'_, Result<HttpResponse, Error>> {
for (name, value) in &self.default_headers {
if !request.headers.contains_key(name) {
request.headers.insert(name, value.clone());
}
}
let receiver = self.spawn_js(request);
Box::pin(async move {
match receiver?.await {
Ok(result) => result,
Err(e) => Err(Error::new(e)),
}
})
}
}
/// Send a `fetch()` request using the browser APIs.
async fn fetch(request: HttpRequest) -> Result<HttpResponse, Error> {
let HttpRequest {
url,
method,
headers,
body,
options: HttpRequestOptions {
gzip: _,
cors_proxy,
},
} = request;
let mut opts = RequestInit::new();
opts.method(method.as_str());
opts.mode(RequestMode::Cors);
if let Some(data) = body {
let data_len = data.len();
let array = js_sys::Uint8Array::new_with_length(data_len as u32);
array.copy_from(&data[..]);
opts.body(Some(&array));
}
let request = {
let request = web_sys::Request::new_with_str_and_init(url.as_str(), &opts)
.map_err(js_error)
.context("Could not construct request object")?;
let set_headers = request.headers();
for (name, val) in headers.iter() {
let val = String::from_utf8_lossy(val.as_bytes());
set_headers
.set(name.as_str(), &val)
.map_err(js_error)
.with_context(|| format!("could not apply request header: '{name}': '{val}'"))?;
}
request
};
let resp_value = match call_fetch(&request).await {
Ok(a) => a,
Err(e) => {
// If the request failed it may be because of CORS so if a cors proxy
// is configured then try again with the cors proxy
let url = if let Some(cors_proxy) = cors_proxy {
format!("https://{}/{}", cors_proxy, url)
} else {
return Err(js_error(e).context(format!("Could not fetch '{url}'")));
};
let request = web_sys::Request::new_with_str_and_init(&url, &opts)
.map_err(js_error)
.with_context(|| format!("Could not construct request for url '{url}'"))?;
let set_headers = request.headers();
for (name, val) in headers.iter() {
let value = String::from_utf8_lossy(val.as_bytes());
set_headers
.set(name.as_str(), &value)
.map_err(js_error)
.with_context(|| {
anyhow::anyhow!("Could not apply request header: '{name}': '{value}'")
})?;
}
call_fetch(&request)
.await
.map_err(js_error)
.with_context(|| format!("Could not fetch '{url}'"))?
}
};
let response = resp_value.dyn_ref().unwrap();
read_response(response).await
}
async fn read_response(response: &web_sys::Response) -> Result<HttpResponse, anyhow::Error> {
let status = http::StatusCode::from_u16(response.status())?;
let headers = headers(response.headers()).context("Unable to read the headers")?;
let body = get_response_data(response).await?;
Ok(HttpResponse {
body: Some(body),
redirected: response.redirected(),
status,
headers,
})
}
fn headers(headers: web_sys::Headers) -> Result<http::HeaderMap, anyhow::Error> {
let iter = js_sys::try_iter(&headers)
.map_err(js_error)?
.context("Not an iterator")?;
let mut header_map = http::HeaderMap::new();
for pair in iter {
let pair = pair.map_err(js_error)?;
let [key, value]: [js_sys::JsString; 2] =
js_array(&pair).context("Unable to unpack the header's key-value pairs")?;
let key = String::from(key);
let key: http::HeaderName = key.parse()?;
let value = String::from(value);
let value = http::HeaderValue::from_str(&value)
.with_context(|| format!("Invalid header value: {value}"))?;
header_map.insert(key, value);
}
Ok(header_map)
}
fn js_array<T, const N: usize>(value: &JsValue) -> Result<[T; N], anyhow::Error>
where
T: JsCast,
{
let array: &js_sys::Array = value.dyn_ref().context("Not an array")?;
let mut items = Vec::new();
for value in array.iter() {
let item = value
.dyn_into()
.map_err(|_| anyhow::anyhow!("Unable to cast to a {}", std::any::type_name::<T>()))?;
items.push(item);
}
<[T; N]>::try_from(items).map_err(|original| {
anyhow::anyhow!(
"Unable to turn a list of {} items into an array of {N} items",
original.len()
)
})
}
pub async fn get_response_data(resp: &web_sys::Response) -> Result<Vec<u8>, anyhow::Error> {
let buffer = JsFuture::from(resp.array_buffer().unwrap())
.await
.map_err(js_error)
.with_context(|| "Could not retrieve response body".to_string())?;
let buffer = js_sys::Uint8Array::new(&buffer);
Ok(buffer.to_vec())
}
fn call_fetch(request: &web_sys::Request) -> JsFuture {
let global = js_sys::global();
if JsValue::from_str("WorkerGlobalScope").js_in(&global)
&& global.is_instance_of::<WorkerGlobalScope>()
{
JsFuture::from(
global
.unchecked_into::<WorkerGlobalScope>()
.fetch_with_request(request),
)
} else {
JsFuture::from(
global
.unchecked_into::<Window>()
.fetch_with_request(request),
)
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::runtime::resolver::WapmSource;
#[wasm_bindgen_test::wasm_bindgen_test]
async fn query_the_wasmer_registry_graphql_endpoint() {
let http_client = WebHttpClient::default();
let query = r#"{
"query": "{ info { defaultFrontend } }"
}"#;
let request = http::Request::post(WapmSource::WASMER_PROD_ENDPOINT)
.header(http::header::CONTENT_TYPE, "application/json")
.body(query)
.unwrap();
let response = http_client.request(request.into()).await.unwrap();
assert_eq!(
response
.headers
.get(http::header::CONTENT_TYPE)
.unwrap()
.to_str()
.unwrap(),
"application/json",
);
let body: serde_json::Value =
serde_json::from_slice(response.body.as_deref().unwrap()).unwrap();
let frontend_url = body
.pointer("/data/info/defaultFrontend")
.unwrap()
.as_str()
.unwrap();
assert_eq!(frontend_url, "https://wasmer.io");
}
}