client/
error.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::any::Any;
16
17use common_error::ext::{BoxedError, ErrorExt};
18use common_error::status_code::{convert_tonic_code_to_status_code, StatusCode};
19use common_error::{GREPTIME_DB_HEADER_ERROR_CODE, GREPTIME_DB_HEADER_ERROR_MSG};
20use common_macro::stack_trace_debug;
21use snafu::{location, Location, Snafu};
22use tonic::metadata::errors::InvalidMetadataValue;
23use tonic::{Code, Status};
24
25#[derive(Snafu)]
26#[snafu(visibility(pub))]
27#[stack_trace_debug]
28pub enum Error {
29    #[snafu(display("Illegal Flight messages, reason: {}", reason))]
30    IllegalFlightMessages {
31        reason: String,
32        #[snafu(implicit)]
33        location: Location,
34    },
35
36    #[snafu(display("Failed to do Flight get, code: {}", tonic_code))]
37    FlightGet {
38        addr: String,
39        tonic_code: Code,
40        source: BoxedError,
41    },
42
43    #[snafu(display("Failed to convert FlightData"))]
44    ConvertFlightData {
45        #[snafu(implicit)]
46        location: Location,
47        source: common_grpc::Error,
48    },
49
50    #[snafu(display("Illegal GRPC client state: {}", err_msg))]
51    IllegalGrpcClientState {
52        err_msg: String,
53        #[snafu(implicit)]
54        location: Location,
55    },
56
57    #[snafu(display("Missing required field in protobuf, field: {}", field))]
58    MissingField {
59        field: String,
60        #[snafu(implicit)]
61        location: Location,
62    },
63
64    #[snafu(display("Failed to create gRPC channel, peer address: {}", addr))]
65    CreateChannel {
66        addr: String,
67        #[snafu(implicit)]
68        location: Location,
69        source: common_grpc::error::Error,
70    },
71
72    #[snafu(display("Failed to create Tls channel manager"))]
73    CreateTlsChannel {
74        #[snafu(implicit)]
75        location: Location,
76        source: common_grpc::error::Error,
77    },
78
79    #[snafu(display("Failed to request RegionServer {}, code: {}", addr, code))]
80    RegionServer {
81        addr: String,
82        code: Code,
83        source: BoxedError,
84        #[snafu(implicit)]
85        location: Location,
86    },
87
88    #[snafu(display("Failed to request FlowServer {}, code: {}", addr, code))]
89    FlowServer {
90        addr: String,
91        code: Code,
92        source: BoxedError,
93        #[snafu(implicit)]
94        location: Location,
95    },
96
97    // Server error carried in Tonic Status's metadata.
98    #[snafu(display("{}", msg))]
99    Server {
100        code: StatusCode,
101        msg: String,
102        #[snafu(implicit)]
103        location: Location,
104    },
105
106    #[snafu(display("Illegal Database response: {err_msg}"))]
107    IllegalDatabaseResponse {
108        err_msg: String,
109        #[snafu(implicit)]
110        location: Location,
111    },
112
113    #[snafu(display("Invalid Tonic metadata value"))]
114    InvalidTonicMetadataValue {
115        #[snafu(source)]
116        error: InvalidMetadataValue,
117        #[snafu(implicit)]
118        location: Location,
119    },
120
121    #[snafu(display("Failed to convert Schema"))]
122    ConvertSchema {
123        #[snafu(implicit)]
124        location: Location,
125        source: datatypes::error::Error,
126    },
127}
128
129pub type Result<T> = std::result::Result<T, Error>;
130
131impl ErrorExt for Error {
132    fn status_code(&self) -> StatusCode {
133        match self {
134            Error::IllegalFlightMessages { .. }
135            | Error::MissingField { .. }
136            | Error::IllegalDatabaseResponse { .. } => StatusCode::Internal,
137
138            Error::Server { code, .. } => *code,
139            Error::FlightGet { source, .. }
140            | Error::RegionServer { source, .. }
141            | Error::FlowServer { source, .. } => source.status_code(),
142            Error::CreateChannel { source, .. }
143            | Error::ConvertFlightData { source, .. }
144            | Error::CreateTlsChannel { source, .. } => source.status_code(),
145            Error::IllegalGrpcClientState { .. } => StatusCode::Unexpected,
146            Error::InvalidTonicMetadataValue { .. } => StatusCode::InvalidArguments,
147            Error::ConvertSchema { source, .. } => source.status_code(),
148        }
149    }
150
151    fn as_any(&self) -> &dyn Any {
152        self
153    }
154}
155
156impl From<Status> for Error {
157    fn from(e: Status) -> Self {
158        fn get_metadata_value(e: &Status, key: &str) -> Option<String> {
159            e.metadata()
160                .get(key)
161                .and_then(|v| String::from_utf8(v.as_bytes().to_vec()).ok())
162        }
163
164        let code = get_metadata_value(&e, GREPTIME_DB_HEADER_ERROR_CODE).and_then(|s| {
165            if let Ok(code) = s.parse::<u32>() {
166                StatusCode::from_u32(code)
167            } else {
168                None
169            }
170        });
171        let tonic_code = e.code();
172        let code = code.unwrap_or_else(|| convert_tonic_code_to_status_code(tonic_code));
173
174        let msg = get_metadata_value(&e, GREPTIME_DB_HEADER_ERROR_MSG)
175            .unwrap_or_else(|| e.message().to_string());
176
177        Self::Server {
178            code,
179            msg,
180            location: location!(),
181        }
182    }
183}
184
185impl Error {
186    pub fn should_retry(&self) -> bool {
187        // TODO(weny): figure out each case of these codes.
188        matches!(
189            self,
190            Self::RegionServer {
191                code: Code::Cancelled,
192                ..
193            } | Self::RegionServer {
194                code: Code::DeadlineExceeded,
195                ..
196            } | Self::RegionServer {
197                code: Code::Unavailable,
198                ..
199            }
200        )
201    }
202}