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