Skip to content

Commit 73bb708

Browse files
committed
Do not consume HttpClient when calling get or post
1 parent 7f0c61c commit 73bb708

File tree

1 file changed

+21
-14
lines changed

1 file changed

+21
-14
lines changed

lightning-block-sync/src/http_clients.rs

Lines changed: 21 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -67,7 +67,7 @@ impl HttpClient {
6767
}
6868

6969
/// Sends a `GET` request for a resource identified by `uri` at the `host`.
70-
async fn get<F>(mut self, uri: &str, host: &str) -> std::io::Result<F>
70+
async fn get<F>(&mut self, uri: &str, host: &str) -> std::io::Result<F>
7171
where F: TryFrom<Vec<u8>, Error = std::io::Error> {
7272
let request = format!(
7373
"GET {} HTTP/1.1\r\n\
@@ -88,7 +88,7 @@ impl HttpClient {
8888
///
8989
/// The request body consists of the provided JSON `content`. Returns the response body in `F`
9090
/// format.
91-
async fn post<F>(mut self, uri: &str, host: &str, auth: &str, content: serde_json::Value) -> std::io::Result<F>
91+
async fn post<F>(&mut self, uri: &str, host: &str, auth: &str, content: serde_json::Value) -> std::io::Result<F>
9292
where F: TryFrom<Vec<u8>, Error = std::io::Error> {
9393
let content = content.to_string();
9494
let request = format!(
@@ -110,8 +110,14 @@ impl HttpClient {
110110
}
111111

112112
/// Reads an HTTP response message.
113-
async fn read_response(self) -> std::io::Result<Vec<u8>> {
114-
let limited_stream = self.stream.take(MAX_HTTP_MESSAGE_HEADER_SIZE as u64);
113+
async fn read_response(&mut self) -> std::io::Result<Vec<u8>> {
114+
#[cfg(feature = "tokio")]
115+
let stream = self.stream.split().0;
116+
#[cfg(not(feature = "tokio"))]
117+
let stream = std::io::Read::by_ref(&mut self.stream);
118+
119+
let limited_stream = stream.take(MAX_HTTP_MESSAGE_HEADER_SIZE as u64);
120+
115121
#[cfg(feature = "tokio")]
116122
let mut reader = tokio::io::BufReader::new(limited_stream);
117123
#[cfg(not(feature = "tokio"))]
@@ -306,7 +312,7 @@ impl RESTClient {
306312
let host = format!("{}:{}", self.endpoint.host(), self.endpoint.port());
307313
let uri = format!("{}/{}", self.endpoint.path().trim_end_matches("/"), resource_path);
308314

309-
let client = HttpClient::connect(&self.endpoint)?;
315+
let mut client = HttpClient::connect(&self.endpoint)?;
310316
client.get::<F>(&uri, &host).await?.try_into()
311317
}
312318
}
@@ -338,7 +344,7 @@ impl RPCClient {
338344
"id": &self.id.fetch_add(1, Ordering::AcqRel).to_string()
339345
});
340346

341-
let client = HttpClient::connect(&self.endpoint)?;
347+
let mut client = HttpClient::connect(&self.endpoint)?;
342348
let mut response = client.post::<JsonResponse>(&uri, &host, &self.basic_auth, content).await?.0;
343349
if !response.is_object() {
344350
return Err(std::io::Error::new(std::io::ErrorKind::InvalidData, "expected JSON object"));
@@ -629,6 +635,7 @@ mod tests {
629635
fn responding_with(response: String) -> Self {
630636
let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
631637
let address = listener.local_addr().unwrap();
638+
632639
let _handler = std::thread::spawn(move || {
633640
let (mut stream, _) = listener.accept().unwrap();
634641
let lines_read = std::io::BufReader::new(&stream)
@@ -740,7 +747,7 @@ mod tests {
740747
async fn read_empty_message() {
741748
let server = HttpServer::responding_with("".to_string());
742749

743-
let client = HttpClient::connect(&server.endpoint()).unwrap();
750+
let mut client = HttpClient::connect(&server.endpoint()).unwrap();
744751
drop(server);
745752
match client.get::<BinaryResponse>("/foo", "foo.com").await {
746753
Err(e) => {
@@ -755,7 +762,7 @@ mod tests {
755762
async fn read_incomplete_message() {
756763
let server = HttpServer::responding_with("HTTP/1.1 200 OK".to_string());
757764

758-
let client = HttpClient::connect(&server.endpoint()).unwrap();
765+
let mut client = HttpClient::connect(&server.endpoint()).unwrap();
759766
drop(server);
760767
match client.get::<BinaryResponse>("/foo", "foo.com").await {
761768
Err(e) => {
@@ -774,7 +781,7 @@ mod tests {
774781
\r\n", "Z".repeat(MAX_HTTP_MESSAGE_HEADER_SIZE));
775782
let server = HttpServer::responding_with(response);
776783

777-
let client = HttpClient::connect(&server.endpoint()).unwrap();
784+
let mut client = HttpClient::connect(&server.endpoint()).unwrap();
778785
match client.get::<BinaryResponse>("/foo", "foo.com").await {
779786
Err(e) => {
780787
assert_eq!(e.kind(), std::io::ErrorKind::InvalidData);
@@ -789,7 +796,7 @@ mod tests {
789796
let body = "Z".repeat(MAX_HTTP_MESSAGE_BODY_SIZE + 1);
790797
let server = HttpServer::responding_with_ok::<String>(MessageBody::Content(body));
791798

792-
let client = HttpClient::connect(&server.endpoint()).unwrap();
799+
let mut client = HttpClient::connect(&server.endpoint()).unwrap();
793800
match client.get::<BinaryResponse>("/foo", "foo.com").await {
794801
Err(e) => {
795802
assert_eq!(e.kind(), std::io::ErrorKind::InvalidData);
@@ -808,7 +815,7 @@ mod tests {
808815
foobar");
809816
let server = HttpServer::responding_with(response);
810817

811-
let client = HttpClient::connect(&server.endpoint()).unwrap();
818+
let mut client = HttpClient::connect(&server.endpoint()).unwrap();
812819
match client.get::<BinaryResponse>("/foo", "foo.com").await {
813820
Err(e) => {
814821
assert_eq!(e.kind(), std::io::ErrorKind::InvalidInput);
@@ -822,7 +829,7 @@ mod tests {
822829
async fn read_empty_message_body() {
823830
let server = HttpServer::responding_with_ok::<String>(MessageBody::Empty);
824831

825-
let client = HttpClient::connect(&server.endpoint()).unwrap();
832+
let mut client = HttpClient::connect(&server.endpoint()).unwrap();
826833
match client.get::<BinaryResponse>("/foo", "foo.com").await {
827834
Err(e) => panic!("Unexpected error: {:?}", e),
828835
Ok(bytes) => assert_eq!(bytes.0, Vec::<u8>::new()),
@@ -835,7 +842,7 @@ mod tests {
835842
let content = MessageBody::Content(body.clone());
836843
let server = HttpServer::responding_with_ok::<String>(content);
837844

838-
let client = HttpClient::connect(&server.endpoint()).unwrap();
845+
let mut client = HttpClient::connect(&server.endpoint()).unwrap();
839846
match client.get::<BinaryResponse>("/foo", "foo.com").await {
840847
Err(e) => panic!("Unexpected error: {:?}", e),
841848
Ok(bytes) => assert_eq!(bytes.0, body.as_bytes()),
@@ -848,7 +855,7 @@ mod tests {
848855
let chunked_content = MessageBody::ChunkedContent(body.clone());
849856
let server = HttpServer::responding_with_ok::<String>(chunked_content);
850857

851-
let client = HttpClient::connect(&server.endpoint()).unwrap();
858+
let mut client = HttpClient::connect(&server.endpoint()).unwrap();
852859
match client.get::<BinaryResponse>("/foo", "foo.com").await {
853860
Err(e) => panic!("Unexpected error: {:?}", e),
854861
Ok(bytes) => assert_eq!(bytes.0, body.as_bytes()),

0 commit comments

Comments
 (0)