Skip to main content

metric_engine/
error.rs

1// Copyright 2023 Greptime Team
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15use std::any::Any;
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 datatypes::prelude::ConcreteDataType;
22use snafu::{Location, Snafu};
23use store_api::region_request::RegionRequest;
24use store_api::storage::{FileId, RegionId};
25
26#[derive(Snafu)]
27#[snafu(visibility(pub))]
28#[stack_trace_debug]
29pub enum Error {
30    #[snafu(display("Failed to create mito region, region type: {}", region_type))]
31    CreateMitoRegion {
32        region_type: String,
33        source: BoxedError,
34        #[snafu(implicit)]
35        location: Location,
36    },
37
38    #[snafu(display("Failed to open mito region, region type: {}", region_type))]
39    OpenMitoRegion {
40        region_type: String,
41        source: BoxedError,
42        #[snafu(implicit)]
43        location: Location,
44    },
45
46    #[snafu(display("Failed to clean up mito region, region type: {}", region_type))]
47    CleanUpMitoRegion {
48        region_type: String,
49        source: BoxedError,
50        #[snafu(implicit)]
51        location: Location,
52    },
53
54    #[snafu(display("Failed to batch open mito region"))]
55    BatchOpenMitoRegion {
56        source: BoxedError,
57        #[snafu(implicit)]
58        location: Location,
59    },
60
61    #[snafu(display("Failed to batch catchup mito region"))]
62    BatchCatchupMitoRegion {
63        source: BoxedError,
64        #[snafu(implicit)]
65        location: Location,
66    },
67
68    #[snafu(display("No open region result for region {}", region_id))]
69    NoOpenRegionResult {
70        region_id: RegionId,
71        #[snafu(implicit)]
72        location: Location,
73    },
74
75    #[snafu(display("Failed to close mito region, region id: {}", region_id))]
76    CloseMitoRegion {
77        region_id: RegionId,
78        source: BoxedError,
79        #[snafu(implicit)]
80        location: Location,
81    },
82
83    #[snafu(display("Failed to deserialize column metadata from {}", raw))]
84    DeserializeColumnMetadata {
85        raw: String,
86        #[snafu(source)]
87        error: serde_json::Error,
88        #[snafu(implicit)]
89        location: Location,
90    },
91
92    #[snafu(display("Failed to serialize column metadata"))]
93    SerializeColumnMetadata {
94        #[snafu(source)]
95        error: serde_json::Error,
96        #[snafu(implicit)]
97        location: Location,
98    },
99
100    #[snafu(display("Failed to serialize region manifest info"))]
101    SerializeRegionManifestInfo {
102        #[snafu(source)]
103        error: serde_json::Error,
104        #[snafu(implicit)]
105        location: Location,
106    },
107
108    #[snafu(display("Failed to decode base64 column value"))]
109    DecodeColumnValue {
110        #[snafu(source)]
111        error: base64::DecodeError,
112        #[snafu(implicit)]
113        location: Location,
114    },
115
116    #[snafu(display("Failed to parse region id from {}", raw))]
117    ParseRegionId {
118        raw: String,
119        #[snafu(source)]
120        error: <u64 as std::str::FromStr>::Err,
121        #[snafu(implicit)]
122        location: Location,
123    },
124
125    #[snafu(display("Failed to parse region options: {}", reason))]
126    ParseRegionOptions {
127        reason: String,
128        #[snafu(implicit)]
129        location: Location,
130    },
131
132    #[snafu(display("Mito read operation fails"))]
133    MitoReadOperation {
134        source: BoxedError,
135        #[snafu(implicit)]
136        location: Location,
137    },
138
139    #[snafu(display(
140        "Mito copy region from operation fails, source region id: {}, target region id: {}",
141        source_region_id,
142        target_region_id
143    ))]
144    MitoCopyRegionFromOperation {
145        source: BoxedError,
146        #[snafu(implicit)]
147        location: Location,
148        source_region_id: RegionId,
149        target_region_id: RegionId,
150    },
151
152    #[snafu(display("Failed to pause compaction for region {}", region_id))]
153    MitoPauseCompactionOperation {
154        region_id: RegionId,
155        source: BoxedError,
156        #[snafu(implicit)]
157        location: Location,
158    },
159
160    #[snafu(display("Mito edit region operation fails, region id: {}", region_id))]
161    MitoEditRegion {
162        region_id: RegionId,
163        source: BoxedError,
164        #[snafu(implicit)]
165        location: Location,
166    },
167
168    #[snafu(display("Failed to encode primary key"))]
169    EncodePrimaryKey {
170        source: mito_codec::error::Error,
171        #[snafu(implicit)]
172        location: Location,
173    },
174
175    #[snafu(display("Mito write operation fails"))]
176    MitoWriteOperation {
177        source: BoxedError,
178        #[snafu(implicit)]
179        location: Location,
180    },
181
182    #[snafu(display("Mito flush operation fails"))]
183    MitoFlushOperation {
184        source: BoxedError,
185        #[snafu(implicit)]
186        location: Location,
187    },
188
189    #[snafu(display("Mito truncate operation fails"))]
190    MitoTruncateOperation {
191        source: BoxedError,
192        #[snafu(implicit)]
193        location: Location,
194    },
195
196    #[snafu(display("Mito discard pending tails operation fails"))]
197    MitoDiscardPendingTailsOperation {
198        source: BoxedError,
199        #[snafu(implicit)]
200        location: Location,
201    },
202
203    #[snafu(display("Mito sync operation fails"))]
204    MitoSyncOperation {
205        source: BoxedError,
206        #[snafu(implicit)]
207        location: Location,
208    },
209
210    #[snafu(display("Mito enter staging operation fails"))]
211    MitoEnterStagingOperation {
212        source: BoxedError,
213        #[snafu(implicit)]
214        location: Location,
215    },
216
217    #[snafu(display("Failed to collect record batch stream"))]
218    CollectRecordBatchStream {
219        source: common_recordbatch::error::Error,
220        #[snafu(implicit)]
221        location: Location,
222    },
223
224    #[snafu(display("Internal column {} is reserved", column))]
225    InternalColumnOccupied {
226        column: String,
227        #[snafu(implicit)]
228        location: Location,
229    },
230
231    #[snafu(display("Required table option is missing"))]
232    MissingRegionOption {
233        #[snafu(implicit)]
234        location: Location,
235    },
236
237    #[snafu(display("Region options are conflicted"))]
238    ConflictRegionOption {
239        #[snafu(implicit)]
240        location: Location,
241    },
242
243    #[snafu(display("Physical region {} not found", region_id))]
244    PhysicalRegionNotFound {
245        region_id: RegionId,
246        #[snafu(implicit)]
247        location: Location,
248    },
249
250    #[snafu(display("Logical region {} not found", region_id))]
251    LogicalRegionNotFound {
252        region_id: RegionId,
253        #[snafu(implicit)]
254        location: Location,
255    },
256
257    #[snafu(display("Column type mismatch. Expect {:?}, got {:?}", expect, actual))]
258    ColumnTypeMismatch {
259        expect: ConcreteDataType,
260        actual: ConcreteDataType,
261        #[snafu(implicit)]
262        location: Location,
263    },
264
265    #[snafu(display("Column {} not found in logical region {}", name, region_id))]
266    ColumnNotFound {
267        name: String,
268        region_id: RegionId,
269        #[snafu(implicit)]
270        location: Location,
271    },
272
273    #[snafu(display(
274        "Column {} is missing from physical region {} after adding columns",
275        name,
276        region_id
277    ))]
278    MissingPhysicalColumn {
279        name: String,
280        region_id: RegionId,
281        #[snafu(implicit)]
282        location: Location,
283    },
284
285    #[snafu(display("Table id count mismatch. Expect {}, got {}", expected, actual))]
286    TableIdCountMismatch {
287        expected: usize,
288        actual: usize,
289        #[snafu(implicit)]
290        location: Location,
291    },
292
293    #[snafu(display("Alter request to physical region is forbidden"))]
294    ForbiddenPhysicalAlter {
295        #[snafu(implicit)]
296        location: Location,
297    },
298
299    #[snafu(display("Write request to physical region is forbidden"))]
300    ForbiddenPhysicalWrite {
301        #[snafu(implicit)]
302        location: Location,
303    },
304
305    #[snafu(display("Invalid region metadata"))]
306    InvalidMetadata {
307        source: store_api::metadata::MetadataError,
308        #[snafu(implicit)]
309        location: Location,
310    },
311
312    #[snafu(display("Invalid request for region {}, reason: {}", region_id, reason))]
313    InvalidRequest {
314        reason: String,
315        region_id: RegionId,
316        #[snafu(implicit)]
317        location: Location,
318    },
319
320    #[snafu(display(
321        "Physical region {} is busy, there are still some logical regions using it",
322        region_id
323    ))]
324    PhysicalRegionBusy {
325        region_id: RegionId,
326        #[snafu(implicit)]
327        location: Location,
328    },
329
330    #[snafu(display("Unsupported region request: {}", request))]
331    UnsupportedRegionRequest {
332        request: Box<RegionRequest>,
333        #[snafu(implicit)]
334        location: Location,
335    },
336
337    #[snafu(display("Unsupported remap manifests request for region {}", region_id))]
338    UnsupportedRemapManifestsRequest {
339        region_id: RegionId,
340        #[snafu(implicit)]
341        location: Location,
342    },
343
344    #[snafu(display("Unsupported sync region from request for region {}", region_id))]
345    UnsupportedSyncRegionFromRequest {
346        region_id: RegionId,
347        #[snafu(implicit)]
348        location: Location,
349    },
350
351    #[snafu(display("Missing file metas in region {}, file ids: {:?}", region_id, file_ids))]
352    MissingFiles {
353        region_id: RegionId,
354        #[snafu(implicit)]
355        location: Location,
356        file_ids: Vec<FileId>,
357    },
358
359    #[snafu(display("Unsupported alter kind: {}", kind))]
360    UnsupportedAlterKind {
361        kind: String,
362        #[snafu(implicit)]
363        location: Location,
364    },
365
366    #[snafu(display("Multiple field column found: {} and {}", previous, current))]
367    MultipleFieldColumn {
368        previous: String,
369        current: String,
370        #[snafu(implicit)]
371        location: Location,
372    },
373
374    #[snafu(display("Adding field column {} to physical table", name))]
375    AddingFieldColumn {
376        name: String,
377        #[snafu(implicit)]
378        location: Location,
379    },
380
381    #[snafu(display("No field column found"))]
382    NoFieldColumn {
383        #[snafu(implicit)]
384        location: Location,
385    },
386
387    #[snafu(display("Failed to set SKIPPING index option"))]
388    SetSkippingIndexOption {
389        source: datatypes::error::Error,
390        #[snafu(implicit)]
391        location: Location,
392    },
393
394    #[snafu(display(
395        "Failed to create default value for column {} of region {}",
396        column,
397        region_id
398    ))]
399    CreateDefault {
400        region_id: RegionId,
401        column: String,
402        source: datatypes::error::Error,
403        #[snafu(implicit)]
404        location: Location,
405    },
406
407    #[snafu(display("Unexpected request: {}", reason))]
408    UnexpectedRequest {
409        reason: String,
410        #[snafu(implicit)]
411        location: Location,
412    },
413
414    #[snafu(display("Expected metric manifest info, region: {}", region_id))]
415    MetricManifestInfo {
416        region_id: RegionId,
417        #[snafu(implicit)]
418        location: Location,
419    },
420
421    #[snafu(display("Failed to start repeated task: {}", name))]
422    StartRepeatedTask {
423        name: String,
424        source: common_runtime::error::Error,
425        #[snafu(implicit)]
426        location: Location,
427    },
428
429    #[snafu(display("Get value from cache"))]
430    CacheGet {
431        source: Arc<Error>,
432        #[snafu(implicit)]
433        location: Location,
434    },
435}
436
437pub type Result<T, E = Error> = std::result::Result<T, E>;
438
439impl ErrorExt for Error {
440    fn status_code(&self) -> StatusCode {
441        use Error::*;
442
443        match self {
444            InternalColumnOccupied { .. }
445            | MissingRegionOption { .. }
446            | ConflictRegionOption { .. }
447            | ColumnTypeMismatch { .. }
448            | TableIdCountMismatch { .. }
449            | PhysicalRegionBusy { .. }
450            | MultipleFieldColumn { .. }
451            | NoFieldColumn { .. }
452            | AddingFieldColumn { .. }
453            | ParseRegionOptions { .. }
454            | UnexpectedRequest { .. }
455            | UnsupportedAlterKind { .. }
456            | UnsupportedRemapManifestsRequest { .. }
457            | UnsupportedSyncRegionFromRequest { .. }
458            | InvalidRequest { .. }
459            | CreateDefault { .. } => StatusCode::InvalidArguments,
460
461            ForbiddenPhysicalAlter { .. }
462            | ForbiddenPhysicalWrite { .. }
463            | UnsupportedRegionRequest { .. } => StatusCode::Unsupported,
464            MissingFiles { .. } => StatusCode::StorageUnavailable,
465
466            DeserializeColumnMetadata { .. }
467            | SerializeColumnMetadata { .. }
468            | DecodeColumnValue { .. }
469            | ParseRegionId { .. }
470            | InvalidMetadata { .. }
471            | SetSkippingIndexOption { .. }
472            | SerializeRegionManifestInfo { .. }
473            | NoOpenRegionResult { .. } => StatusCode::Unexpected,
474
475            PhysicalRegionNotFound { .. } | LogicalRegionNotFound { .. } => {
476                StatusCode::RegionNotFound
477            }
478
479            ColumnNotFound { .. } => StatusCode::TableColumnNotFound,
480
481            // The physical region was read twice around the alter and lost a column in
482            // between, so the failure is an inconsistent server state, not a bad request.
483            MissingPhysicalColumn { .. } => StatusCode::Unexpected,
484
485            CreateMitoRegion { source, .. }
486            | OpenMitoRegion { source, .. }
487            | CleanUpMitoRegion { source, .. }
488            | CloseMitoRegion { source, .. }
489            | MitoReadOperation { source, .. }
490            | MitoWriteOperation { source, .. }
491            | MitoFlushOperation { source, .. }
492            | MitoTruncateOperation { source, .. }
493            | MitoDiscardPendingTailsOperation { source, .. }
494            | MitoSyncOperation { source, .. }
495            | MitoEnterStagingOperation { source, .. }
496            | BatchOpenMitoRegion { source, .. }
497            | BatchCatchupMitoRegion { source, .. }
498            | MitoCopyRegionFromOperation { source, .. }
499            | MitoPauseCompactionOperation { source, .. }
500            | MitoEditRegion { source, .. } => source.status_code(),
501
502            EncodePrimaryKey { source, .. } => source.status_code(),
503
504            CollectRecordBatchStream { source, .. } => source.status_code(),
505
506            StartRepeatedTask { source, .. } => source.status_code(),
507
508            MetricManifestInfo { .. } => StatusCode::Internal,
509
510            CacheGet { source, .. } => source.status_code(),
511        }
512    }
513
514    fn as_any(&self) -> &dyn Any {
515        self
516    }
517
518    fn retry_hint(&self) -> RetryHint {
519        use Error::*;
520
521        match self {
522            MissingFiles { .. } => RetryHint::Retryable,
523            PhysicalRegionNotFound { .. } | LogicalRegionNotFound { .. } => {
524                RetryHint::RetryAfterRouteRefresh
525            }
526            CreateMitoRegion { source, .. }
527            | OpenMitoRegion { source, .. }
528            | CleanUpMitoRegion { source, .. }
529            | BatchOpenMitoRegion { source, .. }
530            | BatchCatchupMitoRegion { source, .. }
531            | CloseMitoRegion { source, .. }
532            | MitoReadOperation { source, .. }
533            | MitoWriteOperation { source, .. }
534            | MitoFlushOperation { source, .. }
535            | MitoTruncateOperation { source, .. }
536            | MitoDiscardPendingTailsOperation { source, .. }
537            | MitoSyncOperation { source, .. }
538            | MitoEnterStagingOperation { source, .. }
539            | MitoCopyRegionFromOperation { source, .. }
540            | MitoPauseCompactionOperation { source, .. }
541            | MitoEditRegion { source, .. } => source.retry_hint(),
542
543            EncodePrimaryKey { source, .. } => source.retry_hint(),
544            CollectRecordBatchStream { source, .. } => source.retry_hint(),
545            StartRepeatedTask { source, .. } => source.retry_hint(),
546            CacheGet { source, .. } => source.retry_hint(),
547
548            _ => RetryHint::NonRetryable,
549        }
550    }
551}
552
553#[cfg(test)]
554mod tests {
555    use super::*;
556
557    #[test]
558    fn test_metadata_sync_missing_files_instruction_retry_hint() {
559        use common_meta::instruction::InstructionError;
560        use snafu::IntoError;
561
562        let source = RegionId::new(1, 1);
563        let target = RegionId::new(1, 2);
564        let missing_source = mito2::error::MetadataCopyFileNotFoundSnafu {
565            path: "table/data.parquet",
566        }
567        .into_error(object_store::Error::new(
568            object_store::ErrorKind::NotFound,
569            "missing",
570        ));
571        for err in [
572            MitoCopyRegionFromOperationSnafu {
573                source_region_id: source,
574                target_region_id: target,
575            }
576            .into_error(BoxedError::new(missing_source)),
577            MissingFilesSnafu {
578                region_id: target,
579                file_ids: vec![FileId::random()],
580            }
581            .build(),
582        ] {
583            let reply = InstructionError::from_error(&err);
584            assert_eq!(reply.code, StatusCode::StorageUnavailable);
585            assert_eq!(reply.retry_hint, RetryHint::Retryable);
586        }
587    }
588
589    #[test]
590    fn test_missing_region_retry_hints() {
591        let region_id = RegionId::new(1024, 1);
592        for error in [
593            PhysicalRegionNotFoundSnafu { region_id }.build(),
594            LogicalRegionNotFoundSnafu { region_id }.build(),
595        ] {
596            assert_eq!(error.status_code(), StatusCode::RegionNotFound);
597            assert_eq!(error.retry_hint(), RetryHint::RetryAfterRouteRefresh);
598        }
599    }
600}