1use std::any::Any;
16use std::sync::Arc;
17use std::time::Duration;
18
19use common_error::define_into_tonic_status;
20use common_error::ext::{BoxedError, ErrorExt, RetryHint};
21use common_error::status_code::StatusCode;
22use common_macro::stack_trace_debug;
23use common_runtime::JoinError;
24use snafu::{Location, Snafu};
25use store_api::storage::RegionId;
26use table::error::Error as TableError;
27use tokio::time::error::Elapsed;
28
29#[derive(Snafu)]
31#[snafu(visibility(pub))]
32#[stack_trace_debug]
33pub enum Error {
34 #[snafu(display("Failed to write a batch group"))]
35 BatchWrite { source: std::sync::Arc<Error> },
36
37 #[snafu(display("Failed to execute async task"))]
38 AsyncTaskExecute {
39 #[snafu(implicit)]
40 location: Location,
41 source: Arc<Error>,
42 },
43
44 #[snafu(display("Failed to watch change"))]
45 WatchAsyncTaskChange {
46 #[snafu(implicit)]
47 location: Location,
48 #[snafu(source)]
49 error: tokio::sync::watch::error::RecvError,
50 },
51
52 #[snafu(display("Failed to handle heartbeat response"))]
53 HandleHeartbeatResponse {
54 #[snafu(implicit)]
55 location: Location,
56 source: common_meta::error::Error,
57 },
58
59 #[snafu(display("Failed to get info from meta server"))]
60 GetMetadata {
61 #[snafu(implicit)]
62 location: Location,
63 source: common_meta::error::Error,
64 },
65
66 #[snafu(display("Failed to execute logical plan"))]
67 ExecuteLogicalPlan {
68 #[snafu(implicit)]
69 location: Location,
70 source: query::error::Error,
71 },
72
73 #[snafu(display("Failed to join datanode runtime task, request_type: {}", request_type))]
74 RuntimeJoin {
75 request_type: &'static str,
76 #[snafu(source)]
77 error: JoinError,
78 #[snafu(implicit)]
79 location: Location,
80 },
81
82 #[snafu(display("Failed to create plan decoder"))]
83 NewPlanDecoder {
84 #[snafu(implicit)]
85 location: Location,
86 source: query::error::Error,
87 },
88
89 #[snafu(display("Failed to decode logical plan"))]
90 DecodeLogicalPlan {
91 #[snafu(implicit)]
92 location: Location,
93 source: common_query::error::Error,
94 },
95
96 #[snafu(display("Schema not found: {}", name))]
97 SchemaNotFound {
98 name: String,
99 #[snafu(implicit)]
100 location: Location,
101 },
102
103 #[snafu(display("Missing timestamp column in request"))]
104 MissingTimestampColumn {
105 #[snafu(implicit)]
106 location: Location,
107 },
108
109 #[snafu(display("Failed to delete value from table: {}", table_name))]
110 Delete {
111 table_name: String,
112 #[snafu(implicit)]
113 location: Location,
114 source: TableError,
115 },
116
117 #[snafu(display("Failed to start server"))]
118 StartServer {
119 #[snafu(implicit)]
120 location: Location,
121 source: servers::error::Error,
122 },
123
124 #[snafu(display("Failed to parse address {}", addr))]
125 ParseAddr {
126 addr: String,
127 #[snafu(source)]
128 error: std::net::AddrParseError,
129 },
130
131 #[snafu(display("Failed to create directory {}", dir))]
132 CreateDir {
133 dir: String,
134 #[snafu(source)]
135 error: std::io::Error,
136 },
137
138 #[snafu(display("Failed to remove directory {}", dir))]
139 RemoveDir {
140 dir: String,
141 #[snafu(source)]
142 error: std::io::Error,
143 },
144
145 #[snafu(display("Failed to open log store"))]
146 OpenLogStore {
147 #[snafu(implicit)]
148 location: Location,
149 source: Box<log_store::error::Error>,
150 },
151
152 #[snafu(display("Invalid query context: {}", reason))]
153 InvalidQueryContext {
154 reason: String,
155 #[snafu(implicit)]
156 location: Location,
157 },
158
159 #[snafu(display("Invalid SQL, error: {}", msg))]
160 InvalidSql { msg: String },
161
162 #[snafu(display("Illegal primary keys definition: {}", msg))]
163 IllegalPrimaryKeysDef {
164 msg: String,
165 #[snafu(implicit)]
166 location: Location,
167 },
168
169 #[snafu(display("Schema {} already exists", name))]
170 SchemaExists {
171 name: String,
172 #[snafu(implicit)]
173 location: Location,
174 },
175
176 #[snafu(display("Failed to initialize meta client"))]
177 MetaClientInit {
178 #[snafu(implicit)]
179 location: Location,
180 source: meta_client::error::Error,
181 },
182
183 #[snafu(display("Missing node id in Datanode config"))]
184 MissingNodeId {
185 #[snafu(implicit)]
186 location: Location,
187 },
188
189 #[snafu(display("Failed to build datanode"))]
190 BuildDatanode {
191 #[snafu(implicit)]
192 location: Location,
193 source: BoxedError,
194 },
195
196 #[snafu(display("Failed to build http client"))]
197 BuildHttpClient {
198 #[snafu(implicit)]
199 location: Location,
200 #[snafu(source)]
201 error: reqwest::Error,
202 },
203
204 #[snafu(display("Missing required field: {}", name))]
205 MissingRequiredField {
206 name: String,
207 #[snafu(implicit)]
208 location: Location,
209 },
210
211 #[snafu(display(
212 "No valid default value can be built automatically, column: {}",
213 column,
214 ))]
215 ColumnNoneDefaultValue {
216 column: String,
217 #[snafu(implicit)]
218 location: Location,
219 },
220
221 #[snafu(display("Failed to shutdown server"))]
222 ShutdownServer {
223 #[snafu(implicit)]
224 location: Location,
225 #[snafu(source)]
226 source: servers::error::Error,
227 },
228
229 #[snafu(display("Failed to shutdown instance"))]
230 ShutdownInstance {
231 #[snafu(implicit)]
232 location: Location,
233 #[snafu(source)]
234 source: BoxedError,
235 },
236
237 #[snafu(display("Payload not exist"))]
238 PayloadNotExist {
239 #[snafu(implicit)]
240 location: Location,
241 },
242
243 #[snafu(display("Unexpected, violated: {}", violated))]
244 Unexpected {
245 violated: String,
246 #[snafu(implicit)]
247 location: Location,
248 },
249
250 #[snafu(display("Failed to handle request for region {}", region_id))]
251 HandleRegionRequest {
252 region_id: RegionId,
253 #[snafu(implicit)]
254 location: Location,
255 source: BoxedError,
256 },
257
258 #[snafu(display("Failed to open batch regions"))]
259 HandleBatchOpenRequest {
260 #[snafu(implicit)]
261 location: Location,
262 source: BoxedError,
263 },
264
265 #[snafu(display("Failed to handle batch ddl request, ddl_type: {}", ddl_type))]
266 HandleBatchDdlRequest {
267 #[snafu(implicit)]
268 location: Location,
269 source: BoxedError,
270 ddl_type: String,
271 },
272
273 #[snafu(display("RegionId {} not found", region_id))]
274 RegionNotFound {
275 region_id: RegionId,
276 #[snafu(implicit)]
277 location: Location,
278 },
279
280 #[snafu(display("Region {} not ready", region_id))]
281 RegionNotReady {
282 region_id: RegionId,
283 #[snafu(implicit)]
284 location: Location,
285 },
286
287 #[snafu(display("Region {} is busy", region_id))]
288 RegionBusy {
289 region_id: RegionId,
290 #[snafu(implicit)]
291 location: Location,
292 },
293
294 #[snafu(display("Region engine {} is not registered", name))]
295 RegionEngineNotFound {
296 name: String,
297 #[snafu(implicit)]
298 location: Location,
299 },
300
301 #[snafu(display(
302 "GC configuration mismatch: metasrv.gc.enable={}, datanode.region_engine.mito.gc.enable={}",
303 metasrv_gc_enabled,
304 datanode_gc_enabled,
305 ))]
306 GcConfigMismatch {
307 metasrv_gc_enabled: bool,
308 datanode_gc_enabled: bool,
309 #[snafu(implicit)]
310 location: Location,
311 },
312
313 #[snafu(display(
314 "Duplicate region engine config '{engine}' at region_engine[{first_index}] and region_engine[{duplicate_index}] (indices are zero-based); each engine type may be configured only once"
315 ))]
316 DuplicateRegionEngineConfig {
317 engine: &'static str,
318 first_index: usize,
319 duplicate_index: usize,
320 #[snafu(implicit)]
321 location: Location,
322 },
323
324 #[snafu(display("Invalid object store WAL config, {} = {:?}: {}", field, value, reason))]
325 InvalidObjectStoreWalConfig {
326 field: &'static str,
327 value: String,
328 reason: String,
329 #[snafu(implicit)]
330 location: Location,
331 },
332
333 #[snafu(display(
334 "Object store WAL supports standalone only in this build; metasrv-controlled deployment requires a build with distributed object-store WAL integration"
335 ))]
336 ObjectStoreWalNotStandalone {
337 #[snafu(implicit)]
338 location: Location,
339 },
340
341 #[snafu(display("Unsupported output type, expected: {}", expected))]
342 UnsupportedOutput {
343 expected: String,
344 #[snafu(implicit)]
345 location: Location,
346 },
347
348 #[snafu(display("Failed to build region requests"))]
349 BuildRegionRequests {
350 #[snafu(implicit)]
351 location: Location,
352 source: store_api::metadata::MetadataError,
353 },
354
355 #[snafu(display("Failed to serialize WAL options for region {}", region_id))]
356 SerializeWalOptions {
357 region_id: RegionId,
358 #[snafu(source)]
359 error: serde_json::Error,
360 #[snafu(implicit)]
361 location: Location,
362 },
363
364 #[snafu(display("Failed to stop region engine {}", name))]
365 StopRegionEngine {
366 name: String,
367 #[snafu(implicit)]
368 location: Location,
369 source: BoxedError,
370 },
371
372 #[snafu(display(
373 "Failed to find logical regions in physical region {}",
374 physical_region_id
375 ))]
376 FindLogicalRegions {
377 physical_region_id: RegionId,
378 source: metric_engine::error::Error,
379 #[snafu(implicit)]
380 location: Location,
381 },
382
383 #[snafu(display("Failed to build mito engine"))]
384 BuildMitoEngine {
385 source: mito2::error::Error,
386 #[snafu(implicit)]
387 location: Location,
388 },
389
390 #[snafu(display("Failed to build metric engine"))]
391 BuildMetricEngine {
392 source: metric_engine::error::Error,
393 #[snafu(implicit)]
394 location: Location,
395 },
396
397 #[snafu(display("Failed to run gc for region {}", region_id))]
398 GcMitoEngine {
399 region_id: RegionId,
400 source: mito2::error::Error,
401 #[snafu(implicit)]
402 location: Location,
403 },
404
405 #[snafu(display("Failed to list SST entries from storage"))]
406 ListStorageSsts {
407 #[snafu(implicit)]
408 location: Location,
409 source: mito2::error::Error,
410 },
411
412 #[snafu(display("Failed to serialize options to TOML"))]
413 TomlFormat {
414 #[snafu(implicit)]
415 location: Location,
416 #[snafu(source(from(common_config::error::Error, Box::new)))]
417 source: Box<common_config::error::Error>,
418 },
419
420 #[snafu(display(
421 "Failed to get region metadata from engine {} for region_id {}",
422 engine,
423 region_id,
424 ))]
425 GetRegionMetadata {
426 engine: String,
427 region_id: RegionId,
428 #[snafu(implicit)]
429 location: Location,
430 source: BoxedError,
431 },
432
433 #[snafu(display("DataFusion"))]
434 DataFusion {
435 #[snafu(source)]
436 error: datafusion::error::DataFusionError,
437 #[snafu(implicit)]
438 location: Location,
439 },
440
441 #[snafu(display("Failed to acquire permit, source closed"))]
442 ConcurrentQueryLimiterClosed {
443 #[snafu(source)]
444 error: tokio::sync::AcquireError,
445 #[snafu(implicit)]
446 location: Location,
447 },
448
449 #[snafu(display("Failed to acquire permit under timeouts"))]
450 ConcurrentQueryLimiterTimeout {
451 #[snafu(source)]
452 error: Elapsed,
453 #[snafu(implicit)]
454 location: Location,
455 },
456
457 #[snafu(display("Cache not found in registry"))]
458 MissingCache {
459 #[snafu(implicit)]
460 location: Location,
461 },
462
463 #[snafu(display("Failed to serialize json"))]
464 SerializeJson {
465 #[snafu(source)]
466 error: serde_json::Error,
467 #[snafu(implicit)]
468 location: Location,
469 },
470
471 #[snafu(display("Failed object store operation"))]
472 ObjectStore {
473 source: object_store::error::Error,
474 #[snafu(implicit)]
475 location: Location,
476 },
477
478 #[snafu(display("Failed to run object storage probe for provider '{name}' at step '{step}'"))]
479 ObjectStoreProbe {
480 name: String,
481 step: &'static str,
482 #[snafu(source)]
483 error: object_store::Error,
484 #[snafu(implicit)]
485 location: Location,
486 },
487
488 #[snafu(display("Object storage probe for provider '{name}' timed out after {timeout:?}"))]
489 ObjectStoreProbeTimeout {
490 name: String,
491 timeout: Duration,
492 #[snafu(implicit)]
493 location: Location,
494 },
495
496 #[snafu(display("Not yet implemented: {what}"))]
497 NotYetImplemented { what: String },
498}
499
500pub type Result<T> = std::result::Result<T, Error>;
501
502impl ErrorExt for Error {
503 fn status_code(&self) -> StatusCode {
504 use Error::*;
505 match self {
506 Self::BatchWrite { source } => source.status_code(),
507 NewPlanDecoder { source, .. } | ExecuteLogicalPlan { source, .. } => {
508 source.status_code()
509 }
510
511 BuildRegionRequests { source, .. } => source.status_code(),
512 HandleHeartbeatResponse { source, .. } | GetMetadata { source, .. } => {
513 source.status_code()
514 }
515
516 DecodeLogicalPlan { source, .. } => source.status_code(),
517
518 Delete { source, .. } => source.status_code(),
519
520 InvalidQueryContext { .. }
521 | InvalidSql { .. }
522 | IllegalPrimaryKeysDef { .. }
523 | MissingTimestampColumn { .. }
524 | SchemaNotFound { .. }
525 | SchemaExists { .. }
526 | MissingNodeId { .. }
527 | ColumnNoneDefaultValue { .. }
528 | MissingRequiredField { .. }
529 | RegionEngineNotFound { .. }
530 | GcConfigMismatch { .. }
531 | ParseAddr { .. }
532 | TomlFormat { .. }
533 | DuplicateRegionEngineConfig { .. }
534 | InvalidObjectStoreWalConfig { .. }
535 | ObjectStoreWalNotStandalone { .. }
536 | BuildDatanode { .. } => StatusCode::InvalidArguments,
537
538 PayloadNotExist { .. }
539 | Unexpected { .. }
540 | SerializeWalOptions { .. }
541 | WatchAsyncTaskChange { .. }
542 | BuildHttpClient { .. } => StatusCode::Unexpected,
543
544 AsyncTaskExecute { source, .. } => source.status_code(),
545
546 CreateDir { .. }
547 | RemoveDir { .. }
548 | ShutdownInstance { .. }
549 | DataFusion { .. }
550 | RuntimeJoin { .. } => StatusCode::Internal,
551
552 RegionNotFound { .. } => StatusCode::RegionNotFound,
553 RegionNotReady { .. } => StatusCode::RegionNotReady,
554 RegionBusy { .. } => StatusCode::RegionBusy,
555
556 StartServer { source, .. } | ShutdownServer { source, .. } => source.status_code(),
557
558 OpenLogStore { source, .. } => source.status_code(),
559 MetaClientInit { source, .. } => source.status_code(),
560 UnsupportedOutput { .. } | NotYetImplemented { .. } => StatusCode::Unsupported,
561 HandleRegionRequest { source, .. }
562 | GetRegionMetadata { source, .. }
563 | HandleBatchOpenRequest { source, .. }
564 | HandleBatchDdlRequest { source, .. } => source.status_code(),
565 StopRegionEngine { source, .. } => source.status_code(),
566
567 FindLogicalRegions { source, .. } => source.status_code(),
568 BuildMitoEngine { source, .. } | GcMitoEngine { source, .. } => source.status_code(),
569 BuildMetricEngine { source, .. } => source.status_code(),
570 ListStorageSsts { source, .. } => source.status_code(),
571 ConcurrentQueryLimiterClosed { .. } | ConcurrentQueryLimiterTimeout { .. } => {
572 StatusCode::RegionBusy
573 }
574 MissingCache { .. } => StatusCode::Internal,
575 SerializeJson { .. } => StatusCode::Internal,
576
577 ObjectStore { source, .. } => source.status_code(),
578 ObjectStoreProbe { .. } | ObjectStoreProbeTimeout { .. } => {
579 StatusCode::StorageUnavailable
580 }
581 }
582 }
583
584 fn as_any(&self) -> &dyn Any {
585 self
586 }
587
588 fn retry_hint(&self) -> RetryHint {
589 use Error::*;
590
591 match self {
592 Self::BatchWrite { source } => source.retry_hint(),
593 RegionNotReady { .. } | RegionNotFound { .. } => RetryHint::RetryAfterRouteRefresh,
594 RegionBusy { .. }
595 | ConcurrentQueryLimiterClosed { .. }
596 | ConcurrentQueryLimiterTimeout { .. }
597 | ObjectStoreProbeTimeout { .. } => RetryHint::Retryable,
598 NewPlanDecoder { source, .. } | ExecuteLogicalPlan { source, .. } => {
599 source.retry_hint()
600 }
601 HandleHeartbeatResponse { source, .. } | GetMetadata { source, .. } => {
602 source.retry_hint()
603 }
604 DecodeLogicalPlan { source, .. } => source.retry_hint(),
605 Delete { source, .. } => source.retry_hint(),
606 AsyncTaskExecute { source, .. } => source.retry_hint(),
607 StartServer { source, .. } | ShutdownServer { source, .. } => source.retry_hint(),
608 OpenLogStore { source, .. } => source.retry_hint(),
609 MetaClientInit { source, .. } => source.retry_hint(),
610 HandleRegionRequest { source, .. }
611 | GetRegionMetadata { source, .. }
612 | HandleBatchOpenRequest { source, .. }
613 | HandleBatchDdlRequest { source, .. }
614 | StopRegionEngine { source, .. } => source.retry_hint(),
615 FindLogicalRegions { source, .. } => source.retry_hint(),
616 BuildMitoEngine { source, .. } => source.retry_hint(),
617 GcMitoEngine { source, .. } => source.retry_hint(),
618 BuildMetricEngine { source, .. } => source.retry_hint(),
619 ListStorageSsts { source, .. } => source.retry_hint(),
620 ObjectStore { source, .. } => source.retry_hint(),
621 ObjectStoreProbe { error, .. } => {
622 object_store::error::retry_hint_from_opendal_error(error)
623 }
624 _ => RetryHint::NonRetryable,
625 }
626 }
627}
628
629define_into_tonic_status!(Error);
630
631#[cfg(test)]
632mod tests {
633 use common_error::ext::RetryHint;
634
635 use super::*;
636
637 #[test]
638 fn test_region_state_retry_hints() {
639 let region_id = RegionId::new(1024, 1);
640 for (error, status, hint) in [
641 (
642 RegionBusySnafu { region_id }.build(),
643 StatusCode::RegionBusy,
644 RetryHint::Retryable,
645 ),
646 (
647 RegionNotReadySnafu { region_id }.build(),
648 StatusCode::RegionNotReady,
649 RetryHint::RetryAfterRouteRefresh,
650 ),
651 (
652 RegionNotFoundSnafu { region_id }.build(),
653 StatusCode::RegionNotFound,
654 RetryHint::RetryAfterRouteRefresh,
655 ),
656 ] {
657 assert_eq!(error.status_code(), status);
658 assert_eq!(error.retry_hint(), hint);
659 }
660 }
661
662 #[test]
663 fn test_default_hint_is_non_retryable() {
664 let err = UnexpectedSnafu {
665 violated: "mock error",
666 }
667 .build();
668
669 assert_eq!(err.retry_hint(), RetryHint::NonRetryable);
670 }
671}