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
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
// 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 common_error::ext::ErrorExt;
use common_error::status_code::StatusCode;
use common_macro::stack_trace_debug;
use console::{style, Style};
use datafusion::error::DataFusionError;
use datatypes::arrow::error::ArrowError;
use datatypes::error::Error as DataTypeError;
use query::error::Error as QueryError;
use rustpython_codegen::error::CodegenError;
use rustpython_parser::ast::Location;
use rustpython_parser::ParseError;
pub use snafu::ensure;
use snafu::prelude::Snafu;
use snafu::Location as SnafuLocation;
pub type Result<T> = std::result::Result<T, Error>;

pub(crate) fn ret_other_error_with(reason: String) -> OtherSnafu<String> {
    OtherSnafu { reason }
}

#[derive(Snafu)]
#[snafu(visibility(pub(crate)))]
#[stack_trace_debug]
pub enum Error {
    #[snafu(display("Datatype error"))]
    TypeCast {
        #[snafu(implicit)]
        location: SnafuLocation,
        source: DataTypeError,
    },

    #[snafu(display("Failed to query"))]
    DatabaseQuery {
        #[snafu(implicit)]
        location: SnafuLocation,
        source: QueryError,
    },

    #[snafu(display("Failed to parse script"))]
    PyParse {
        #[snafu(implicit)]
        location: SnafuLocation,
        #[snafu(source)]
        error: ParseError,
    },

    #[snafu(display("Failed to compile script"))]
    PyCompile {
        #[snafu(implicit)]
        location: SnafuLocation,
        #[snafu(source)]
        error: CodegenError,
    },

    /// rustpython problem, using python virtual machines' backtrace instead
    #[snafu(display("Python Runtime error, error: {}", msg))]
    PyRuntime {
        msg: String,
        #[snafu(implicit)]
        location: SnafuLocation,
    },

    #[snafu(display("Arrow error"))]
    Arrow {
        #[snafu(implicit)]
        location: SnafuLocation,
        #[snafu(source)]
        error: ArrowError,
    },

    #[snafu(display("DataFusion error"))]
    DataFusion {
        #[snafu(implicit)]
        location: SnafuLocation,
        #[snafu(source)]
        error: DataFusionError,
    },

    /// errors in coprocessors' parse check for types and etc.
    #[snafu(display("Coprocessor error: {} {}.", reason,
                    if let Some(loc) = loc{
                        format!("at {loc:?}")
                    }else{
                        "".into()
                    }))]
    CoprParse {
        #[snafu(implicit)]
        location: SnafuLocation,
        reason: String,
        // location is option because maybe errors can't give a clear location?
        loc: Option<Location>,
    },

    /// Other types of error that isn't any of above
    #[snafu(display("Coprocessor's Internal error: {}", reason))]
    Other {
        #[snafu(implicit)]
        location: SnafuLocation,
        reason: String,
    },

    #[snafu(display("Unsupported sql in coprocessor: {}", sql))]
    UnsupportedSql {
        sql: String,
        #[snafu(implicit)]
        location: SnafuLocation,
    },

    #[snafu(display("Failed to retrieve record batches"))]
    RecordBatch {
        #[snafu(implicit)]
        location: SnafuLocation,
        source: common_recordbatch::error::Error,
    },

    #[snafu(display("Failed to create record batch"))]
    NewRecordBatch {
        #[snafu(implicit)]
        location: SnafuLocation,
        source: common_recordbatch::error::Error,
    },
    #[snafu(display("Failed to create tokio task"))]
    TokioJoin {
        #[snafu(source)]
        error: tokio::task::JoinError,
    },
}

impl ErrorExt for Error {
    fn status_code(&self) -> StatusCode {
        match self {
            Error::DataFusion { .. }
            | Error::Arrow { .. }
            | Error::PyRuntime { .. }
            | Error::TokioJoin { .. }
            | Error::Other { .. } => StatusCode::Internal,

            Error::RecordBatch { source, .. } | Error::NewRecordBatch { source, .. } => {
                source.status_code()
            }
            Error::DatabaseQuery { source, .. } => source.status_code(),
            Error::TypeCast { source, .. } => source.status_code(),

            Error::PyParse { .. }
            | Error::PyCompile { .. }
            | Error::CoprParse { .. }
            | Error::UnsupportedSql { .. } => StatusCode::InvalidArguments,
        }
    }

    fn as_any(&self) -> &dyn std::any::Any {
        self
    }
}

/// pretty print [`Error`] in given script,
/// basically print a arrow which point to where error occurs(if possible to get a location)
pub fn pretty_print_error_in_src(
    script: &str,
    err: &Error,
    ln_offset: usize,
    filename: &str,
) -> String {
    let (reason, loc) = get_error_reason_loc(err);
    if let Some(loc) = loc {
        visualize_loc(script, &loc, &err.to_string(), &reason, ln_offset, filename)
    } else {
        // No location provide
        format!("\n{}: {}", style("error").red().bold(), err)
    }
}

/// pretty print a location in script with desc.
///
/// `ln_offset` is line offset number that added to `loc`'s `row`, `filename` is the file's name display with it's row and columns info.
pub fn visualize_loc(
    script: &str,
    loc: &Location,
    err_ty: &str,
    desc: &str,
    ln_offset: usize,
    filename: &str,
) -> String {
    let lines: Vec<&str> = script.split('\n').collect();
    let (row, col) = (loc.row(), loc.column());
    let red_bold = Style::new().red().bold();
    let blue_bold = Style::new().blue().bold();
    let col_space = (ln_offset + row).to_string().len().max(1);
    let space: String = " ".repeat(col_space - 1);
    let indicate = format!(
        "
{error}: {err_ty}
{space}{r_arrow}{filename}:{row}:{col}
{prow:col_space$}{ln_pad} {line}
{space} {ln_pad} {arrow:>pad$} {desc}
",
        error = red_bold.apply_to("error"),
        err_ty = style(err_ty).bold(),
        r_arrow = blue_bold.apply_to("-->"),
        filename = filename,
        row = ln_offset + row,
        col = col,
        line = lines[loc.row() - 1],
        pad = loc.column(),
        arrow = red_bold.apply_to("^"),
        desc = red_bold.apply_to(desc),
        ln_pad = blue_bold.apply_to("|"),
        prow = blue_bold.apply_to(ln_offset + row),
        space = space
    );
    indicate
}

/// extract a reason for [`Error`] in string format, also return a location if possible
pub fn get_error_reason_loc(err: &Error) -> (String, Option<Location>) {
    match err {
        Error::CoprParse { reason, loc, .. } => (reason.clone(), *loc),
        Error::Other { reason, .. } => (reason.clone(), None),
        Error::PyRuntime { msg, .. } => (msg.clone(), None),
        Error::PyParse { error, .. } => (error.error.to_string(), Some(error.location)),
        Error::PyCompile { error, .. } => (error.error.to_string(), Some(error.location)),
        _ => (format!("Unknown error: {err:?}"), None),
    }
}