meta_srv/service/admin/
util.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::fmt::Debug;
16
17use axum::http::StatusCode;
18use axum::response::{IntoResponse, Response};
19use serde::Serialize;
20use snafu::ResultExt;
21use tonic::codegen::http;
22
23use crate::error::{self, Result};
24
25/// Returns a 200 response with a text body.
26pub fn to_text_response(text: &str) -> Result<http::Response<String>> {
27    http::Response::builder()
28        .header("Content-Type", "text/plain")
29        .status(http::StatusCode::OK)
30        .body(text.to_string())
31        .context(error::InvalidHttpBodySnafu)
32}
33
34/// Returns a 200 response with a JSON body.
35pub fn to_json_response<T>(response: T) -> Result<http::Response<String>>
36where
37    T: Serialize + Debug,
38{
39    let response = serde_json::to_string(&response).context(error::SerializeToJsonSnafu {
40        input: format!("{response:?}"),
41    })?;
42    http::Response::builder()
43        .header("Content-Type", "application/json")
44        .status(http::StatusCode::OK)
45        .body(response)
46        .context(error::InvalidHttpBodySnafu)
47}
48
49/// Returns a 404 response with an empty body.
50pub fn to_not_found_response() -> Result<http::Response<String>> {
51    http::Response::builder()
52        .status(http::StatusCode::NOT_FOUND)
53        .body("".to_string())
54        .context(error::InvalidHttpBodySnafu)
55}
56
57/// A wrapper for error handling in admin services.
58pub(crate) struct ErrorHandler<E>(E)
59where
60    E: std::error::Error + Send + Sync + Sized;
61
62impl<E> ErrorHandler<E>
63where
64    E: std::error::Error + Send + Sync + Sized,
65{
66    pub(crate) fn new(error: E) -> Self {
67        Self(error)
68    }
69}
70
71impl<E> IntoResponse for ErrorHandler<E>
72where
73    E: std::error::Error + Send + Sync + Sized,
74{
75    fn into_response(self) -> Response {
76        (StatusCode::INTERNAL_SERVER_ERROR, self.0.to_string()).into_response()
77    }
78}