Skip to main content

flow/
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
15//! Error definition for flow module
16
17use std::any::Any;
18
19use api::v1::CreateTableExpr;
20use arrow_schema::ArrowError;
21use common_error::ext::{BoxedError, RetryHint};
22use common_error::{
23    GREPTIME_DB_HEADER_ERROR_RETRY_HINT, define_into_tonic_status, from_err_code_msg_to_header,
24};
25use common_macro::stack_trace_debug;
26use common_telemetry::common_error::ext::ErrorExt;
27use common_telemetry::common_error::status_code::StatusCode;
28use snafu::{Location, Snafu};
29use tonic::codegen::http::HeaderValue;
30use tonic::metadata::MetadataMap;
31
32use crate::FlowId;
33
34/// This error is used to represent all possible errors that can occur in the flow module.
35#[derive(Snafu)]
36#[snafu(visibility(pub))]
37#[stack_trace_debug]
38pub enum Error {
39    #[snafu(display(
40        "Failed to insert into flow: region_id={}, flow_ids={:?}",
41        region_id,
42        flow_ids
43    ))]
44    InsertIntoFlow {
45        region_id: u64,
46        flow_ids: Vec<u64>,
47        source: BoxedError,
48        #[snafu(implicit)]
49        location: Location,
50    },
51
52    #[snafu(display("Flow engine is still recovering"))]
53    FlowNotRecovered {
54        #[snafu(implicit)]
55        location: Location,
56    },
57
58    #[snafu(display("Error encountered while creating flow: {sql}"))]
59    CreateFlow {
60        sql: String,
61        source: BoxedError,
62        #[snafu(implicit)]
63        location: Location,
64    },
65
66    #[snafu(display("Error encountered while creating sink table for flow: {create:?}"))]
67    CreateSinkTable {
68        create: CreateTableExpr,
69        source: BoxedError,
70        #[snafu(implicit)]
71        location: Location,
72    },
73
74    #[snafu(display("Time error"))]
75    Time {
76        source: common_time::error::Error,
77        #[snafu(implicit)]
78        location: Location,
79    },
80
81    #[snafu(display("No available frontend found after timeout: {timeout:?}, context: {context}"))]
82    NoAvailableFrontend {
83        timeout: std::time::Duration,
84        context: String,
85        #[snafu(implicit)]
86        location: Location,
87    },
88
89    #[snafu(display("External error"))]
90    External {
91        source: BoxedError,
92        #[snafu(implicit)]
93        location: Location,
94    },
95
96    #[snafu(display("Internal error"))]
97    Internal {
98        reason: String,
99        #[snafu(implicit)]
100        location: Location,
101    },
102
103    #[snafu(display("Table not found: {name}"))]
104    TableNotFound {
105        name: String,
106        #[snafu(implicit)]
107        location: Location,
108    },
109
110    #[snafu(display("Table not found: {msg}, meta error: {source}"))]
111    TableNotFoundMeta {
112        source: common_meta::error::Error,
113        msg: String,
114        #[snafu(implicit)]
115        location: Location,
116    },
117
118    #[snafu(display("Flow not found, id={id}"))]
119    FlowNotFound {
120        id: FlowId,
121        #[snafu(implicit)]
122        location: Location,
123    },
124
125    #[snafu(display("Failed to list flows in flownode={id:?}"))]
126    ListFlows {
127        id: Option<common_meta::FlownodeId>,
128        source: common_meta::error::Error,
129        #[snafu(implicit)]
130        location: Location,
131    },
132
133    #[snafu(display("Flow already exist, id={id}"))]
134    FlowAlreadyExist {
135        id: FlowId,
136        #[snafu(implicit)]
137        location: Location,
138    },
139
140    #[snafu(display("Failed to join task"))]
141    JoinTask {
142        #[snafu(source)]
143        error: tokio::task::JoinError,
144        #[snafu(implicit)]
145        location: Location,
146    },
147
148    #[snafu(display("Invalid query: {reason}"))]
149    InvalidQuery {
150        reason: String,
151        #[snafu(implicit)]
152        location: Location,
153    },
154
155    #[snafu(display("Flow plan error: {reason}"))]
156    Plan {
157        reason: String,
158        #[snafu(implicit)]
159        location: Location,
160    },
161
162    #[snafu(display("Unsupported: {reason}"))]
163    Unsupported {
164        reason: String,
165        #[snafu(implicit)]
166        location: Location,
167    },
168
169    #[snafu(display("Permission denied: {reason}"))]
170    PermissionDenied {
171        reason: String,
172        #[snafu(implicit)]
173        location: Location,
174    },
175
176    #[snafu(display("Datatypes error: {source} with extra message: {extra}"))]
177    Datatypes {
178        source: datatypes::Error,
179        extra: String,
180        #[snafu(implicit)]
181        location: Location,
182    },
183
184    #[snafu(display("Arrow error: {raw:?} in context: {context}"))]
185    Arrow {
186        #[snafu(source)]
187        raw: ArrowError,
188        context: String,
189        #[snafu(implicit)]
190        location: Location,
191    },
192
193    #[snafu(display("Datafusion error: {raw:?} in context: {context}"))]
194    Datafusion {
195        #[snafu(source)]
196        raw: datafusion_common::DataFusionError,
197        context: String,
198        #[snafu(implicit)]
199        location: Location,
200    },
201
202    #[snafu(display("Unexpected: {reason}"))]
203    Unexpected {
204        reason: String,
205        #[snafu(implicit)]
206        location: Location,
207    },
208
209    #[snafu(display("Illegal check task state: {reason}"))]
210    IllegalCheckTaskState {
211        reason: String,
212        #[snafu(implicit)]
213        location: Location,
214    },
215
216    #[snafu(display(
217        "Failed to sync with check task for flow {} with allow_drop={}",
218        flow_id,
219        allow_drop
220    ))]
221    SyncCheckTask {
222        flow_id: FlowId,
223        allow_drop: bool,
224        #[snafu(implicit)]
225        location: Location,
226    },
227
228    #[snafu(display("Failed to start server"))]
229    StartServer {
230        #[snafu(implicit)]
231        location: Location,
232        source: servers::error::Error,
233    },
234
235    #[snafu(display("Failed to shutdown server"))]
236    ShutdownServer {
237        #[snafu(implicit)]
238        location: Location,
239        source: servers::error::Error,
240    },
241
242    #[snafu(display("Failed to initialize meta client"))]
243    MetaClientInit {
244        #[snafu(implicit)]
245        location: Location,
246        source: meta_client::error::Error,
247    },
248
249    #[snafu(display("Failed to parse address {}", addr))]
250    ParseAddr {
251        addr: String,
252        #[snafu(source)]
253        error: std::net::AddrParseError,
254    },
255
256    #[snafu(display("Failed to get cache from cache registry: {}", name))]
257    CacheRequired {
258        #[snafu(implicit)]
259        location: Location,
260        name: String,
261    },
262
263    #[snafu(display("Invalid request: {context}"))]
264    InvalidRequest {
265        context: String,
266        source: client::Error,
267        #[snafu(implicit)]
268        location: Location,
269    },
270
271    #[snafu(display("Failed to encode logical plan in substrait"))]
272    SubstraitEncodeLogicalPlan {
273        #[snafu(implicit)]
274        location: Location,
275        source: substrait::error::Error,
276    },
277
278    #[snafu(display("Failed to convert column schema to proto column def"))]
279    ConvertColumnSchema {
280        #[snafu(implicit)]
281        location: Location,
282        source: operator::error::Error,
283    },
284
285    #[snafu(display("Failed to create channel manager for gRPC client"))]
286    InvalidClientConfig {
287        #[snafu(implicit)]
288        location: Location,
289        source: common_grpc::error::Error,
290    },
291}
292
293/// the outer message is the full error stack, and inner message in header is the last error message that can be show directly to user
294pub fn to_status_with_last_err(err: impl ErrorExt) -> tonic::Status {
295    let msg = err.to_string();
296    let last_err_msg = common_error::ext::StackError::last(&err).to_string();
297    let code = err.status_code() as u32;
298    let mut header = from_err_code_msg_to_header(code, &last_err_msg);
299    header.insert(
300        GREPTIME_DB_HEADER_ERROR_RETRY_HINT,
301        HeaderValue::from_static(err.retry_hint().as_str()),
302    );
303
304    tonic::Status::with_metadata(
305        tonic::Code::InvalidArgument,
306        msg,
307        MetadataMap::from_headers(header),
308    )
309}
310
311/// Result type for flow module
312pub type Result<T> = std::result::Result<T, Error>;
313
314impl ErrorExt for Error {
315    fn status_code(&self) -> StatusCode {
316        match self {
317            Self::JoinTask { .. }
318            | Self::Datafusion { .. }
319            | Self::InsertIntoFlow { .. }
320            | Self::NoAvailableFrontend { .. }
321            | Self::FlowNotRecovered { .. } => StatusCode::Internal,
322            Self::FlowAlreadyExist { .. } => StatusCode::TableAlreadyExists,
323            Self::TableNotFound { .. }
324            | Self::TableNotFoundMeta { .. }
325            | Self::ListFlows { .. } => StatusCode::TableNotFound,
326            Self::FlowNotFound { .. } => StatusCode::FlowNotFound,
327            Self::Plan { .. } | Self::Datatypes { .. } => StatusCode::PlanQuery,
328            Self::PermissionDenied { .. } => StatusCode::PermissionDenied,
329            Self::CreateFlow { source, .. } => {
330                if source.status_code() == StatusCode::PermissionDenied {
331                    StatusCode::PermissionDenied
332                } else {
333                    StatusCode::EngineExecuteQuery
334                }
335            }
336            Self::CreateSinkTable { .. } | Self::Arrow { .. } | Self::Time { .. } => {
337                StatusCode::EngineExecuteQuery
338            }
339            Self::Unexpected { .. }
340            | Self::SyncCheckTask { .. }
341            | Self::IllegalCheckTaskState { .. } => StatusCode::Unexpected,
342            Self::Unsupported { .. } => StatusCode::Unsupported,
343            Self::External { source, .. } => source.status_code(),
344            Self::Internal { .. } | Self::CacheRequired { .. } => StatusCode::Internal,
345            Self::StartServer { source, .. } | Self::ShutdownServer { source, .. } => {
346                source.status_code()
347            }
348            Self::MetaClientInit { source, .. } => source.status_code(),
349
350            Self::InvalidQuery { .. }
351            | Self::InvalidRequest { .. }
352            | Self::ParseAddr { .. }
353            | Self::InvalidClientConfig { .. } => StatusCode::InvalidArguments,
354
355            Error::SubstraitEncodeLogicalPlan { source, .. } => source.status_code(),
356
357            Error::ConvertColumnSchema { source, .. } => source.status_code(),
358        }
359    }
360
361    fn as_any(&self) -> &dyn Any {
362        self
363    }
364
365    fn retry_hint(&self) -> RetryHint {
366        match self {
367            Self::FlowNotRecovered { .. } | Self::NoAvailableFrontend { .. } => {
368                RetryHint::Retryable
369            }
370
371            Self::InsertIntoFlow { source, .. }
372            | Self::CreateFlow { source, .. }
373            | Self::CreateSinkTable { source, .. }
374            | Self::External { source, .. } => source.retry_hint(),
375
376            Self::Time { source, .. } => source.retry_hint(),
377            Self::TableNotFoundMeta { source, .. } | Self::ListFlows { source, .. } => {
378                source.retry_hint()
379            }
380            Self::Datatypes { source, .. } => source.retry_hint(),
381            Self::StartServer { source, .. } | Self::ShutdownServer { source, .. } => {
382                source.retry_hint()
383            }
384            Self::MetaClientInit { source, .. } => source.retry_hint(),
385            Self::InvalidRequest { source, .. } => source.retry_hint(),
386            Self::SubstraitEncodeLogicalPlan { source, .. } => source.retry_hint(),
387            Self::ConvertColumnSchema { source, .. } => source.retry_hint(),
388            Self::InvalidClientConfig { source, .. } => source.retry_hint(),
389
390            _ => RetryHint::NonRetryable,
391        }
392    }
393}
394
395define_into_tonic_status!(Error);