Skip to main content

frontend/
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::define_into_tonic_status;
18use common_error::ext::{BoxedError, ErrorExt, RetryHint};
19use common_error::status_code::StatusCode;
20use common_macro::stack_trace_debug;
21use common_query::error::datafusion_status_code;
22use datafusion::error::DataFusionError;
23use session::ReadPreference;
24use snafu::{Location, Snafu};
25use store_api::storage::RegionId;
26
27#[derive(Snafu)]
28#[snafu(visibility(pub))]
29#[stack_trace_debug]
30pub enum Error {
31    #[snafu(display("Failed to handle heartbeat response"))]
32    HandleHeartbeatResponse {
33        #[snafu(implicit)]
34        location: Location,
35        source: common_meta::error::Error,
36    },
37
38    #[snafu(display("External error"))]
39    External {
40        #[snafu(implicit)]
41        location: Location,
42        source: BoxedError,
43    },
44
45    #[snafu(display("Failed to query"))]
46    RequestQuery {
47        #[snafu(implicit)]
48        location: Location,
49        source: common_meta::error::Error,
50    },
51
52    #[snafu(display("Failed to start server"))]
53    StartServer {
54        #[snafu(implicit)]
55        location: Location,
56        source: servers::error::Error,
57    },
58
59    #[snafu(display("Failed to shutdown server"))]
60    ShutdownServer {
61        #[snafu(implicit)]
62        location: Location,
63        source: servers::error::Error,
64    },
65
66    #[snafu(display("Failed to parse address {}", addr))]
67    ParseAddr {
68        addr: String,
69        #[snafu(source)]
70        error: std::net::AddrParseError,
71    },
72
73    #[snafu(display("Failed to parse SQL"))]
74    ParseSql {
75        #[snafu(implicit)]
76        location: Location,
77        source: sql::error::Error,
78    },
79
80    #[snafu(display("Invalid SQL, error: {}", err_msg))]
81    InvalidSql {
82        err_msg: String,
83        #[snafu(implicit)]
84        location: Location,
85    },
86
87    #[snafu(display("Incomplete GRPC request: {}", err_msg))]
88    IncompleteGrpcRequest {
89        err_msg: String,
90        #[snafu(implicit)]
91        location: Location,
92    },
93
94    #[snafu(display("Table not found: {}", table_name))]
95    TableNotFound { table_name: String },
96
97    #[snafu(display("General catalog error"))]
98    Catalog {
99        #[snafu(implicit)]
100        location: Location,
101        source: catalog::error::Error,
102    },
103
104    #[snafu(display("Failed to create heartbeat stream to Metasrv"))]
105    CreateMetaHeartbeatStream {
106        source: meta_client::error::Error,
107        #[snafu(implicit)]
108        location: Location,
109    },
110
111    #[snafu(display(
112        "Failed to find region peer for region id {}, read preference: {}",
113        region_id,
114        read_preference
115    ))]
116    FindRegionPeer {
117        region_id: RegionId,
118        read_preference: ReadPreference,
119        #[snafu(implicit)]
120        location: Location,
121        source: partition::error::Error,
122    },
123
124    #[snafu(display("Table occurs error"))]
125    Table {
126        #[snafu(implicit)]
127        location: Location,
128        source: table::error::Error,
129    },
130
131    #[snafu(display("Cannot find column by name: {}", msg))]
132    ColumnNotFound {
133        msg: String,
134        #[snafu(implicit)]
135        location: Location,
136    },
137
138    #[snafu(display(
139        "Ambiguous value column in table '{table_name}', candidates: {field_columns:?}"
140    ))]
141    AmbiguousValueColumn {
142        table_name: String,
143        field_columns: Vec<String>,
144        #[snafu(implicit)]
145        location: Location,
146    },
147
148    #[snafu(display("Unexpected type {data_type} for column '{column}' of table '{table_name}'"))]
149    UnexpectedColumnType {
150        table_name: String,
151        column: String,
152        data_type: String,
153        #[snafu(implicit)]
154        location: Location,
155    },
156
157    #[snafu(display("Failed to collect recordbatch"))]
158    CollectRecordbatch {
159        #[snafu(implicit)]
160        location: Location,
161        source: common_recordbatch::error::Error,
162    },
163
164    #[snafu(display("Failed to plan statement"))]
165    PlanStatement {
166        #[snafu(implicit)]
167        location: Location,
168        source: query::error::Error,
169    },
170
171    #[snafu(display("Failed to read table: {table_name}"))]
172    ReadTable {
173        table_name: String,
174        #[snafu(implicit)]
175        location: Location,
176        source: query::error::Error,
177    },
178
179    #[snafu(display("Failed to execute logical plan"))]
180    ExecLogicalPlan {
181        #[snafu(implicit)]
182        location: Location,
183        source: query::error::Error,
184    },
185
186    #[snafu(display("Not supported: {}", feat))]
187    NotSupported { feat: String },
188
189    #[snafu(display("SQL execution intercepted"))]
190    SqlExecIntercepted {
191        #[snafu(implicit)]
192        location: Location,
193        source: BoxedError,
194    },
195
196    // TODO(ruihang): merge all query execution error kinds
197    #[snafu(display("Failed to execute PromQL query {}", query))]
198    ExecutePromql {
199        query: String,
200        #[snafu(implicit)]
201        location: Location,
202        source: servers::error::Error,
203    },
204
205    #[snafu(display("Invalid Prometheus remote read schema: {detail}"))]
206    InvalidPromRemoteReadSchema {
207        detail: String,
208        #[snafu(implicit)]
209        location: Location,
210    },
211
212    #[snafu(display("Failed to create logical plan for prometheus query"))]
213    PromStoreRemoteQueryPlan {
214        #[snafu(implicit)]
215        location: Location,
216        source: servers::error::Error,
217    },
218
219    #[snafu(display("Failed to create logical plan for prometheus metric names query"))]
220    PrometheusMetricNamesQueryPlan {
221        #[snafu(implicit)]
222        location: Location,
223        source: servers::error::Error,
224    },
225
226    #[snafu(display("Failed to create logical plan for prometheus label values query"))]
227    PrometheusLabelValuesQueryPlan {
228        #[snafu(implicit)]
229        location: Location,
230        source: query::promql::error::Error,
231    },
232
233    #[snafu(display("Failed to describe schema for given statement"))]
234    DescribeStatement {
235        #[snafu(implicit)]
236        location: Location,
237        source: query::error::Error,
238    },
239
240    #[snafu(display("Failed to pass permission check"))]
241    Permission {
242        source: auth::error::Error,
243        #[snafu(implicit)]
244        location: Location,
245    },
246
247    #[snafu(display("Table operation error"))]
248    TableOperation {
249        source: operator::error::Error,
250        #[snafu(implicit)]
251        location: Location,
252    },
253
254    #[snafu(display("Invalid auth config"))]
255    IllegalAuthConfig { source: auth::error::Error },
256
257    #[snafu(display("Failed to serialize options to TOML"))]
258    TomlFormat {
259        #[snafu(implicit)]
260        location: Location,
261        #[snafu(source(from(common_config::error::Error, Box::new)))]
262        source: Box<common_config::error::Error>,
263    },
264
265    #[snafu(display("Failed to get cache from cache registry: {}", name))]
266    CacheRequired {
267        #[snafu(implicit)]
268        location: Location,
269        name: String,
270    },
271
272    #[snafu(display("Invalid write retry config: {}", reason))]
273    InvalidWriteRetryConfig {
274        reason: &'static str,
275        #[snafu(implicit)]
276        location: Location,
277    },
278
279    #[snafu(display("Invalid rollup cache config: {reason}"))]
280    InvalidPromqlRollupCacheConfig {
281        reason: String,
282        #[snafu(implicit)]
283        location: Location,
284    },
285
286    #[snafu(display("Invalid tls config"))]
287    InvalidTlsConfig {
288        #[snafu(source)]
289        error: common_grpc::error::Error,
290        #[snafu(implicit)]
291        location: Location,
292    },
293
294    #[snafu(display("Failed to init plugin"))]
295    // this comment is to bypass the unused snafu check in "check-snafu.py"
296    InitPlugin {
297        #[snafu(implicit)]
298        location: Location,
299        source: BoxedError,
300    },
301
302    #[snafu(display("Failed to decode logical plan from substrait"))]
303    SubstraitDecodeLogicalPlan {
304        #[snafu(implicit)]
305        location: Location,
306        source: common_query::error::Error,
307    },
308
309    #[snafu(display("DataFusionError"))]
310    DataFusion {
311        #[snafu(source)]
312        error: DataFusionError,
313        #[snafu(implicit)]
314        location: Location,
315    },
316
317    #[snafu(display("Query has been cancelled"))]
318    Cancelled {
319        #[snafu(implicit)]
320        location: Location,
321    },
322
323    #[snafu(display("Canceling statement due to statement timeout"))]
324    StatementTimeout {
325        #[snafu(implicit)]
326        location: Location,
327    },
328
329    #[snafu(display("Service suspended"))]
330    Suspended {
331        #[snafu(implicit)]
332        location: Location,
333    },
334}
335
336pub type Result<T> = std::result::Result<T, Error>;
337
338impl ErrorExt for Error {
339    fn status_code(&self) -> StatusCode {
340        match self {
341            Error::TomlFormat { .. }
342            | Error::ParseAddr { .. }
343            | Error::InvalidSql { .. }
344            | Error::ColumnNotFound { .. }
345            | Error::AmbiguousValueColumn { .. }
346            | Error::InvalidPromRemoteReadSchema { .. }
347            | Error::IllegalAuthConfig { .. }
348            | Error::IncompleteGrpcRequest { .. }
349            | Error::InvalidTlsConfig { .. }
350            | Error::InvalidPromqlRollupCacheConfig { .. }
351            | Error::InvalidWriteRetryConfig { .. } => StatusCode::InvalidArguments,
352
353            Error::NotSupported { .. } => StatusCode::Unsupported,
354
355            Error::Permission { source, .. } => source.status_code(),
356
357            Error::DescribeStatement { source, .. } => source.status_code(),
358
359            Error::HandleHeartbeatResponse { source, .. } => source.status_code(),
360
361            Error::PromStoreRemoteQueryPlan { source, .. }
362            | Error::PrometheusMetricNamesQueryPlan { source, .. }
363            | Error::ExecutePromql { source, .. } => source.status_code(),
364
365            Error::SubstraitDecodeLogicalPlan { source, .. } => source.status_code(),
366
367            Error::PrometheusLabelValuesQueryPlan { source, .. } => source.status_code(),
368
369            Error::CollectRecordbatch { source, .. } => source.status_code(),
370
371            Error::SqlExecIntercepted { source, .. } => source.status_code(),
372            Error::StartServer { source, .. } => source.status_code(),
373            Error::ShutdownServer { source, .. } => source.status_code(),
374
375            Error::ParseSql { source, .. } => source.status_code(),
376
377            Error::Table { source, .. } => source.status_code(),
378
379            Error::RequestQuery { source, .. } => source.status_code(),
380
381            Error::CacheRequired { .. } | Error::UnexpectedColumnType { .. } => {
382                StatusCode::Internal
383            }
384
385            Error::TableNotFound { .. } => StatusCode::TableNotFound,
386
387            Error::Catalog { source, .. } => source.status_code(),
388
389            Error::CreateMetaHeartbeatStream { source, .. } => source.status_code(),
390
391            Error::PlanStatement { source, .. }
392            | Error::ReadTable { source, .. }
393            | Error::ExecLogicalPlan { source, .. } => source.status_code(),
394
395            Error::External { source, .. } | Error::InitPlugin { source, .. } => {
396                source.status_code()
397            }
398            Error::FindRegionPeer { source, .. } => source.status_code(),
399
400            Error::TableOperation { source, .. } => source.status_code(),
401
402            Error::DataFusion { error, .. } => datafusion_status_code::<Self>(error, None),
403
404            Error::Cancelled { .. } => StatusCode::Cancelled,
405
406            Error::StatementTimeout { .. } => StatusCode::Cancelled,
407
408            Error::Suspended { .. } => StatusCode::Suspended,
409        }
410    }
411
412    fn as_any(&self) -> &dyn Any {
413        self
414    }
415
416    fn retry_hint(&self) -> RetryHint {
417        match self {
418            Error::HandleHeartbeatResponse { source, .. } | Error::RequestQuery { source, .. } => {
419                source.retry_hint()
420            }
421
422            Error::External { source, .. }
423            | Error::SqlExecIntercepted { source, .. }
424            | Error::InitPlugin { source, .. } => source.retry_hint(),
425
426            Error::StartServer { source, .. }
427            | Error::ShutdownServer { source, .. }
428            | Error::ExecutePromql { source, .. }
429            | Error::PromStoreRemoteQueryPlan { source, .. }
430            | Error::PrometheusMetricNamesQueryPlan { source, .. } => source.retry_hint(),
431
432            Error::ParseSql { source, .. } => source.retry_hint(),
433            Error::Catalog { source, .. } => source.retry_hint(),
434            Error::CreateMetaHeartbeatStream { source, .. } => source.retry_hint(),
435            Error::FindRegionPeer { source, .. } => source.retry_hint(),
436            Error::Table { source, .. } => source.retry_hint(),
437            Error::CollectRecordbatch { source, .. } => source.retry_hint(),
438            Error::PlanStatement { source, .. }
439            | Error::ReadTable { source, .. }
440            | Error::ExecLogicalPlan { source, .. }
441            | Error::DescribeStatement { source, .. } => source.retry_hint(),
442            Error::PrometheusLabelValuesQueryPlan { source, .. } => source.retry_hint(),
443            Error::Permission { source, .. } => source.retry_hint(),
444            Error::TableOperation { source, .. } => source.retry_hint(),
445            Error::IllegalAuthConfig { source, .. } => source.retry_hint(),
446            Error::TomlFormat { source, .. } => source.retry_hint(),
447            Error::InvalidTlsConfig { error, .. } => error.retry_hint(),
448            Error::SubstraitDecodeLogicalPlan { source, .. } => source.retry_hint(),
449
450            _ => RetryHint::NonRetryable,
451        }
452    }
453}
454
455define_into_tonic_status!(Error);
456
457impl From<operator::error::Error> for Error {
458    fn from(e: operator::error::Error) -> Error {
459        Error::TableOperation {
460            source: e,
461            location: Location::default(),
462        }
463    }
464}