1use common_error::define_from_tonic_status;
16use common_error::ext::{ErrorExt, RetryHint};
17use common_error::status_code::StatusCode;
18use common_macro::stack_trace_debug;
19use snafu::{Location, Snafu};
20
21#[derive(Snafu)]
22#[snafu(visibility(pub))]
23#[stack_trace_debug]
24pub enum Error {
25 #[snafu(display("Illegal GRPC client state: {}", err_msg))]
26 IllegalGrpcClientState {
27 err_msg: String,
28 #[snafu(implicit)]
29 location: Location,
30 },
31
32 #[snafu(display("{}, code: {}, tonic code: {}", msg, code, tonic_code))]
33 MetaServer {
34 code: StatusCode,
35 msg: String,
36 tonic_code: tonic::Code,
37 retry_hint: RetryHint,
38 #[snafu(implicit)]
39 location: Location,
40 },
41
42 #[snafu(display("No leader, should ask leader first"))]
43 NoLeader {
44 #[snafu(implicit)]
45 location: Location,
46 },
47
48 #[snafu(display("Ask leader timeout"))]
49 AskLeaderTimeout {
50 #[snafu(implicit)]
51 location: Location,
52 #[snafu(source)]
53 error: tokio::time::error::Elapsed,
54 },
55
56 #[snafu(display("Failed to create gRPC channel"))]
57 CreateChannel {
58 #[snafu(implicit)]
59 location: Location,
60 source: common_grpc::error::Error,
61 },
62
63 #[snafu(display("{} not started", name))]
64 NotStarted {
65 name: String,
66 #[snafu(implicit)]
67 location: Location,
68 },
69
70 #[snafu(display("Procedure submission requires query context"))]
71 MissingQueryContext {
72 #[snafu(implicit)]
73 location: Location,
74 },
75
76 #[snafu(display("Failed to send heartbeat: {}", err_msg))]
77 SendHeartbeat {
78 err_msg: String,
79 #[snafu(implicit)]
80 location: Location,
81 },
82
83 #[snafu(display("Failed create heartbeat stream to server"))]
84 CreateHeartbeatStream {
85 #[snafu(implicit)]
86 location: Location,
87 },
88
89 #[snafu(display("Invalid response header"))]
90 InvalidResponseHeader {
91 #[snafu(implicit)]
92 location: Location,
93 source: common_meta::error::Error,
94 },
95
96 #[snafu(display("Failed to convert Metasrv request"))]
97 ConvertMetaRequest {
98 #[snafu(implicit)]
99 location: Location,
100 source: common_meta::error::Error,
101 },
102
103 #[snafu(display("Failed to convert Metasrv response"))]
104 ConvertMetaResponse {
105 #[snafu(implicit)]
106 location: Location,
107 source: common_meta::error::Error,
108 },
109
110 #[snafu(display("Failed to get flow stat"))]
111 GetFlowStat {
112 #[snafu(implicit)]
113 location: Location,
114 source: common_meta::error::Error,
115 },
116
117 #[snafu(display("Retry exceeded max times({}), message: {}", times, msg))]
118 RetryTimesExceeded { times: usize, msg: String },
119
120 #[snafu(display("Trying to write to a read-only kv backend: {}", name))]
121 ReadOnlyKvBackend {
122 name: String,
123 #[snafu(implicit)]
124 location: Location,
125 },
126
127 #[snafu(display("Failed to convert meta config"))]
128 ConvertMetaConfig {
129 #[snafu(implicit)]
130 location: Location,
131 #[snafu(source)]
132 error: serde_json::Error,
133 },
134}
135
136#[allow(dead_code)]
137pub type Result<T> = std::result::Result<T, Error>;
138
139impl ErrorExt for Error {
140 fn as_any(&self) -> &dyn std::any::Any {
141 self
142 }
143
144 fn status_code(&self) -> StatusCode {
145 match self {
146 Error::IllegalGrpcClientState { .. }
147 | Error::NoLeader { .. }
148 | Error::AskLeaderTimeout { .. }
149 | Error::NotStarted { .. }
150 | Error::MissingQueryContext { .. }
151 | Error::SendHeartbeat { .. }
152 | Error::CreateHeartbeatStream { .. }
153 | Error::CreateChannel { .. }
154 | Error::RetryTimesExceeded { .. }
155 | Error::ConvertMetaConfig { .. } => StatusCode::Internal,
156
157 Error::ReadOnlyKvBackend { .. } => StatusCode::Unsupported,
158
159 Error::MetaServer { code, .. } => *code,
160
161 Error::InvalidResponseHeader { source, .. }
162 | Error::ConvertMetaRequest { source, .. }
163 | Error::ConvertMetaResponse { source, .. }
164 | Error::GetFlowStat { source, .. } => source.status_code(),
165 }
166 }
167
168 fn retry_hint(&self) -> RetryHint {
169 match self {
170 Error::MetaServer { retry_hint, .. } => *retry_hint,
171 Error::InvalidResponseHeader { source, .. }
172 | Error::ConvertMetaRequest { source, .. }
173 | Error::ConvertMetaResponse { source, .. }
174 | Error::GetFlowStat { source, .. } => source.retry_hint(),
175 Error::CreateChannel { source, .. } => source.retry_hint(),
176 _ => RetryHint::NonRetryable,
177 }
178 }
179}
180
181impl Error {
182 pub fn is_exceeded_size_limit(&self) -> bool {
183 matches!(
184 self,
185 Error::MetaServer {
186 tonic_code: tonic::Code::OutOfRange | tonic::Code::ResourceExhausted,
187 ..
188 }
189 )
190 }
191}
192
193define_from_tonic_status!(Error, MetaServer);
194
195#[cfg(test)]
196mod tests {
197 use common_error::ext::{ErrorExt, RetryHint};
198 use common_error::{GREPTIME_DB_HEADER_ERROR_CODE, GREPTIME_DB_HEADER_ERROR_RETRY_HINT};
199 use tonic::codegen::http::{HeaderMap, HeaderValue};
200 use tonic::metadata::MetadataMap;
201
202 use super::*;
203
204 #[test]
205 fn test_from_tonic_status_fallbacks_to_status_code() {
206 let status = tonic::Status::new(tonic::Code::Internal, "blabla");
207
208 let err: Error = status.into();
209
210 assert_eq!(err.retry_hint(), RetryHint::NonRetryable);
211 }
212
213 #[test]
214 fn test_from_tonic_status_fallback_can_be_non_retryable() {
215 let mut headers = HeaderMap::new();
216 headers.insert(
217 GREPTIME_DB_HEADER_ERROR_CODE,
218 HeaderValue::from(StatusCode::InvalidArguments as u32),
219 );
220 let status = tonic::Status::with_metadata(
221 tonic::Code::Internal,
222 "blabla",
223 MetadataMap::from_headers(headers),
224 );
225
226 let err: Error = status.into();
227
228 assert_eq!(err.retry_hint(), RetryHint::NonRetryable);
229 }
230
231 #[test]
232 fn test_from_tonic_status_with_retry_hint() {
233 let mut headers = HeaderMap::new();
234 headers.insert(
235 GREPTIME_DB_HEADER_ERROR_CODE,
236 HeaderValue::from(StatusCode::Internal as u32),
237 );
238 headers.insert(
239 GREPTIME_DB_HEADER_ERROR_RETRY_HINT,
240 HeaderValue::from_static(RetryHint::Retryable.as_str()),
241 );
242 let status = tonic::Status::with_metadata(
243 tonic::Code::Internal,
244 "blabla",
245 MetadataMap::from_headers(headers),
246 );
247
248 let err: Error = status.into();
249
250 assert_eq!(err.retry_hint(), RetryHint::Retryable);
251 }
252
253 #[test]
254 fn test_is_exceeded_size_limit_for_out_of_range() {
255 let err = Error::from(tonic::Status::new(tonic::Code::OutOfRange, "any message"));
256
257 assert!(err.is_exceeded_size_limit());
258 }
259
260 #[test]
261 fn test_is_exceeded_size_limit_for_resource_exhausted() {
262 let err = Error::from(tonic::Status::new(
263 tonic::Code::ResourceExhausted,
264 "arbitrary message",
265 ));
266
267 assert!(err.is_exceeded_size_limit());
268 }
269
270 #[test]
271 fn test_is_exceeded_size_limit_for_non_size_code() {
272 let err = Error::from(tonic::Status::new(tonic::Code::Internal, "message"));
273
274 assert!(!err.is_exceeded_size_limit());
275 }
276}