From fdbfa1549094ac8c671e590cc376ccbe5e662928 Mon Sep 17 00:00:00 2001 From: Ivan Reshetnikov Date: Sun, 17 Nov 2024 00:46:14 +0500 Subject: [PATCH] Add health check endpoint --- src/main.rs | 1 + src/web/controllers/health.rs | 30 ++++++++++++++++++++++++++++++ src/web/controllers/mod.rs | 2 ++ 3 files changed, 33 insertions(+) create mode 100644 src/web/controllers/health.rs diff --git a/src/main.rs b/src/main.rs index 52c7e56..2a30843 100644 --- a/src/main.rs +++ b/src/main.rs @@ -42,6 +42,7 @@ async fn main() { .route("/openid/signin", post(controllers::signin)) .route("/openid/exchange-code", get(controllers::exchange_code)) .route("/logout", post(controllers::logout)) + .route("/health", get(controllers::health)) .route("/api/images", post(controllers::upload_image)) .route( "/api/images/:image_id", diff --git a/src/web/controllers/health.rs b/src/web/controllers/health.rs new file mode 100644 index 0000000..c1fbccb --- /dev/null +++ b/src/web/controllers/health.rs @@ -0,0 +1,30 @@ +use axum::{extract::State, http::StatusCode, response::IntoResponse, Json}; +use serde::Serialize; +use std::sync::Arc; + +#[derive(Serialize)] +pub struct HealthyStatus { + ok: bool, +} + +#[derive(Serialize)] +pub struct UnhealthyStatus { + ok: bool, + err: String, +} + +pub async fn health( + State(state): State>, +) -> Result, impl IntoResponse> { + let res = sqlx::query("SELECT 1").execute(&state.db).await; + + if let Err(err) = res { + let status = Json(UnhealthyStatus { + ok: false, + err: err.to_string(), + }); + return Err((StatusCode::INTERNAL_SERVER_ERROR, status)); + } + + Ok(Json(HealthyStatus { ok: true })) +} diff --git a/src/web/controllers/mod.rs b/src/web/controllers/mod.rs index b450480..bb6d34a 100644 --- a/src/web/controllers/mod.rs +++ b/src/web/controllers/mod.rs @@ -2,6 +2,7 @@ mod admin; mod auth; mod ctx; mod error; +mod health; mod home; mod images; mod openid; @@ -9,6 +10,7 @@ mod rules; pub use admin::*; pub use auth::*; +pub use health::*; pub use home::*; pub use images::{delete_image, get_image, upload_image}; pub use openid::*;