Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
54 changes: 54 additions & 0 deletions crates/rustmail/src/api/handler/health.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
use crate::bot::ShardManagerKey;
use crate::prelude::types::*;
use axum::Json;
use axum::extract::State;
use axum::http::StatusCode;
use axum::response::IntoResponse;
use serenity::all::ShardId;
use std::sync::Arc;
use tokio::sync::Mutex;

pub async fn handle_health(State(bot_state): State<Arc<Mutex<BotState>>>) -> impl IntoResponse {
let state_lock = bot_state.lock().await;

let mut db_ok = false;
if let Some(pool) = &state_lock.db_pool {
if sqlx::query("SELECT 1").execute(pool).await.is_ok() {
db_ok = true;
}
}

let bot_running = matches!(state_lock.status, BotStatus::Running { .. });

let ctx_guard = state_lock.bot_context.read().await;
let bot_connected = ctx_guard.is_some();

let mut bot_latency = None;
if let Some(ctx) = ctx_guard.as_ref() {
let data = ctx.data.read().await;
if let Some(shard_manager) = data.get::<ShardManagerKey>() {
let runners = shard_manager.runners.lock().await;
if let Some(runner) = runners.get(&ShardId(0)) {
bot_latency = runner.latency.map(|d| d.as_millis());
}
}
}

let mut status_code = StatusCode::OK;
if !db_ok || (bot_running && !bot_connected) {
status_code = StatusCode::SERVICE_UNAVAILABLE;
}

(
status_code,
Json(serde_json::json!({
"status": if db_ok && (!bot_running || bot_connected) { "healthy" } else { "unhealthy" },
"database": if db_ok { "connected" } else { "disconnected" },
"bot": {
"running": bot_running,
"connected": bot_connected,
"latency_ms": bot_latency,
}
})),
)
}
2 changes: 2 additions & 0 deletions crates/rustmail/src/api/handler/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ pub mod auth;
pub mod bot;
pub mod categories;
pub mod externals;
pub mod health;
pub mod panel;
pub mod user;

Expand All @@ -13,5 +14,6 @@ pub use auth::*;
pub use bot::*;
pub use categories::*;
pub use externals::*;
pub use health::*;
pub use panel::*;
pub use user::*;
1 change: 1 addition & 0 deletions crates/rustmail/src/api/router.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ pub fn create_api_router(bot_state: Arc<Mutex<BotState>>) -> Router {
let external_router = create_external_router(bot_state.clone());

let app = Router::new()
.route("/api/health", axum::routing::get(handle_health))
.nest("/api/admin", admin_router)
.nest("/api/apikeys", apikeys_router)
.nest("/api/categories", categories_router)
Expand Down
Loading