1use 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#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
39pub enum StoreOperation {
40 Load,
42 Start,
44 Shutdown,
46 Append,
48 Flush,
50 Read,
52 QueryOffset,
54 Replicate,
56 AppendDerived,
58 Admin,
60}
61
62impl StoreOperation {
63 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 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#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
96pub enum StoreComponent {
97 #[default]
98 Store,
100 Configuration,
102 CommitLog,
104 MappedFile,
106 RocksDb,
108 TieredStore,
110 HighAvailability,
112 DLedger,
114}
115
116impl StoreComponent {
117 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 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
144pub struct StoreError {
151 error: CanonicalError,
152 operation: StoreOperation,
153 component: StoreComponent,
154 private_detail: Option<Sensitive<String>>,
155}
156
157impl StoreError {
158 #[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 #[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 pub fn in_component(mut self, component: StoreComponent) -> Self {
195 self.component = component;
196 self.rebuild_context()
197 }
198
199 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 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 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 pub const fn descriptor(&self) -> &'static ErrorDescriptor {
219 self.error.descriptor()
220 }
221
222 pub const fn code(&self) -> ErrorCode {
224 self.error.code()
225 }
226
227 pub const fn condition(&self) -> CanonicalCondition {
229 self.error.condition()
230 }
231
232 pub const fn severity(&self) -> ErrorSeverity {
234 self.error.severity()
235 }
236
237 pub const fn recovery_hint(&self) -> RecoveryHint {
239 self.error.recovery_hint()
240 }
241
242 pub const fn operation(&self) -> StoreOperation {
244 self.operation
245 }
246
247 pub const fn component(&self) -> StoreComponent {
249 self.component
250 }
251
252 pub const fn context(&self) -> &ErrorContext {
254 self.error.context()
255 }
256
257 pub const fn location(&self) -> &'static Location<'static> {
259 self.error.location()
260 }
261
262 pub const fn backtrace(&self) -> Option<&Backtrace> {
264 self.error.backtrace()
265 }
266
267 pub fn public_view(&self) -> Result<PublicErrorView<'_>, ViewContextViolation> {
274 self.error.public_view()
275 }
276
277 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}