error.rs (10443B)
1 //! Safe public errors with separately preserved internal sources. 2 3 use core::fmt; 4 use std::error::Error; 5 6 /// Maximum byte length of every public host-error message. 7 pub const MAX_SAFE_ERROR_MESSAGE_BYTES: usize = 96; 8 9 /// Stable public error codes for host-mechanism failures. 10 #[derive(Clone, Copy, Debug, PartialEq, Eq)] 11 pub enum HostErrorCode { 12 ConfigDocument, 13 Lifecycle, 14 AdminTransport, 15 OperationsBind, 16 OperationsServe, 17 PathContext, 18 TaskFailure, 19 InvalidHostContract, 20 } 21 22 impl HostErrorCode { 23 /// Returns the stable lowercase wire representation of this code. 24 #[must_use] 25 pub const fn as_str(self) -> &'static str { 26 match self { 27 Self::ConfigDocument => "host_config_document", 28 Self::Lifecycle => "host_lifecycle", 29 Self::AdminTransport => "host_admin_transport", 30 Self::OperationsBind => "host_operations_bind", 31 Self::OperationsServe => "host_operations_serve", 32 Self::PathContext => "host_path_context", 33 Self::TaskFailure => "host_task_failure", 34 Self::InvalidHostContract => "invalid_host_contract", 35 } 36 } 37 } 38 39 impl fmt::Display for HostErrorCode { 40 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { 41 formatter.write_str(self.as_str()) 42 } 43 } 44 45 /// Service-neutral failure categories accepted by the host boundary. 46 #[derive(Clone, Copy, Debug, PartialEq, Eq)] 47 pub enum HostErrorKind { 48 ConfigDocument, 49 Lifecycle, 50 AdminTransport, 51 OperationsBind, 52 OperationsServe, 53 PathContext, 54 TaskFailure, 55 InvalidHostContract, 56 } 57 58 impl HostErrorKind { 59 /// Returns the bounded representation safe for public boundaries. 60 #[must_use] 61 pub const fn safe_error(self) -> SafeHostError { 62 match self { 63 Self::ConfigDocument => SafeHostError::new( 64 HostErrorCode::ConfigDocument, 65 "service configuration document is invalid", 66 ), 67 Self::Lifecycle => SafeHostError::new( 68 HostErrorCode::Lifecycle, 69 "service lifecycle operation failed", 70 ), 71 Self::AdminTransport => SafeHostError::new( 72 HostErrorCode::AdminTransport, 73 "local administration transport failed", 74 ), 75 Self::OperationsBind => SafeHostError::new( 76 HostErrorCode::OperationsBind, 77 "operations listener could not be bound", 78 ), 79 Self::OperationsServe => SafeHostError::new( 80 HostErrorCode::OperationsServe, 81 "operations listener stopped unexpectedly", 82 ), 83 Self::PathContext => SafeHostError::new( 84 HostErrorCode::PathContext, 85 "service path context is invalid", 86 ), 87 Self::TaskFailure => SafeHostError::new( 88 HostErrorCode::TaskFailure, 89 "authoritative service task failed", 90 ), 91 Self::InvalidHostContract => SafeHostError::new( 92 HostErrorCode::InvalidHostContract, 93 "service host contract is invalid", 94 ), 95 } 96 } 97 } 98 99 /// Error information safe for logs, status, metrics, and wire envelopes. 100 #[derive(Clone, Copy, Debug, PartialEq, Eq)] 101 pub struct SafeHostError { 102 code: HostErrorCode, 103 message: &'static str, 104 } 105 106 impl SafeHostError { 107 const fn new(code: HostErrorCode, message: &'static str) -> Self { 108 assert!(message.len() <= MAX_SAFE_ERROR_MESSAGE_BYTES); 109 Self { code, message } 110 } 111 112 /// Returns the typed public code. 113 #[must_use] 114 pub const fn code(self) -> HostErrorCode { 115 self.code 116 } 117 118 /// Returns the stable string used to serialize the public code. 119 #[must_use] 120 pub const fn code_str(self) -> &'static str { 121 self.code.as_str() 122 } 123 124 /// Returns the bounded public message. 125 #[must_use] 126 pub const fn message(self) -> &'static str { 127 self.message 128 } 129 } 130 131 impl fmt::Display for SafeHostError { 132 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { 133 write!(formatter, "{}: {}", self.code, self.message) 134 } 135 } 136 137 /// A typed host failure whose Display and Debug never render its internal cause. 138 pub struct HostError { 139 kind: HostErrorKind, 140 source: Option<Box<dyn Error + Send + Sync + 'static>>, 141 } 142 143 impl HostError { 144 /// Creates a host failure without an upstream cause. 145 #[must_use] 146 pub const fn new(kind: HostErrorKind) -> Self { 147 Self { kind, source: None } 148 } 149 150 /// Creates a host failure while retaining its cause for trusted inspection. 151 pub fn with_source(kind: HostErrorKind, source: impl Error + Send + Sync + 'static) -> Self { 152 Self { 153 kind, 154 source: Some(Box::new(source)), 155 } 156 } 157 158 /// Returns the service-neutral failure category. 159 #[must_use] 160 pub const fn kind(&self) -> HostErrorKind { 161 self.kind 162 } 163 164 /// Returns the bounded representation safe for public boundaries. 165 #[must_use] 166 pub const fn safe_error(&self) -> SafeHostError { 167 self.kind.safe_error() 168 } 169 } 170 171 impl fmt::Debug for HostError { 172 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { 173 formatter 174 .debug_struct("HostError") 175 .field("kind", &self.kind) 176 .field("source", &self.source.as_ref().map(|_| "<redacted>")) 177 .finish() 178 } 179 } 180 181 impl fmt::Display for HostError { 182 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { 183 self.safe_error().fmt(formatter) 184 } 185 } 186 187 impl Error for HostError { 188 fn source(&self) -> Option<&(dyn Error + 'static)> { 189 self.source 190 .as_deref() 191 .map(|source| source as &(dyn Error + 'static)) 192 } 193 } 194 195 #[cfg(test)] 196 mod tests { 197 use super::*; 198 199 #[derive(Debug)] 200 struct SensitiveCause(&'static str); 201 202 impl fmt::Display for SensitiveCause { 203 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { 204 formatter.write_str(self.0) 205 } 206 } 207 208 impl Error for SensitiveCause {} 209 210 #[test] 211 fn display_is_safe_while_source_is_preserved() { 212 let error = HostError::with_source( 213 HostErrorKind::ConfigDocument, 214 SensitiveCause("secret upstream detail"), 215 ); 216 217 assert_eq!( 218 error.to_string(), 219 "host_config_document: service configuration document is invalid" 220 ); 221 assert!(!error.to_string().contains("secret")); 222 assert_eq!( 223 error.source().map(ToString::to_string).as_deref(), 224 Some("secret upstream detail") 225 ); 226 } 227 228 #[test] 229 fn ordinary_debug_preserves_category_and_redacts_trusted_cause() { 230 let marker = "synthetic private diagnostic input"; 231 let error = HostError::with_source(HostErrorKind::ConfigDocument, SensitiveCause(marker)); 232 233 for rendered in [ 234 format!("{error:?}"), 235 format!("{error:#?}"), 236 error.to_string(), 237 ] { 238 assert!(!rendered.contains(marker)); 239 } 240 assert!(format!("{error:?}").contains("ConfigDocument")); 241 assert_eq!(error.kind(), HostErrorKind::ConfigDocument); 242 assert_eq!( 243 error 244 .source() 245 .unwrap() 246 .downcast_ref::<SensitiveCause>() 247 .unwrap() 248 .0, 249 marker 250 ); 251 assert_eq!(error.source().unwrap().to_string(), marker); 252 253 let unsourced = HostError::new(HostErrorKind::TaskFailure); 254 assert!(unsourced.source().is_none()); 255 assert!(format!("{unsourced:?}").contains("TaskFailure")); 256 assert!(format!("{unsourced:#?}").contains("TaskFailure")); 257 } 258 259 #[test] 260 fn ordinary_debug_does_not_format_retained_dependency_cause() { 261 struct ExplicitInspectionCause; 262 263 impl fmt::Debug for ExplicitInspectionCause { 264 fn fmt(&self, _formatter: &mut fmt::Formatter<'_>) -> fmt::Result { 265 panic!("dependency Debug requires explicit trusted inspection") 266 } 267 } 268 269 impl fmt::Display for ExplicitInspectionCause { 270 fn fmt(&self, _formatter: &mut fmt::Formatter<'_>) -> fmt::Result { 271 panic!("dependency Display requires explicit trusted inspection") 272 } 273 } 274 275 impl Error for ExplicitInspectionCause {} 276 277 let error = HostError::with_source(HostErrorKind::TaskFailure, ExplicitInspectionCause); 278 assert!(format!("{error:?}").contains("TaskFailure")); 279 assert!(format!("{error:#?}").contains("TaskFailure")); 280 assert_eq!( 281 error.to_string(), 282 HostErrorKind::TaskFailure.safe_error().to_string() 283 ); 284 assert!(error.source().unwrap().is::<ExplicitInspectionCause>()); 285 } 286 287 #[test] 288 fn safe_codes_have_stable_serialization_helpers() { 289 let expected = [ 290 (HostErrorKind::ConfigDocument, "host_config_document"), 291 (HostErrorKind::Lifecycle, "host_lifecycle"), 292 (HostErrorKind::AdminTransport, "host_admin_transport"), 293 (HostErrorKind::OperationsBind, "host_operations_bind"), 294 (HostErrorKind::OperationsServe, "host_operations_serve"), 295 (HostErrorKind::PathContext, "host_path_context"), 296 (HostErrorKind::TaskFailure, "host_task_failure"), 297 (HostErrorKind::InvalidHostContract, "invalid_host_contract"), 298 ]; 299 300 for (kind, code) in expected { 301 let safe = kind.safe_error(); 302 assert_eq!(safe.code_str(), code); 303 assert_eq!(safe.code().to_string(), code); 304 } 305 } 306 307 #[test] 308 fn all_public_messages_are_nonempty_bounded_and_fixed() { 309 for kind in [ 310 HostErrorKind::ConfigDocument, 311 HostErrorKind::Lifecycle, 312 HostErrorKind::AdminTransport, 313 HostErrorKind::OperationsBind, 314 HostErrorKind::OperationsServe, 315 HostErrorKind::PathContext, 316 HostErrorKind::TaskFailure, 317 HostErrorKind::InvalidHostContract, 318 ] { 319 let safe = kind.safe_error(); 320 assert!(!safe.message().is_empty()); 321 assert!(safe.message().len() <= MAX_SAFE_ERROR_MESSAGE_BYTES); 322 assert!(safe.message().is_ascii()); 323 } 324 } 325 }