use std::backtrace::Backtrace;
use std::error::Error as StdError;
use std::fmt;
use std::panic::Location;
use rocketmq_error::fields;
use rocketmq_error::CanonicalCondition;
use rocketmq_error::DiagnosticView;
use rocketmq_error::Error as CanonicalError;
use rocketmq_error::ErrorCode;
use rocketmq_error::ErrorContext;
use rocketmq_error::ErrorDescriptor;
use rocketmq_error::ErrorSeverity;
use rocketmq_error::PublicErrorView;
use rocketmq_error::RecoveryHint;
use rocketmq_error::Sensitive;
use rocketmq_error::ViewContextViolation;
type BoxError = Box<dyn StdError + Send + Sync>;
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum StoreOperation {
Load,
Start,
Shutdown,
Append,
Flush,
Read,
QueryOffset,
Replicate,
AppendDerived,
Admin,
}
impl StoreOperation {
pub const ALL: &'static [Self] = &[
Self::Load,
Self::Start,
Self::Shutdown,
Self::Append,
Self::Flush,
Self::Read,
Self::QueryOffset,
Self::Replicate,
Self::AppendDerived,
Self::Admin,
];
pub const fn as_str(self) -> &'static str {
match self {
Self::Load => "load",
Self::Start => "start",
Self::Shutdown => "shutdown",
Self::Append => "append",
Self::Flush => "flush",
Self::Read => "read",
Self::QueryOffset => "query_offset",
Self::Replicate => "replicate",
Self::AppendDerived => "append_derived",
Self::Admin => "admin",
}
}
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum StoreComponent {
#[default]
Store,
Configuration,
CommitLog,
MappedFile,
RocksDb,
TieredStore,
HighAvailability,
DLedger,
}
impl StoreComponent {
pub const ALL: &'static [Self] = &[
Self::Store,
Self::Configuration,
Self::CommitLog,
Self::MappedFile,
Self::RocksDb,
Self::TieredStore,
Self::HighAvailability,
Self::DLedger,
];
pub const fn as_str(self) -> &'static str {
match self {
Self::Store => "store",
Self::Configuration => "configuration",
Self::CommitLog => "commit_log",
Self::MappedFile => "mapped_file",
Self::RocksDb => "rocksdb",
Self::TieredStore => "tiered_store",
Self::HighAvailability => "high_availability",
Self::DLedger => "dledger",
}
}
}
pub struct StoreError {
error: CanonicalError,
operation: StoreOperation,
component: StoreComponent,
private_detail: Option<Sensitive<String>>,
}
impl StoreError {
#[track_caller]
pub fn new(descriptor: &'static ErrorDescriptor, operation: StoreOperation) -> Self {
Self::try_new(descriptor, operation)
.expect("StoreError requires one of the twelve canonical storage descriptors")
}
#[track_caller]
pub fn try_new(descriptor: &'static ErrorDescriptor, operation: StoreOperation) -> Option<Self> {
if !is_storage_descriptor(descriptor) {
return None;
}
let component = StoreComponent::Store;
Some(Self {
error: CanonicalError::new(descriptor).with_context(store_context(operation, component, false, false)),
operation,
component,
private_detail: None,
})
}
pub fn in_component(mut self, component: StoreComponent) -> Self {
self.component = component;
self.rebuild_context()
}
pub fn with_detail(mut self, detail: impl Into<String>) -> Self {
self.private_detail = Some(Sensitive::new(detail.into()));
self.rebuild_context()
}
pub fn with_source(mut self, source: impl StdError + Send + Sync + 'static) -> Self {
self.error = self.error.with_source(source);
self.rebuild_context()
}
pub fn with_boxed_source(mut self, source: BoxError) -> Self {
self.error = self.error.with_boxed_source(source);
self.rebuild_context()
}
pub const fn descriptor(&self) -> &'static ErrorDescriptor {
self.error.descriptor()
}
pub const fn code(&self) -> ErrorCode {
self.error.code()
}
pub const fn condition(&self) -> CanonicalCondition {
self.error.condition()
}
pub const fn severity(&self) -> ErrorSeverity {
self.error.severity()
}
pub const fn recovery_hint(&self) -> RecoveryHint {
self.error.recovery_hint()
}
pub const fn operation(&self) -> StoreOperation {
self.operation
}
pub const fn component(&self) -> StoreComponent {
self.component
}
pub const fn context(&self) -> &ErrorContext {
self.error.context()
}
pub const fn location(&self) -> &'static Location<'static> {
self.error.location()
}
pub const fn backtrace(&self) -> Option<&Backtrace> {
self.error.backtrace()
}
pub fn public_view(&self) -> Result<PublicErrorView<'_>, ViewContextViolation> {
self.error.public_view()
}
pub fn diagnostic_view(&self) -> Result<DiagnosticView<'_>, ViewContextViolation> {
self.error.diagnostic_view()
}
fn rebuild_context(self) -> Self {
let context = store_context(
self.operation,
self.component,
self.private_detail.is_some(),
self.error.source().is_some(),
);
Self {
error: self.error.with_context(context),
..self
}
}
}
fn is_storage_descriptor(descriptor: &ErrorDescriptor) -> bool {
matches!(
descriptor.code().as_str(),
"storage.lifecycle.not_started"
| "storage.unavailable"
| "storage.request.invalid"
| "storage.mapped_file.not_found"
| "storage.capacity.exhausted"
| "storage.read.failed"
| "storage.write.failed"
| "storage.io.failed"
| "storage.state.corrupted"
| "storage.operation.timed_out"
| "storage.operation.unsupported"
| "storage.internal.failure"
)
}
fn store_context(
operation: StoreOperation,
component: StoreComponent,
detail_present: bool,
source_present: bool,
) -> ErrorContext {
let mut context = ErrorContext::new()
.with_text(fields::STORE_OPERATION, operation.as_str())
.with_text(fields::STORE_COMPONENT, component.as_str());
if detail_present {
context = context.with_secret_presence(fields::STORE_DETAIL_PRESENT);
}
if source_present {
context = context.with_secret_presence(fields::SOURCE_PRESENT);
}
context
}
impl fmt::Display for StoreError {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Display::fmt(&self.error, formatter)
}
}
impl fmt::Debug for StoreError {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter
.debug_struct("StoreError")
.field("code", &self.code())
.field("message", &self.descriptor().public_message())
.field("operation", &self.operation)
.field("component", &self.component)
.field("detail_present", &self.private_detail.is_some())
.field("source_present", &self.error.source().is_some())
.finish()
}
}
impl StdError for StoreError {
fn source(&self) -> Option<&(dyn StdError + 'static)> {
self.error.source()
}
}
#[cfg(test)]
mod tests {
use std::io;
use rocketmq_error::ContextVisibility;
use rocketmq_error::ViewValueRef;
use rocketmq_error::PROTOCOL_HEADER_INVALID;
use rocketmq_error::STORAGE_UNAVAILABLE;
use rocketmq_error::STORAGE_WRITE_FAILED;
use super::*;
#[derive(Debug)]
struct StoreCause {
source: io::Error,
}
impl fmt::Display for StoreCause {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter.write_str("store cause")
}
}
impl StdError for StoreCause {
fn source(&self) -> Option<&(dyn StdError + 'static)> {
Some(&self.source)
}
}
#[test]
fn storage_vocabularies_remain_exact() {
assert_eq!(StoreOperation::ALL.len(), 10);
assert_eq!(StoreComponent::ALL.len(), 8);
}
#[test]
fn storage_error_exposes_catalog_metadata() {
let error = StoreError::new(&STORAGE_UNAVAILABLE, StoreOperation::Append)
.in_component(StoreComponent::HighAvailability);
assert_eq!(&STORAGE_UNAVAILABLE, error.descriptor());
assert_eq!("storage.unavailable", error.code().as_str());
assert_eq!(StoreOperation::Append, error.operation());
assert_eq!(StoreComponent::HighAvailability, error.component());
}
#[test]
fn storage_not_started_facade_uses_corrected_boundary_projection() {
let error = StoreError::new(&rocketmq_error::STORAGE_LIFECYCLE_NOT_STARTED, StoreOperation::Start);
let public = error.public_view().expect("valid storage public view");
let projection = public.projection();
assert_eq!("storage.lifecycle.not_started", public.code().as_str());
assert_eq!(rocketmq_error::HttpStatusCode::CONFLICT, projection.http().status);
assert_eq!(rocketmq_error::CliExitCode::DATA, projection.cli().exit_code);
}
#[test]
fn storage_error_rejects_non_storage_catalog_identity() {
assert!(StoreError::try_new(&PROTOCOL_HEADER_INVALID, StoreOperation::Read).is_none());
assert!(
std::panic::catch_unwind(|| { StoreError::new(&PROTOCOL_HEADER_INVALID, StoreOperation::Read) }).is_err()
);
}
#[test]
fn storage_error_preserves_typed_source_and_safe_views() {
let error = StoreError::new(&STORAGE_WRITE_FAILED, StoreOperation::Flush)
.in_component(StoreComponent::MappedFile)
.with_detail("C:\\secret\\commitlog")
.with_source(io::Error::other("disk-secret"));
assert!(error
.source()
.and_then(|source| source.downcast_ref::<io::Error>())
.is_some());
assert_eq!("storage.write.failed: Storage write failed", error.to_string());
assert!(!error.to_string().contains("secret"));
assert!(!format!("{error:?}").contains("disk-secret"));
assert!(!format!("{error:?}").contains("commitlog"));
let public = error.public_view().expect("valid public view");
assert!(public.fields().next().is_none());
let fields = error
.diagnostic_view()
.expect("valid diagnostic view")
.fields()
.map(|field| (field.name(), field.visibility(), field.value()))
.collect::<Vec<_>>();
assert_eq!(fields.len(), 4);
assert_eq!(fields[0].2, ViewValueRef::Text("flush"));
assert_eq!(fields[1].2, ViewValueRef::Text("mapped_file"));
assert_eq!(fields[2].1, ContextVisibility::SecretPresenceOnly);
assert_eq!(fields[2].2, ViewValueRef::Redacted);
assert_eq!(fields[3].2, ViewValueRef::Redacted);
}
#[test]
fn storage_error_preserves_causal_order_and_downcasts() {
let error = StoreError::new(&STORAGE_WRITE_FAILED, StoreOperation::Flush).with_source(StoreCause {
source: io::Error::other("typed leaf"),
});
let cause = error
.source()
.and_then(|source| source.downcast_ref::<StoreCause>())
.expect("first cause remains typed");
let leaf = cause
.source()
.and_then(|source| source.downcast_ref::<io::Error>())
.expect("leaf cause follows the wrapper");
assert_eq!(leaf.to_string(), "typed leaf");
assert!(leaf.source().is_none());
}
#[test]
fn storage_error_preserves_an_already_boxed_source_as_the_direct_leaf() {
let source: BoxError = Box::new(io::Error::other("boxed leaf"));
let error = StoreError::new(&STORAGE_WRITE_FAILED, StoreOperation::Flush).with_boxed_source(source);
let leaf = error
.source()
.and_then(|source| source.downcast_ref::<io::Error>())
.expect("boxed source remains the direct typed leaf");
assert_eq!(leaf.to_string(), "boxed leaf");
}
#[test]
fn storage_error_builders_preserve_first_promotion_provenance() {
let caller_line = line!() + 1;
let error = StoreError::new(&STORAGE_WRITE_FAILED, StoreOperation::Flush)
.in_component(StoreComponent::MappedFile)
.with_detail("private detail")
.with_source(io::Error::other("typed leaf"));
assert_eq!(error.location().file(), file!());
assert_eq!(error.location().line(), caller_line);
assert_eq!(error.context().len(), 4);
}
}