-
Notifications
You must be signed in to change notification settings - Fork 96
/
http.rs
182 lines (153 loc) · 5.56 KB
/
http.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
use async_trait::async_trait;
use log::trace;
use reqwest::{Client, Url};
use serde::{de::DeserializeOwned, Serialize};
use crate::{
jsonrpc::{transports::JsonRpcTransport, JsonRpcMethod, JsonRpcResponse},
ProviderRequestData,
};
/// A [`JsonRpcTransport`] implementation that uses HTTP connections.
#[derive(Debug)]
pub struct HttpTransport {
client: Client,
url: Url,
headers: Vec<(String, String)>,
}
/// Errors using [`HttpTransport`].
#[derive(Debug, thiserror::Error)]
#[error(transparent)]
pub enum HttpTransportError {
/// HTTP-related errors.
Reqwest(reqwest::Error),
/// JSON serialization/deserialization errors.
Json(serde_json::Error),
/// Unexpected response ID.
#[error("unexpected response ID: {0}")]
UnexpectedResponseId(u64),
}
#[derive(Debug, Serialize)]
struct JsonRpcRequest<T> {
id: u64,
jsonrpc: &'static str,
method: JsonRpcMethod,
params: T,
}
impl HttpTransport {
/// Constructs [`HttpTransport`] from a JSON-RPC server URL, using default HTTP client settings.
///
/// To use custom HTTP settings (e.g. proxy, timeout), use
/// [`new_with_client`](fn.new_with_client) instead.
pub fn new(url: impl Into<Url>) -> Self {
Self::new_with_client(url, Client::new())
}
/// Constructs [`HttpTransport`] from a JSON-RPC server URL and a custom `reqwest` client.
pub fn new_with_client(url: impl Into<Url>, client: Client) -> Self {
Self {
client,
url: url.into(),
headers: vec![],
}
}
/// Consumes the current [`HttpTransport`] instance and returns a new one with the header
/// appended. Same as calling [`add_header`](fn.add_header).
pub fn with_header(self, name: String, value: String) -> Self {
let mut headers = self.headers;
headers.push((name, value));
Self {
client: self.client,
url: self.url,
headers,
}
}
/// Adds a custom HTTP header to be sent for requests.
pub fn add_header(&mut self, name: String, value: String) {
self.headers.push((name, value))
}
}
#[cfg_attr(not(target_arch = "wasm32"), async_trait)]
#[cfg_attr(target_arch = "wasm32", async_trait(?Send))]
impl JsonRpcTransport for HttpTransport {
type Error = HttpTransportError;
async fn send_request<P, R>(
&self,
method: JsonRpcMethod,
params: P,
) -> Result<JsonRpcResponse<R>, Self::Error>
where
P: Serialize + Send,
R: DeserializeOwned,
{
let request_body = JsonRpcRequest {
id: 1,
jsonrpc: "2.0",
method,
params,
};
let request_body = serde_json::to_string(&request_body).map_err(Self::Error::Json)?;
trace!("Sending request via JSON-RPC: {}", request_body);
let mut request = self
.client
.post(self.url.clone())
.body(request_body)
.header("Content-Type", "application/json");
for (name, value) in &self.headers {
request = request.header(name, value);
}
let response = request.send().await.map_err(Self::Error::Reqwest)?;
let response_body = response.text().await.map_err(Self::Error::Reqwest)?;
trace!("Response from JSON-RPC: {}", response_body);
let parsed_response = serde_json::from_str(&response_body).map_err(Self::Error::Json)?;
Ok(parsed_response)
}
async fn send_requests<R>(
&self,
requests: R,
) -> Result<Vec<JsonRpcResponse<serde_json::Value>>, Self::Error>
where
R: AsRef<[ProviderRequestData]> + Send + Sync,
{
let request_bodies = requests
.as_ref()
.iter()
.enumerate()
.map(|(ind, request)| JsonRpcRequest {
id: ind as u64,
jsonrpc: "2.0",
method: request.jsonrpc_method(),
params: request,
})
.collect::<Vec<_>>();
let request_count = request_bodies.len();
let request_body = serde_json::to_string(&request_bodies).map_err(Self::Error::Json)?;
trace!("Sending request via JSON-RPC: {}", request_body);
let mut request = self
.client
.post(self.url.clone())
.body(request_body)
.header("Content-Type", "application/json");
for (name, value) in &self.headers {
request = request.header(name, value);
}
let response = request.send().await.map_err(Self::Error::Reqwest)?;
let response_body = response.text().await.map_err(Self::Error::Reqwest)?;
trace!("Response from JSON-RPC: {}", response_body);
let parsed_response: Vec<JsonRpcResponse<serde_json::Value>> =
serde_json::from_str(&response_body).map_err(Self::Error::Json)?;
let mut responses: Vec<Option<JsonRpcResponse<serde_json::Value>>> = vec![];
responses.resize(request_bodies.len(), None);
// Re-order the responses as servers do not maintain order.
for response_item in parsed_response {
let id = match &response_item {
JsonRpcResponse::Success { id, .. } | JsonRpcResponse::Error { id, .. } => {
*id as usize
}
};
if id >= request_count {
return Err(HttpTransportError::UnexpectedResponseId(id as u64));
}
responses[id] = Some(response_item);
}
let responses = responses.into_iter().flatten().collect::<Vec<_>>();
Ok(responses)
}
}