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