Skip to main content

elemental_core/http/
client.rs

1use std::fmt;
2use std::sync::{Arc, RwLock, RwLockReadGuard, RwLockWriteGuard};
3
4use reqwest::header::{HeaderMap, HeaderName, HeaderValue};
5
6use super::config::{HttpClientConfig, Result};
7
8struct ClientState {
9    config: HttpClientConfig,
10    client: reqwest::Client,
11    no_redirect_client: reqwest::Client,
12}
13
14impl ClientState {
15    fn from_config(config: HttpClientConfig) -> Result<Self> {
16        let client = config.build()?;
17        let no_redirect_client = config.build_no_redirect()?;
18        Ok(Self {
19            config,
20            client,
21            no_redirect_client,
22        })
23    }
24}
25
26/// Config-swappable distributor of `reqwest::Client` instances.
27///
28/// Cloning a `SwappableClient` shares the same underlying state. Calling
29/// [`Self::swap`] or [`Self::update`] builds the replacement clients up front
30/// and atomically publishes them: in-flight requests retain their previously
31/// cloned `reqwest::Client` until completion, while new requests receive the
32/// updated client.
33#[derive(Clone)]
34pub struct SwappableClient {
35    inner: Arc<RwLock<ClientState>>,
36    headers: HeaderMap,
37}
38
39impl Default for SwappableClient {
40    fn default() -> Self {
41        Self::try_default().expect("build default HTTP client")
42    }
43}
44
45impl fmt::Debug for SwappableClient {
46    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
47        let state = self.read_state();
48        f.debug_struct("SwappableClient")
49            .field("config", &state.config)
50            .field("scoped_headers_len", &self.headers.len())
51            .finish()
52    }
53}
54
55impl SwappableClient {
56    /// Builds a new `SwappableClient` from the provided [`HttpClientConfig`].
57    pub fn new(config: HttpClientConfig) -> Result<Self> {
58        let state = ClientState::from_config(config)?;
59        Ok(Self {
60            inner: Arc::new(RwLock::new(state)),
61            headers: HeaderMap::new(),
62        })
63    }
64
65    /// Builds a new `SwappableClient` using [`HttpClientConfig::default`].
66    pub fn try_default() -> Result<Self> {
67        Self::new(HttpClientConfig::default())
68    }
69
70    /// Wraps an already-built `reqwest::Client`.
71    ///
72    /// Both [`Self::client`] and [`Self::no_redirect_client`] return clones of
73    /// `client` until [`Self::swap`] or [`Self::update`] replaces the state.
74    pub fn from_client(client: reqwest::Client) -> Self {
75        let state = ClientState {
76            config: HttpClientConfig::default(),
77            no_redirect_client: client.clone(),
78            client,
79        };
80        Self {
81            inner: Arc::new(RwLock::new(state)),
82            headers: HeaderMap::new(),
83        }
84    }
85
86    /// Replaces per-handle headers attached to requests created via [`Self::get`],
87    /// while continuing to share the underlying hot-swappable client state.
88    pub fn with_headers(mut self, headers: HeaderMap) -> Self {
89        self.headers = headers;
90        self
91    }
92
93    /// Inserts a per-handle header attached to requests created via [`Self::get`],
94    /// while continuing to share the underlying hot-swappable client state.
95    pub fn with_header(mut self, name: HeaderName, value: HeaderValue) -> Self {
96        self.headers.insert(name, value);
97        self
98    }
99
100    /// Returns the per-handle headers attached by [`Self::get`].
101    pub fn scoped_headers(&self) -> &HeaderMap {
102        &self.headers
103    }
104
105    /// Starts an HTTP request using the active `reqwest::Client` and this handle's scoped headers.
106    pub fn request(
107        &self,
108        method: reqwest::Method,
109        url: impl reqwest::IntoUrl,
110    ) -> reqwest::RequestBuilder {
111        let builder = self.client().request(method, url);
112        if self.headers.is_empty() {
113            builder
114        } else {
115            builder.headers(self.headers.clone())
116        }
117    }
118
119    /// Starts a `GET` request using the active `reqwest::Client` and this handle's scoped headers.
120    pub fn get(&self, url: impl reqwest::IntoUrl) -> reqwest::RequestBuilder {
121        self.request(reqwest::Method::GET, url)
122    }
123
124    /// Returns a clone of the currently active [`HttpClientConfig`].
125    pub fn config(&self) -> HttpClientConfig {
126        self.read_state().config.clone()
127    }
128
129    /// Returns a cheap clone of the currently active `reqwest::Client`.
130    pub fn client(&self) -> reqwest::Client {
131        self.read_state().client.clone()
132    }
133
134    /// Returns a cheap clone of the currently active no-redirect `reqwest::Client`.
135    pub fn no_redirect_client(&self) -> reqwest::Client {
136        self.read_state().no_redirect_client.clone()
137    }
138
139    /// Builds replacement clients from `config` and swaps them in atomically.
140    ///
141    /// If building either client fails, the previous clients remain active.
142    pub fn swap(&self, config: HttpClientConfig) -> Result<()> {
143        let next_state = ClientState::from_config(config)?;
144        *self.write_state() = next_state;
145        Ok(())
146    }
147
148    /// Replaces the active `reqwest::Client` directly with an already-built instance.
149    pub fn swap_client(&self, client: reqwest::Client) {
150        let mut state = self.write_state();
151        state.no_redirect_client = client.clone();
152        state.client = client;
153    }
154
155    /// Clones the active [`HttpClientConfig`], transforms it with `configure`,
156    /// and swaps in the rebuilt clients.
157    ///
158    /// If building fails, the previous configuration and clients remain active.
159    pub fn update<F>(&self, configure: F) -> Result<()>
160    where
161        F: FnOnce(HttpClientConfig) -> HttpClientConfig,
162    {
163        let next_config = configure(self.config());
164        self.swap(next_config)
165    }
166
167    fn read_state(&self) -> RwLockReadGuard<'_, ClientState> {
168        self.inner
169            .read()
170            .unwrap_or_else(|poisoned| poisoned.into_inner())
171    }
172
173    fn write_state(&self) -> RwLockWriteGuard<'_, ClientState> {
174        self.inner
175            .write()
176            .unwrap_or_else(|poisoned| poisoned.into_inner())
177    }
178}