ckpool_api/
builder.rs

1//! Client builder
2
3#[cfg(feature = "socks")]
4use std::net::SocketAddr;
5use std::time::Duration;
6
7#[cfg(feature = "socks")]
8use reqwest::Proxy;
9use reqwest::{Client, ClientBuilder};
10use url::Url;
11
12use crate::client::CKPoolClient;
13use crate::error::Error;
14
15/// CKPool client builder
16#[derive(Debug, Clone)]
17pub struct CKPoolClientBuilder {
18    /// Endpoint URL
19    pub url: Url,
20    /// Timeout for requests
21    pub timeout: Duration,
22    /// Socks5 proxy
23    #[cfg(feature = "socks")]
24    pub proxy: Option<SocketAddr>,
25}
26
27impl CKPoolClientBuilder {
28    /// Construct a new builder
29    pub fn new(url: Url) -> Self {
30        Self {
31            url,
32            timeout: Duration::from_secs(60),
33            #[cfg(feature = "socks")]
34            proxy: None,
35        }
36    }
37
38    /// Set a custom timeout
39    #[inline]
40    pub fn timeout(mut self, timeout: Duration) -> Self {
41        self.timeout = timeout;
42        self
43    }
44
45    /// Set proxy
46    #[inline]
47    #[cfg(feature = "socks")]
48    pub fn proxy(mut self, proxy: SocketAddr) -> Self {
49        self.proxy = Some(proxy);
50        self
51    }
52
53    /// Build mempool client
54    pub fn build(self) -> Result<CKPoolClient, Error> {
55        // Construct builder
56        let mut builder: ClientBuilder = Client::builder();
57
58        // Set proxy
59        #[cfg(all(feature = "socks", not(target_arch = "wasm32")))]
60        if let Some(proxy) = self.proxy {
61            let proxy: String = format!("socks5h://{proxy}");
62            builder = builder.proxy(Proxy::all(proxy)?);
63        }
64
65        // Set timeout
66        builder = builder.timeout(self.timeout);
67
68        // Build client
69        let client: Client = builder.build()?;
70
71        // Construct client
72        Ok(CKPoolClient::from_client(self.url, client))
73    }
74}