summaryrefslogtreecommitdiffstats
path: root/src/api.rs
blob: 8dfd2cab1a8d8cef7794172b313326bd0bdc5df9 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
use std::collections::HashMap;

use axum::{extract::State, response::IntoResponse, Json};
use serde::{Deserialize, Serialize};

use crate::{service::Services, Status};

pub mod services;

pub fn router() -> axum::Router<Services> {
    use axum::routing::get;

    axum::Router::new()
        .route("/healthcheck", get(healthcheck))
        .merge(services::router())
}

#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct Health {
    #[serde(flatten)]
    pub status: Status,
    pub checks: HashMap<String, Status>,
}

impl<T: std::error::Error> From<T> for Health {
    fn from(value: T) -> Self {
        Health {
            status: value.into(),
            ..Default::default()
        }
    }
}

impl IntoResponse for Health {
    fn into_response(self) -> axum::response::Response {
        Json(self).into_response()
    }
}

pub async fn healthcheck(State(services): State<Services>) -> Health {
    let checks = match services.check().await {
        Ok(c) => c,
        Err(err) => return err.into(),
    };

    let status = match checks
        .values()
        .filter(|s| !matches!(s, Status::Pass))
        .count()
    {
        0 => Status::Pass,
        1 => Status::Fail(Some("1 issue detected".to_string())),
        n => Status::Fail(Some(format!("{n} issues detected"))),
    };

    Health { status, checks }
}