Skip to main content

rocketmq_store_api/
error.rs

1// Copyright 2023 The RocketMQ Rust Authors
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
15//! Canonical errors exposed by storage capabilities.
16
17use std::backtrace::Backtrace;
18use std::error::Error as StdError;
19use std::fmt;
20use std::panic::Location;
21
22use rocketmq_error::fields;
23use rocketmq_error::CanonicalCondition;
24use rocketmq_error::DiagnosticView;
25use rocketmq_error::Error as CanonicalError;
26use rocketmq_error::ErrorCode;
27use rocketmq_error::ErrorContext;
28use rocketmq_error::ErrorDescriptor;
29use rocketmq_error::ErrorSeverity;
30use rocketmq_error::PublicErrorView;
31use rocketmq_error::RecoveryHint;
32use rocketmq_error::Sensitive;
33use rocketmq_error::ViewContextViolation;
34
35type BoxError = Box<dyn StdError + Send + Sync>;
36
37/// Closed vocabulary for operations that may cross the capability boundary.
38#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
39pub enum StoreOperation {
40    /// Represents the load case.
41    Load,
42    /// Represents the start case.
43    Start,
44    /// Represents the shutdown case.
45    Shutdown,
46    /// Represents the append case.
47    Append,
48    /// Represents the flush case.
49    Flush,
50    /// Represents the read case.
51    Read,
52    /// Represents the query offset case.
53    QueryOffset,
54    /// Represents the replicate case.
55    Replicate,
56    /// Represents the append derived case.
57    AppendDerived,
58    /// Represents the admin case.
59    Admin,
60}
61
62impl StoreOperation {
63    /// Every storage operation accepted by [`StoreError`].
64    pub const ALL: &'static [Self] = &[
65        Self::Load,
66        Self::Start,
67        Self::Shutdown,
68        Self::Append,
69        Self::Flush,
70        Self::Read,
71        Self::QueryOffset,
72        Self::Replicate,
73        Self::AppendDerived,
74        Self::Admin,
75    ];
76
77    /// Returns the stable machine-readable operation name.
78    pub const fn as_str(self) -> &'static str {
79        match self {
80            Self::Load => "load",
81            Self::Start => "start",
82            Self::Shutdown => "shutdown",
83            Self::Append => "append",
84            Self::Flush => "flush",
85            Self::Read => "read",
86            Self::QueryOffset => "query_offset",
87            Self::Replicate => "replicate",
88            Self::AppendDerived => "append_derived",
89            Self::Admin => "admin",
90        }
91    }
92}
93
94/// Closed vocabulary identifying the storage component that failed.
95#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
96pub enum StoreComponent {
97    #[default]
98    /// Represents the store case.
99    Store,
100    /// Represents the configuration case.
101    Configuration,
102    /// Represents the commit log case.
103    CommitLog,
104    /// Represents the mapped file case.
105    MappedFile,
106    /// Represents the rocks db case.
107    RocksDb,
108    /// Represents the tiered store case.
109    TieredStore,
110    /// Represents the high availability case.
111    HighAvailability,
112    /// Represents the dledger case.
113    DLedger,
114}
115
116impl StoreComponent {
117    /// Every storage component accepted by [`StoreError`].
118    pub const ALL: &'static [Self] = &[
119        Self::Store,
120        Self::Configuration,
121        Self::CommitLog,
122        Self::MappedFile,
123        Self::RocksDb,
124        Self::TieredStore,
125        Self::HighAvailability,
126        Self::DLedger,
127    ];
128
129    /// Returns the stable machine-readable component name.
130    pub const fn as_str(self) -> &'static str {
131        match self {
132            Self::Store => "store",
133            Self::Configuration => "configuration",
134            Self::CommitLog => "commit_log",
135            Self::MappedFile => "mapped_file",
136            Self::RocksDb => "rocksdb",
137            Self::TieredStore => "tiered_store",
138            Self::HighAvailability => "high_availability",
139            Self::DLedger => "dledger",
140        }
141    }
142}
143
144/// Canonical storage failure shared by the capability and implementation layers.
145///
146/// Stable identity and policy come exclusively from the catalog descriptor.
147/// Operation and component are typed diagnostic context. Private detail and a
148/// typed source are retained for local diagnosis, but their values are never
149/// formatted by this facade or exposed through its public view.
150pub struct StoreError {
151    error: CanonicalError,
152    operation: StoreOperation,
153    component: StoreComponent,
154    private_detail: Option<Sensitive<String>>,
155}
156
157impl StoreError {
158    /// Creates a storage error with catalog-owned identity.
159    ///
160    /// Callers select one of the twelve `STORAGE_*` descriptors exported by
161    /// `rocketmq-error`; runtime detail must never select or override identity.
162    ///
163    /// # Panics
164    ///
165    /// Panics when `descriptor` is not one of the twelve canonical storage
166    /// descriptors. This is a programmer contract: runtime failures select a
167    /// reviewed storage identity before constructing the facade.
168    #[track_caller]
169    pub fn new(descriptor: &'static ErrorDescriptor, operation: StoreOperation) -> Self {
170        Self::try_new(descriptor, operation)
171            .expect("StoreError requires one of the twelve canonical storage descriptors")
172    }
173
174    /// Attempts to create a storage error with a validated catalog identity.
175    ///
176    /// Returns `None` when `descriptor` belongs to another error domain. The
177    /// facade never accepts caller-provided context, so successful construction
178    /// also guarantees that only the four storage context fields can be emitted.
179    #[track_caller]
180    pub fn try_new(descriptor: &'static ErrorDescriptor, operation: StoreOperation) -> Option<Self> {
181        if !is_storage_descriptor(descriptor) {
182            return None;
183        }
184        let component = StoreComponent::Store;
185        Some(Self {
186            error: CanonicalError::new(descriptor).with_context(store_context(operation, component, false, false)),
187            operation,
188            component,
189            private_detail: None,
190        })
191    }
192
193    /// Adds the closed component classification as diagnostic context.
194    pub fn in_component(mut self, component: StoreComponent) -> Self {
195        self.component = component;
196        self.rebuild_context()
197    }
198
199    /// Retains sensitive diagnostic detail without exposing its value.
200    pub fn with_detail(mut self, detail: impl Into<String>) -> Self {
201        self.private_detail = Some(Sensitive::new(detail.into()));
202        self.rebuild_context()
203    }
204
205    /// Preserves a typed cause in the standard source chain.
206    pub fn with_source(mut self, source: impl StdError + Send + Sync + 'static) -> Self {
207        self.error = self.error.with_source(source);
208        self.rebuild_context()
209    }
210
211    /// Preserves an already boxed typed cause in the standard source chain.
212    pub fn with_boxed_source(mut self, source: BoxError) -> Self {
213        self.error = self.error.with_boxed_source(source);
214        self.rebuild_context()
215    }
216
217    /// Returns the immutable catalog descriptor that owns this error's identity.
218    pub const fn descriptor(&self) -> &'static ErrorDescriptor {
219        self.error.descriptor()
220    }
221
222    /// Returns the stable dotted catalog code.
223    pub const fn code(&self) -> ErrorCode {
224        self.error.code()
225    }
226
227    /// Returns the protocol-independent condition.
228    pub const fn condition(&self) -> CanonicalCondition {
229        self.error.condition()
230    }
231
232    /// Returns the catalog-owned severity.
233    pub const fn severity(&self) -> ErrorSeverity {
234        self.error.severity()
235    }
236
237    /// Returns the catalog-owned recovery hint.
238    pub const fn recovery_hint(&self) -> RecoveryHint {
239        self.error.recovery_hint()
240    }
241
242    /// Returns the operation that failed.
243    pub const fn operation(&self) -> StoreOperation {
244        self.operation
245    }
246
247    /// Returns the component that failed.
248    pub const fn component(&self) -> StoreComponent {
249        self.component
250    }
251
252    /// Returns the bounded context retained by the canonical error.
253    pub const fn context(&self) -> &ErrorContext {
254        self.error.context()
255    }
256
257    /// Returns the first-promotion caller location.
258    pub const fn location(&self) -> &'static Location<'static> {
259        self.error.location()
260    }
261
262    /// Returns the catalog-controlled captured backtrace, when enabled.
263    pub const fn backtrace(&self) -> Option<&Backtrace> {
264        self.error.backtrace()
265    }
266
267    /// Creates the descriptor-validated public projection.
268    ///
269    /// # Errors
270    ///
271    /// Returns a schema violation if the catalog and the internally generated
272    /// storage context become inconsistent.
273    pub fn public_view(&self) -> Result<PublicErrorView<'_>, ViewContextViolation> {
274        self.error.public_view()
275    }
276
277    /// Creates the descriptor-validated controlled diagnostic projection.
278    ///
279    /// # Errors
280    ///
281    /// Returns a schema violation if the catalog and the internally generated
282    /// storage context become inconsistent.
283    pub fn diagnostic_view(&self) -> Result<DiagnosticView<'_>, ViewContextViolation> {
284        self.error.diagnostic_view()
285    }
286
287    fn rebuild_context(self) -> Self {
288        let context = store_context(
289            self.operation,
290            self.component,
291            self.private_detail.is_some(),
292            self.error.source().is_some(),
293        );
294        Self {
295            error: self.error.with_context(context),
296            ..self
297        }
298    }
299}
300
301fn is_storage_descriptor(descriptor: &ErrorDescriptor) -> bool {
302    matches!(
303        descriptor.code().as_str(),
304        "storage.lifecycle.not_started"
305            | "storage.backend.unavailable"
306            | "storage.request.invalid"
307            | "storage.mapped_file.not_found"
308            | "storage.capacity.exhausted"
309            | "storage.read.failed"
310            | "storage.write.failed"
311            | "storage.io.failed"
312            | "storage.state.corrupted"
313            | "storage.operation.timed_out"
314            | "storage.operation.unsupported"
315            | "storage.internal.failure"
316    )
317}
318
319fn store_context(
320    operation: StoreOperation,
321    component: StoreComponent,
322    detail_present: bool,
323    source_present: bool,
324) -> ErrorContext {
325    let mut context = ErrorContext::new()
326        .with_text(fields::STORE_OPERATION, operation.as_str())
327        .with_text(fields::STORE_COMPONENT, component.as_str());
328    if detail_present {
329        context = context.with_secret_presence(fields::STORE_DETAIL_PRESENT);
330    }
331    if source_present {
332        context = context.with_secret_presence(fields::SOURCE_PRESENT);
333    }
334    context
335}
336
337impl fmt::Display for StoreError {
338    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
339        fmt::Display::fmt(&self.error, formatter)
340    }
341}
342
343impl fmt::Debug for StoreError {
344    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
345        formatter
346            .debug_struct("StoreError")
347            .field("code", &self.code())
348            .field("message", &self.descriptor().public_message())
349            .field("operation", &self.operation)
350            .field("component", &self.component)
351            .field("detail_present", &self.private_detail.is_some())
352            .field("source_present", &self.error.source().is_some())
353            .finish()
354    }
355}
356
357impl StdError for StoreError {
358    fn source(&self) -> Option<&(dyn StdError + 'static)> {
359        self.error.source()
360    }
361}
362
363#[cfg(test)]
364mod tests {
365    use std::io;
366
367    use rocketmq_error::ContextVisibility;
368    use rocketmq_error::ViewValueRef;
369    use rocketmq_error::PROTOCOL_HEADER_INVALID;
370    use rocketmq_error::STORAGE_BACKEND_UNAVAILABLE;
371    use rocketmq_error::STORAGE_WRITE_FAILED;
372
373    use super::*;
374
375    #[derive(Debug)]
376    struct StoreCause {
377        source: io::Error,
378    }
379
380    impl fmt::Display for StoreCause {
381        fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
382            formatter.write_str("store cause")
383        }
384    }
385
386    impl StdError for StoreCause {
387        fn source(&self) -> Option<&(dyn StdError + 'static)> {
388            Some(&self.source)
389        }
390    }
391
392    #[test]
393    fn storage_vocabularies_remain_exact() {
394        assert_eq!(StoreOperation::ALL.len(), 10);
395        assert_eq!(StoreComponent::ALL.len(), 8);
396    }
397
398    #[test]
399    fn storage_error_exposes_catalog_metadata() {
400        let error = StoreError::new(&STORAGE_BACKEND_UNAVAILABLE, StoreOperation::Append)
401            .in_component(StoreComponent::HighAvailability);
402
403        assert_eq!(&STORAGE_BACKEND_UNAVAILABLE, error.descriptor());
404        assert_eq!("storage.backend.unavailable", error.code().as_str());
405        assert_eq!(StoreOperation::Append, error.operation());
406        assert_eq!(StoreComponent::HighAvailability, error.component());
407    }
408
409    #[test]
410    fn storage_not_started_facade_uses_corrected_boundary_projection() {
411        let error = StoreError::new(&rocketmq_error::STORAGE_LIFECYCLE_NOT_STARTED, StoreOperation::Start);
412        let public = error.public_view().expect("valid storage public view");
413        let projection = public.projection();
414
415        assert_eq!("storage.lifecycle.not_started", public.code().as_str());
416        assert_eq!(rocketmq_error::HttpStatusCode::CONFLICT, projection.http().status);
417        assert_eq!(rocketmq_error::CliExitCode::DATA, projection.cli().exit_code);
418    }
419
420    #[test]
421    fn storage_error_rejects_non_storage_catalog_identity() {
422        assert!(StoreError::try_new(&PROTOCOL_HEADER_INVALID, StoreOperation::Read).is_none());
423        assert!(
424            std::panic::catch_unwind(|| { StoreError::new(&PROTOCOL_HEADER_INVALID, StoreOperation::Read) }).is_err()
425        );
426    }
427
428    #[test]
429    fn storage_error_preserves_typed_source_and_safe_views() {
430        let error = StoreError::new(&STORAGE_WRITE_FAILED, StoreOperation::Flush)
431            .in_component(StoreComponent::MappedFile)
432            .with_detail("C:\\secret\\commitlog")
433            .with_source(io::Error::other("disk-secret"));
434
435        assert!(error
436            .source()
437            .and_then(|source| source.downcast_ref::<io::Error>())
438            .is_some());
439        assert_eq!("storage.write.failed: Storage write failed", error.to_string());
440        assert!(!error.to_string().contains("secret"));
441        assert!(!format!("{error:?}").contains("disk-secret"));
442        assert!(!format!("{error:?}").contains("commitlog"));
443
444        let public = error.public_view().expect("valid public view");
445        assert!(public.fields().next().is_none());
446
447        let fields = error
448            .diagnostic_view()
449            .expect("valid diagnostic view")
450            .fields()
451            .map(|field| (field.name(), field.visibility(), field.value()))
452            .collect::<Vec<_>>();
453        assert_eq!(fields.len(), 4);
454        assert_eq!(fields[0].2, ViewValueRef::Text("flush"));
455        assert_eq!(fields[1].2, ViewValueRef::Text("mapped_file"));
456        assert_eq!(fields[2].1, ContextVisibility::SecretPresenceOnly);
457        assert_eq!(fields[2].2, ViewValueRef::Redacted);
458        assert_eq!(fields[3].2, ViewValueRef::Redacted);
459    }
460
461    #[test]
462    fn storage_error_preserves_causal_order_and_downcasts() {
463        let error = StoreError::new(&STORAGE_WRITE_FAILED, StoreOperation::Flush).with_source(StoreCause {
464            source: io::Error::other("typed leaf"),
465        });
466
467        let cause = error
468            .source()
469            .and_then(|source| source.downcast_ref::<StoreCause>())
470            .expect("first cause remains typed");
471        let leaf = cause
472            .source()
473            .and_then(|source| source.downcast_ref::<io::Error>())
474            .expect("leaf cause follows the wrapper");
475        assert_eq!(leaf.to_string(), "typed leaf");
476        assert!(leaf.source().is_none());
477    }
478
479    #[test]
480    fn storage_error_preserves_an_already_boxed_source_as_the_direct_leaf() {
481        let source: BoxError = Box::new(io::Error::other("boxed leaf"));
482        let error = StoreError::new(&STORAGE_WRITE_FAILED, StoreOperation::Flush).with_boxed_source(source);
483
484        let leaf = error
485            .source()
486            .and_then(|source| source.downcast_ref::<io::Error>())
487            .expect("boxed source remains the direct typed leaf");
488        assert_eq!(leaf.to_string(), "boxed leaf");
489    }
490
491    #[test]
492    fn storage_error_builders_preserve_first_promotion_provenance() {
493        let caller_line = line!() + 1;
494        let error = StoreError::new(&STORAGE_WRITE_FAILED, StoreOperation::Flush)
495            .in_component(StoreComponent::MappedFile)
496            .with_detail("private detail")
497            .with_source(io::Error::other("typed leaf"));
498
499        assert_eq!(error.location().file(), file!());
500        assert_eq!(error.location().line(), caller_line);
501        assert_eq!(error.context().len(), 4);
502    }
503}