1#![warn(missing_docs)]
23
24mod api;
25mod error;
26mod pagination;
27pub mod types;
28
29pub use error::{Error, Result};
30pub use pagination::{Paginated, PaginationQuery};
31
32use api::handle_response;
33use reqwest::header::{HeaderMap, HeaderValue, AUTHORIZATION, CONTENT_TYPE};
34use serde::de::DeserializeOwned;
35use serde::Serialize;
36
37pub const DEFAULT_VHOST: &str = "/";
39
40#[derive(Clone)]
45pub struct Client {
46 http: reqwest::Client,
47 base_url: reqwest::Url,
50 auth: Option<HeaderValue>,
55}
56
57pub struct ClientBuilder {
59 base_url: String,
60 username: String,
61 password: String,
62 http: Option<reqwest::Client>,
63}
64
65impl Client {
66 pub fn builder(
73 base_url: impl Into<String>,
74 username: impl Into<String>,
75 password: impl Into<String>,
76 ) -> ClientBuilder {
77 ClientBuilder {
78 base_url: base_url.into(),
79 username: username.into(),
80 password: password.into(),
81 http: None,
82 }
83 }
84
85 pub fn new(base_url: &str, username: &str, password: &str) -> Result<Self> {
88 Self::builder(base_url, username, password).build()
89 }
90
91 pub async fn whoami(&self) -> Result<types::WhoAmI> {
94 self.get_ctx("whoami", None, "whoami").await
95 }
96
97 pub(crate) async fn get<T: DeserializeOwned>(
99 &self,
100 path: &str,
101 query: Option<&PaginationQuery>,
102 ) -> Result<T> {
103 let url = self.url(path)?;
104 let mut req = self
105 .http
106 .get(url)
107 .query(&query.map(|q| q.to_pairs()).unwrap_or_default());
108 if let Some(auth) = &self.auth {
109 req = req.header(AUTHORIZATION, auth.clone());
110 }
111 let resp = req.send().await?;
112 let body = handle_response(resp).await?;
113 serde_json::from_str(&body).map_err(|e| Error::Deserialize { source: e, body })
114 }
115
116 pub(crate) async fn get_ctx<T: DeserializeOwned>(
120 &self,
121 path: &str,
122 query: Option<&PaginationQuery>,
123 ctx: &str,
124 ) -> Result<T> {
125 self.get(path, query).await.map_err(|e| api::nf(e, ctx))
126 }
127
128 pub(crate) async fn put<B: Serialize>(&self, path: &str, body: &B) -> Result<()> {
130 let resp = self
131 .request_with_auth(self.http.put(self.url(path)?))
132 .json(body)
133 .send()
134 .await?;
135 handle_response(resp).await?;
136 Ok(())
137 }
138
139 pub(crate) async fn post<B: Serialize>(&self, path: &str, body: &B) -> Result<()> {
141 let resp = self
142 .request_with_auth(self.http.post(self.url(path)?))
143 .json(body)
144 .send()
145 .await?;
146 handle_response(resp).await?;
147 Ok(())
148 }
149
150 pub(crate) async fn post_json<B, T>(&self, path: &str, body: &B) -> Result<T>
153 where
154 B: Serialize,
155 T: DeserializeOwned,
156 {
157 let resp = self
158 .request_with_auth(self.http.post(self.url(path)?))
159 .json(body)
160 .send()
161 .await?;
162 let body = handle_response(resp).await?;
163 serde_json::from_str(&body).map_err(|e| Error::Deserialize { source: e, body })
164 }
165
166 pub(crate) async fn delete(&self, path: &str) -> Result<()> {
168 self.delete_with_headers(path, &[]).await
169 }
170
171 pub(crate) async fn delete_with_headers(
174 &self,
175 path: &str,
176 headers: &[(&str, &str)],
177 ) -> Result<()> {
178 let mut req = self.request_with_auth(self.http.delete(self.url(path)?));
179 for (k, v) in headers {
180 req = req.header(*k, *v);
181 }
182 let resp = req.send().await?;
183 handle_response(resp).await?;
184 Ok(())
185 }
186
187 pub(crate) async fn delete_ctx(&self, path: &str, ctx: &str) -> Result<()> {
190 self.delete(path).await.map_err(|e| api::nf(e, ctx))
191 }
192
193 fn url(&self, path: &str) -> Result<reqwest::Url> {
200 debug_assert!(
201 !path.starts_with('/'),
202 "API paths must be relative (no leading '/'): {path}"
203 );
204 self.base_url
205 .join(path)
206 .map_err(|e| Error::InvalidUrl(format!("{path}: {e}")))
207 }
208
209 fn request_with_auth(&self, req: reqwest::RequestBuilder) -> reqwest::RequestBuilder {
214 match &self.auth {
215 Some(auth) => req.header(AUTHORIZATION, auth.clone()),
216 None => req,
217 }
218 }
219}
220
221impl ClientBuilder {
222 pub fn http_client(mut self, http: reqwest::Client) -> Self {
229 self.http = Some(http);
230 self
231 }
232
233 pub fn build(self) -> Result<Client> {
242 let trimmed = self.base_url.trim_end_matches('/');
243 let with_api = if trimmed.ends_with("/api") {
244 format!("{trimmed}/")
245 } else {
246 format!("{trimmed}/api/")
247 };
248 let base_url = reqwest::Url::parse(&with_api)
249 .map_err(|e| Error::InvalidUrl(format!("{}: {e}", self.base_url)))?;
250 if base_url.scheme() != "http" && base_url.scheme() != "https" {
251 return Err(Error::InvalidUrl(format!(
252 "invalid base URL '{}': scheme must be http or https",
253 self.base_url
254 )));
255 }
256 if base_url.cannot_be_a_base() {
257 return Err(Error::InvalidUrl(format!(
258 "invalid base URL '{}': cannot be used as a base URL",
259 self.base_url
260 )));
261 }
262
263 let mut headers = HeaderMap::new();
264 let auth = format!("{}:{}", self.username, self.password);
265 let mut auth_value =
266 HeaderValue::from_str(&format!("Basic {}", base64_encode(auth.as_bytes())))
267 .map_err(|e| Error::InvalidUrl(format!("invalid credentials: {e}")))?;
268 auth_value.set_sensitive(true);
269 let auth_value_for_requests = auth_value.clone();
273 headers.insert(AUTHORIZATION, auth_value);
274 headers.insert(CONTENT_TYPE, HeaderValue::from_static("application/json"));
275
276 let http = match self.http {
277 Some(c) => c,
278 None => reqwest::Client::builder()
279 .default_headers(headers)
280 .build()?,
281 };
282
283 Ok(Client {
284 http,
285 base_url,
286 auth: Some(auth_value_for_requests),
287 })
288 }
289}
290
291fn base64_encode(data: &[u8]) -> String {
294 const ALPHABET: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
295 let mut out = String::with_capacity(data.len().div_ceil(3) * 4);
296 for chunk in data.chunks(3) {
297 let b = [
298 chunk[0],
299 *chunk.get(1).unwrap_or(&0),
300 *chunk.get(2).unwrap_or(&0),
301 ];
302 let n = u32::from(b[0]) << 16 | u32::from(b[1]) << 8 | u32::from(b[2]);
303 out.push(ALPHABET[(n >> 18) as usize & 0x3f] as char);
304 out.push(ALPHABET[(n >> 12) as usize & 0x3f] as char);
305 out.push(if chunk.len() > 1 {
306 ALPHABET[(n >> 6) as usize & 0x3f] as char
307 } else {
308 '='
309 });
310 out.push(if chunk.len() > 2 {
311 ALPHABET[n as usize & 0x3f] as char
312 } else {
313 '='
314 });
315 }
316 out
317}
318
319#[cfg(test)]
320mod tests {
321 use super::*;
322
323 #[test]
324 fn url_joins_relative_path_onto_api_base() {
325 let c = Client::new("http://localhost:15672", "guest", "guest").unwrap();
326 let u = c.url("nodes").unwrap();
327 assert_eq!(u.as_str(), "http://localhost:15672/api/nodes");
328 }
329
330 #[cfg(debug_assertions)]
331 #[test]
332 #[should_panic(expected = "API paths must be relative")]
333 fn url_panics_on_leading_slash_in_debug_builds() {
334 let c = Client::new("http://localhost:15672", "guest", "guest").unwrap();
335 let _ = c.url("/nodes");
336 }
337}