meta_srv/service/admin/
health.rs

1// Copyright 2023 Greptime Team
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15use std::collections::HashMap;
16
17use axum::response::{IntoResponse, Response};
18use tonic::codegen::http;
19
20use crate::error::Result;
21use crate::service::admin::HttpHandler;
22
23const HTTP_OK: &str = "OK\n";
24
25#[derive(Clone)]
26pub struct HealthHandler;
27
28/// Health check endpoint that returns HTTP 200 OK if the service is healthy.
29#[axum_macros::debug_handler]
30pub(crate) async fn health() -> Response {
31    http::Response::builder()
32        .status(http::StatusCode::OK)
33        .body(HTTP_OK.to_owned())
34        .unwrap()
35        .into_response()
36}
37
38#[async_trait::async_trait]
39impl HttpHandler for HealthHandler {
40    async fn handle(
41        &self,
42        _: &str,
43        _: http::Method,
44        _: &HashMap<String, String>,
45    ) -> Result<http::Response<String>> {
46        Ok(http::Response::builder()
47            .status(http::StatusCode::OK)
48            .body(HTTP_OK.to_owned())
49            .unwrap())
50    }
51}
52
53#[cfg(test)]
54mod tests {
55    use super::*;
56
57    #[tokio::test]
58    async fn test_health_handle() {
59        let health_handler = HealthHandler {};
60        let path = "any";
61        let params = HashMap::default();
62        let res = health_handler
63            .handle(path, http::Method::GET, &params)
64            .await
65            .unwrap();
66
67        assert!(res.status().is_success());
68        assert_eq!(HTTP_OK.to_owned(), res.body().clone());
69    }
70}