Skip to main content

common_meta/
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::str::Utf8Error;
16use std::sync::Arc;
17
18use common_error::ext::{BoxedError, ErrorExt, RetryHint};
19use common_error::status_code::StatusCode;
20use common_macro::stack_trace_debug;
21use common_procedure::ProcedureId;
22use common_wal::kafka::rskafka_client_error_to_retry_hint;
23use object_store::error::retry_hint_from_opendal_error;
24use serde_json::error::Error as JsonError;
25use snafu::{Location, Snafu};
26use store_api::storage::RegionId;
27use table::metadata::TableId;
28
29use crate::DatanodeId;
30use crate::peer::Peer;
31
32mod retry_hint;
33
34pub use retry_hint::retry_hint_from_etcd_error;
35#[cfg(feature = "mysql_kvbackend")]
36pub use retry_hint::retry_hint_from_sqlx_error;
37#[cfg(feature = "pg_kvbackend")]
38pub use retry_hint::{retry_hint_from_postgres_error, retry_hint_from_postgres_pool_error};
39
40#[derive(Snafu)]
41#[snafu(visibility(pub))]
42#[stack_trace_debug]
43pub enum Error {
44    #[snafu(display("Failed to execute batch request"))]
45    BatchRequest { source: Arc<Error> },
46
47    #[snafu(display(
48        "Region request has {} failed entries; {}",
49        response.failures.len(),
50        response.first_failure().map(|(index, error)| format!("entry {index}: {}", error.output_msg())).unwrap_or_default()
51    ))]
52    PartialRegion {
53        response: Box<api::region::BatchRegionResponse<Error>>,
54    },
55
56    #[snafu(display("Empty key is not allowed"))]
57    EmptyKey {
58        #[snafu(implicit)]
59        location: Location,
60    },
61
62    #[snafu(display(
63        "Another procedure is operating the region: {} on peer: {}",
64        region_id,
65        peer_id
66    ))]
67    RegionOperatingRace {
68        #[snafu(implicit)]
69        location: Location,
70        peer_id: DatanodeId,
71        region_id: RegionId,
72    },
73
74    #[snafu(display("Failed to connect to Etcd"))]
75    ConnectEtcd {
76        #[snafu(source)]
77        error: etcd_client::Error,
78        #[snafu(implicit)]
79        location: Location,
80    },
81
82    #[snafu(display("Failed to execute via Etcd"))]
83    EtcdFailed {
84        #[snafu(source)]
85        error: etcd_client::Error,
86        #[snafu(implicit)]
87        location: Location,
88    },
89
90    #[snafu(display("Failed to execute {} txn operations via Etcd", max_operations))]
91    EtcdTxnFailed {
92        max_operations: usize,
93        #[snafu(source)]
94        error: etcd_client::Error,
95        #[snafu(implicit)]
96        location: Location,
97    },
98
99    #[snafu(display("Failed to get sequence: {}", err_msg))]
100    NextSequence {
101        err_msg: String,
102        #[snafu(implicit)]
103        location: Location,
104    },
105
106    #[snafu(display("Unexpected sequence value: {}", err_msg))]
107    UnexpectedSequenceValue {
108        err_msg: String,
109        #[snafu(implicit)]
110        location: Location,
111    },
112
113    #[snafu(display("Table info not found: {}", table))]
114    TableInfoNotFound {
115        table: String,
116        #[snafu(implicit)]
117        location: Location,
118    },
119
120    #[snafu(display("Failed to register procedure loader, type name: {}", type_name))]
121    RegisterProcedureLoader {
122        type_name: String,
123        #[snafu(implicit)]
124        location: Location,
125        source: common_procedure::error::Error,
126    },
127
128    #[snafu(display("Failed to register repartition procedure loader"))]
129    RegisterRepartitionProcedureLoader {
130        #[snafu(implicit)]
131        location: Location,
132        source: BoxedError,
133    },
134
135    #[snafu(display("Failed to create repartition procedure"))]
136    CreateRepartitionProcedure {
137        source: BoxedError,
138        #[snafu(implicit)]
139        location: Location,
140    },
141
142    #[snafu(display("Failed to persist the repartition GC requirement"))]
143    PersistRepartitionGcRequirement {
144        source: BoxedError,
145        #[snafu(implicit)]
146        location: Location,
147    },
148
149    #[snafu(display("Failed to submit procedure"))]
150    SubmitProcedure {
151        #[snafu(implicit)]
152        location: Location,
153        source: common_procedure::Error,
154    },
155
156    #[snafu(display("Failed to query procedure"))]
157    QueryProcedure {
158        #[snafu(implicit)]
159        location: Location,
160        source: common_procedure::Error,
161    },
162
163    #[snafu(display("Procedure not found: {pid}"))]
164    ProcedureNotFound {
165        #[snafu(implicit)]
166        location: Location,
167        pid: String,
168    },
169
170    #[snafu(display("Failed to parse procedure id: {key}"))]
171    ParseProcedureId {
172        #[snafu(implicit)]
173        location: Location,
174        key: String,
175        #[snafu(source)]
176        error: common_procedure::ParseIdError,
177    },
178
179    #[snafu(display("Unsupported operation {}", operation))]
180    Unsupported {
181        operation: String,
182        #[snafu(implicit)]
183        location: Location,
184    },
185
186    #[snafu(display("Trying to write to a read-only kv backend: {}", name))]
187    ReadOnlyKvBackend {
188        name: String,
189        #[snafu(implicit)]
190        location: Location,
191    },
192
193    #[snafu(display("Failed to get procedure state receiver, procedure id: {procedure_id}"))]
194    ProcedureStateReceiver {
195        procedure_id: ProcedureId,
196        #[snafu(implicit)]
197        location: Location,
198        source: common_procedure::Error,
199    },
200
201    #[snafu(display("Procedure state receiver not found: {procedure_id}"))]
202    ProcedureStateReceiverNotFound {
203        procedure_id: ProcedureId,
204        #[snafu(implicit)]
205        location: Location,
206    },
207
208    #[snafu(display("Failed to wait procedure done"))]
209    WaitProcedure {
210        #[snafu(implicit)]
211        location: Location,
212        source: common_procedure::Error,
213    },
214
215    #[snafu(display(
216        "DDL request timed out after {timeout:?}; a submitted procedure may still be running"
217    ))]
218    DdlTaskTimeout {
219        timeout: std::time::Duration,
220        #[snafu(implicit)]
221        location: Location,
222    },
223
224    #[snafu(display("Failed to start procedure manager"))]
225    StartProcedureManager {
226        #[snafu(implicit)]
227        location: Location,
228        source: common_procedure::Error,
229    },
230
231    #[snafu(display("Failed to stop procedure manager"))]
232    StopProcedureManager {
233        #[snafu(implicit)]
234        location: Location,
235        source: common_procedure::Error,
236    },
237
238    #[snafu(display(
239        "Failed to get procedure output, procedure id: {procedure_id}, error: {err_msg}"
240    ))]
241    ProcedureOutput {
242        procedure_id: String,
243        err_msg: String,
244        #[snafu(implicit)]
245        location: Location,
246    },
247
248    #[snafu(display("Primary key '{key}' not found when creating region request"))]
249    PrimaryKeyNotFound {
250        key: String,
251        #[snafu(implicit)]
252        location: Location,
253    },
254
255    #[snafu(display("Failed to build table meta for table: {}", table_name))]
256    BuildTableMeta {
257        table_name: String,
258        #[snafu(source)]
259        error: table::metadata::TableMetaBuilderError,
260        #[snafu(implicit)]
261        location: Location,
262    },
263
264    #[snafu(display("Table occurs error"))]
265    Table {
266        #[snafu(implicit)]
267        location: Location,
268        source: table::error::Error,
269    },
270
271    #[snafu(display("Failed to find table route for table id {}", table_id))]
272    TableRouteNotFound {
273        table_id: TableId,
274        #[snafu(implicit)]
275        location: Location,
276    },
277
278    #[snafu(display("Failed to find table repartition metadata for table id {}", table_id))]
279    TableRepartNotFound {
280        table_id: TableId,
281        #[snafu(implicit)]
282        location: Location,
283    },
284
285    #[snafu(display("Failed to decode packed file references"))]
286    DecodePackedFileRefs {
287        #[snafu(implicit)]
288        location: Location,
289        #[snafu(source)]
290        error: base64::DecodeError,
291    },
292
293    #[snafu(display("Invalid packed file references framing"))]
294    InvalidPackedFileRefs {
295        #[snafu(implicit)]
296        location: Location,
297    },
298
299    #[snafu(display("Failed to encode object into json"))]
300    EncodeJson {
301        #[snafu(implicit)]
302        location: Location,
303        #[snafu(source)]
304        error: JsonError,
305    },
306
307    #[snafu(display("Failed to decode object from json"))]
308    DecodeJson {
309        #[snafu(implicit)]
310        location: Location,
311        #[snafu(source)]
312        error: JsonError,
313    },
314
315    #[snafu(display("Failed to serialize to json: {}", input))]
316    SerializeToJson {
317        input: String,
318        #[snafu(source)]
319        error: serde_json::error::Error,
320        #[snafu(implicit)]
321        location: Location,
322    },
323
324    #[snafu(display("Failed to deserialize from json: {}", input))]
325    DeserializeFromJson {
326        input: String,
327        #[snafu(source)]
328        error: serde_json::error::Error,
329        #[snafu(implicit)]
330        location: Location,
331    },
332
333    #[snafu(display("Payload not exist"))]
334    PayloadNotExist {
335        #[snafu(implicit)]
336        location: Location,
337    },
338
339    #[snafu(display("Failed to serde json"))]
340    SerdeJson {
341        #[snafu(source)]
342        error: serde_json::error::Error,
343        #[snafu(implicit)]
344        location: Location,
345    },
346
347    #[snafu(display("Failed to parse value {} into key {}", value, key))]
348    ParseOption {
349        key: String,
350        value: String,
351        #[snafu(implicit)]
352        location: Location,
353    },
354
355    #[snafu(display(
356        "Conflicting schema options: {}={} and {}={}",
357        first_key,
358        first_value,
359        second_key,
360        second_value
361    ))]
362    ConflictingSchemaOptions {
363        first_key: String,
364        first_value: String,
365        second_key: String,
366        second_value: String,
367        #[snafu(implicit)]
368        location: Location,
369    },
370
371    #[snafu(display("Illegal state from server, code: {}, error: {}", code, err_msg))]
372    IllegalServerState {
373        code: i32,
374        err_msg: String,
375        #[snafu(implicit)]
376        location: Location,
377    },
378
379    #[snafu(display("Failed to convert alter table request"))]
380    ConvertAlterTableRequest {
381        source: common_grpc_expr::error::Error,
382        #[snafu(implicit)]
383        location: Location,
384    },
385
386    #[snafu(display("Invalid protobuf message: {err_msg}"))]
387    InvalidProtoMsg {
388        err_msg: String,
389        #[snafu(implicit)]
390        location: Location,
391    },
392
393    #[snafu(display("Unexpected: {err_msg}"))]
394    Unexpected {
395        err_msg: String,
396        #[snafu(implicit)]
397        location: Location,
398    },
399
400    #[snafu(display("Metasrv election has no leader at this moment"))]
401    ElectionNoLeader {
402        #[snafu(implicit)]
403        location: Location,
404    },
405
406    #[snafu(display("Metasrv election leader lease expired"))]
407    ElectionLeaderLeaseExpired {
408        #[snafu(implicit)]
409        location: Location,
410    },
411
412    #[snafu(display("Metasrv election leader lease changed during election"))]
413    ElectionLeaderLeaseChanged {
414        #[snafu(implicit)]
415        location: Location,
416    },
417
418    #[snafu(display("Table already exists, table: {}", table_name))]
419    TableAlreadyExists {
420        table_name: String,
421        #[snafu(implicit)]
422        location: Location,
423    },
424
425    #[snafu(display(
426        "Cannot drop table '{}': an older tombstone already uses the same full name",
427        table_name
428    ))]
429    /// Raised when a live table is recreated with a name still reserved by an older tombstone.
430    TableNameTombstoneConflict {
431        table_name: String,
432        existing_table_id: TableId,
433        dropping_table_id: TableId,
434        #[snafu(implicit)]
435        location: Location,
436    },
437
438    #[snafu(display("View already exists, view: {}", view_name))]
439    ViewAlreadyExists {
440        view_name: String,
441        #[snafu(implicit)]
442        location: Location,
443    },
444
445    #[snafu(display("Flow already exists: {}", flow_name))]
446    FlowAlreadyExists {
447        flow_name: String,
448        #[snafu(implicit)]
449        location: Location,
450    },
451
452    #[snafu(display("Schema already exists, catalog:{}, schema: {}", catalog, schema))]
453    SchemaAlreadyExists {
454        catalog: String,
455        schema: String,
456        #[snafu(implicit)]
457        location: Location,
458    },
459
460    #[snafu(display("Failed to convert raw key to str"))]
461    ConvertRawKey {
462        #[snafu(implicit)]
463        location: Location,
464        #[snafu(source)]
465        error: Utf8Error,
466    },
467
468    #[snafu(display("Table not found: '{}'", table_name))]
469    TableNotFound {
470        table_name: String,
471        #[snafu(implicit)]
472        location: Location,
473    },
474
475    #[snafu(display("Region not found: {}", region_id))]
476    RegionNotFound {
477        region_id: RegionId,
478        #[snafu(implicit)]
479        location: Location,
480    },
481
482    #[snafu(display("View not found: '{}'", view_name))]
483    ViewNotFound {
484        view_name: String,
485        #[snafu(implicit)]
486        location: Location,
487    },
488
489    #[snafu(display("Flow not found: '{}'", flow_name))]
490    FlowNotFound {
491        flow_name: String,
492        #[snafu(implicit)]
493        location: Location,
494    },
495
496    #[snafu(display("Flow route not found: '{}'", flow_name))]
497    FlowRouteNotFound {
498        flow_name: String,
499        #[snafu(implicit)]
500        location: Location,
501    },
502
503    #[snafu(display("Schema nod found, schema: {}", table_schema))]
504    SchemaNotFound {
505        table_schema: String,
506        #[snafu(implicit)]
507        location: Location,
508    },
509
510    #[snafu(display("Catalog not found, catalog: {}", catalog))]
511    CatalogNotFound {
512        catalog: String,
513        #[snafu(implicit)]
514        location: Location,
515    },
516
517    #[snafu(display("Invalid metadata, err: {}", err_msg))]
518    InvalidMetadata {
519        err_msg: String,
520        #[snafu(implicit)]
521        location: Location,
522    },
523
524    #[snafu(display("Invalid view info, err: {}", err_msg))]
525    InvalidViewInfo {
526        err_msg: String,
527        #[snafu(implicit)]
528        location: Location,
529    },
530
531    #[snafu(display("Invalid SQL, error: {err_msg}"))]
532    InvalidFlowOption {
533        err_msg: String,
534        #[snafu(implicit)]
535        location: Location,
536    },
537
538    #[snafu(display("Invalid flow request body: {:?}", body))]
539    InvalidFlowRequestBody {
540        body: Box<Option<api::v1::flow::flow_request::Body>>,
541        #[snafu(implicit)]
542        location: Location,
543    },
544
545    #[snafu(display("Failed to get kv cache, err: {}", err_msg))]
546    GetKvCache { err_msg: String },
547
548    #[snafu(display("Get null from cache, key: {}", key))]
549    CacheNotGet {
550        key: String,
551        #[snafu(implicit)]
552        location: Location,
553    },
554
555    #[snafu(display("Etcd txn error: {err_msg}"))]
556    EtcdTxnOpResponse {
557        err_msg: String,
558        #[snafu(implicit)]
559        location: Location,
560    },
561
562    #[snafu(display("External error"))]
563    External {
564        #[snafu(implicit)]
565        location: Location,
566        source: BoxedError,
567    },
568
569    #[snafu(display("The response exceeded size limit"))]
570    ResponseExceededSizeLimit {
571        #[snafu(implicit)]
572        location: Location,
573        source: BoxedError,
574    },
575
576    #[snafu(display("Invalid heartbeat response"))]
577    InvalidHeartbeatResponse {
578        #[snafu(implicit)]
579        location: Location,
580    },
581
582    #[snafu(display("Failed to operate on datanode: {}", peer))]
583    OperateDatanode {
584        #[snafu(implicit)]
585        location: Location,
586        peer: Peer,
587        source: BoxedError,
588    },
589
590    #[snafu(display("Retry later"))]
591    RetryLater {
592        source: BoxedError,
593        clean_poisons: bool,
594    },
595
596    #[snafu(display("Abort procedure"))]
597    AbortProcedure {
598        #[snafu(implicit)]
599        location: Location,
600        source: BoxedError,
601        clean_poisons: bool,
602    },
603
604    #[snafu(display("Failed to serialize WAL options for region: {region_id}"))]
605    SerializeWalOptions {
606        region_id: RegionId,
607        #[snafu(source)]
608        error: serde_json::Error,
609        #[snafu(implicit)]
610        location: Location,
611    },
612
613    #[snafu(display("Invalid number of topics {}", num_topics))]
614    InvalidNumTopics {
615        num_topics: usize,
616        #[snafu(implicit)]
617        location: Location,
618    },
619
620    #[snafu(display(
621        "Failed to build a Kafka client, broker endpoints: {:?}",
622        broker_endpoints
623    ))]
624    BuildKafkaClient {
625        broker_endpoints: Vec<String>,
626        #[snafu(implicit)]
627        location: Location,
628        #[snafu(source)]
629        error: rskafka::client::error::Error,
630    },
631
632    #[snafu(display("Failed to create TLS Config"))]
633    TlsConfig {
634        #[snafu(implicit)]
635        location: Location,
636        source: common_wal::error::Error,
637    },
638
639    #[snafu(display("Failed to build a Kafka controller client"))]
640    BuildKafkaCtrlClient {
641        #[snafu(implicit)]
642        location: Location,
643        #[snafu(source)]
644        error: rskafka::client::error::Error,
645    },
646
647    #[snafu(display(
648        "Failed to get a Kafka partition client, topic: {}, partition: {}",
649        topic,
650        partition
651    ))]
652    KafkaPartitionClient {
653        topic: String,
654        partition: i32,
655        #[snafu(implicit)]
656        location: Location,
657        #[snafu(source)]
658        error: rskafka::client::error::Error,
659    },
660
661    #[snafu(display(
662        "Failed to get offset from Kafka, topic: {}, partition: {}",
663        topic,
664        partition
665    ))]
666    KafkaGetOffset {
667        topic: String,
668        partition: i32,
669        #[snafu(implicit)]
670        location: Location,
671        #[snafu(source)]
672        error: rskafka::client::error::Error,
673    },
674
675    #[snafu(display("Failed to produce records to Kafka, topic: {}", topic))]
676    ProduceRecord {
677        topic: String,
678        #[snafu(implicit)]
679        location: Location,
680        #[snafu(source)]
681        error: rskafka::client::error::Error,
682    },
683
684    #[snafu(display("Failed to create a Kafka wal topic"))]
685    CreateKafkaWalTopic {
686        #[snafu(implicit)]
687        location: Location,
688        #[snafu(source)]
689        error: rskafka::client::error::Error,
690    },
691
692    #[snafu(display("The topic pool is empty"))]
693    EmptyTopicPool {
694        #[snafu(implicit)]
695        location: Location,
696    },
697
698    #[snafu(display("Unexpected table route type: {}", err_msg))]
699    UnexpectedLogicalRouteTable {
700        #[snafu(implicit)]
701        location: Location,
702        err_msg: String,
703    },
704
705    #[snafu(display("The tasks of {} cannot be empty", name))]
706    EmptyDdlTasks {
707        name: String,
708        #[snafu(implicit)]
709        location: Location,
710    },
711
712    #[snafu(display("Metadata corruption: {}", err_msg))]
713    MetadataCorruption {
714        err_msg: String,
715        #[snafu(implicit)]
716        location: Location,
717    },
718
719    #[snafu(display("Alter logical tables invalid arguments: {}", err_msg))]
720    AlterLogicalTablesInvalidArguments {
721        err_msg: String,
722        #[snafu(implicit)]
723        location: Location,
724    },
725
726    #[snafu(display("Create logical tables invalid arguments: {}", err_msg))]
727    CreateLogicalTablesInvalidArguments {
728        err_msg: String,
729        #[snafu(implicit)]
730        location: Location,
731    },
732
733    #[snafu(display("Invalid node info key: {}", key))]
734    InvalidNodeInfoKey {
735        key: String,
736        #[snafu(implicit)]
737        location: Location,
738    },
739
740    #[snafu(display("Invalid node stat key: {}", key))]
741    InvalidStatKey {
742        key: String,
743        #[snafu(implicit)]
744        location: Location,
745    },
746
747    #[snafu(display("Failed to parse number: {}", err_msg))]
748    ParseNum {
749        err_msg: String,
750        #[snafu(source)]
751        error: std::num::ParseIntError,
752        #[snafu(implicit)]
753        location: Location,
754    },
755
756    #[snafu(display("Invalid role: {}", role))]
757    InvalidRole {
758        role: i32,
759        #[snafu(implicit)]
760        location: Location,
761    },
762
763    #[snafu(display("Invalid set database option, key: {}, value: {}", key, value))]
764    InvalidSetDatabaseOption {
765        key: String,
766        value: String,
767        #[snafu(implicit)]
768        location: Location,
769    },
770
771    #[snafu(display("Invalid unset database option, key: {}", key))]
772    InvalidUnsetDatabaseOption {
773        key: String,
774        #[snafu(implicit)]
775        location: Location,
776    },
777
778    #[snafu(display("Invalid prefix: {}, key: {}", prefix, key))]
779    MismatchPrefix {
780        prefix: String,
781        key: String,
782        #[snafu(implicit)]
783        location: Location,
784    },
785
786    #[snafu(display("Failed to move values: {err_msg}"))]
787    MoveValues {
788        err_msg: String,
789        #[snafu(implicit)]
790        location: Location,
791    },
792
793    #[snafu(display("Failed to restore tombstone, target key already exists: {key}"))]
794    TombstoneTargetAlreadyExists {
795        key: String,
796        #[snafu(implicit)]
797        location: Location,
798    },
799
800    #[snafu(display("Failed to parse {} from utf8", name))]
801    FromUtf8 {
802        name: String,
803        #[snafu(source)]
804        error: std::string::FromUtf8Error,
805        #[snafu(implicit)]
806        location: Location,
807    },
808
809    #[snafu(display("Value not exists"))]
810    ValueNotExist {
811        #[snafu(implicit)]
812        location: Location,
813    },
814
815    #[snafu(display("Failed to get cache"))]
816    GetCache { source: Arc<Error> },
817
818    #[snafu(display(
819        "Failed to get latest cache value after {} attempts due to concurrent invalidation",
820        attempts
821    ))]
822    GetLatestCacheRetryExceeded {
823        attempts: usize,
824        #[snafu(implicit)]
825        location: Location,
826    },
827
828    #[cfg(feature = "pg_kvbackend")]
829    #[snafu(display("Failed to execute via Postgres, sql: {}", sql))]
830    PostgresExecution {
831        sql: String,
832        #[snafu(source)]
833        error: tokio_postgres::Error,
834        #[snafu(implicit)]
835        location: Location,
836    },
837
838    #[cfg(feature = "pg_kvbackend")]
839    #[snafu(display("Failed to create connection pool for Postgres"))]
840    CreatePostgresPool {
841        #[snafu(source)]
842        error: deadpool_postgres::CreatePoolError,
843        #[snafu(implicit)]
844        location: Location,
845    },
846
847    #[cfg(feature = "pg_kvbackend")]
848    #[snafu(display("Failed to get Postgres connection from pool: {}", reason))]
849    GetPostgresConnection {
850        reason: String,
851        #[snafu(implicit)]
852        location: Location,
853    },
854
855    #[cfg(feature = "pg_kvbackend")]
856    #[snafu(display("Failed to get Postgres client"))]
857    GetPostgresClient {
858        #[snafu(source)]
859        error: deadpool::managed::PoolError<tokio_postgres::Error>,
860        #[snafu(implicit)]
861        location: Location,
862    },
863
864    #[cfg(feature = "pg_kvbackend")]
865    #[snafu(display("Failed to {} Postgres transaction", operation))]
866    PostgresTransaction {
867        #[snafu(source)]
868        error: tokio_postgres::Error,
869        #[snafu(implicit)]
870        location: Location,
871        operation: String,
872    },
873
874    #[cfg(feature = "pg_kvbackend")]
875    #[snafu(display("Failed to setup PostgreSQL TLS configuration: {}", reason))]
876    PostgresTlsConfig {
877        reason: String,
878        #[snafu(implicit)]
879        location: Location,
880    },
881
882    #[snafu(display("Failed to load TLS certificate from path: {}", path))]
883    LoadTlsCertificate {
884        path: String,
885        #[snafu(source)]
886        error: std::io::Error,
887        #[snafu(implicit)]
888        location: Location,
889    },
890
891    #[cfg(feature = "mysql_kvbackend")]
892    #[snafu(display("Failed to execute via MySql, sql: {}", sql))]
893    MySqlExecution {
894        sql: String,
895        #[snafu(source)]
896        error: sqlx::Error,
897        #[snafu(implicit)]
898        location: Location,
899    },
900
901    #[cfg(feature = "mysql_kvbackend")]
902    #[snafu(display("Failed to create connection pool for MySql"))]
903    CreateMySqlPool {
904        #[snafu(source)]
905        error: sqlx::Error,
906        #[snafu(implicit)]
907        location: Location,
908    },
909
910    #[cfg(feature = "mysql_kvbackend")]
911    #[snafu(display("Failed to decode sql value"))]
912    DecodeSqlValue {
913        #[snafu(source)]
914        error: sqlx::error::Error,
915        #[snafu(implicit)]
916        location: Location,
917    },
918
919    #[cfg(feature = "mysql_kvbackend")]
920    #[snafu(display("Failed to acquire mysql client from pool"))]
921    AcquireMySqlClient {
922        #[snafu(source)]
923        error: sqlx::Error,
924        #[snafu(implicit)]
925        location: Location,
926    },
927
928    #[cfg(feature = "mysql_kvbackend")]
929    #[snafu(display("Failed to {} MySql transaction", operation))]
930    MySqlTransaction {
931        #[snafu(source)]
932        error: sqlx::Error,
933        #[snafu(implicit)]
934        location: Location,
935        operation: String,
936    },
937
938    #[cfg(any(feature = "pg_kvbackend", feature = "mysql_kvbackend"))]
939    #[snafu(display("Rds transaction retry failed"))]
940    RdsTransactionRetryFailed {
941        #[snafu(implicit)]
942        location: Location,
943    },
944
945    #[cfg(any(feature = "pg_kvbackend", feature = "mysql_kvbackend"))]
946    #[snafu(display("Sql execution timeout, sql: {}, duration: {:?}", sql, duration))]
947    SqlExecutionTimeout {
948        sql: String,
949        duration: std::time::Duration,
950        #[snafu(implicit)]
951        location: Location,
952    },
953
954    #[snafu(display(
955        "Datanode table info not found, table id: {}, datanode id: {}",
956        table_id,
957        datanode_id
958    ))]
959    DatanodeTableInfoNotFound {
960        datanode_id: DatanodeId,
961        table_id: TableId,
962        #[snafu(implicit)]
963        location: Location,
964    },
965
966    #[snafu(display("Invalid object store WAL prefix {:?}: {}", prefix, reason))]
967    InvalidObjectStoreWalPrefix {
968        prefix: String,
969        reason: &'static str,
970        #[snafu(implicit)]
971        location: Location,
972    },
973
974    #[snafu(display("Invalid topic name prefix: {}", prefix))]
975    InvalidTopicNamePrefix {
976        prefix: String,
977        #[snafu(implicit)]
978        location: Location,
979    },
980
981    #[snafu(display("No leader found for table_id: {}", table_id))]
982    NoLeader {
983        table_id: TableId,
984        #[snafu(implicit)]
985        location: Location,
986    },
987
988    #[snafu(display(
989        "Procedure poison key already exists with a different value, key: {}, value: {}",
990        key,
991        value
992    ))]
993    ProcedurePoisonConflict {
994        key: String,
995        value: String,
996        #[snafu(implicit)]
997        location: Location,
998    },
999
1000    #[snafu(display("Failed to put poison, table metadata may be corrupted"))]
1001    PutPoison {
1002        #[snafu(implicit)]
1003        location: Location,
1004        #[snafu(source)]
1005        source: common_procedure::error::Error,
1006    },
1007
1008    #[snafu(display("Invalid file path: {}", file_path))]
1009    InvalidFilePath {
1010        #[snafu(implicit)]
1011        location: Location,
1012        file_path: String,
1013    },
1014
1015    #[snafu(display("Failed to serialize flexbuffers"))]
1016    SerializeFlexbuffers {
1017        #[snafu(implicit)]
1018        location: Location,
1019        #[snafu(source)]
1020        error: flexbuffers::SerializationError,
1021    },
1022
1023    #[snafu(display("Failed to deserialize flexbuffers"))]
1024    DeserializeFlexbuffers {
1025        #[snafu(implicit)]
1026        location: Location,
1027        #[snafu(source)]
1028        error: flexbuffers::DeserializationError,
1029    },
1030
1031    #[snafu(display("Failed to read flexbuffers"))]
1032    ReadFlexbuffers {
1033        #[snafu(implicit)]
1034        location: Location,
1035        #[snafu(source)]
1036        error: flexbuffers::ReaderError,
1037    },
1038
1039    #[snafu(display("Invalid file name: {}", reason))]
1040    InvalidFileName {
1041        #[snafu(implicit)]
1042        location: Location,
1043        reason: String,
1044    },
1045
1046    #[snafu(display("Invalid file extension: {}", reason))]
1047    InvalidFileExtension {
1048        #[snafu(implicit)]
1049        location: Location,
1050        reason: String,
1051    },
1052
1053    #[snafu(display("Failed to {} Authority Head JSON", operation))]
1054    AuthorityFormat {
1055        operation: &'static str,
1056        #[snafu(source)]
1057        error: serde_json::Error,
1058        #[snafu(implicit)]
1059        location: Location,
1060    },
1061
1062    #[snafu(display("Failed to decode Authority Head at {}", path))]
1063    AuthorityReadHead {
1064        path: String,
1065        source: BoxedError,
1066        #[snafu(implicit)]
1067        location: Location,
1068    },
1069
1070    #[snafu(display("Unsupported Authority Head format version: {}", version))]
1071    AuthorityVersion {
1072        version: u32,
1073        #[snafu(implicit)]
1074        location: Location,
1075    },
1076
1077    #[snafu(display("Authority Head counter overflow: {}", counter))]
1078    AuthorityOverflow {
1079        counter: &'static str,
1080        #[snafu(implicit)]
1081        location: Location,
1082    },
1083
1084    #[snafu(display("Authority Head is missing at {}; operator recovery is required", path))]
1085    AuthorityMissing {
1086        path: String,
1087        #[snafu(source)]
1088        error: object_store::Error,
1089        #[snafu(implicit)]
1090        location: Location,
1091    },
1092
1093    #[snafu(display("Authority Head metadata is unusable: {}", reason))]
1094    AuthorityMetadata {
1095        reason: &'static str,
1096        #[snafu(implicit)]
1097        location: Location,
1098    },
1099
1100    #[snafu(display(
1101        "Object store {} is not admitted for Authority Head: {}",
1102        scheme,
1103        reason
1104    ))]
1105    AuthorityCapability {
1106        scheme: &'static str,
1107        reason: &'static str,
1108        #[snafu(implicit)]
1109        location: Location,
1110    },
1111
1112    #[snafu(display("Authority storage probe failed: {}", reason))]
1113    AuthorityProbe {
1114        reason: &'static str,
1115        #[snafu(implicit)]
1116        location: Location,
1117    },
1118
1119    #[snafu(display("Authority storage request failed: {}", operation))]
1120    AuthorityStorage {
1121        operation: &'static str,
1122        #[snafu(source)]
1123        error: object_store::Error,
1124        #[snafu(implicit)]
1125        location: Location,
1126    },
1127
1128    #[snafu(display("Authority is closed"))]
1129    AuthorityClosed {
1130        #[snafu(implicit)]
1131        location: Location,
1132    },
1133
1134    #[snafu(display("Authority Head requires operator recovery"))]
1135    AuthorityRecoveryRequired {
1136        #[snafu(implicit)]
1137        location: Location,
1138    },
1139
1140    #[snafu(display("Authority operation was not executed: {}", reason))]
1141    AuthorityRejected {
1142        reason: &'static str,
1143        #[snafu(implicit)]
1144        location: Location,
1145    },
1146
1147    #[snafu(display(
1148        "Authority Head write sequence mismatch: expected {}, actual {}",
1149        expected,
1150        actual
1151    ))]
1152    AuthorityWriteSeqMismatch {
1153        expected: u64,
1154        actual: u64,
1155        #[snafu(implicit)]
1156        location: Location,
1157    },
1158
1159    #[snafu(display("Authority {} timed out", operation))]
1160    AuthorityTimeout {
1161        operation: &'static str,
1162        #[snafu(implicit)]
1163        location: Location,
1164    },
1165
1166    #[snafu(display("Authority PUT outcome is unknown"))]
1167    AuthorityUnknown {
1168        source: Box<Error>,
1169        #[snafu(implicit)]
1170        location: Location,
1171    },
1172
1173    #[snafu(display("Failed to open Authority storage"))]
1174    AuthorityOpen {
1175        #[snafu(source)]
1176        error: object_store::error::Error,
1177        #[snafu(implicit)]
1178        location: Location,
1179    },
1180
1181    #[snafu(display("Failed to write object, file path: {}", file_path))]
1182    WriteObject {
1183        #[snafu(implicit)]
1184        location: Location,
1185        file_path: String,
1186        #[snafu(source)]
1187        error: object_store::Error,
1188    },
1189
1190    #[snafu(display("Failed to read object, file path: {}", file_path))]
1191    ReadObject {
1192        #[snafu(implicit)]
1193        location: Location,
1194        file_path: String,
1195        #[snafu(source)]
1196        error: object_store::Error,
1197    },
1198
1199    #[snafu(display("Missing column ids"))]
1200    MissingColumnIds {
1201        #[snafu(implicit)]
1202        location: Location,
1203    },
1204
1205    #[snafu(display(
1206        "Missing column in column metadata: {}, table: {}, table_id: {}",
1207        column_name,
1208        table_name,
1209        table_id,
1210    ))]
1211    MissingColumnInColumnMetadata {
1212        column_name: String,
1213        #[snafu(implicit)]
1214        location: Location,
1215        table_name: String,
1216        table_id: TableId,
1217    },
1218
1219    #[snafu(display(
1220        "Mismatch column id: column_name: {}, column_id: {}, table: {}, table_id: {}",
1221        column_name,
1222        column_id,
1223        table_name,
1224        table_id,
1225    ))]
1226    MismatchColumnId {
1227        column_name: String,
1228        column_id: u32,
1229        #[snafu(implicit)]
1230        location: Location,
1231        table_name: String,
1232        table_id: TableId,
1233    },
1234
1235    #[snafu(display("Failed to convert column def, column: {}", column))]
1236    ConvertColumnDef {
1237        column: String,
1238        #[snafu(implicit)]
1239        location: Location,
1240        source: api::error::Error,
1241    },
1242
1243    #[snafu(display("Failed to convert time ranges"))]
1244    ConvertTimeRanges {
1245        #[snafu(implicit)]
1246        location: Location,
1247        source: api::error::Error,
1248    },
1249
1250    #[snafu(display(
1251        "Column metadata inconsistencies found in table: {}, table_id: {}",
1252        table_name,
1253        table_id
1254    ))]
1255    ColumnMetadataConflicts {
1256        table_name: String,
1257        table_id: TableId,
1258    },
1259
1260    #[snafu(display(
1261        "Column not found in column metadata, column_name: {}, column_id: {}",
1262        column_name,
1263        column_id
1264    ))]
1265    ColumnNotFound { column_name: String, column_id: u32 },
1266
1267    #[snafu(display(
1268        "Column id mismatch, column_name: {}, expected column_id: {}, actual column_id: {}",
1269        column_name,
1270        expected_column_id,
1271        actual_column_id
1272    ))]
1273    ColumnIdMismatch {
1274        column_name: String,
1275        expected_column_id: u32,
1276        actual_column_id: u32,
1277    },
1278
1279    #[snafu(display(
1280        "Timestamp column mismatch, expected column_name: {}, expected column_id: {}, actual column_name: {}, actual column_id: {}",
1281        expected_column_name,
1282        expected_column_id,
1283        actual_column_name,
1284        actual_column_id,
1285    ))]
1286    TimestampMismatch {
1287        expected_column_name: String,
1288        expected_column_id: u32,
1289        actual_column_name: String,
1290        actual_column_id: u32,
1291    },
1292
1293    #[snafu(display(
1294        "Partition expression of region {} is incompatible with the altered column '{}': the persisted bound can no longer be compared with the new column type {}",
1295        region_id,
1296        column,
1297        target_type
1298    ))]
1299    PartitionExprIncompatible {
1300        region_id: RegionId,
1301        column: String,
1302        target_type: String,
1303        #[snafu(implicit)]
1304        location: Location,
1305    },
1306
1307    #[cfg(feature = "enterprise")]
1308    #[snafu(display("Too large duration"))]
1309    TooLargeDuration {
1310        #[snafu(source)]
1311        error: prost_types::DurationError,
1312        #[snafu(implicit)]
1313        location: Location,
1314    },
1315
1316    #[cfg(feature = "enterprise")]
1317    #[snafu(display("Negative duration"))]
1318    NegativeDuration {
1319        #[snafu(source)]
1320        error: prost_types::DurationError,
1321        #[snafu(implicit)]
1322        location: Location,
1323    },
1324
1325    #[cfg(feature = "enterprise")]
1326    #[snafu(display("Missing interval field"))]
1327    MissingInterval {
1328        #[snafu(implicit)]
1329        location: Location,
1330    },
1331}
1332
1333pub type Result<T> = std::result::Result<T, Error>;
1334
1335impl ErrorExt for Error {
1336    fn status_code(&self) -> StatusCode {
1337        use Error::*;
1338        match self {
1339            Error::PartialRegion { response } => response
1340                .first_failure()
1341                .map_or(StatusCode::Internal, |(_, error)| error.status_code()),
1342            Error::BatchRequest { source } => source.status_code(),
1343            IllegalServerState { .. }
1344            | EtcdTxnOpResponse { .. }
1345            | EtcdFailed { .. }
1346            | EtcdTxnFailed { .. }
1347            | ConnectEtcd { .. }
1348            | MoveValues { .. }
1349            | TombstoneTargetAlreadyExists { .. }
1350            | GetCache { .. }
1351            | GetLatestCacheRetryExceeded { .. }
1352            | SerializeToJson { .. }
1353            | DeserializeFromJson { .. }
1354            | ElectionNoLeader { .. }
1355            | ElectionLeaderLeaseExpired { .. }
1356            | ElectionLeaderLeaseChanged { .. } => StatusCode::Internal,
1357
1358            AuthorityFormat { .. } | AuthorityVersion { .. } | AuthorityOverflow { .. } => {
1359                StatusCode::IllegalState
1360            }
1361            AuthorityReadHead { source, .. } => source.status_code(),
1362            AuthorityCapability { .. } | AuthorityProbe { .. } => StatusCode::Unsupported,
1363            AuthorityMissing { .. }
1364            | AuthorityMetadata { .. }
1365            | AuthorityStorage { .. }
1366            | AuthorityOpen { .. }
1367            | AuthorityClosed { .. }
1368            | AuthorityRecoveryRequired { .. }
1369            | AuthorityTimeout { .. }
1370            | AuthorityUnknown { .. } => StatusCode::StorageUnavailable,
1371            AuthorityRejected { .. } => StatusCode::IllegalState,
1372            AuthorityWriteSeqMismatch { .. } => StatusCode::RequestOutdated,
1373            NoLeader { .. } => StatusCode::TableUnavailable,
1374            ValueNotExist { .. }
1375            | ProcedurePoisonConflict { .. }
1376            | ProcedureStateReceiverNotFound { .. }
1377            | MissingColumnIds { .. }
1378            | MissingColumnInColumnMetadata { .. }
1379            | MismatchColumnId { .. }
1380            | ColumnMetadataConflicts { .. }
1381            | ColumnNotFound { .. }
1382            | ColumnIdMismatch { .. }
1383            | TimestampMismatch { .. } => StatusCode::Unexpected,
1384
1385            Unsupported { .. } | ReadOnlyKvBackend { .. } => StatusCode::Unsupported,
1386            WriteObject { .. } | ReadObject { .. } => StatusCode::StorageUnavailable,
1387
1388            SerdeJson { .. }
1389            | ParseOption { .. }
1390            | InvalidProtoMsg { .. }
1391            | InvalidMetadata { .. }
1392            | Unexpected { .. }
1393            | TableInfoNotFound { .. }
1394            | NextSequence { .. }
1395            | UnexpectedSequenceValue { .. }
1396            | InvalidHeartbeatResponse { .. }
1397            | EncodeJson { .. }
1398            | DecodeJson { .. }
1399            | PayloadNotExist { .. }
1400            | ConvertRawKey { .. }
1401            | DecodePackedFileRefs { .. }
1402            | InvalidPackedFileRefs { .. }
1403            | BuildTableMeta { .. }
1404            | TableRouteNotFound { .. }
1405            | TableRepartNotFound { .. }
1406            | RegionOperatingRace { .. }
1407            | SerializeWalOptions { .. }
1408            | BuildKafkaClient { .. }
1409            | BuildKafkaCtrlClient { .. }
1410            | KafkaPartitionClient { .. }
1411            | ProduceRecord { .. }
1412            | CreateKafkaWalTopic { .. }
1413            | EmptyTopicPool { .. }
1414            | UnexpectedLogicalRouteTable { .. }
1415            | ProcedureOutput { .. }
1416            | FromUtf8 { .. }
1417            | MetadataCorruption { .. }
1418            | KafkaGetOffset { .. }
1419            | ReadFlexbuffers { .. }
1420            | SerializeFlexbuffers { .. }
1421            | DeserializeFlexbuffers { .. }
1422            | ConvertTimeRanges { .. } => StatusCode::Unexpected,
1423
1424            GetKvCache { .. } | CacheNotGet { .. } => StatusCode::Internal,
1425
1426            SchemaAlreadyExists { .. } => StatusCode::DatabaseAlreadyExists,
1427
1428            ProcedureNotFound { .. }
1429            | InvalidViewInfo { .. }
1430            | InvalidFlowOption { .. }
1431            | PrimaryKeyNotFound { .. }
1432            | EmptyKey { .. }
1433            | AlterLogicalTablesInvalidArguments { .. }
1434            | CreateLogicalTablesInvalidArguments { .. }
1435            | MismatchPrefix { .. }
1436            | TlsConfig { .. }
1437            | InvalidSetDatabaseOption { .. }
1438            | InvalidUnsetDatabaseOption { .. }
1439            | InvalidTopicNamePrefix { .. }
1440            | InvalidObjectStoreWalPrefix { .. }
1441            | InvalidFileExtension { .. }
1442            | InvalidFileName { .. }
1443            | InvalidFlowRequestBody { .. }
1444            | InvalidFilePath { .. }
1445            | ConflictingSchemaOptions { .. }
1446            | PartitionExprIncompatible { .. } => StatusCode::InvalidArguments,
1447
1448            #[cfg(feature = "enterprise")]
1449            MissingInterval { .. } | NegativeDuration { .. } | TooLargeDuration { .. } => {
1450                StatusCode::InvalidArguments
1451            }
1452
1453            FlowNotFound { .. } => StatusCode::FlowNotFound,
1454            FlowRouteNotFound { .. } => StatusCode::Unexpected,
1455            FlowAlreadyExists { .. } => StatusCode::FlowAlreadyExists,
1456
1457            ViewNotFound { .. } | TableNotFound { .. } | RegionNotFound { .. } => {
1458                StatusCode::TableNotFound
1459            }
1460            ViewAlreadyExists { .. }
1461            | TableAlreadyExists { .. }
1462            | TableNameTombstoneConflict { .. } => StatusCode::TableAlreadyExists,
1463
1464            SubmitProcedure { source, .. }
1465            | QueryProcedure { source, .. }
1466            | WaitProcedure { source, .. }
1467            | StartProcedureManager { source, .. }
1468            | StopProcedureManager { source, .. } => source.status_code(),
1469            RegisterProcedureLoader { source, .. } => source.status_code(),
1470            External { source, .. } => source.status_code(),
1471            ResponseExceededSizeLimit { source, .. } => source.status_code(),
1472            OperateDatanode { source, .. } => source.status_code(),
1473            Table { source, .. } => source.status_code(),
1474            RetryLater { source, .. } => source.status_code(),
1475            AbortProcedure { source, .. } => source.status_code(),
1476            ConvertAlterTableRequest { source, .. } => source.status_code(),
1477            PutPoison { source, .. } => source.status_code(),
1478            ConvertColumnDef { source, .. } => source.status_code(),
1479            ProcedureStateReceiver { source, .. } => source.status_code(),
1480            RegisterRepartitionProcedureLoader { source, .. } => source.status_code(),
1481            CreateRepartitionProcedure { source, .. } => source.status_code(),
1482            PersistRepartitionGcRequirement { source, .. } => source.status_code(),
1483
1484            ParseProcedureId { .. }
1485            | InvalidNumTopics { .. }
1486            | SchemaNotFound { .. }
1487            | CatalogNotFound { .. }
1488            | InvalidNodeInfoKey { .. }
1489            | InvalidStatKey { .. }
1490            | ParseNum { .. }
1491            | InvalidRole { .. }
1492            | EmptyDdlTasks { .. } => StatusCode::InvalidArguments,
1493
1494            // DeadlineExceeded is treated as unreachable by MetaClient and
1495            // retried. A wait timeout must not resubmit a running procedure.
1496            DdlTaskTimeout { .. } => StatusCode::Cancelled,
1497            LoadTlsCertificate { .. } => StatusCode::Internal,
1498
1499            #[cfg(feature = "pg_kvbackend")]
1500            PostgresExecution { .. }
1501            | CreatePostgresPool { .. }
1502            | GetPostgresConnection { .. }
1503            | GetPostgresClient { .. }
1504            | PostgresTransaction { .. }
1505            | PostgresTlsConfig { .. } => StatusCode::Internal,
1506            #[cfg(feature = "mysql_kvbackend")]
1507            MySqlExecution { .. }
1508            | CreateMySqlPool { .. }
1509            | DecodeSqlValue { .. }
1510            | AcquireMySqlClient { .. }
1511            | MySqlTransaction { .. } => StatusCode::Internal,
1512            #[cfg(any(feature = "pg_kvbackend", feature = "mysql_kvbackend"))]
1513            RdsTransactionRetryFailed { .. } | SqlExecutionTimeout { .. } => StatusCode::Internal,
1514            DatanodeTableInfoNotFound { .. } => StatusCode::Internal,
1515        }
1516    }
1517
1518    fn as_any(&self) -> &dyn std::any::Any {
1519        self
1520    }
1521
1522    fn retry_hint(&self) -> RetryHint {
1523        use Error::*;
1524
1525        match self {
1526            Error::PartialRegion { .. } => RetryHint::Retryable,
1527            Error::BatchRequest { source } => source.retry_hint(),
1528            RetryLater { source, .. } => match source.retry_hint() {
1529                RetryHint::RetryAfterRouteRefresh => RetryHint::RetryAfterRouteRefresh,
1530                RetryHint::Retryable | RetryHint::NonRetryable => RetryHint::Retryable,
1531            },
1532            GetLatestCacheRetryExceeded { .. }
1533            | NoLeader { .. }
1534            | ElectionNoLeader { .. }
1535            | ElectionLeaderLeaseExpired { .. }
1536            | ElectionLeaderLeaseChanged { .. } => RetryHint::Retryable,
1537            ConnectEtcd { error, .. } | EtcdFailed { error, .. } | EtcdTxnFailed { error, .. } => {
1538                retry_hint_from_etcd_error(error)
1539            }
1540            WriteObject { error, .. } | ReadObject { error, .. } => {
1541                retry_hint_from_opendal_error(error)
1542            }
1543            BuildKafkaClient { error, .. }
1544            | BuildKafkaCtrlClient { error, .. }
1545            | KafkaPartitionClient { error, .. }
1546            | KafkaGetOffset { error, .. }
1547            | ProduceRecord { error, .. }
1548            | CreateKafkaWalTopic { error, .. } => rskafka_client_error_to_retry_hint(error),
1549            SubmitProcedure { source, .. }
1550            | QueryProcedure { source, .. }
1551            | WaitProcedure { source, .. }
1552            | StartProcedureManager { source, .. }
1553            | StopProcedureManager { source, .. }
1554            | RegisterProcedureLoader { source, .. }
1555            | PutPoison { source, .. } => source.retry_hint(),
1556            External { source, .. }
1557            | ResponseExceededSizeLimit { source, .. }
1558            | OperateDatanode { source, .. }
1559            | RegisterRepartitionProcedureLoader { source, .. }
1560            | CreateRepartitionProcedure { source, .. }
1561            | PersistRepartitionGcRequirement { source, .. } => source.retry_hint(),
1562            // These errors end an operation; their sources cannot make it retryable.
1563            AbortProcedure { .. } | ProcedureStateReceiver { .. } => RetryHint::NonRetryable,
1564            Table { source, .. } => source.retry_hint(),
1565            ConvertAlterTableRequest { source, .. } => source.retry_hint(),
1566            ConvertColumnDef { source, .. } => source.retry_hint(),
1567            GetCache { source, .. } => source.retry_hint(),
1568            #[cfg(feature = "pg_kvbackend")]
1569            PostgresExecution { error, .. } | PostgresTransaction { error, .. } => {
1570                retry_hint_from_postgres_error(error)
1571            }
1572            #[cfg(feature = "pg_kvbackend")]
1573            GetPostgresClient { error, .. } => retry_hint_from_postgres_pool_error(error),
1574            #[cfg(feature = "mysql_kvbackend")]
1575            MySqlExecution { error, .. }
1576            | CreateMySqlPool { error, .. }
1577            | AcquireMySqlClient { error, .. }
1578            | MySqlTransaction { error, .. } => retry_hint_from_sqlx_error(error),
1579            #[cfg(any(feature = "pg_kvbackend", feature = "mysql_kvbackend"))]
1580            RdsTransactionRetryFailed { .. } | SqlExecutionTimeout { .. } => RetryHint::Retryable,
1581            _ => RetryHint::NonRetryable,
1582        }
1583    }
1584}
1585
1586impl Error {
1587    /// Returns the original Authority request error without inviting write replay.
1588    pub fn authority_storage_error(&self) -> Option<&object_store::Error> {
1589        match self {
1590            Self::AuthorityStorage { error, .. } | Self::AuthorityMissing { error, .. } => {
1591                Some(error)
1592            }
1593            Self::AuthorityUnknown { source, .. } => source.authority_storage_error(),
1594            _ => None,
1595        }
1596    }
1597
1598    #[cfg(any(feature = "pg_kvbackend", feature = "mysql_kvbackend"))]
1599    /// Check if the error is a serialization error.
1600    pub fn is_serialization_error(&self) -> bool {
1601        match self {
1602            #[cfg(feature = "pg_kvbackend")]
1603            Error::PostgresExecution { error, .. } | Error::PostgresTransaction { error, .. } => {
1604                retry_hint::is_postgres_serialization_error(error)
1605            }
1606            #[cfg(feature = "mysql_kvbackend")]
1607            Error::MySqlExecution { error, .. } | Error::MySqlTransaction { error, .. } => {
1608                retry_hint::is_mysql_serialization_error(error)
1609            }
1610            _ => false,
1611        }
1612    }
1613
1614    /// Creates a new [Error::RetryLater] error from source `err`.
1615    pub fn retry_later<E: ErrorExt + Send + Sync + 'static>(err: E) -> Error {
1616        Error::RetryLater {
1617            source: BoxedError::new(err),
1618            clean_poisons: false,
1619        }
1620    }
1621
1622    /// Determine whether it is a retry later type through [StatusCode]
1623    pub fn is_retry_later(&self) -> bool {
1624        matches!(
1625            self,
1626            Error::RetryLater { .. } | Error::GetLatestCacheRetryExceeded { .. }
1627        )
1628    }
1629
1630    /// Determine whether it needs to clean poisons.
1631    pub fn need_clean_poisons(&self) -> bool {
1632        matches!(
1633            self,
1634            Error::AbortProcedure { clean_poisons, .. } if *clean_poisons
1635        ) || matches!(
1636            self,
1637            Error::RetryLater { clean_poisons, .. } if *clean_poisons
1638        )
1639    }
1640
1641    /// Returns true if the response exceeds the size limit.
1642    pub fn is_exceeded_size_limit(&self) -> bool {
1643        match self {
1644            Error::EtcdFailed {
1645                error: etcd_client::Error::GRpcStatus(status),
1646                ..
1647            } => status.code() == tonic::Code::OutOfRange,
1648            Error::ResponseExceededSizeLimit { .. } => true,
1649            _ => false,
1650        }
1651    }
1652}
1653
1654#[cfg(test)]
1655mod retry_hint_tests {
1656    use std::sync::Arc;
1657
1658    use common_error::mock::MockError;
1659    use snafu::ResultExt;
1660
1661    use super::*;
1662
1663    #[test]
1664    fn test_retry_later_hint_is_retryable() {
1665        let err = Error::retry_later(MockError::new(StatusCode::Internal));
1666
1667        assert_eq!(err.retry_hint(), RetryHint::Retryable);
1668    }
1669
1670    #[test]
1671    fn test_latest_cache_retry_exceeded_hint_is_retryable() {
1672        let err = GetLatestCacheRetryExceededSnafu { attempts: 3_usize }.build();
1673
1674        assert_eq!(err.retry_hint(), RetryHint::Retryable);
1675    }
1676
1677    #[test]
1678    fn test_leader_retry_hints() {
1679        for (error, expected) in [
1680            (
1681                NoLeaderSnafu { table_id: 1_u32 }.build(),
1682                RetryHint::Retryable,
1683            ),
1684            (ElectionNoLeaderSnafu.build(), RetryHint::Retryable),
1685            (
1686                ElectionLeaderLeaseExpiredSnafu.build(),
1687                RetryHint::Retryable,
1688            ),
1689            (
1690                ElectionLeaderLeaseChangedSnafu.build(),
1691                RetryHint::Retryable,
1692            ),
1693        ] {
1694            assert_eq!(error.retry_hint(), expected, "{error:?}");
1695        }
1696    }
1697
1698    #[test]
1699    fn test_procedure_error_retry_hints() {
1700        let source = common_procedure::Error::retry_later(MockError::new(StatusCode::Internal));
1701        let err = Err::<(), _>(source).context(PutPoisonSnafu).unwrap_err();
1702        assert_eq!(err.retry_hint(), RetryHint::Retryable);
1703
1704        let source = common_procedure::Error::retry_later(MockError::new(StatusCode::Internal));
1705        let err = Err::<(), _>(source)
1706            .context(ProcedureStateReceiverSnafu {
1707                procedure_id: ProcedureId::random(),
1708            })
1709            .unwrap_err();
1710        assert_eq!(err.retry_hint(), RetryHint::NonRetryable);
1711    }
1712
1713    #[test]
1714    fn test_get_cache_forwards_retry_hint() {
1715        let source = Arc::new(Error::retry_later(MockError::new(StatusCode::Internal)));
1716        let err = Error::GetCache { source };
1717
1718        assert_eq!(err.retry_hint(), RetryHint::Retryable);
1719    }
1720
1721    #[cfg(any(feature = "pg_kvbackend", feature = "mysql_kvbackend"))]
1722    #[test]
1723    fn test_sql_execution_timeout_hint_is_retryable() {
1724        let err = SqlExecutionTimeoutSnafu {
1725            sql: "SELECT 1".to_string(),
1726            duration: std::time::Duration::from_secs(1),
1727        }
1728        .build();
1729
1730        assert_eq!(err.retry_hint(), RetryHint::Retryable);
1731    }
1732
1733    #[cfg(any(feature = "pg_kvbackend", feature = "mysql_kvbackend"))]
1734    #[test]
1735    fn test_rds_transaction_retry_failed_hint_is_retryable() {
1736        let err = RdsTransactionRetryFailedSnafu.build();
1737
1738        assert_eq!(err.retry_hint(), RetryHint::Retryable);
1739    }
1740
1741    #[test]
1742    fn test_default_hint_is_non_retryable() {
1743        let err = UnexpectedSnafu {
1744            err_msg: "mock error",
1745        }
1746        .build();
1747
1748        assert_eq!(err.retry_hint(), RetryHint::NonRetryable);
1749    }
1750}