-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathfetch.rs
More file actions
96 lines (81 loc) · 2.7 KB
/
Copy pathfetch.rs
File metadata and controls
96 lines (81 loc) · 2.7 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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
use anyhow::{anyhow, Result};
use hyper::Request;
use lagoss_runtime_http::request_from_v8;
use reqwest::{redirect::Policy, Client, ClientBuilder};
use std::sync::OnceLock;
use crate::{bindings::PromiseResult, Isolate};
use super::BindingResult;
static CLIENT: OnceLock<Client> = OnceLock::new();
type Arg = Request<String>;
pub fn fetch_init(scope: &mut v8::PinScope<'_, '_>, args: v8::FunctionCallbackArguments) -> Result<Arg> {
let id = scope
.get_continuation_preserved_embedder_data()
.to_uint32(scope)
.map_or(0, |value| value.value());
let state = Isolate::state(scope);
let fetch_calls = {
let mut state = state.borrow_mut();
if let Some(handler_result) = state.handler_results.get_mut(&id) {
handler_result.context.fetch_calls += 1;
handler_result.context.fetch_calls
} else {
0
}
};
if fetch_calls > 20 {
return Err(anyhow!("fetch() can only be called 20 times per requests"));
}
let request = match args.get(0).to_object(scope) {
Some(request) => request,
None => return Err(anyhow!("Invalid request")),
};
request_from_v8(scope, request.into())
}
pub async fn fetch_binding(id: usize, arg: Arg) -> BindingResult {
let client = CLIENT.get_or_init(|| {
ClientBuilder::new()
.use_rustls_tls()
.redirect(Policy::custom(|attempt| {
if attempt.previous().len() >= 5 {
attempt.error("Too many redirects")
} else {
attempt.follow()
}
}))
.build()
.unwrap()
});
let (parts, body) = arg.into_parts();
match client
.request(parts.method, parts.uri.to_string())
.headers(parts.headers)
.body(body)
.send()
.await
{
Ok(response) => {
let status = response.status().as_u16();
let headers = response.headers().clone();
let bytes = match response.bytes().await {
Ok(bytes) => bytes,
Err(error) => {
return BindingResult {
id,
result: PromiseResult::Error(format!(
"Failed to read response body: {}",
error
)),
}
}
};
BindingResult {
id,
result: PromiseResult::Response((status, headers, bytes)),
}
}
Err(error) => BindingResult {
id,
result: PromiseResult::Error(error.without_url().to_string()),
},
}
}