use std::fmt;
use std::sync::Arc;
use bytes::Bytes;
use serde::{Deserialize, Serialize};
use crate::client::{
ClientBuilder, ConfigError, Core, HeaderNames, Query, UnavailableReason, decode, error_body,
json_body,
};
use crate::transport::{ReqwestTransport, Transport};
pub struct AdminClient<T = ReqwestTransport> {
core: Arc<Core<T>>,
}
impl<T> AdminClient<T> {
pub(crate) fn from_core(core: Arc<Core<T>>) -> Self {
Self { core }
}
}
impl<T> Clone for AdminClient<T> {
fn clone(&self) -> Self {
Self {
core: Arc::clone(&self.core),
}
}
}
impl<T> fmt::Debug for AdminClient<T> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("AdminClient")
.field("base_url", &self.core.base_url)
.field("header_names", &HeaderNames(&self.core.headers))
.field("timeout", &self.core.timeout)
.finish_non_exhaustive()
}
}
impl AdminClient {
pub fn new(base_url: impl Into<String>) -> Result<Self, ConfigError> {
ClientBuilder::new(base_url).admin()
}
}
impl<T: Transport> AdminClient<T> {
pub async fn health(&self) -> Result<AdminHealth, AdminError> {
let response = self.get("/health").await?;
decode(response.body()).map_err(AdminError::Unavailable)
}
pub async fn metrics(&self) -> Result<String, AdminError> {
let response = self.get("/metrics").await?;
Ok(String::from_utf8_lossy(response.body()).into_owned())
}
pub async fn config(&self) -> Result<serde_json::Map<String, serde_json::Value>, AdminError> {
let response = self.get("/v1/config").await?;
decode(response.body()).map_err(AdminError::Unavailable)
}
pub async fn list_dead_letters(
&self,
params: &ListDeadLettersParams,
) -> Result<DlqPage, AdminError> {
let mut query = Query::new();
if let Some(source_id) = params.source_id.as_deref() {
query.push_str("source_id", source_id);
}
if let Some(since) = params.since {
query.push_display("since", since);
}
if let Some(limit) = params.limit {
query.push_display("limit", limit);
}
let response = self.get(&format!("/v1/dlq{}", query.finish())).await?;
decode(response.body()).map_err(AdminError::Unavailable)
}
pub async fn replay_dead_letters(&self, filter: &ReplayFilter) -> Result<Replayed, AdminError> {
let body = json_body(filter).map_err(AdminError::Unavailable)?;
let response = self
.core
.send(http::Method::POST, "/v1/dlq/replay", Some(body))
.await
.map_err(AdminError::Unavailable)?;
let response = check(response)?;
decode(response.body()).map_err(AdminError::Unavailable)
}
pub async fn list_quarantined(
&self,
params: &ListQuarantinedParams,
) -> Result<QuarantinePage, AdminError> {
let mut query = Query::new();
if let Some(limit) = params.limit {
query.push_display("limit", limit);
}
let response = self
.get(&format!("/v1/quarantine{}", query.finish()))
.await?;
decode(response.body()).map_err(AdminError::Unavailable)
}
async fn get(&self, path_and_query: &str) -> Result<http::Response<Bytes>, AdminError> {
let response = self
.core
.send(http::Method::GET, path_and_query, None)
.await
.map_err(AdminError::Unavailable)?;
check(response)
}
}
fn check(response: http::Response<Bytes>) -> Result<http::Response<Bytes>, AdminError> {
let status = response.status();
if status.is_success() {
return Ok(response);
}
if status == http::StatusCode::CONFLICT {
let body = error_body(response.body());
let string = |key: &str| {
body.get(key)
.and_then(serde_json::Value::as_str)
.map(str::to_owned)
};
if string("error").as_deref() == Some("role_not_enabled") {
return Err(AdminError::RoleNotEnabled {
role: string("role"),
});
}
return Err(AdminError::Rejected {
status,
code: string("error"),
});
}
if status.is_client_error() {
return Err(AdminError::Rejected {
status,
code: error_body(response.body())
.get("error")
.and_then(serde_json::Value::as_str)
.map(str::to_owned),
});
}
Err(AdminError::Unavailable(UnavailableReason::Status(status)))
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[non_exhaustive]
pub struct AdminHealth {
pub status: String,
pub instance: String,
pub roles: Vec<String>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[non_exhaustive]
pub struct DlqEntry {
pub id: String,
pub source_id: String,
pub tenant_id: Option<String>,
pub seq: Option<u64>,
pub received_at: i64,
pub dead_lettered_at: i64,
pub size: u64,
pub content_type: Option<String>,
pub reason: String,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[non_exhaustive]
pub struct DlqPage {
pub total: u64,
pub entries: Vec<DlqEntry>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[non_exhaustive]
pub struct QuarantineEntry {
pub id: String,
pub source_id: String,
pub received_at: i64,
pub reason: String,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[non_exhaustive]
pub struct QuarantinePage {
pub entries: Vec<QuarantineEntry>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[non_exhaustive]
pub struct Replayed {
pub replayed: u64,
}
#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
pub struct ReplayFilter {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub source_id: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub id: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub since: Option<i64>,
}
#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
pub struct ListDeadLettersParams {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub source_id: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub since: Option<i64>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub limit: Option<u32>,
}
#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
pub struct ListQuarantinedParams {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub limit: Option<u32>,
}
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum AdminError {
#[error("role not enabled on this node: {}", role.as_deref().unwrap_or("unknown"))]
RoleNotEnabled {
role: Option<String>,
},
#[error("operator API rejected the request (HTTP {status})")]
Rejected {
status: http::StatusCode,
code: Option<String>,
},
#[error("operator API unavailable")]
Unavailable(#[source] UnavailableReason),
}
impl AdminError {
#[must_use]
pub fn is_retryable(&self) -> bool {
matches!(self, Self::Unavailable(_))
}
}
#[cfg(test)]
mod tests {
use super::{AdminClient, AdminError, ListDeadLettersParams};
use crate::client::{ClientBuilder, test_support::Recording};
fn client(transport: Recording) -> AdminClient<Recording> {
ClientBuilder::with_transport("http://gateway.invalid", transport)
.admin()
.expect("valid client")
}
#[tokio::test]
async fn list_dead_letters_writes_the_query_in_field_order() {
let transport = Recording::new(200, r#"{"total":0,"entries":[]}"#);
let targets = transport.targets();
let client = client(transport);
let params = ListDeadLettersParams {
source_id: Some("a b".to_owned()),
since: Some(1_720_000_000_000),
limit: Some(50),
};
client.list_dead_letters(¶ms).await.expect("listed");
assert_eq!(
targets.lock().expect("not poisoned").as_slice(),
["/v1/dlq?source_id=a%20b&since=1720000000000&limit=50"]
);
}
#[tokio::test]
async fn a_role_not_enabled_conflict_names_the_role() {
let client = client(Recording::new(
409,
r#"{"error":"role_not_enabled","role":"dispatch"}"#,
));
let err = client.health().await.expect_err("role missing");
match err {
AdminError::RoleNotEnabled { role } => assert_eq!(role.as_deref(), Some("dispatch")),
other => panic!("expected RoleNotEnabled, got {other:?}"),
}
}
#[tokio::test]
async fn metrics_replaces_invalid_utf8() {
let transport = Recording::new(200, "ok");
let client = client(transport);
assert_eq!(client.metrics().await.expect("text"), "ok");
}
}