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