Avoid connection-per-RPC-call again by caching connections
[rust-lightning] / lightning-block-sync / src / rest.rs
index c2926b7a0f766fdc975614735f025d80c05e5e9f..4300893013c06d7a3ee81c715b256066f4d28333 100644 (file)
@@ -9,10 +9,12 @@ use bitcoin::hashes::hex::ToHex;
 
 use std::convert::TryFrom;
 use std::convert::TryInto;
+use std::sync::Mutex;
 
 /// A simple REST client for requesting resources using HTTP `GET`.
 pub struct RestClient {
        endpoint: HttpEndpoint,
+       client: Mutex<Option<HttpClient>>,
 }
 
 impl RestClient {
@@ -20,7 +22,7 @@ impl RestClient {
        ///
        /// The endpoint should contain the REST path component (e.g., http://127.0.0.1:8332/rest).
        pub fn new(endpoint: HttpEndpoint) -> std::io::Result<Self> {
-               Ok(Self { endpoint })
+               Ok(Self { endpoint, client: Mutex::new(None) })
        }
 
        /// Requests a resource encoded in `F` format and interpreted as type `T`.
@@ -28,8 +30,11 @@ impl RestClient {
        where F: TryFrom<Vec<u8>, Error = std::io::Error> + TryInto<T, Error = std::io::Error> {
                let host = format!("{}:{}", self.endpoint.host(), self.endpoint.port());
                let uri = format!("{}/{}", self.endpoint.path().trim_end_matches("/"), resource_path);
-               let mut client = HttpClient::connect(&self.endpoint)?;
-               client.get::<F>(&uri, &host).await?.try_into()
+               let mut client = if let Some(client) = self.client.lock().unwrap().take() { client }
+                       else { HttpClient::connect(&self.endpoint)? };
+               let res = client.get::<F>(&uri, &host).await?.try_into();
+               *self.client.lock().unwrap() = Some(client);
+               res
        }
 }