Skip to main content

servers/
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;
16use std::net::SocketAddr;
17use std::string::FromUtf8Error;
18
19use axum::http::StatusCode as HttpStatusCode;
20use axum::response::{IntoResponse, Response};
21use axum::{Json, http};
22use base64::DecodeError;
23use common_error::define_into_tonic_status;
24use common_error::ext::{BoxedError, ErrorExt, RetryHint};
25use common_error::status_code::StatusCode;
26use common_macro::stack_trace_debug;
27use common_telemetry::{error, warn};
28use datafusion::error::DataFusionError;
29use datatypes::prelude::ConcreteDataType;
30use headers::ContentType;
31use http::header::InvalidHeaderValue;
32use query::parser::PromQuery;
33use serde_json::json;
34use snafu::{Location, Snafu};
35
36#[derive(Snafu)]
37#[snafu(visibility(pub))]
38#[stack_trace_debug]
39pub enum Error {
40    #[snafu(display("Failed to bind address: {}", addr))]
41    AddressBind {
42        addr: SocketAddr,
43        #[snafu(source)]
44        error: std::io::Error,
45        #[snafu(implicit)]
46        location: Location,
47    },
48
49    #[snafu(display("Arrow error"))]
50    Arrow {
51        #[snafu(source)]
52        error: arrow_schema::ArrowError,
53        #[snafu(implicit)]
54        location: Location,
55    },
56
57    #[snafu(display("Internal error: {}", err_msg))]
58    Internal { err_msg: String },
59
60    #[snafu(display("Pending rows batcher channel closed"))]
61    BatcherChannelClosed,
62
63    #[snafu(display("Write rejected: {error}"))]
64    WriteRejected {
65        #[snafu(source)]
66        error: meter_core::collect::WriteRejected,
67        #[snafu(implicit)]
68        location: Location,
69    },
70
71    #[snafu(display("Unsupported data type: {}, reason: {}", data_type, reason))]
72    UnsupportedDataType {
73        data_type: ConcreteDataType,
74        reason: String,
75    },
76
77    #[snafu(display("Internal IO error"))]
78    InternalIo {
79        #[snafu(source)]
80        error: std::io::Error,
81    },
82
83    #[snafu(display("Tokio IO error: {}", err_msg))]
84    TokioIo {
85        err_msg: String,
86        #[snafu(source)]
87        error: std::io::Error,
88    },
89
90    #[snafu(display("Failed to collect recordbatch"))]
91    CollectRecordbatch {
92        #[snafu(implicit)]
93        location: Location,
94        source: common_recordbatch::error::Error,
95    },
96
97    #[snafu(display("Failed to start gRPC server"))]
98    StartGrpc {
99        #[snafu(source)]
100        error: tonic::transport::Error,
101    },
102
103    #[snafu(display("Request memory limit exceeded"))]
104    MemoryLimitExceeded {
105        #[snafu(implicit)]
106        location: Location,
107        source: common_memory_manager::Error,
108    },
109
110    #[snafu(display("{} server is already started", server))]
111    AlreadyStarted {
112        server: String,
113        #[snafu(implicit)]
114        location: Location,
115    },
116
117    #[snafu(display("Failed to bind address {}", addr))]
118    TcpBind {
119        addr: SocketAddr,
120        #[snafu(source)]
121        error: std::io::Error,
122    },
123
124    #[snafu(display("Failed to execute query"))]
125    ExecuteQuery {
126        #[snafu(implicit)]
127        location: Location,
128        source: BoxedError,
129    },
130
131    #[snafu(display("Failed to execute plan"))]
132    ExecutePlan {
133        #[snafu(implicit)]
134        location: Location,
135        source: BoxedError,
136    },
137
138    #[snafu(display("Execute gRPC query error"))]
139    ExecuteGrpcQuery {
140        #[snafu(implicit)]
141        location: Location,
142        source: BoxedError,
143    },
144
145    #[snafu(display("Execute gRPC request error"))]
146    ExecuteGrpcRequest {
147        #[snafu(implicit)]
148        location: Location,
149        source: BoxedError,
150    },
151
152    #[snafu(display("Failed to check database validity"))]
153    CheckDatabaseValidity {
154        #[snafu(implicit)]
155        location: Location,
156        source: BoxedError,
157    },
158
159    #[snafu(display("Failed to describe statement"))]
160    DescribeStatement { source: BoxedError },
161
162    #[snafu(display("Pipeline error"))]
163    Pipeline {
164        #[snafu(source)]
165        source: pipeline::error::Error,
166        #[snafu(implicit)]
167        location: Location,
168    },
169
170    #[snafu(display("Not supported: {}", feat))]
171    NotSupported { feat: String },
172
173    #[snafu(display("Invalid request parameter: {}", reason))]
174    InvalidParameter {
175        reason: String,
176        #[snafu(implicit)]
177        location: Location,
178    },
179
180    #[snafu(display("Invalid OTLP metric input: {}", reason))]
181    InvalidOtlpMetricInput { reason: String },
182
183    #[snafu(display("Unsupported operation: {}", operation))]
184    UnsupportedOperation { operation: String },
185
186    #[snafu(display("Invalid query: {}", reason))]
187    InvalidQuery {
188        reason: String,
189        #[snafu(implicit)]
190        location: Location,
191    },
192
193    #[snafu(display("Failed to parse query"))]
194    FailedToParseQuery {
195        #[snafu(implicit)]
196        location: Location,
197        source: sql::error::Error,
198    },
199
200    #[snafu(display("Failed to parse InfluxDB line protocol"))]
201    InfluxdbLineProtocol {
202        #[snafu(implicit)]
203        location: Location,
204        #[snafu(source)]
205        error: influxdb_line_protocol::Error,
206    },
207
208    #[snafu(display("Failed to write row"))]
209    RowWriter {
210        #[snafu(implicit)]
211        location: Location,
212        source: common_grpc::error::Error,
213    },
214
215    #[snafu(display("Failed to convert time precision, name: {}", name))]
216    TimePrecision {
217        name: String,
218        #[snafu(implicit)]
219        location: Location,
220    },
221
222    #[snafu(display("Invalid OpenTSDB Json request"))]
223    InvalidOpentsdbJsonRequest {
224        #[snafu(source)]
225        error: serde_json::error::Error,
226        #[snafu(implicit)]
227        location: Location,
228    },
229
230    #[snafu(display("Failed to decode prometheus remote request"))]
231    DecodePromRemoteRequest {
232        #[snafu(implicit)]
233        location: Location,
234        #[snafu(source)]
235        error: prost::DecodeError,
236    },
237
238    #[snafu(display(
239        "Failed to decode OTLP request (content-type: {content_type}): {error}. The endpoint only accepts 'application/x-protobuf' format."
240    ))]
241    DecodeOtlpRequest {
242        content_type: String,
243        #[snafu(implicit)]
244        location: Location,
245        #[snafu(source)]
246        error: prost::DecodeError,
247    },
248
249    #[snafu(display("Failed to decode Loki request: {error}"))]
250    DecodeLokiRequest {
251        #[snafu(implicit)]
252        location: Location,
253        #[snafu(source)]
254        error: prost::DecodeError,
255    },
256
257    #[snafu(display(
258        "Unsupported content type 'application/json'. OTLP endpoint only supports 'application/x-protobuf'. Please configure your OTLP exporter to use protobuf encoding."
259    ))]
260    UnsupportedJsonContentType {
261        #[snafu(implicit)]
262        location: Location,
263    },
264
265    #[snafu(display("Common Meta error"))]
266    CommonMeta {
267        #[snafu(implicit)]
268        location: Location,
269        #[snafu(source)]
270        source: common_meta::error::Error,
271    },
272
273    #[snafu(display("Failed to decompress snappy prometheus remote request"))]
274    DecompressSnappyPromRemoteRequest {
275        #[snafu(implicit)]
276        location: Location,
277        #[snafu(source)]
278        error: snap::Error,
279    },
280
281    #[snafu(display("Failed to decompress snappy Loki request"))]
282    DecompressSnappyLokiRequest {
283        #[snafu(implicit)]
284        location: Location,
285        #[snafu(source)]
286        error: snap::Error,
287    },
288
289    #[snafu(display("Failed to decompress zstd prometheus remote request"))]
290    DecompressZstdPromRemoteRequest {
291        #[snafu(implicit)]
292        location: Location,
293        #[snafu(source)]
294        error: std::io::Error,
295    },
296
297    #[snafu(display(
298        "Decompressed request body is too large: {} bytes exceeds the limit {} bytes",
299        size,
300        limit
301    ))]
302    DecompressedBodyTooLarge {
303        size: u64,
304        limit: u64,
305        #[snafu(implicit)]
306        location: Location,
307    },
308
309    #[snafu(display("Failed to compress prometheus remote request"))]
310    CompressPromRemoteRequest {
311        #[snafu(implicit)]
312        location: Location,
313        #[snafu(source)]
314        error: snap::Error,
315    },
316
317    #[snafu(display("Invalid prometheus remote request, msg: {}", msg))]
318    InvalidPromRemoteRequest {
319        msg: String,
320        #[snafu(implicit)]
321        location: Location,
322    },
323
324    #[snafu(display("Invalid prometheus remote read query result, msg: {}", msg))]
325    InvalidPromRemoteReadQueryResult {
326        msg: String,
327        #[snafu(implicit)]
328        location: Location,
329    },
330
331    #[snafu(display("Invalid Flight ticket"))]
332    InvalidFlightTicket {
333        #[snafu(source)]
334        error: api::DecodeError,
335        #[snafu(implicit)]
336        location: Location,
337    },
338
339    #[snafu(display("Tls is required for {}, plain connection is rejected", server))]
340    TlsRequired { server: String },
341
342    #[snafu(display("Failed to get user info"))]
343    Auth {
344        #[snafu(implicit)]
345        location: Location,
346        source: auth::error::Error,
347    },
348
349    #[snafu(display("Not found http or grpc authorization header"))]
350    NotFoundAuthHeader {},
351
352    #[snafu(display("Not found influx http authorization info"))]
353    NotFoundInfluxAuth {},
354
355    #[snafu(display("Unsupported http auth scheme, name: {}", name))]
356    UnsupportedAuthScheme { name: String },
357
358    #[snafu(display("Invalid visibility ASCII chars"))]
359    InvalidAuthHeaderInvisibleASCII {
360        #[snafu(source)]
361        error: hyper::header::ToStrError,
362        #[snafu(implicit)]
363        location: Location,
364    },
365
366    #[snafu(display("Invalid utf-8 value"))]
367    InvalidAuthHeaderInvalidUtf8Value {
368        #[snafu(source)]
369        error: FromUtf8Error,
370        #[snafu(implicit)]
371        location: Location,
372    },
373
374    #[snafu(display("Invalid http authorization header"))]
375    InvalidAuthHeader {
376        #[snafu(implicit)]
377        location: Location,
378    },
379
380    #[snafu(display("Invalid base64 value"))]
381    InvalidBase64Value {
382        #[snafu(source)]
383        error: DecodeError,
384        #[snafu(implicit)]
385        location: Location,
386    },
387
388    #[snafu(display("Invalid http header value"))]
389    InvalidHeaderValue {
390        #[snafu(source)]
391        error: InvalidHeaderValue,
392        #[snafu(implicit)]
393        location: Location,
394    },
395
396    #[snafu(transparent)]
397    Catalog {
398        source: catalog::error::Error,
399        #[snafu(implicit)]
400        location: Location,
401    },
402
403    #[snafu(display("Cannot find requested table: {}.{}.{}", catalog, schema, table))]
404    TableNotFound {
405        catalog: String,
406        schema: String,
407        table: String,
408        #[snafu(implicit)]
409        location: Location,
410    },
411
412    #[cfg(feature = "mem-prof")]
413    #[snafu(display("Failed to dump profile data"))]
414    DumpProfileData {
415        #[snafu(implicit)]
416        location: Location,
417        source: common_mem_prof::error::Error,
418    },
419
420    #[snafu(display("Invalid prepare statement: {}", err_msg))]
421    InvalidPrepareStatement {
422        err_msg: String,
423        #[snafu(implicit)]
424        location: Location,
425    },
426
427    #[snafu(display("Failed to build HTTP response"))]
428    BuildHttpResponse {
429        #[snafu(source)]
430        error: http::Error,
431        #[snafu(implicit)]
432        location: Location,
433    },
434
435    #[snafu(display("Failed to parse PromQL: {query:?}"))]
436    ParsePromQL {
437        query: Box<PromQuery>,
438        #[snafu(implicit)]
439        location: Location,
440        source: query::error::Error,
441    },
442
443    #[snafu(display("Failed to parse timestamp: {}", timestamp))]
444    ParseTimestamp {
445        timestamp: String,
446        #[snafu(implicit)]
447        location: Location,
448        #[snafu(source)]
449        error: query::error::Error,
450    },
451
452    #[snafu(display("Failed to infer parameter types"))]
453    InferParameterTypes {
454        #[snafu(implicit)]
455        location: Location,
456        #[snafu(source)]
457        error: query::error::Error,
458    },
459
460    #[snafu(display("{}", reason))]
461    UnexpectedResult {
462        reason: String,
463        #[snafu(implicit)]
464        location: Location,
465    },
466
467    // this error is used for custom error mapping
468    // please do not delete it
469    #[snafu(display("Other error"))]
470    Other {
471        source: BoxedError,
472        #[snafu(implicit)]
473        location: Location,
474    },
475
476    #[snafu(display("Failed to join task"))]
477    JoinTask {
478        #[snafu(source)]
479        error: tokio::task::JoinError,
480        #[snafu(implicit)]
481        location: Location,
482    },
483
484    #[cfg(feature = "pprof")]
485    #[snafu(display("Failed to dump pprof data"))]
486    DumpPprof { source: common_pprof::error::Error },
487
488    #[cfg(not(windows))]
489    #[snafu(display("Failed to update jemalloc metrics"))]
490    UpdateJemallocMetrics {
491        #[snafu(source)]
492        error: tikv_jemalloc_ctl::Error,
493        #[snafu(implicit)]
494        location: Location,
495    },
496
497    #[snafu(display("DataFrame operation error"))]
498    DataFrame {
499        #[snafu(source)]
500        error: datafusion::error::DataFusionError,
501        #[snafu(implicit)]
502        location: Location,
503    },
504
505    #[snafu(display("Failed to convert scalar value"))]
506    ConvertScalarValue {
507        source: datatypes::error::Error,
508        #[snafu(implicit)]
509        location: Location,
510    },
511
512    #[snafu(display("Expected type: {:?}, actual: {:?}", expected, actual))]
513    PreparedStmtTypeMismatch {
514        expected: ConcreteDataType,
515        actual: opensrv_mysql::ColumnType,
516        #[snafu(implicit)]
517        location: Location,
518    },
519
520    #[snafu(display(
521        "Column: {}, {} incompatible, expected: {}, actual: {}",
522        column_name,
523        datatype,
524        expected,
525        actual
526    ))]
527    IncompatibleSchema {
528        column_name: String,
529        datatype: String,
530        expected: i32,
531        actual: i32,
532        #[snafu(implicit)]
533        location: Location,
534    },
535
536    #[snafu(display("Failed to convert to json"))]
537    ToJson {
538        #[snafu(source)]
539        error: serde_json::error::Error,
540        #[snafu(implicit)]
541        location: Location,
542    },
543
544    #[snafu(display("Failed to parse payload as json"))]
545    ParseJson {
546        #[snafu(source)]
547        error: serde_json::error::Error,
548        #[snafu(implicit)]
549        location: Location,
550    },
551
552    #[snafu(display("Invalid Loki labels: {}", msg))]
553    InvalidLokiLabels {
554        msg: String,
555        #[snafu(implicit)]
556        location: Location,
557    },
558
559    #[snafu(display("Invalid Loki JSON request: {}", msg))]
560    InvalidLokiPayload {
561        msg: String,
562        #[snafu(implicit)]
563        location: Location,
564    },
565
566    #[snafu(display("Unsupported content type: {:?}", content_type))]
567    UnsupportedContentType {
568        content_type: ContentType,
569        #[snafu(implicit)]
570        location: Location,
571    },
572
573    #[snafu(display("Failed to decode url"))]
574    UrlDecode {
575        #[snafu(source)]
576        error: FromUtf8Error,
577        #[snafu(implicit)]
578        location: Location,
579    },
580
581    #[snafu(display("Failed to convert Mysql value, error: {}", err_msg))]
582    MysqlValueConversion {
583        err_msg: String,
584        #[snafu(implicit)]
585        location: Location,
586    },
587
588    #[snafu(display("Timestamp overflow: {}", error))]
589    TimestampOverflow {
590        error: String,
591        #[snafu(implicit)]
592        location: Location,
593    },
594
595    #[snafu(display("Unsupported json data type for tag: {} {}", key, ty))]
596    UnsupportedJsonDataTypeForTag {
597        key: String,
598        ty: String,
599        #[snafu(implicit)]
600        location: Location,
601    },
602
603    #[snafu(display("Convert SQL value error"))]
604    ConvertSqlValue {
605        source: datatypes::error::Error,
606        #[snafu(implicit)]
607        location: Location,
608    },
609
610    #[snafu(display("Prepare statement not found: {}", name))]
611    PrepareStatementNotFound {
612        name: String,
613        #[snafu(implicit)]
614        location: Location,
615    },
616
617    #[snafu(display("Invalid elasticsearch input, reason: {}", reason))]
618    InvalidElasticsearchInput {
619        reason: String,
620        #[snafu(implicit)]
621        location: Location,
622    },
623
624    #[snafu(display("Invalid Jaeger query, reason: {}", reason))]
625    InvalidJaegerQuery {
626        reason: String,
627        #[snafu(implicit)]
628        location: Location,
629    },
630
631    #[snafu(display("DataFusion error"))]
632    DataFusion {
633        #[snafu(source)]
634        error: DataFusionError,
635        #[snafu(implicit)]
636        location: Location,
637    },
638
639    #[snafu(display("Failed to handle otel-arrow request, error message: {}", err_msg))]
640    HandleOtelArrowRequest {
641        err_msg: String,
642        #[snafu(implicit)]
643        location: Location,
644    },
645
646    #[snafu(display("Unknown hint: {}", hint))]
647    UnknownHint { hint: String },
648
649    #[snafu(display("Query has been cancelled"))]
650    Cancelled {
651        #[snafu(implicit)]
652        location: Location,
653    },
654
655    #[snafu(display("Service suspended"))]
656    Suspended {
657        #[snafu(implicit)]
658        location: Location,
659    },
660
661    #[snafu(transparent)]
662    Operator {
663        source: operator::error::Error,
664        #[snafu(implicit)]
665        location: Location,
666    },
667
668    #[snafu(transparent)]
669    GreptimeProto {
670        source: api::error::Error,
671        #[snafu(implicit)]
672        location: Location,
673    },
674
675    #[snafu(transparent)]
676    DataTypes {
677        source: datatypes::error::Error,
678        #[snafu(implicit)]
679        location: Location,
680    },
681
682    #[snafu(transparent)]
683    Partition {
684        source: partition::error::Error,
685        #[snafu(implicit)]
686        location: Location,
687    },
688
689    #[snafu(transparent)]
690    MetricEngine {
691        source: metric_engine::error::Error,
692        #[snafu(implicit)]
693        location: Location,
694    },
695}
696
697pub type Result<T, E = Error> = std::result::Result<T, E>;
698
699impl ErrorExt for Error {
700    fn status_code(&self) -> StatusCode {
701        use Error::*;
702        match self {
703            Internal { .. }
704            | BatcherChannelClosed
705            | InternalIo { .. }
706            | TokioIo { .. }
707            | StartGrpc { .. }
708            | TcpBind { .. }
709            | BuildHttpResponse { .. }
710            | Arrow { .. } => StatusCode::Internal,
711
712            AddressBind { .. }
713            | AlreadyStarted { .. }
714            | InvalidPromRemoteReadQueryResult { .. } => StatusCode::IllegalState,
715
716            UnsupportedDataType { .. } | UnsupportedOperation { .. } => StatusCode::Unsupported,
717
718            #[cfg(not(windows))]
719            UpdateJemallocMetrics { .. } => StatusCode::Internal,
720
721            CollectRecordbatch { source, .. } => source.status_code(),
722
723            ExecuteQuery { source, .. }
724            | ExecutePlan { source, .. }
725            | ExecuteGrpcQuery { source, .. }
726            | ExecuteGrpcRequest { source, .. }
727            | CheckDatabaseValidity { source, .. } => source.status_code(),
728
729            Pipeline { source, .. } => source.status_code(),
730            CommonMeta { source, .. } => source.status_code(),
731
732            NotSupported { .. }
733            | InvalidParameter { .. }
734            | InvalidOtlpMetricInput { .. }
735            | InvalidQuery { .. }
736            | InfluxdbLineProtocol { .. }
737            | InvalidOpentsdbJsonRequest { .. }
738            | DecodePromRemoteRequest { .. }
739            | DecodeOtlpRequest { .. }
740            | DecodeLokiRequest { .. }
741            | UnsupportedJsonContentType { .. }
742            | CompressPromRemoteRequest { .. }
743            | DecompressSnappyPromRemoteRequest { .. }
744            | DecompressSnappyLokiRequest { .. }
745            | DecompressZstdPromRemoteRequest { .. }
746            | DecompressedBodyTooLarge { .. }
747            | InvalidPromRemoteRequest { .. }
748            | InvalidFlightTicket { .. }
749            | InvalidPrepareStatement { .. }
750            | InferParameterTypes { .. }
751            | DataFrame { .. }
752            | PreparedStmtTypeMismatch { .. }
753            | TimePrecision { .. }
754            | UrlDecode { .. }
755            | IncompatibleSchema { .. }
756            | MysqlValueConversion { .. }
757            | ParseJson { .. }
758            | InvalidLokiLabels { .. }
759            | InvalidLokiPayload { .. }
760            | UnsupportedContentType { .. }
761            | TimestampOverflow { .. }
762            | UnsupportedJsonDataTypeForTag { .. }
763            | PrepareStatementNotFound { .. }
764            | FailedToParseQuery { .. }
765            | InvalidElasticsearchInput { .. }
766            | InvalidJaegerQuery { .. }
767            | ParseTimestamp { .. }
768            | UnknownHint { .. } => StatusCode::InvalidArguments,
769
770            Catalog { source, .. } => source.status_code(),
771            RowWriter { source, .. } => source.status_code(),
772            DataTypes { source, .. } => source.status_code(),
773
774            TlsRequired { .. } => StatusCode::Unknown,
775            Auth { source, .. } => source.status_code(),
776            DescribeStatement { source } => source.status_code(),
777
778            NotFoundAuthHeader { .. } | NotFoundInfluxAuth { .. } => StatusCode::AuthHeaderNotFound,
779            InvalidAuthHeaderInvisibleASCII { .. }
780            | UnsupportedAuthScheme { .. }
781            | InvalidAuthHeader { .. }
782            | InvalidBase64Value { .. }
783            | InvalidAuthHeaderInvalidUtf8Value { .. } => StatusCode::InvalidAuthHeader,
784
785            TableNotFound { .. } => StatusCode::TableNotFound,
786
787            #[cfg(feature = "mem-prof")]
788            DumpProfileData { source, .. } => source.status_code(),
789
790            InvalidHeaderValue { .. } => StatusCode::InvalidArguments,
791
792            ParsePromQL { source, .. } => source.status_code(),
793            Other { source, .. } => source.status_code(),
794
795            UnexpectedResult { .. } => StatusCode::Unexpected,
796
797            JoinTask { error, .. } => {
798                if error.is_cancelled() {
799                    StatusCode::Cancelled
800                } else if error.is_panic() {
801                    StatusCode::Unexpected
802                } else {
803                    StatusCode::Unknown
804                }
805            }
806
807            #[cfg(feature = "pprof")]
808            DumpPprof { source, .. } => source.status_code(),
809
810            ConvertScalarValue { source, .. } => source.status_code(),
811
812            ToJson { .. } | DataFusion { .. } => StatusCode::Internal,
813
814            ConvertSqlValue { source, .. } => source.status_code(),
815
816            HandleOtelArrowRequest { .. } => StatusCode::Internal,
817
818            Cancelled { .. } => StatusCode::Cancelled,
819
820            Suspended { .. } => StatusCode::Suspended,
821
822            MemoryLimitExceeded { .. } | WriteRejected { .. } => StatusCode::RateLimited,
823
824            GreptimeProto { source, .. } => source.status_code(),
825            Partition { source, .. } => source.status_code(),
826            MetricEngine { source, .. } => source.status_code(),
827            Operator { source, .. } => source.status_code(),
828        }
829    }
830
831    fn retry_hint(&self) -> RetryHint {
832        use Error::*;
833        match self {
834            ExecuteQuery { source, .. }
835            | ExecutePlan { source, .. }
836            | ExecuteGrpcQuery { source, .. }
837            | ExecuteGrpcRequest { source, .. }
838            | CheckDatabaseValidity { source, .. }
839            | DescribeStatement { source } => source.retry_hint(),
840
841            Pipeline { source, .. } => source.retry_hint(),
842            CommonMeta { source, .. } => source.retry_hint(),
843            Catalog { source, .. } => source.retry_hint(),
844            RowWriter { source, .. } => source.retry_hint(),
845            Auth { source, .. } => source.retry_hint(),
846
847            #[cfg(feature = "mem-prof")]
848            DumpProfileData { source, .. } => source.retry_hint(),
849
850            ParsePromQL { source, .. } => source.retry_hint(),
851            Other { source, .. } => source.retry_hint(),
852
853            #[cfg(feature = "pprof")]
854            DumpPprof { source, .. } => source.retry_hint(),
855
856            ConvertScalarValue { source, .. } => source.retry_hint(),
857            ConvertSqlValue { source, .. } => source.retry_hint(),
858            GreptimeProto { source, .. } => source.retry_hint(),
859            Partition { source, .. } => source.retry_hint(),
860            MetricEngine { source, .. } => source.retry_hint(),
861            Operator { source, .. } => source.retry_hint(),
862
863            MemoryLimitExceeded { source, .. } => source.retry_hint(),
864            CollectRecordbatch { source, .. } => source.retry_hint(),
865
866            WriteRejected { .. } => RetryHint::Retryable,
867
868            _ => RetryHint::NonRetryable,
869        }
870    }
871
872    fn as_any(&self) -> &dyn Any {
873        self
874    }
875}
876
877define_into_tonic_status!(Error);
878
879impl From<std::io::Error> for Error {
880    fn from(e: std::io::Error) -> Self {
881        Error::InternalIo { error: e }
882    }
883}
884
885pub(crate) fn log_error_if_necessary(error: &Error) {
886    if error.status_code().should_log_error() {
887        error!(error; "Failed to handle HTTP request ");
888    } else {
889        warn!(error; "Failed to handle HTTP request ");
890    }
891}
892
893impl IntoResponse for Error {
894    fn into_response(self) -> Response {
895        let error_msg = self.output_msg();
896        let status = status_code_to_http_status(&self.status_code());
897
898        log_error_if_necessary(&self);
899
900        let body = Json(json!({
901            "error": error_msg,
902        }));
903        (status, body).into_response()
904    }
905}
906
907/// Converts [StatusCode] to [HttpStatusCode].
908pub fn status_code_to_http_status(status_code: &StatusCode) -> HttpStatusCode {
909    match status_code {
910        StatusCode::Success => HttpStatusCode::OK,
911
912        // When a request is cancelled by the client (e.g., by a client side timeout),
913        // we should return a gateway timeout status code to the external client.
914        StatusCode::Cancelled | StatusCode::DeadlineExceeded => HttpStatusCode::GATEWAY_TIMEOUT,
915
916        StatusCode::Unsupported
917        | StatusCode::InvalidArguments
918        | StatusCode::InvalidSyntax
919        | StatusCode::RequestOutdated
920        | StatusCode::RegionAlreadyExists
921        | StatusCode::TableColumnExists
922        | StatusCode::TableAlreadyExists
923        | StatusCode::RegionNotFound
924        | StatusCode::DatabaseNotFound
925        | StatusCode::TableNotFound
926        | StatusCode::TableColumnNotFound
927        | StatusCode::PlanQuery
928        | StatusCode::DatabaseAlreadyExists
929        | StatusCode::TriggerAlreadyExists
930        | StatusCode::TriggerNotFound
931        | StatusCode::FlowNotFound
932        | StatusCode::FlowAlreadyExists => HttpStatusCode::BAD_REQUEST,
933
934        StatusCode::AuthHeaderNotFound
935        | StatusCode::InvalidAuthHeader
936        | StatusCode::UserNotFound
937        | StatusCode::UnsupportedPasswordType
938        | StatusCode::UserPasswordMismatch
939        | StatusCode::RegionReadonly => HttpStatusCode::UNAUTHORIZED,
940
941        StatusCode::PermissionDenied | StatusCode::AccessDenied => HttpStatusCode::FORBIDDEN,
942
943        StatusCode::RateLimited => HttpStatusCode::TOO_MANY_REQUESTS,
944
945        StatusCode::RegionNotReady
946        | StatusCode::TableUnavailable
947        | StatusCode::RegionBusy
948        | StatusCode::StorageUnavailable
949        | StatusCode::External
950        | StatusCode::Suspended => HttpStatusCode::SERVICE_UNAVAILABLE,
951
952        StatusCode::Internal
953        | StatusCode::Unexpected
954        | StatusCode::IllegalState
955        | StatusCode::PartialFailure
956        | StatusCode::Unknown
957        | StatusCode::RuntimeResourcesExhausted
958        | StatusCode::EngineExecuteQuery => HttpStatusCode::INTERNAL_SERVER_ERROR,
959    }
960}
961
962#[cfg(test)]
963mod tests {
964    use common_error::ext::PlainError;
965    use common_error::mock::MockError;
966    use common_error::{GREPTIME_DB_HEADER_ERROR_CODE, GREPTIME_DB_HEADER_ERROR_RETRY_HINT};
967
968    use super::*;
969
970    #[test]
971    fn collect_recordbatch_preserves_poll_stream_status_in_tonic_status() {
972        let error = Error::CollectRecordbatch {
973            source: common_recordbatch::error::Error::PollStream {
974                error: DataFusionError::External(Box::new(BoxedError::new(PlainError::new(
975                    "neutral error".to_string(),
976                    StatusCode::RequestOutdated,
977                )))),
978                location: Location::default(),
979            },
980            location: Location::default(),
981        };
982
983        let status: tonic::Status = error.into();
984        assert_eq!(status.code(), tonic::Code::InvalidArgument);
985        assert_eq!(
986            status
987                .metadata()
988                .get(GREPTIME_DB_HEADER_ERROR_CODE)
989                .unwrap()
990                .to_str()
991                .unwrap(),
992            (StatusCode::RequestOutdated as u32).to_string()
993        );
994    }
995
996    #[tokio::test]
997    async fn test_storage_write_retry_hints_reach_tonic_status() {
998        for hint in [
999            RetryHint::NonRetryable,
1000            RetryHint::Retryable,
1001            RetryHint::RetryAfterRouteRefresh,
1002        ] {
1003            let source =
1004                BoxedError::new(MockError::new(StatusCode::RequestOutdated).with_retry_hint(hint));
1005            let completion = common_query::WriteCompletion::new(std::future::ready(Err(source)));
1006            let error = Error::ExecuteGrpcQuery {
1007                source: completion.wait().await.unwrap_err(),
1008                location: Location::default(),
1009            };
1010            let status: tonic::Status = error.into();
1011            assert_eq!(status.code(), tonic::Code::InvalidArgument);
1012            assert_eq!(
1013                status
1014                    .metadata()
1015                    .get(GREPTIME_DB_HEADER_ERROR_CODE)
1016                    .unwrap()
1017                    .to_str()
1018                    .unwrap(),
1019                (StatusCode::RequestOutdated as u32).to_string()
1020            );
1021            assert_eq!(
1022                status
1023                    .metadata()
1024                    .get(GREPTIME_DB_HEADER_ERROR_RETRY_HINT)
1025                    .unwrap()
1026                    .to_str()
1027                    .unwrap(),
1028                hint.as_str()
1029            );
1030        }
1031    }
1032}