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