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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
// Copyright 2023 Greptime Team
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

use axum::response::IntoResponse;
use axum::Json;
use http::header::CONTENT_TYPE;
use http::HeaderValue;
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};

use crate::http::header::{GREPTIME_DB_HEADER_EXECUTION_TIME, GREPTIME_DB_HEADER_FORMAT};

/// Greptimedb Manage Api Response struct
/// Currently we have `Pipelines` and `Scripts` as control panel api
#[derive(Serialize, Deserialize, Debug, JsonSchema)]
pub struct GreptimedbManageResponse {
    #[serde(flatten)]
    pub(crate) manage_result: ManageResult,
    pub(crate) execution_time_ms: u64,
}

impl GreptimedbManageResponse {
    pub fn from_pipeline(name: String, version: String, execution_time_ms: u64) -> Self {
        GreptimedbManageResponse {
            manage_result: ManageResult::Pipelines {
                pipelines: vec![PipelineOutput { name, version }],
            },
            execution_time_ms,
        }
    }

    pub fn from_pipelines(pipelines: Vec<PipelineOutput>, execution_time_ms: u64) -> Self {
        GreptimedbManageResponse {
            manage_result: ManageResult::Pipelines { pipelines },
            execution_time_ms,
        }
    }

    pub fn with_execution_time(mut self, execution_time: u64) -> Self {
        self.execution_time_ms = execution_time;
        self
    }

    pub fn execution_time_ms(&self) -> u64 {
        self.execution_time_ms
    }
}

#[derive(Serialize, Deserialize, Debug, JsonSchema)]
#[serde(untagged)]
pub enum ManageResult {
    Pipelines { pipelines: Vec<PipelineOutput> },
    // todo(shuiyisong): refactor scripts api
    Scripts(),
}

#[derive(Serialize, Deserialize, Debug, JsonSchema)]
pub struct PipelineOutput {
    name: String,
    version: String,
}

impl IntoResponse for GreptimedbManageResponse {
    fn into_response(self) -> axum::response::Response {
        let execution_time = self.execution_time_ms;

        let mut resp = Json(self).into_response();

        // We deliberately don't add this format into [`crate::http::ResponseFormat`]
        // because this is a format for manage api other than the data query api
        resp.headers_mut().insert(
            &GREPTIME_DB_HEADER_FORMAT,
            HeaderValue::from_static("greptimedb_manage"),
        );
        resp.headers_mut().insert(
            &GREPTIME_DB_HEADER_EXECUTION_TIME,
            HeaderValue::from(execution_time),
        );
        resp.headers_mut().insert(
            CONTENT_TYPE,
            HeaderValue::from_str(mime_guess::mime::APPLICATION_JSON.as_ref()).unwrap(),
        );

        resp
    }
}

#[cfg(test)]
mod tests {

    use arrow::datatypes::ToByteSlice;
    use http_body::Body;
    use hyper::body::to_bytes;

    use super::*;

    #[tokio::test]
    async fn test_into_response() {
        let resp = GreptimedbManageResponse {
            manage_result: ManageResult::Pipelines {
                pipelines: vec![PipelineOutput {
                    name: "test_name".to_string(),
                    version: "test_version".to_string(),
                }],
            },
            execution_time_ms: 42,
        };

        let mut re = resp.into_response();
        let data = re.data();

        let data_str = format!("{:?}", data);
        assert_eq!(
            data_str,
            r#"Data(Response { status: 200, version: HTTP/1.1, headers: {"content-type": "application/json", "x-greptime-format": "greptimedb_manage", "x-greptime-execution-time": "42"}, body: UnsyncBoxBody })"#
        );

        let body_bytes = to_bytes(re.into_body()).await.unwrap();
        let body_str = String::from_utf8_lossy(body_bytes.to_byte_slice());
        assert_eq!(
            body_str,
            r#"{"pipelines":[{"name":"test_name","version":"test_version"}],"execution_time_ms":42}"#
        );
    }
}