#![warn(missing_docs)]
mod api;
mod error;
mod pagination;
pub mod types;
pub use error::{Error, Result};
pub use pagination::{Paginated, PaginationQuery};
use api::handle_response;
use reqwest::header::{HeaderMap, HeaderValue, AUTHORIZATION, CONTENT_TYPE};
use serde::de::DeserializeOwned;
use serde::Serialize;
pub const DEFAULT_VHOST: &str = "/";
#[derive(Clone)]
pub struct Client {
http: reqwest::Client,
base_url: reqwest::Url,
auth: Option<HeaderValue>,
}
pub struct ClientBuilder {
base_url: String,
username: String,
password: String,
http: Option<reqwest::Client>,
}
impl Client {
pub fn builder(
base_url: impl Into<String>,
username: impl Into<String>,
password: impl Into<String>,
) -> ClientBuilder {
ClientBuilder {
base_url: base_url.into(),
username: username.into(),
password: password.into(),
http: None,
}
}
pub fn new(base_url: &str, username: &str, password: &str) -> Result<Self> {
Self::builder(base_url, username, password).build()
}
pub async fn whoami(&self) -> Result<types::WhoAmI> {
self.get_ctx("whoami", None, "whoami").await
}
pub(crate) async fn get<T: DeserializeOwned>(
&self,
path: &str,
query: Option<&PaginationQuery>,
) -> Result<T> {
let url = self.url(path)?;
let mut req = self
.http
.get(url)
.query(&query.map(|q| q.to_pairs()).unwrap_or_default());
if let Some(auth) = &self.auth {
req = req.header(AUTHORIZATION, auth.clone());
}
let resp = req.send().await?;
let body = handle_response(resp).await?;
serde_json::from_str(&body).map_err(|e| Error::Deserialize { source: e, body })
}
pub(crate) async fn get_ctx<T: DeserializeOwned>(
&self,
path: &str,
query: Option<&PaginationQuery>,
ctx: &str,
) -> Result<T> {
self.get(path, query).await.map_err(|e| api::nf(e, ctx))
}
pub(crate) async fn put<B: Serialize>(&self, path: &str, body: &B) -> Result<()> {
let resp = self
.request_with_auth(self.http.put(self.url(path)?))
.json(body)
.send()
.await?;
handle_response(resp).await?;
Ok(())
}
pub(crate) async fn post<B: Serialize>(&self, path: &str, body: &B) -> Result<()> {
let resp = self
.request_with_auth(self.http.post(self.url(path)?))
.json(body)
.send()
.await?;
handle_response(resp).await?;
Ok(())
}
pub(crate) async fn post_json<B, T>(&self, path: &str, body: &B) -> Result<T>
where
B: Serialize,
T: DeserializeOwned,
{
let resp = self
.request_with_auth(self.http.post(self.url(path)?))
.json(body)
.send()
.await?;
let body = handle_response(resp).await?;
serde_json::from_str(&body).map_err(|e| Error::Deserialize { source: e, body })
}
pub(crate) async fn delete(&self, path: &str) -> Result<()> {
self.delete_with_headers(path, &[]).await
}
pub(crate) async fn delete_with_headers(
&self,
path: &str,
headers: &[(&str, &str)],
) -> Result<()> {
let mut req = self.request_with_auth(self.http.delete(self.url(path)?));
for (k, v) in headers {
req = req.header(*k, *v);
}
let resp = req.send().await?;
handle_response(resp).await?;
Ok(())
}
pub(crate) async fn delete_ctx(&self, path: &str, ctx: &str) -> Result<()> {
self.delete(path).await.map_err(|e| api::nf(e, ctx))
}
fn url(&self, path: &str) -> Result<reqwest::Url> {
debug_assert!(
!path.starts_with('/'),
"API paths must be relative (no leading '/'): {path}"
);
self.base_url
.join(path)
.map_err(|e| Error::InvalidUrl(format!("{path}: {e}")))
}
fn request_with_auth(&self, req: reqwest::RequestBuilder) -> reqwest::RequestBuilder {
match &self.auth {
Some(auth) => req.header(AUTHORIZATION, auth.clone()),
None => req,
}
}
}
impl ClientBuilder {
pub fn http_client(mut self, http: reqwest::Client) -> Self {
self.http = Some(http);
self
}
pub fn build(self) -> Result<Client> {
let trimmed = self.base_url.trim_end_matches('/');
let with_api = if trimmed.ends_with("/api") {
format!("{trimmed}/")
} else {
format!("{trimmed}/api/")
};
let base_url = reqwest::Url::parse(&with_api)
.map_err(|e| Error::InvalidUrl(format!("{}: {e}", self.base_url)))?;
if base_url.scheme() != "http" && base_url.scheme() != "https" {
return Err(Error::InvalidUrl(format!(
"invalid base URL '{}': scheme must be http or https",
self.base_url
)));
}
if base_url.cannot_be_a_base() {
return Err(Error::InvalidUrl(format!(
"invalid base URL '{}': cannot be used as a base URL",
self.base_url
)));
}
let mut headers = HeaderMap::new();
let auth = format!("{}:{}", self.username, self.password);
let mut auth_value =
HeaderValue::from_str(&format!("Basic {}", base64_encode(auth.as_bytes())))
.map_err(|e| Error::InvalidUrl(format!("invalid credentials: {e}")))?;
auth_value.set_sensitive(true);
let auth_value_for_requests = auth_value.clone();
headers.insert(AUTHORIZATION, auth_value);
headers.insert(CONTENT_TYPE, HeaderValue::from_static("application/json"));
let http = match self.http {
Some(c) => c,
None => reqwest::Client::builder()
.default_headers(headers)
.build()?,
};
Ok(Client {
http,
base_url,
auth: Some(auth_value_for_requests),
})
}
}
fn base64_encode(data: &[u8]) -> String {
const ALPHABET: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
let mut out = String::with_capacity(data.len().div_ceil(3) * 4);
for chunk in data.chunks(3) {
let b = [
chunk[0],
*chunk.get(1).unwrap_or(&0),
*chunk.get(2).unwrap_or(&0),
];
let n = u32::from(b[0]) << 16 | u32::from(b[1]) << 8 | u32::from(b[2]);
out.push(ALPHABET[(n >> 18) as usize & 0x3f] as char);
out.push(ALPHABET[(n >> 12) as usize & 0x3f] as char);
out.push(if chunk.len() > 1 {
ALPHABET[(n >> 6) as usize & 0x3f] as char
} else {
'='
});
out.push(if chunk.len() > 2 {
ALPHABET[n as usize & 0x3f] as char
} else {
'='
});
}
out
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn url_joins_relative_path_onto_api_base() {
let c = Client::new("http://localhost:15672", "guest", "guest").unwrap();
let u = c.url("nodes").unwrap();
assert_eq!(u.as_str(), "http://localhost:15672/api/nodes");
}
#[cfg(debug_assertions)]
#[test]
#[should_panic(expected = "API paths must be relative")]
fn url_panics_on_leading_slash_in_debug_builds() {
let c = Client::new("http://localhost:15672", "guest", "guest").unwrap();
let _ = c.url("/nodes");
}
}