#![allow(clippy::needless_for_each)]
use std::sync::Arc;
use arc_swap::ArcSwap;
use axum::Router;
use axum::extract::State;
use axum::response::Json;
use axum::routing::get;
use serde::Serialize;
use tokio::net::TcpListener;
use utoipa::{OpenApi, ToSchema};
use utoipa_scalar::{Scalar, Servable};
use crate::clients::ClientRegistry;
use crate::config::Config;
use crate::pool::PoolManager;
use crate::topology::TopologyManager;
#[derive(Clone)]
struct AppState {
config: Arc<ArcSwap<Config>>,
pools: Arc<PoolManager>,
topology: Arc<TopologyManager>,
clients: Arc<ClientRegistry>,
}
#[derive(OpenApi)]
#[openapi(
paths(health, ready, get_pools, get_servers, get_clients, get_queues),
components(schemas(
HealthResponse,
HealthStatus,
ReadyResponse,
ClusterReadiness,
PoolInfo,
ClusterServers,
ServerInfo,
ServerRole,
ClientInfo,
ClientStateDto,
WaitTargetDto,
WaitRoleDto,
QueueInfoDto,
)),
info(
title = "Halephant Admin API",
version = "0.1.0",
description = "Operational endpoints for health checks and pool introspection."
)
)]
struct ApiDoc;
#[derive(Serialize, ToSchema)]
struct HealthResponse {
status: HealthStatus,
}
#[derive(Serialize, ToSchema)]
#[serde(rename_all = "lowercase")]
enum HealthStatus {
Ok,
}
#[derive(Serialize, ToSchema)]
struct ReadyResponse {
ready: bool,
clusters: Vec<ClusterReadiness>,
}
#[derive(Serialize, ToSchema)]
struct ClusterReadiness {
name: String,
has_primary: bool,
}
#[derive(Serialize, ToSchema)]
struct PoolInfo {
node: String,
database: String,
user: String,
active: u32,
idle: u32,
resetting: u32,
}
#[derive(Serialize, ToSchema)]
struct ServerInfo {
address: String,
role: ServerRole,
}
#[derive(Serialize, ToSchema)]
#[serde(rename_all = "lowercase")]
enum ServerRole {
Primary,
Replica,
Unreachable,
}
#[derive(Serialize, ToSchema)]
struct ClusterServers {
cluster: String,
servers: Vec<ServerInfo>,
}
#[derive(Serialize, ToSchema)]
struct ClientInfo {
id: u64,
remote: String,
state: ClientStateDto,
uptime_secs: f64,
state_since_secs: f64,
database: Option<String>,
user: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
waiting_for: Option<WaitTargetDto>,
}
#[derive(Serialize, ToSchema)]
#[serde(rename_all = "snake_case")]
enum ClientStateDto {
Negotiating,
Authenticating,
Idle,
InTransaction,
Waiting,
}
impl From<crate::clients::ClientState> for ClientStateDto {
fn from(s: crate::clients::ClientState) -> Self {
use crate::clients::ClientState;
match s {
ClientState::Negotiating => Self::Negotiating,
ClientState::Authenticating => Self::Authenticating,
ClientState::Idle => Self::Idle,
ClientState::InTransaction => Self::InTransaction,
ClientState::Waiting => Self::Waiting,
}
}
}
#[derive(Serialize, ToSchema)]
struct WaitTargetDto {
database: String,
user: String,
role: WaitRoleDto,
}
#[derive(Serialize, ToSchema)]
#[serde(rename_all = "snake_case")]
enum WaitRoleDto {
Primary,
Replica,
}
impl From<crate::pool::Routing> for WaitRoleDto {
fn from(role: crate::pool::Routing) -> Self {
use crate::pool::Routing;
match role {
Routing::Primary => WaitRoleDto::Primary,
Routing::Replica => WaitRoleDto::Replica,
}
}
}
impl From<crate::clients::WaitTarget> for WaitTargetDto {
fn from(t: crate::clients::WaitTarget) -> Self {
use crate::clients::WaitRole;
Self {
database: t.database,
user: t.user,
role: match t.role {
WaitRole::Primary => WaitRoleDto::Primary,
WaitRole::Replica => WaitRoleDto::Replica,
},
}
}
}
#[derive(Serialize, ToSchema)]
struct QueueInfoDto {
database: String,
user: String,
role: WaitRoleDto,
depth: u32,
oldest_wait_secs: f64,
}
#[utoipa::path(
get,
path = "/health",
responses((status = 200, body = HealthResponse)),
tag = "health"
)]
async fn health() -> Json<HealthResponse> {
Json(HealthResponse {
status: HealthStatus::Ok,
})
}
#[utoipa::path(
get,
path = "/ready",
responses(
(status = 200, body = ReadyResponse, description = "All clusters have a primary"),
(status = 503, body = ReadyResponse, description = "One or more clusters lack a primary")
),
tag = "health"
)]
async fn ready(State(state): State<AppState>) -> (axum::http::StatusCode, Json<ReadyResponse>) {
let cfg = state.config.load_full();
let clusters: Vec<ClusterReadiness> = cfg
.cluster
.keys()
.map(|name| {
let has_primary = state.topology.primary(name).is_some();
ClusterReadiness {
name: name.clone(),
has_primary,
}
})
.collect();
let all_ready = clusters.iter().all(|c| c.has_primary);
let status = if all_ready {
axum::http::StatusCode::OK
} else {
axum::http::StatusCode::SERVICE_UNAVAILABLE
};
(
status,
Json(ReadyResponse {
ready: all_ready,
clusters,
}),
)
}
#[utoipa::path(
get,
path = "/admin/pools",
responses((status = 200, body = Vec<PoolInfo>)),
tag = "admin"
)]
async fn get_pools(State(state): State<AppState>) -> Json<Vec<PoolInfo>> {
let stats = state
.pools
.pool_stats()
.into_iter()
.map(|(key, stats)| PoolInfo {
node: key.node,
database: key.database,
user: key.user,
active: stats.active,
idle: stats.idle,
resetting: stats.resetting,
})
.collect();
Json(stats)
}
#[utoipa::path(
get,
path = "/admin/servers",
responses((status = 200, body = Vec<ClusterServers>)),
tag = "admin"
)]
async fn get_servers(State(state): State<AppState>) -> Json<Vec<ClusterServers>> {
let cfg = state.config.load_full();
let result = cfg
.cluster
.keys()
.map(|name| {
let mut servers = Vec::new();
if let Some(topo) = state.topology.get(name) {
if let Some(ref primary) = topo.primary {
servers.push(ServerInfo {
address: primary.clone(),
role: ServerRole::Primary,
});
}
for replica in &topo.replicas {
servers.push(ServerInfo {
address: replica.clone(),
role: ServerRole::Replica,
});
}
for node in &topo.unreachable {
servers.push(ServerInfo {
address: node.clone(),
role: ServerRole::Unreachable,
});
}
}
ClusterServers {
cluster: name.clone(),
servers,
}
})
.collect();
Json(result)
}
#[utoipa::path(
get,
path = "/admin/clients",
responses((status = 200, body = Vec<ClientInfo>)),
tag = "admin"
)]
async fn get_clients(State(state): State<AppState>) -> Json<Vec<ClientInfo>> {
let now = std::time::Instant::now();
let result = state
.clients
.snapshot()
.into_iter()
.map(|entry| ClientInfo {
id: entry.id.as_u64(),
remote: entry.remote.to_string(),
state: entry.state.into(),
uptime_secs: now
.saturating_duration_since(entry.accepted_at)
.as_secs_f64(),
state_since_secs: now
.saturating_duration_since(entry.state_since)
.as_secs_f64(),
database: entry.database,
user: entry.user,
waiting_for: entry.waiting_for.map(Into::into),
})
.collect();
Json(result)
}
#[utoipa::path(
get,
path = "/admin/queues",
responses((status = 200, body = Vec<QueueInfoDto>)),
tag = "admin"
)]
async fn get_queues(State(state): State<AppState>) -> Json<Vec<QueueInfoDto>> {
let result = state
.pools
.queue_stats()
.into_iter()
.map(|q| QueueInfoDto {
database: q.database,
user: q.user,
role: WaitRoleDto::from(q.role),
depth: q.depth,
oldest_wait_secs: q.oldest_wait_secs,
})
.collect();
Json(result)
}
pub fn router(
config: Arc<ArcSwap<Config>>,
pools: Arc<PoolManager>,
topology: Arc<TopologyManager>,
clients: Arc<ClientRegistry>,
) -> Router {
let state = AppState {
config,
pools,
topology,
clients,
};
Router::new()
.route("/health", get(health))
.route("/ready", get(ready))
.route("/admin/pools", get(get_pools))
.route("/admin/servers", get(get_servers))
.route("/admin/clients", get(get_clients))
.route("/admin/queues", get(get_queues))
.merge(Scalar::with_url("/docs", ApiDoc::openapi()))
.with_state(state)
}
pub async fn serve(
addr: &str,
config: Arc<ArcSwap<Config>>,
pools: Arc<PoolManager>,
topology: Arc<TopologyManager>,
clients: Arc<ClientRegistry>,
) -> std::io::Result<()> {
let app = router(config, pools, topology, clients);
let listener = TcpListener::bind(addr).await?;
tracing::info!(%addr, "admin API listening");
axum::serve(listener, app).await?;
Ok(())
}