common_error/lib.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
15pub mod ext;
16pub mod mock;
17pub mod status_code;
18
19use http::{HeaderMap, HeaderValue};
20pub use snafu;
21
22use crate::status_code::StatusCode;
23
24// HACK - these headers are here for shared in gRPC services. For common HTTP headers,
25// please define in `src/servers/src/http/header.rs`.
26pub const GREPTIME_DB_HEADER_ERROR_CODE: &str = "x-greptime-err-code";
27pub const GREPTIME_DB_HEADER_ERROR_MSG: &str = "x-greptime-err-msg";
28pub const GREPTIME_DB_HEADER_ERROR_RETRY_HINT: &str = "x-greptime-err-retry-hint";
29
30/// Create a http header map from error code and message.
31/// using `GREPTIME_DB_HEADER_ERROR_CODE` and `GREPTIME_DB_HEADER_ERROR_MSG` as keys.
32pub fn from_err_code_msg_to_header(code: u32, msg: &str) -> HeaderMap {
33 let mut header = HeaderMap::new();
34
35 let msg = HeaderValue::from_str(msg).unwrap_or_else(|_| {
36 HeaderValue::from_bytes(
37 &msg.as_bytes()
38 .iter()
39 .flat_map(|b| std::ascii::escape_default(*b))
40 .collect::<Vec<u8>>(),
41 )
42 .expect("Already escaped string should be valid ascii")
43 });
44
45 header.insert(GREPTIME_DB_HEADER_ERROR_CODE, code.into());
46 header.insert(GREPTIME_DB_HEADER_ERROR_MSG, msg);
47 header
48}
49
50/// Extract [StatusCode] and error message from [HeaderMap], if any.
51///
52/// Note that if the [StatusCode] is illegal, for example, a random number that is not pre-defined
53/// as a [StatusCode], the result is still `None`.
54pub fn from_header_to_err_code_msg(headers: &HeaderMap) -> Option<(StatusCode, &str)> {
55 let code = headers
56 .get(GREPTIME_DB_HEADER_ERROR_CODE)
57 .and_then(|value| {
58 value
59 .to_str()
60 .ok()
61 .and_then(|x| x.parse::<u32>().ok())
62 .and_then(StatusCode::from_u32)
63 });
64 let msg = headers
65 .get(GREPTIME_DB_HEADER_ERROR_MSG)
66 .and_then(|x| x.to_str().ok());
67 match (code, msg) {
68 (Some(code), Some(msg)) => Some((code, msg)),
69 _ => None,
70 }
71}
72
73/// Returns the external root cause of the source error (exclude the current error).
74pub fn root_source(err: &dyn std::error::Error) -> Option<&dyn std::error::Error> {
75 // There are some divergence about the behavior of the `sources()` API
76 // in https://github.com/rust-lang/rust/issues/58520
77 // So this function iterates the sources manually.
78 let mut root = err.source();
79 while let Some(r) = root {
80 if let Some(s) = r.source() {
81 root = Some(s);
82 } else {
83 break;
84 }
85 }
86 root
87}