pub struct ErrorRecoveryManager { /* private fields */ }
Expand description
Error recovery manager
Implementations§
Source§impl ErrorRecoveryManager
impl ErrorRecoveryManager
Sourcepub fn new() -> Self
pub fn new() -> Self
Create a new error recovery manager
Examples found in repository?
examples/resilience_example.rs (line 141)
140async fn demonstrate_error_handling() -> Result<(), Box<dyn std::error::Error>> {
141 let error_manager = ErrorRecoveryManager::new();
142
143 // Simulate different types of errors
144 let errors = vec![
145 ("Rate Limit", ai_lib::types::AiLibError::RateLimitExceeded("API rate limit exceeded".to_string())),
146 ("Network", ai_lib::types::AiLibError::NetworkError("Connection timeout".to_string())),
147 ("Authentication", ai_lib::types::AiLibError::AuthenticationError("Invalid API key".to_string())),
148 ("Context Length", ai_lib::types::AiLibError::ContextLengthExceeded("Request too long".to_string())),
149 ];
150
151 println!("Error Handling and Pattern Analysis:");
152 for (error_type, error) in errors {
153 let context = ErrorContext::new("demo_provider".to_string(), "/demo/endpoint".to_string());
154 let result = error_manager.handle_error(&error, &context).await;
155
156 println!(" {} Error: {}", error_type, error);
157 println!(" Suggested Action: {:?}", context.suggested_action);
158 println!(" Recovery Result: {}", if result.is_ok() { "Success" } else { "Failed" });
159 }
160
161 // Show error statistics
162 let stats = error_manager.get_error_statistics();
163 println!("\nError Statistics:");
164 println!(" Total Errors: {}", stats.total_errors);
165 println!(" Unique Error Types: {}", stats.unique_error_types);
166 println!(" Most Common: {:?}", stats.most_common_error);
167
168 // Show error patterns
169 let patterns = error_manager.get_error_patterns();
170 for (error_type, pattern) in patterns {
171 println!(" {:?}: {} occurrences, {:.2} errors/min",
172 error_type, pattern.count, pattern.frequency);
173 }
174
175 Ok(())
176}
177
178async fn demonstrate_integrated_resilience() -> Result<(), Box<dyn std::error::Error>> {
179 // Create all resilience components
180 let circuit_breaker = CircuitBreaker::new(CircuitBreakerConfig::development());
181 let rate_limiter = TokenBucket::new(RateLimiterConfig::development());
182 let error_manager = ErrorRecoveryManager::new();
183
184 println!("Integrated Resilience Components:");
185 println!(" Circuit Breaker: {:?}", circuit_breaker.state());
186 println!(" Rate Limiter: {:.1}% success rate", rate_limiter.success_rate());
187 println!(" Error Manager: {} total errors", error_manager.get_error_statistics().total_errors);
188
189 // Simulate a resilient operation
190 println!("\nSimulating resilient operation:");
191 for i in 1..=5 {
192 println!(" Operation {}:", i);
193
194 // Step 1: Rate limiting
195 match rate_limiter.acquire(1).await {
196 Ok(_) => println!(" ✅ Rate limit passed"),
197 Err(e) => {
198 println!(" ❌ Rate limited: {}", e);
199 continue;
200 }
201 }
202
203 // Step 2: Circuit breaker protection
204 let result = circuit_breaker.call(async {
205 // Simulate API call with occasional failures
206 if i % 4 == 0 {
207 Err(ai_lib::types::AiLibError::ProviderError("Simulated provider error".to_string()))
208 } else {
209 Ok(format!("API response {}", i))
210 }
211 }).await;
212
213 // Step 3: Error handling
214 match result {
215 Ok(response) => {
216 println!(" ✅ Success: {}", response);
217 rate_limiter.adjust_rate(true);
218 }
219 Err(e) => {
220 println!(" ❌ Failed: {}", e);
221 rate_limiter.adjust_rate(false);
222
223 // Convert CircuitBreakerError to AiLibError for error manager
224 let ai_error = match e {
225 CircuitBreakerError::Underlying(err) => err,
226 CircuitBreakerError::CircuitOpen(msg) => ai_lib::types::AiLibError::ProviderError(msg),
227 CircuitBreakerError::RequestTimeout(msg) => ai_lib::types::AiLibError::TimeoutError(msg),
228 CircuitBreakerError::Disabled => ai_lib::types::AiLibError::ConfigurationError("Circuit breaker disabled".to_string()),
229 };
230
231 let context = ErrorContext::new("demo_provider".to_string(), "/demo/endpoint".to_string());
232 let _ = error_manager.handle_error(&ai_error, &context).await;
233 }
234 }
235
236 // Show current state
237 println!(" State: CB={:?}, RL={:.1}%",
238 circuit_breaker.state(), rate_limiter.success_rate());
239 }
240
241 Ok(())
242}
Sourcepub fn with_metrics(metrics: Arc<dyn Metrics>) -> Self
pub fn with_metrics(metrics: Arc<dyn Metrics>) -> Self
Create a new error recovery manager with metrics
Sourcepub fn register_strategy(
&mut self,
error_type: ErrorType,
strategy: Box<dyn RecoveryStrategy>,
)
pub fn register_strategy( &mut self, error_type: ErrorType, strategy: Box<dyn RecoveryStrategy>, )
Register a recovery strategy for a specific error type
Sourcepub async fn handle_error(
&self,
error: &AiLibError,
context: &ErrorContext,
) -> Result<(), AiLibError>
pub async fn handle_error( &self, error: &AiLibError, context: &ErrorContext, ) -> Result<(), AiLibError>
Handle an error and attempt recovery
Examples found in repository?
examples/resilience_example.rs (line 154)
140async fn demonstrate_error_handling() -> Result<(), Box<dyn std::error::Error>> {
141 let error_manager = ErrorRecoveryManager::new();
142
143 // Simulate different types of errors
144 let errors = vec![
145 ("Rate Limit", ai_lib::types::AiLibError::RateLimitExceeded("API rate limit exceeded".to_string())),
146 ("Network", ai_lib::types::AiLibError::NetworkError("Connection timeout".to_string())),
147 ("Authentication", ai_lib::types::AiLibError::AuthenticationError("Invalid API key".to_string())),
148 ("Context Length", ai_lib::types::AiLibError::ContextLengthExceeded("Request too long".to_string())),
149 ];
150
151 println!("Error Handling and Pattern Analysis:");
152 for (error_type, error) in errors {
153 let context = ErrorContext::new("demo_provider".to_string(), "/demo/endpoint".to_string());
154 let result = error_manager.handle_error(&error, &context).await;
155
156 println!(" {} Error: {}", error_type, error);
157 println!(" Suggested Action: {:?}", context.suggested_action);
158 println!(" Recovery Result: {}", if result.is_ok() { "Success" } else { "Failed" });
159 }
160
161 // Show error statistics
162 let stats = error_manager.get_error_statistics();
163 println!("\nError Statistics:");
164 println!(" Total Errors: {}", stats.total_errors);
165 println!(" Unique Error Types: {}", stats.unique_error_types);
166 println!(" Most Common: {:?}", stats.most_common_error);
167
168 // Show error patterns
169 let patterns = error_manager.get_error_patterns();
170 for (error_type, pattern) in patterns {
171 println!(" {:?}: {} occurrences, {:.2} errors/min",
172 error_type, pattern.count, pattern.frequency);
173 }
174
175 Ok(())
176}
177
178async fn demonstrate_integrated_resilience() -> Result<(), Box<dyn std::error::Error>> {
179 // Create all resilience components
180 let circuit_breaker = CircuitBreaker::new(CircuitBreakerConfig::development());
181 let rate_limiter = TokenBucket::new(RateLimiterConfig::development());
182 let error_manager = ErrorRecoveryManager::new();
183
184 println!("Integrated Resilience Components:");
185 println!(" Circuit Breaker: {:?}", circuit_breaker.state());
186 println!(" Rate Limiter: {:.1}% success rate", rate_limiter.success_rate());
187 println!(" Error Manager: {} total errors", error_manager.get_error_statistics().total_errors);
188
189 // Simulate a resilient operation
190 println!("\nSimulating resilient operation:");
191 for i in 1..=5 {
192 println!(" Operation {}:", i);
193
194 // Step 1: Rate limiting
195 match rate_limiter.acquire(1).await {
196 Ok(_) => println!(" ✅ Rate limit passed"),
197 Err(e) => {
198 println!(" ❌ Rate limited: {}", e);
199 continue;
200 }
201 }
202
203 // Step 2: Circuit breaker protection
204 let result = circuit_breaker.call(async {
205 // Simulate API call with occasional failures
206 if i % 4 == 0 {
207 Err(ai_lib::types::AiLibError::ProviderError("Simulated provider error".to_string()))
208 } else {
209 Ok(format!("API response {}", i))
210 }
211 }).await;
212
213 // Step 3: Error handling
214 match result {
215 Ok(response) => {
216 println!(" ✅ Success: {}", response);
217 rate_limiter.adjust_rate(true);
218 }
219 Err(e) => {
220 println!(" ❌ Failed: {}", e);
221 rate_limiter.adjust_rate(false);
222
223 // Convert CircuitBreakerError to AiLibError for error manager
224 let ai_error = match e {
225 CircuitBreakerError::Underlying(err) => err,
226 CircuitBreakerError::CircuitOpen(msg) => ai_lib::types::AiLibError::ProviderError(msg),
227 CircuitBreakerError::RequestTimeout(msg) => ai_lib::types::AiLibError::TimeoutError(msg),
228 CircuitBreakerError::Disabled => ai_lib::types::AiLibError::ConfigurationError("Circuit breaker disabled".to_string()),
229 };
230
231 let context = ErrorContext::new("demo_provider".to_string(), "/demo/endpoint".to_string());
232 let _ = error_manager.handle_error(&ai_error, &context).await;
233 }
234 }
235
236 // Show current state
237 println!(" State: CB={:?}, RL={:.1}%",
238 circuit_breaker.state(), rate_limiter.success_rate());
239 }
240
241 Ok(())
242}
Sourcepub fn get_error_patterns(&self) -> HashMap<ErrorType, ErrorPattern>
pub fn get_error_patterns(&self) -> HashMap<ErrorType, ErrorPattern>
Get error patterns for analysis
Examples found in repository?
examples/resilience_example.rs (line 169)
140async fn demonstrate_error_handling() -> Result<(), Box<dyn std::error::Error>> {
141 let error_manager = ErrorRecoveryManager::new();
142
143 // Simulate different types of errors
144 let errors = vec![
145 ("Rate Limit", ai_lib::types::AiLibError::RateLimitExceeded("API rate limit exceeded".to_string())),
146 ("Network", ai_lib::types::AiLibError::NetworkError("Connection timeout".to_string())),
147 ("Authentication", ai_lib::types::AiLibError::AuthenticationError("Invalid API key".to_string())),
148 ("Context Length", ai_lib::types::AiLibError::ContextLengthExceeded("Request too long".to_string())),
149 ];
150
151 println!("Error Handling and Pattern Analysis:");
152 for (error_type, error) in errors {
153 let context = ErrorContext::new("demo_provider".to_string(), "/demo/endpoint".to_string());
154 let result = error_manager.handle_error(&error, &context).await;
155
156 println!(" {} Error: {}", error_type, error);
157 println!(" Suggested Action: {:?}", context.suggested_action);
158 println!(" Recovery Result: {}", if result.is_ok() { "Success" } else { "Failed" });
159 }
160
161 // Show error statistics
162 let stats = error_manager.get_error_statistics();
163 println!("\nError Statistics:");
164 println!(" Total Errors: {}", stats.total_errors);
165 println!(" Unique Error Types: {}", stats.unique_error_types);
166 println!(" Most Common: {:?}", stats.most_common_error);
167
168 // Show error patterns
169 let patterns = error_manager.get_error_patterns();
170 for (error_type, pattern) in patterns {
171 println!(" {:?}: {} occurrences, {:.2} errors/min",
172 error_type, pattern.count, pattern.frequency);
173 }
174
175 Ok(())
176}
Sourcepub fn get_error_statistics(&self) -> ErrorStatistics
pub fn get_error_statistics(&self) -> ErrorStatistics
Get error statistics
Examples found in repository?
examples/resilience_example.rs (line 162)
140async fn demonstrate_error_handling() -> Result<(), Box<dyn std::error::Error>> {
141 let error_manager = ErrorRecoveryManager::new();
142
143 // Simulate different types of errors
144 let errors = vec![
145 ("Rate Limit", ai_lib::types::AiLibError::RateLimitExceeded("API rate limit exceeded".to_string())),
146 ("Network", ai_lib::types::AiLibError::NetworkError("Connection timeout".to_string())),
147 ("Authentication", ai_lib::types::AiLibError::AuthenticationError("Invalid API key".to_string())),
148 ("Context Length", ai_lib::types::AiLibError::ContextLengthExceeded("Request too long".to_string())),
149 ];
150
151 println!("Error Handling and Pattern Analysis:");
152 for (error_type, error) in errors {
153 let context = ErrorContext::new("demo_provider".to_string(), "/demo/endpoint".to_string());
154 let result = error_manager.handle_error(&error, &context).await;
155
156 println!(" {} Error: {}", error_type, error);
157 println!(" Suggested Action: {:?}", context.suggested_action);
158 println!(" Recovery Result: {}", if result.is_ok() { "Success" } else { "Failed" });
159 }
160
161 // Show error statistics
162 let stats = error_manager.get_error_statistics();
163 println!("\nError Statistics:");
164 println!(" Total Errors: {}", stats.total_errors);
165 println!(" Unique Error Types: {}", stats.unique_error_types);
166 println!(" Most Common: {:?}", stats.most_common_error);
167
168 // Show error patterns
169 let patterns = error_manager.get_error_patterns();
170 for (error_type, pattern) in patterns {
171 println!(" {:?}: {} occurrences, {:.2} errors/min",
172 error_type, pattern.count, pattern.frequency);
173 }
174
175 Ok(())
176}
177
178async fn demonstrate_integrated_resilience() -> Result<(), Box<dyn std::error::Error>> {
179 // Create all resilience components
180 let circuit_breaker = CircuitBreaker::new(CircuitBreakerConfig::development());
181 let rate_limiter = TokenBucket::new(RateLimiterConfig::development());
182 let error_manager = ErrorRecoveryManager::new();
183
184 println!("Integrated Resilience Components:");
185 println!(" Circuit Breaker: {:?}", circuit_breaker.state());
186 println!(" Rate Limiter: {:.1}% success rate", rate_limiter.success_rate());
187 println!(" Error Manager: {} total errors", error_manager.get_error_statistics().total_errors);
188
189 // Simulate a resilient operation
190 println!("\nSimulating resilient operation:");
191 for i in 1..=5 {
192 println!(" Operation {}:", i);
193
194 // Step 1: Rate limiting
195 match rate_limiter.acquire(1).await {
196 Ok(_) => println!(" ✅ Rate limit passed"),
197 Err(e) => {
198 println!(" ❌ Rate limited: {}", e);
199 continue;
200 }
201 }
202
203 // Step 2: Circuit breaker protection
204 let result = circuit_breaker.call(async {
205 // Simulate API call with occasional failures
206 if i % 4 == 0 {
207 Err(ai_lib::types::AiLibError::ProviderError("Simulated provider error".to_string()))
208 } else {
209 Ok(format!("API response {}", i))
210 }
211 }).await;
212
213 // Step 3: Error handling
214 match result {
215 Ok(response) => {
216 println!(" ✅ Success: {}", response);
217 rate_limiter.adjust_rate(true);
218 }
219 Err(e) => {
220 println!(" ❌ Failed: {}", e);
221 rate_limiter.adjust_rate(false);
222
223 // Convert CircuitBreakerError to AiLibError for error manager
224 let ai_error = match e {
225 CircuitBreakerError::Underlying(err) => err,
226 CircuitBreakerError::CircuitOpen(msg) => ai_lib::types::AiLibError::ProviderError(msg),
227 CircuitBreakerError::RequestTimeout(msg) => ai_lib::types::AiLibError::TimeoutError(msg),
228 CircuitBreakerError::Disabled => ai_lib::types::AiLibError::ConfigurationError("Circuit breaker disabled".to_string()),
229 };
230
231 let context = ErrorContext::new("demo_provider".to_string(), "/demo/endpoint".to_string());
232 let _ = error_manager.handle_error(&ai_error, &context).await;
233 }
234 }
235
236 // Show current state
237 println!(" State: CB={:?}, RL={:.1}%",
238 circuit_breaker.state(), rate_limiter.success_rate());
239 }
240
241 Ok(())
242}
Auto Trait Implementations§
impl Freeze for ErrorRecoveryManager
impl !RefUnwindSafe for ErrorRecoveryManager
impl Send for ErrorRecoveryManager
impl Sync for ErrorRecoveryManager
impl Unpin for ErrorRecoveryManager
impl !UnwindSafe for ErrorRecoveryManager
Blanket Implementations§
Source§impl<T> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
Source§fn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
Mutably borrows from an owned value. Read more