error.rs (19215B)
1 use core::fmt; 2 use radroots_domain::OperationId; 3 4 use crate::Detail; 5 6 macro_rules! codes { 7 ($($variant:ident => ($code:literal, $message:literal, $retained:literal)),+ $(,)?) => { 8 /// A stable execution failure category. 9 #[derive(Clone, Copy, Debug, Eq, PartialEq)] 10 #[non_exhaustive] 11 pub enum Code { 12 $(#[doc = $message] $variant,)+ 13 } 14 15 impl Code { 16 /// Every supported execution failure category. 17 pub const ALL: &'static [Self] = &[$(Self::$variant),+]; 18 19 /// Returns the stable machine code. 20 pub const fn as_str(self) -> &'static str { 21 match self { $(Self::$variant => $code,)+ } 22 } 23 24 /// Returns an input-free bounded human message. 25 pub const fn message(self) -> &'static str { 26 match self { $(Self::$variant => $message,)+ } 27 } 28 29 const fn requires_reconciliation(self) -> bool { 30 match self { $(Self::$variant => $retained,)+ } 31 } 32 } 33 }; 34 } 35 36 codes! { 37 InvalidInput => ("invalid_input", "Command input is invalid", false), 38 Unauthenticated => ("unauthenticated", "Authentication is required", false), 39 Unauthorized => ("unauthorized", "The action is not authorized", false), 40 GrantRevoked => ("grant_revoked", "The authorizing grant was revoked", false), 41 MissingAuthority => ("missing_authority", "Selected execution authority is missing", false), 42 StaleState => ("stale_state", "Expected state must be refreshed and approved", false), 43 DeadlineExceeded => ("deadline_exceeded", "The captured first-issue deadline has elapsed", false), 44 MissingSource => ("missing_source", "Required source evidence is missing", false), 45 MissingHistory => ("missing_history", "Required authenticated history is missing", false), 46 UnsupportedVersion => ("unsupported_version", "The version is unsupported", false), 47 UnsupportedProfile => ("unsupported_profile", "The profile is unsupported", false), 48 CapabilityUnavailable => ("capability_unavailable", "A required capability is unavailable", false), 49 IdempotencyConflict => ("idempotency_conflict", "The operation identity binds different command inputs", false), 50 InsufficientStock => ("insufficient_stock", "Available stock does not satisfy the command", false), 51 Deficit => ("deficit", "Stock reconciliation is required", false), 52 AuthorityConflict => ("authority_conflict", "Execution authority is conflicted", false), 53 RecordFork => ("record_fork", "Authenticated records contain a causal fork", false), 54 StorageFailure => ("storage_failure", "Storage reported a known failure", false), 55 CommitUnknown => ("commit_unknown", "The retained transaction outcome requires reconciliation", true), 56 RecoveryRequired => ("recovery_required", "Explicit recovery is required", false), 57 SignerRefused => ("signer_refused", "The signer refused the request", false), 58 SignerUnavailable => ("signer_unavailable", "The signer is unavailable", false), 59 SignerTampering => ("signer_tampering", "The signer result does not match the retained intent", true), 60 IdentityChanged => ("identity_changed", "The signer identity changed", false), 61 SigningPending => ("signing_pending", "The retained signing request is pending", true), 62 SigningUnknown => ("signing_unknown", "The retained signing outcome requires reconciliation", true), 63 RetentionExhausted => ("retention_exhausted", "Protected retention capacity is exhausted", false), 64 DeliveryPending => ("delivery_pending", "The retained delivery requires continuation", true), 65 } 66 67 /// How an observer may continue after the reported failure. 68 #[derive(Clone, Copy, Debug, Eq, PartialEq)] 69 #[non_exhaustive] 70 pub enum RetryClass { 71 /// Do not retry this command. 72 Never, 73 /// Resume or reconcile the exact retained operation, without re-preparing it. 74 SafeSameOperation, 75 /// Refresh state and obtain any required new approval before a new command. 76 AfterStateRefresh, 77 /// Require explicit reconciliation by the operator. 78 ManualReconciliation, 79 } 80 81 impl RetryClass { 82 /// Returns the canonical machine retry class. 83 pub const fn as_str(self) -> &'static str { 84 match self { 85 Self::Never => "never", 86 Self::SafeSameOperation => "safe_same_operation", 87 Self::AfterStateRefresh => "after_state_refresh", 88 Self::ManualReconciliation => "manual_reconciliation", 89 } 90 } 91 } 92 93 /// What is known about durable command admission, independently of a later 94 /// signing, installation or delivery result. 95 #[derive(Clone, Copy, Debug, Eq, PartialEq)] 96 #[non_exhaustive] 97 pub enum Admission { 98 /// This command has not been durably admitted. 99 NotAdmitted, 100 /// The executor confirmed durable admission of the original command. 101 Confirmed, 102 /// The initial admission commit is uncertain and must be queried by ID. 103 Unknown, 104 } 105 106 /// An execution report's operation identity and durable-admission disposition. 107 /// 108 /// This value is neither authorization nor evidence that a transaction ran. 109 #[derive(Clone, Copy, Debug, Eq, PartialEq)] 110 pub struct OperationContext { 111 operation_id: Option<OperationId>, 112 admission: Admission, 113 } 114 115 impl OperationContext { 116 /// Reports a failure before durable admission, optionally retaining the 117 /// caller's proposed operation ID. 118 pub const fn proposed(operation_id: Option<OperationId>) -> Self { 119 Self { 120 operation_id, 121 admission: Admission::NotAdmitted, 122 } 123 } 124 125 /// Reports the original identity after the executor has confirmed durable 126 /// admission. Constructing this report does not perform admission. 127 pub const fn retained(operation_id: OperationId) -> Self { 128 Self { 129 operation_id: Some(operation_id), 130 admission: Admission::Confirmed, 131 } 132 } 133 134 /// Reports uncertain initial admission. The original ID is the query 135 /// anchor; neither successful admission nor a known failed commit is claimed. 136 pub const fn admission_unknown(operation_id: OperationId) -> Self { 137 Self { 138 operation_id: Some(operation_id), 139 admission: Admission::Unknown, 140 } 141 } 142 143 /// Returns the proposed or retained operation identity. 144 pub const fn operation_id(self) -> Option<OperationId> { 145 self.operation_id 146 } 147 148 /// Returns the explicit admission disposition. 149 pub const fn admission(self) -> Admission { 150 self.admission 151 } 152 } 153 154 /// An internally inconsistent execution error report. 155 #[derive(Clone, Copy, Debug, Eq, PartialEq)] 156 #[non_exhaustive] 157 pub enum InvalidErrorContext { 158 /// Signing and delivery require confirmed durable preparation. 159 ConfirmedAdmissionRequired, 160 /// Commit uncertainty requires an original retained or uncertain identity. 161 OperationIdentityRequired, 162 /// Same-operation continuation requires retained or uncertain admission. 163 RetainedRetryRequired, 164 /// An uncertain or pending outcome must retain reconciliation semantics. 165 ReconciliationRequired, 166 /// Conflicting inputs cannot resume the operation that bound other inputs. 167 ConflictingRetry, 168 } 169 170 impl fmt::Display for InvalidErrorContext { 171 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { 172 formatter.write_str(match self { 173 Self::ConfirmedAdmissionRequired => "outcome requires confirmed admission", 174 Self::OperationIdentityRequired => "outcome requires an original operation identity", 175 Self::RetainedRetryRequired => "retry requires retained or uncertain admission", 176 Self::ReconciliationRequired => "outcome requires retained reconciliation", 177 Self::ConflictingRetry => "conflicting inputs cannot resume the retained command", 178 }) 179 } 180 } 181 182 impl core::error::Error for InvalidErrorContext {} 183 184 /// An allocation-free error with typed code, bounded redacted details and the 185 /// exact reported operation identity. It never owns backend messages or causes. 186 #[derive(Clone, Copy, Debug, Eq, PartialEq)] 187 pub struct Error { 188 code: Code, 189 context: OperationContext, 190 retry: RetryClass, 191 detail: Option<Detail>, 192 } 193 const _: () = assert!(core::mem::size_of::<Error>() <= 64); 194 195 impl Error { 196 #[cfg(feature = "workspace_session")] 197 pub(crate) const fn signer_tampering(operation: OperationId) -> Self { 198 Self { 199 code: Code::SignerTampering, 200 context: OperationContext::retained(operation), 201 retry: RetryClass::ManualReconciliation, 202 detail: Some(Detail::new(crate::Field::Signer, crate::Reason::Conflict)), 203 } 204 } 205 #[cfg(feature = "workspace_session")] 206 pub(crate) const fn with_context(mut self, context: OperationContext) -> Self { 207 self.context = context; 208 self 209 } 210 211 #[cfg(feature = "workspace_session")] 212 pub(crate) const fn admission_uncertain(operation: OperationId) -> Self { 213 Self { 214 code: Code::CommitUnknown, 215 context: OperationContext::admission_unknown(operation), 216 retry: RetryClass::ManualReconciliation, 217 detail: Some(Detail::new(crate::Field::Storage, crate::Reason::Unknown)), 218 } 219 } 220 221 /// A failed obtained-material append preserves its actual error code while 222 /// requiring explicit reconciliation of the already retained original. 223 #[cfg(feature = "workspace_session")] 224 pub(crate) fn capture_pending( 225 error: radroots_storage::command::OperationError, 226 context: OperationContext, 227 ) -> Self { 228 let mut value = Self::operation(error, context); 229 value.retry = RetryClass::ManualReconciliation; 230 value 231 } 232 233 #[cfg(feature = "workspace_session")] 234 /// Projects a typed journal refusal with its observed admission context. 235 /// This data conversion performs no transaction or authorization check. 236 pub const fn operation( 237 error: radroots_storage::command::OperationError, 238 context: OperationContext, 239 ) -> Self { 240 use radroots_storage::command::OperationError as O; 241 let (code, retry) = match error { 242 O::Workspace(error) => { 243 return Self::workspace(error, context.operation_id()).with_context(context); 244 } 245 O::InvalidCommand => (Code::InvalidInput, RetryClass::Never), 246 O::InvalidEvidence => (Code::RecoveryRequired, RetryClass::ManualReconciliation), 247 O::Unauthorized | O::UnverifiedApproval => (Code::Unauthorized, RetryClass::Never), 248 O::UnsupportedOperation => (Code::CapabilityUnavailable, RetryClass::Never), 249 O::StaleState => (Code::StaleState, RetryClass::AfterStateRefresh), 250 O::MissingHistory => (Code::MissingHistory, RetryClass::AfterStateRefresh), 251 O::DeadlineExceeded => (Code::DeadlineExceeded, RetryClass::AfterStateRefresh), 252 O::IdempotencyConflict => (Code::IdempotencyConflict, RetryClass::Never), 253 O::StorageFailure => (Code::StorageFailure, RetryClass::Never), 254 O::RecoveryRequired | O::DeliveryAttemptLimit => { 255 (Code::RecoveryRequired, RetryClass::ManualReconciliation) 256 } 257 _ => (Code::RecoveryRequired, RetryClass::ManualReconciliation), 258 }; 259 Self { 260 code, 261 context, 262 retry, 263 detail: None, 264 } 265 } 266 #[cfg(feature = "receipts")] 267 pub(crate) const fn retained_deadline_exceeded(operation: OperationId) -> Self { 268 Self { 269 code: Code::DeadlineExceeded, 270 context: OperationContext::retained(operation), 271 retry: RetryClass::ManualReconciliation, 272 detail: Some(Detail::new( 273 crate::Field::Operation, 274 crate::Reason::OutOfRange, 275 )), 276 } 277 } 278 #[cfg(feature = "receipts")] 279 pub(crate) const fn retained_signing_unknown(operation: OperationId) -> Self { 280 Self { 281 code: Code::SigningUnknown, 282 context: OperationContext::retained(operation), 283 retry: RetryClass::ManualReconciliation, 284 detail: Some(Detail::new(crate::Field::Signer, crate::Reason::Unknown)), 285 } 286 } 287 #[cfg(feature = "workspace_session")] 288 pub(crate) const fn workspace( 289 error: radroots_storage::workspace::WorkspaceError, 290 operation: Option<OperationId>, 291 ) -> Self { 292 use crate::{Field as F, Reason as R}; 293 use radroots_storage::workspace::WorkspaceError as W; 294 let (code, retry, field, reason) = match error { 295 W::InvalidInput => ( 296 Code::InvalidInput, 297 RetryClass::Never, 298 F::Input, 299 R::OutOfRange, 300 ), 301 W::Unauthorized => ( 302 Code::Unauthorized, 303 RetryClass::Never, 304 F::Authority, 305 R::Missing, 306 ), 307 W::GrantExpired => ( 308 Code::Unauthorized, 309 RetryClass::AfterStateRefresh, 310 F::Authority, 311 R::OutOfRange, 312 ), 313 W::GrantRevoked => ( 314 Code::GrantRevoked, 315 RetryClass::AfterStateRefresh, 316 F::Authority, 317 R::Conflict, 318 ), 319 W::WriterActive => ( 320 Code::MissingAuthority, 321 RetryClass::AfterStateRefresh, 322 F::Authority, 323 R::Conflict, 324 ), 325 W::WrongNamespace => ( 326 Code::Unauthorized, 327 RetryClass::Never, 328 F::Authority, 329 R::Conflict, 330 ), 331 W::StaleAuthority => ( 332 Code::StaleState, 333 RetryClass::AfterStateRefresh, 334 F::Authority, 335 R::Conflict, 336 ), 337 W::StaleCheckpoint => ( 338 Code::StaleState, 339 RetryClass::AfterStateRefresh, 340 F::History, 341 R::Conflict, 342 ), 343 W::Unavailable => ( 344 Code::CapabilityUnavailable, 345 RetryClass::Never, 346 F::Authority, 347 R::Unavailable, 348 ), 349 W::Closed => ( 350 Code::CapabilityUnavailable, 351 RetryClass::Never, 352 F::Operation, 353 R::Unavailable, 354 ), 355 W::StorageFailure => ( 356 Code::StorageFailure, 357 RetryClass::Never, 358 F::Storage, 359 R::Unavailable, 360 ), 361 W::NamespaceUnavailable => ( 362 Code::RecoveryRequired, 363 RetryClass::ManualReconciliation, 364 F::Storage, 365 R::Unavailable, 366 ), 367 // Attachment/context are pre-admission. An adapter's uncertain 368 // mutation cannot be reported as this command's confirmed admission. 369 W::RecoveryRequired | W::CommitUnknown => ( 370 Code::RecoveryRequired, 371 RetryClass::ManualReconciliation, 372 F::Storage, 373 R::Unknown, 374 ), 375 _ => ( 376 Code::RecoveryRequired, 377 RetryClass::ManualReconciliation, 378 F::Authority, 379 R::Unknown, 380 ), 381 }; 382 Self { 383 code, 384 context: OperationContext::proposed(operation), 385 retry, 386 detail: Some(Detail::new(field, reason)), 387 } 388 } 389 #[cfg(feature = "client_session")] 390 pub(crate) const fn identity_changed() -> Self { 391 Self { 392 code: Code::IdentityChanged, 393 context: OperationContext::proposed(None), 394 retry: RetryClass::Never, 395 detail: Some(Detail::new(crate::Field::Signer, crate::Reason::Conflict)), 396 } 397 } 398 399 #[cfg(feature = "signer_session")] 400 pub(crate) const fn signer_unavailable() -> Self { 401 Self { 402 code: Code::SignerUnavailable, 403 context: OperationContext::proposed(None), 404 retry: RetryClass::Never, 405 detail: Some(Detail::new( 406 crate::Field::Signer, 407 crate::Reason::Unavailable, 408 )), 409 } 410 } 411 412 #[cfg(feature = "session")] 413 pub(crate) const fn session_unavailable(reason: crate::Reason) -> Self { 414 Self { 415 code: Code::CapabilityUnavailable, 416 context: OperationContext::proposed(None), 417 retry: RetryClass::Never, 418 detail: Some(Detail::new(crate::Field::Operation, reason)), 419 } 420 } 421 422 /// Validates the relationship between the outcome, durable identity and 423 /// retry policy. Safe same-operation continuation never means blind reissue. 424 pub const fn new( 425 code: Code, 426 context: OperationContext, 427 retry: RetryClass, 428 detail: Option<Detail>, 429 ) -> core::result::Result<Self, InvalidErrorContext> { 430 if matches!( 431 code, 432 Code::SigningPending 433 | Code::SigningUnknown 434 | Code::DeliveryPending 435 | Code::SignerTampering 436 ) && !matches!(context.admission, Admission::Confirmed) 437 { 438 return Err(InvalidErrorContext::ConfirmedAdmissionRequired); 439 } 440 if matches!(code, Code::CommitUnknown) 441 && matches!(context.admission, Admission::NotAdmitted) 442 { 443 return Err(InvalidErrorContext::OperationIdentityRequired); 444 } 445 if matches!(retry, RetryClass::SafeSameOperation) 446 && matches!(context.admission, Admission::NotAdmitted) 447 { 448 return Err(InvalidErrorContext::RetainedRetryRequired); 449 } 450 if code.requires_reconciliation() 451 && !matches!( 452 retry, 453 RetryClass::SafeSameOperation | RetryClass::ManualReconciliation 454 ) 455 { 456 return Err(InvalidErrorContext::ReconciliationRequired); 457 } 458 if matches!(code, Code::IdempotencyConflict) 459 && matches!(retry, RetryClass::SafeSameOperation) 460 { 461 return Err(InvalidErrorContext::ConflictingRetry); 462 } 463 Ok(Self { 464 code, 465 context, 466 retry, 467 detail, 468 }) 469 } 470 471 /// Returns the stable error category. 472 pub const fn code(self) -> Code { 473 self.code 474 } 475 476 /// Returns the operation identity and admission disposition. 477 pub const fn context(self) -> OperationContext { 478 self.context 479 } 480 481 /// Returns the required continuation class. 482 pub const fn retry(self) -> RetryClass { 483 self.retry 484 } 485 486 /// Returns the optional fixed diagnostic. 487 pub const fn detail(self) -> Option<Detail> { 488 self.detail 489 } 490 } 491 492 impl fmt::Display for Error { 493 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { 494 write!(formatter, "{}: {}", self.code.as_str(), self.code.message()) 495 } 496 } 497 498 impl core::error::Error for Error {}