Skip to main content

rabbitmqadmin_sdk/
lib.rs

1//! Async Rust SDK for the RabbitMQ Management HTTP API.
2//!
3//! This crate provides a strongly-typed async client for the RabbitMQ
4//! Management Plugin HTTP API (`/api/*`, typically port 15672). It supports
5//! monitoring (overview, nodes, queues, exchanges, connections, ...) as well
6//! as administrative actions (declaring and deleting queues, exchanges,
7//! bindings, vhosts, users, policies, purging queues, and more).
8//!
9//! # Example
10//!
11//! ```no_run
12//! use rabbitmqadmin_sdk::Client;
13//!
14//! # async fn example() -> rabbitmqadmin_sdk::Result<()> {
15//! let client = Client::new("http://localhost:15672", "guest", "guest")?;
16//! let me = client.whoami().await?;
17//! println!("logged in as {} (tags: {})", me.name, me.tags.join(","));
18//! # Ok(())
19//! # }
20//! ```
21
22#![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
37/// The default RabbitMQ vhost, `"/"`.
38pub const DEFAULT_VHOST: &str = "/";
39
40/// Async client for the RabbitMQ Management HTTP API.
41///
42/// Construct with [`Client::new`] or [`Client::builder`]. Cloning a `Client`
43/// is cheap (it shares the underlying connection pool).
44#[derive(Clone)]
45pub struct Client {
46    http: reqwest::Client,
47    /// Base URL of the API, always ending in `/api/`
48    /// (e.g. `http://localhost:15672/api/`).
49    base_url: reqwest::Url,
50    /// Basic-auth header value applied per-request. Always `Some` — the
51    /// default reqwest client also carries it as a default header, but when
52    /// the caller supplies their own client we must inject it on every
53    /// request since a built `reqwest::Client`'s headers can't be modified.
54    auth: Option<HeaderValue>,
55}
56
57/// Builder for [`Client`]. See [`Client::builder`].
58pub struct ClientBuilder {
59    base_url: String,
60    username: String,
61    password: String,
62    http: Option<reqwest::Client>,
63}
64
65impl Client {
66    /// Create a [`ClientBuilder`] for the given Management API endpoint and
67    /// credentials.
68    ///
69    /// `base_url` may be given with or without a trailing `/` and with or
70    /// without the `/api` path suffix; it is normalized by
71    /// [`ClientBuilder::build`].
72    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    /// Convenience constructor:
86    /// `Client::new("http://localhost:15672", "guest", "guest")`.
87    pub fn new(base_url: &str, username: &str, password: &str) -> Result<Self> {
88        Self::builder(base_url, username, password).build()
89    }
90
91    /// `GET /api/whoami` — returns the identity the server associates with
92    /// this client's credentials.
93    pub async fn whoami(&self) -> Result<types::WhoAmI> {
94        self.get_ctx("whoami", None, "whoami").await
95    }
96
97    /// Low-level `GET` returning a deserialized JSON body.
98    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    /// Like [`Client::get`], but prefixes [`Error::NotFound`] messages with
117    /// `ctx` (e.g. `"node 'rabbit@host'"` or `"overview"`) so callers can
118    /// tell which resource was missing.
119    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    /// Low-level `PUT` with a JSON body; the response body is ignored.
129    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    /// Low-level `POST` with a JSON body; the response body is ignored.
140    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    /// Low-level `POST` with a JSON body, returning a deserialized JSON
151    /// response body.
152    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    /// Low-level `DELETE`; the response body is ignored.
167    pub(crate) async fn delete(&self, path: &str) -> Result<()> {
168        self.delete_with_headers(path, &[]).await
169    }
170
171    /// Low-level `DELETE` with extra request headers (e.g. `X-Reason`);
172    /// the response body is ignored.
173    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    /// Like [`Client::delete`], but prefixes [`Error::NotFound`] messages
188    /// with `ctx` so callers can tell which resource was missing.
189    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    /// Join a relative API path onto the base URL.
194    ///
195    /// Paths must be relative to the base URL (which always ends in
196    /// `/api/`) and therefore must NOT start with `/` — a leading slash
197    /// would make `Url::join` discard the `/api/` prefix and produce a
198    /// URL outside the API. Debug builds assert on this footgun.
199    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    /// Attach the Basic-auth header to a request builder when it isn't
210    /// already guaranteed by the underlying client's default headers.
211    /// With the default client this is a harmless duplicate; with a
212    /// caller-supplied client it is what actually authenticates the request.
213    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    /// Use a pre-configured [`reqwest::Client`] (e.g. with custom TLS,
223    /// timeouts, or proxies) instead of the default one. The Authorization
224    /// and Content-Type default headers are still applied on top of it:
225    /// Content-Type via `.json(...)` bodies, and Authorization is injected
226    /// on every request (a built `reqwest::Client`'s default headers cannot
227    /// be modified, so the SDK applies it per-request instead).
228    pub fn http_client(mut self, http: reqwest::Client) -> Self {
229        self.http = Some(http);
230        self
231    }
232
233    /// Normalize the base URL, build the HTTP client with default headers
234    /// (HTTP Basic auth and `Content-Type: application/json`), and return
235    /// the [`Client`].
236    ///
237    /// The base URL must use the `http` or `https` scheme; anything else
238    /// (including a missing scheme, which the URL parser would interpret
239    /// as a scheme itself, e.g. `localhost:15672`) is rejected with
240    /// [`Error::InvalidUrl`].
241    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        // Keep a clone for per-request injection (needed when the caller
270        // supplies their own `reqwest::Client`, whose default headers cannot
271        // be modified after construction).
272        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
291/// Minimal base64 (standard alphabet, with padding) encoder, to avoid an
292/// extra dependency just for the Authorization header.
293fn 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}