Skip to main content

opensearch_client/client/
configuration.rs

1/*
2 * opensearch-client
3 *
4 * Rust Client for OpenSearch
5 *
6 * The version of the OpenAPI document: 3.1.0
7 * Contact: alberto.paro@gmail.com
8 * Generated by Paro OpenAPI Generator
9 */
10
11use crate::client::auth_middleware::AuthMiddleware;
12use crate::client::credentials::Credentials;
13use crate::Error;
14use crate::{client::auth_middleware, OsClient};
15#[cfg(not(target_arch = "wasm32"))]
16use reqwest::{NoProxy, Proxy};
17use reqwest_middleware::ClientWithMiddleware;
18use reqwest_retry::{policies::ExponentialBackoff, RetryTransientMiddleware};
19use std::{
20    collections::HashMap,
21    sync::{Arc, Mutex},
22};
23use url::Url;
24
25#[derive(Clone, Debug)]
26pub struct ConfigurationBuilder {
27    baseurl: String,
28    user_agent: Option<String>,
29    retries: u32,
30    credentials: HashMap<String, Credentials>,
31    accept_invalid_certificates: bool,
32    max_bulk_size: u32,
33    #[cfg(not(target_arch = "wasm32"))]
34    proxy: bool,
35    #[cfg(not(target_arch = "wasm32"))]
36    proxy_url: Option<Proxy>,
37    #[cfg(not(target_arch = "wasm32"))]
38    no_proxy_domain: Option<String>,
39}
40
41impl Default for ConfigurationBuilder {
42    fn default() -> Self {
43        Self {
44            baseurl: "http://localhost:9200".to_owned(),
45            user_agent: Some("opensearch-client/0.1.0".to_string()),
46            credentials: HashMap::new(),
47            accept_invalid_certificates: false,
48            max_bulk_size: 200,
49            #[cfg(not(target_arch = "wasm32"))]
50            proxy: false,
51            #[cfg(not(target_arch = "wasm32"))]
52            proxy_url: None,
53            #[cfg(not(target_arch = "wasm32"))]
54            no_proxy_domain: None,
55            #[cfg(not(test))]
56            retries: 2,
57            #[cfg(test)]
58            retries: 0,
59        }
60    }
61}
62
63impl ConfigurationBuilder {
64    pub fn new() -> Self {
65        Default::default()
66    }
67
68    pub fn base_url(mut self, baseurl: impl Into<String>) -> Self {
69        self.baseurl = baseurl.into();
70        self
71    }
72
73    pub fn user_agent(mut self, user_agent: impl Into<String>) -> Self {
74        self.user_agent = Some(user_agent.into());
75        self
76    }
77
78    pub fn accept_invalid_certificates(mut self, accept_invalid_certificates: bool) -> Self {
79        self.accept_invalid_certificates = accept_invalid_certificates;
80        self
81    }
82
83    pub fn max_bulk_size(mut self, max_bulk_size: u32) -> Self {
84        self.max_bulk_size = max_bulk_size;
85        self
86    }
87
88    pub fn basic_auth(mut self, username: impl Into<String>, password: impl Into<String>) -> Self {
89        self.credentials.insert(
90            auth_middleware::nerf_dart(&Url::parse(&self.baseurl).unwrap()),
91            Credentials::Basic {
92                username: username.into(),
93                password: Some(password.into()),
94            },
95        );
96        self
97    }
98
99    pub fn token_auth(mut self, token: impl Into<String>) -> Self {
100        self.credentials.insert(
101            auth_middleware::nerf_dart(&Url::parse(&self.baseurl).unwrap()),
102            Credentials::Token(token.into()),
103        );
104        self
105    }
106
107    pub fn legacy_auth(mut self, legacy_auth_token: impl Into<String>) -> Self {
108        self.credentials.insert(
109            auth_middleware::nerf_dart(&Url::parse(&self.baseurl).unwrap()),
110            Credentials::EncodedBasic(legacy_auth_token.into()),
111        );
112        self
113    }
114
115    pub fn retries(mut self, retries: u32) -> Self {
116        self.retries = retries;
117        self
118    }
119
120    #[cfg(not(target_arch = "wasm32"))]
121    pub fn proxy(mut self, proxy: bool) -> Self {
122        self.proxy = proxy;
123        self
124    }
125
126    #[cfg(not(target_arch = "wasm32"))]
127    pub fn proxy_url(mut self, proxy_url: impl AsRef<str>) -> Result<Self, Error> {
128        match Url::parse(proxy_url.as_ref()) {
129            Ok(url_info) => {
130                let username = url_info.username();
131                let password = url_info.password();
132                let mut proxy = Proxy::all(url_info.as_ref())?;
133
134                if let Some(password_str) = password {
135                    proxy = proxy.basic_auth(username, password_str);
136                }
137
138                proxy = proxy.no_proxy(self.get_no_proxy_domain());
139                self.proxy_url = Some(proxy);
140                self.proxy = true;
141                Ok(self)
142            }
143            Err(e) => Err(Error::UrlParseError(e)),
144        }
145    }
146
147    #[cfg(not(target_arch = "wasm32"))]
148    pub fn no_proxy_domain(mut self, no_proxy_domain: impl AsRef<str>) -> Self {
149        self.no_proxy_domain = Some(no_proxy_domain.as_ref().into());
150        self
151    }
152
153    pub fn build(self) -> OsClient {
154        #[cfg(target_arch = "wasm32")]
155        let client_raw = {
156            let mut client_core = ClientBuilder::new();
157            if self.accept_invalid_certificates {
158                let mut builder = client_raw.clone().builder();
159                builder = builder.danger_accept_invalid_certs(true);
160                builder = builder.danger_accept_invalid_hostnames(true);
161                client_raw = builder.build().unwrap();
162            }
163            client_core.build().expect("Fail to build HTTP client.")
164        };
165
166        #[cfg(not(target_arch = "wasm32"))]
167        let client_raw = {
168            use reqwest::ClientBuilder;
169
170            let mut client_core = ClientBuilder::new()
171                .user_agent("opensearch-client/0.1.0")
172                .pool_max_idle_per_host(20)
173                .timeout(std::time::Duration::from_secs(60 * 5));
174
175            if let Some(url) = self.proxy_url {
176                client_core = client_core.proxy(url);
177            }
178
179            if !self.proxy {
180                client_core = client_core.no_proxy();
181            }
182            if self.accept_invalid_certificates {
183                client_core = client_core.danger_accept_invalid_certs(true);
184                client_core = client_core.danger_accept_invalid_hostnames(true);
185            }
186
187            client_core.build().expect("Fail to build HTTP client.")
188        };
189
190        let retry_policy = ExponentialBackoff::builder()
191            .retry_bounds(
192                std::time::Duration::from_millis(30),
193                std::time::Duration::from_millis(100),
194            )
195            .build_with_max_retries(self.retries);
196        let retry_strategy = RetryTransientMiddleware::new_with_policy(retry_policy);
197        let credentials = Arc::new(self.credentials);
198
199        #[allow(unused_mut)]
200        let mut client_builder = reqwest_middleware::ClientBuilder::new(client_raw.clone())
201            .with(retry_strategy)
202            .with(AuthMiddleware(credentials.clone()));
203
204        let configuration = Configuration {
205            base_path: self.baseurl.clone(),
206            client: client_builder.build(),
207            bulker: Arc::new(Mutex::new(String::new())),
208            bulker_size: Arc::new(Mutex::new(0)),
209            max_bulk_size: self.max_bulk_size,
210        };
211        OsClient::new(Arc::new(configuration))
212    }
213
214    #[cfg(not(target_arch = "wasm32"))]
215    fn get_no_proxy_domain(&self) -> Option<NoProxy> {
216        if let Some(ref no_proxy_conf) = self.no_proxy_domain {
217            if !no_proxy_conf.is_empty() {
218                return NoProxy::from_string(no_proxy_conf);
219            }
220        }
221
222        NoProxy::from_env().or(None)
223    }
224}
225
226#[derive(Debug, Clone)]
227pub struct Configuration {
228    pub(crate) base_path: String,
229    pub(crate) client: ClientWithMiddleware,
230    pub(crate) bulker: Arc<Mutex<String>>,
231    pub(crate) bulker_size: Arc<Mutex<u32>>,
232    pub(crate) max_bulk_size: u32,
233}
234
235impl Configuration {
236    pub fn base_path(&self) -> &str {
237        &self.base_path
238    }
239
240    pub fn client(&self) -> &ClientWithMiddleware {
241        &self.client
242    }
243
244    pub fn bulker(&self) -> Arc<Mutex<String>> {
245        Arc::clone(&self.bulker)
246    }
247
248    pub fn bulker_size(&self) -> Arc<Mutex<u32>> {
249        Arc::clone(&self.bulker_size)
250    }
251
252    pub fn max_bulk_size(&self) -> u32 {
253        self.max_bulk_size
254    }
255}
256
257impl Configuration {
258    pub fn new() -> Configuration {
259        Configuration::default()
260    }
261}
262
263impl Default for Configuration {
264    fn default() -> Self {
265        Configuration {
266            base_path: "http://localhost:9200".to_owned(),
267            client: reqwest_middleware::ClientBuilder::new(reqwest::Client::new()).build(),
268            bulker: Arc::new(Mutex::new(String::new())),
269            bulker_size: Arc::new(Mutex::new(0)),
270            max_bulk_size: 100,
271        }
272    }
273}