error_forge/recovery/forge_extensions.rs
1use crate::error::ForgeError;
2use crate::recovery::{CircuitBreaker, RetryPolicy};
3
4/// Extension trait that adds recovery capabilities to ForgeError types
5pub trait ForgeErrorRecovery: ForgeError {
6 /// Create a retry policy optimized for this error type
7 fn create_retry_policy(&self, max_retries: usize) -> RetryPolicy {
8 RetryPolicy::new_exponential().with_max_retries(max_retries)
9 }
10
11 /// Execute a fallible operation with retries if this error type is retryable.
12 ///
13 /// When `self.is_retryable()` is `false` the operation runs exactly
14 /// once and its result is returned as is. Otherwise it is retried up
15 /// to `max_retries` times with exponential backoff, for as long as
16 /// the error it returns is itself retryable.
17 ///
18 /// # Example
19 ///
20 /// ```
21 /// use error_forge::{recovery::ForgeErrorRecovery, AppError};
22 ///
23 /// // `AppError::config` is not retryable, so the operation runs once.
24 /// let template = AppError::config("bad config");
25 /// let mut calls = 0;
26 /// let result: Result<(), AppError> = template.retry(3, || {
27 /// calls += 1;
28 /// Err(AppError::network("db", None))
29 /// });
30 /// assert!(result.is_err());
31 /// assert_eq!(calls, 1);
32 /// ```
33 fn retry<F, T, E>(&self, max_retries: usize, operation: F) -> Result<T, E>
34 where
35 F: FnMut() -> Result<T, E>,
36 E: ForgeError,
37 {
38 let max_retries = if self.is_retryable() { max_retries } else { 0 };
39 let policy = self.create_retry_policy(max_retries);
40 policy.forge_executor().retry(operation)
41 }
42
43 /// Create a circuit breaker for operations that might result in this error type
44 fn create_circuit_breaker(&self, name: impl Into<String>) -> CircuitBreaker {
45 CircuitBreaker::new(name)
46 }
47}
48
49// Implement the extension trait for all ForgeError types
50impl<T: ForgeError> ForgeErrorRecovery for T {}