ceresdb_client/
errors.rs

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
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
// Copyright 2022 CeresDB Project Authors. Licensed under Apache-2.0.

//! Error in client

use std::fmt::Display;

use thiserror::Error as ThisError;

use crate::model::write::Response;

/// An error generated by the client.
#[derive(Debug, ThisError)]
pub enum Error {
    /// Error from the running server
    #[error("failed in server, err:{0}")]
    Server(ServerError),

    /// Error from the rpc
    /// Note that any error caused by a running server wont be wrapped in the
    /// grpc errors.
    #[error("failed in grpc, err:{0}")]
    Rpc(tonic::Status),

    /// Error about rpc.
    /// It will be throw while connection between client and server is broken
    /// and try for reconnecting is failed(timeout).
    #[error("failed to connect, addr:{addr:?}, err:{source:?}")]
    Connect {
        addr: String,
        source: Box<dyn std::error::Error + Send + Sync>,
    },

    /// Error from the client and basically the rpc request has not been called
    /// yet or the rpc request has already been finished successfully.
    #[error("failed in client, msg:{0}")]
    Client(String),

    /// Error about authentication
    #[error("failed to check auth, err:{0}")]
    AuthFail(AuthFailStatus),

    /// Error from write in route based mode, some of rows may be written
    /// successfully, and others may fail.
    #[error("failed to write with route based client, err:{0}")]
    RouteBasedWriteError(RouteBasedWriteError),

    /// Error unknown
    #[error("unknown error, msg:{0}")]
    Unknown(String),

    #[error("failed to decode, msg:{0}")]
    BuildRows(String),

    #[error("failed to decode arrow payload, msg:{0}")]
    DecodeArrowPayload(Box<dyn std::error::Error + Send + Sync>),

    #[error("failed to find a database")]
    NoDatabase,
}

#[derive(Debug)]
pub struct RouteBasedWriteError {
    pub ok: (Vec<String>, Response),       // (tables, write_response)
    pub errors: Vec<(Vec<String>, Error)>, // [(tables, errors)]
}

impl From<Vec<(Vec<String>, Result<Response>)>> for RouteBasedWriteError {
    fn from(write_results: Vec<(Vec<String>, Result<Response>)>) -> Self {
        let mut success_total = 0;
        let mut failed_total = 0;
        let mut ok_tables = Vec::new();
        let mut errors = Vec::new();
        for (tables, write_result) in write_results {
            match write_result {
                Ok(write_resp) => {
                    success_total += write_resp.success;
                    failed_total += write_resp.failed;
                    ok_tables.extend(tables);
                }
                Err(e) => {
                    errors.push((tables, e));
                }
            }
        }

        Self {
            ok: (ok_tables, Response::new(success_total, failed_total)),
            errors,
        }
    }
}

impl RouteBasedWriteError {
    pub fn all_ok(&self) -> bool {
        self.errors.is_empty()
    }
}

impl Display for RouteBasedWriteError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("RouteBasedWriteError")
            .field("ok", &self.ok)
            .field("errors", &self.errors)
            .finish()
    }
}

#[derive(Debug, Clone)]
pub struct ServerError {
    pub code: u32,
    pub msg: String,
}

impl Display for ServerError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("ServerError")
            .field("code", &self.code)
            .field("msg", &self.msg)
            .finish()
    }
}

#[derive(Debug, Clone)]
pub struct AuthFailStatus {
    pub code: AuthCode,
    pub msg: String,
}

#[derive(Debug, Clone)]
pub enum AuthCode {
    Ok = 0,

    InvalidTenantMeta = 1,

    InvalidTokenMeta = 2,
}

impl Display for AuthFailStatus {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("AuthFailStatus")
            .field("code", &self.code)
            .field("msg", &self.msg)
            .finish()
    }
}

/// A result holding the an [`Error`](Error).
pub type Result<T> = std::result::Result<T, Error>;

#[cfg(test)]
mod test {
    use super::*;

    #[test]
    fn test_error_standardizing() {
        let source_error = Box::new(Error::Unknown("unknown error".to_string()));
        let connect_error = Error::Connect {
            addr: "1.1.1.1:1111".to_string(),
            source: source_error as _,
        };
        assert_eq!(
            &format!("{connect_error}"),
            r#"failed to connect, addr:"1.1.1.1:1111", err:Unknown("unknown error")"#
        );
    }
}