1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
use Error;
/// HTTP-related errors with detailed context for network operations.
///
/// This enum provides comprehensive error classification for HTTP operations
/// throughout the application, including Azure API calls, authentication requests,
/// and other network operations. Each error variant includes relevant context
/// to aid in debugging and error handling.
///
/// # Error Categories
///
/// ## Client Configuration Errors
/// - [`ClientCreation`] - HTTP client initialization failures
///
/// ## Request Execution Errors
/// - [`RequestFailed`] - General request failures with URL and reason
/// - [`Timeout`] - Request timeout with duration and target URL
/// - [`InvalidResponse`] - Unexpected response format or content
///
/// ## Rate Limiting and Service Errors
/// - [`RateLimited`] - Rate limiting with retry timing information
///
/// # Examples
///
/// ## Basic Error Handling
/// ```no_run
/// use quetty_server::common::errors::HttpError;
///
/// async fn handle_http_error(error: HttpError) {
/// match error {
/// HttpError::Timeout { url, seconds } => {
/// eprintln!("Request to {} timed out after {}s", url, seconds);
/// // Implement retry with longer timeout
/// }
/// HttpError::RateLimited { retry_after_seconds } => {
/// println!("Rate limited. Retrying after {}s", retry_after_seconds);
/// // Wait and retry
/// }
/// HttpError::RequestFailed { url, reason } => {
/// eprintln!("Request to {} failed: {}", url, reason);
/// // Log and handle specific failure
/// }
/// HttpError::ClientCreation { reason } => {
/// eprintln!("Failed to create HTTP client: {}", reason);
/// // Reinitialize client with different configuration
/// }
/// HttpError::InvalidResponse { expected, actual } => {
/// eprintln!("Invalid response: expected {}, got {}", expected, actual);
/// // Handle unexpected response format
/// }
/// }
/// }
/// ```
///
/// ## Retry Logic Implementation
/// ```no_run
/// use quetty_server::common::errors::HttpError;
/// use std::time::Duration;
/// use tokio::time::sleep;
///
/// async fn http_request_with_retry<T>(
/// request_fn: impl Fn() -> Result<T, HttpError>
/// ) -> Result<T, HttpError> {
/// let mut attempts = 0;
/// let max_attempts = 3;
///
/// loop {
/// attempts += 1;
///
/// match request_fn() {
/// Ok(result) => return Ok(result),
/// Err(HttpError::RateLimited { retry_after_seconds }) => {
/// if attempts < max_attempts {
/// sleep(Duration::from_secs(retry_after_seconds)).await;
/// continue;
/// }
/// return Err(HttpError::RateLimited { retry_after_seconds });
/// }
/// Err(HttpError::Timeout { url, seconds }) => {
/// if attempts < max_attempts {
/// // Exponential backoff for timeouts
/// sleep(Duration::from_secs(2_u64.pow(attempts))).await;
/// continue;
/// }
/// return Err(HttpError::Timeout { url, seconds });
/// }
/// Err(other) => return Err(other), // Don't retry client errors
/// }
/// }
/// }
/// ```
///
/// ## Azure API Error Handling
/// ```no_run
/// use quetty_server::common::errors::HttpError;
///
/// async fn call_azure_api(endpoint: &str) -> Result<String, HttpError> {
/// // Simulated Azure API call
/// match make_request(endpoint).await {
/// Ok(response) => Ok(response),
/// Err(e) => {
/// // Convert to structured HttpError
/// Err(HttpError::RequestFailed {
/// url: endpoint.to_string(),
/// reason: e.to_string(),
/// })
/// }
/// }
/// }
///
/// // Usage with error context
/// let result = call_azure_api("https://management.azure.com/subscriptions").await;
/// match result {
/// Ok(data) => println!("API call successful: {}", data),
/// Err(HttpError::RequestFailed { url, reason }) => {
/// if reason.contains("401") {
/// // Handle authentication error
/// println!("Authentication required for {}", url);
/// } else if reason.contains("404") {
/// // Handle resource not found
/// println!("Resource not found: {}", url);
/// } else {
/// // Handle other errors
/// println!("Request failed: {} - {}", url, reason);
/// }
/// }
/// Err(other) => {
/// println!("HTTP error: {}", other);
/// }
/// }
/// ```
///
/// # Integration Patterns
///
/// ## Error Conversion
/// This error type is designed to be easily converted to higher-level error types:
///
/// ```no_run
/// use quetty_server::common::errors::HttpError;
/// use quetty_server::service_bus_manager::ServiceBusError;
///
/// impl From<HttpError> for ServiceBusError {
/// fn from(http_error: HttpError) -> Self {
/// match http_error {
/// HttpError::Timeout { .. } => ServiceBusError::OperationTimeout(http_error.to_string()),
/// HttpError::RateLimited { .. } => ServiceBusError::OperationTimeout(http_error.to_string()),
/// _ => ServiceBusError::ConnectionFailed(http_error.to_string()),
/// }
/// }
/// }
/// ```
///
/// ## Logging Integration
/// ```no_run
/// use quetty_server::common::errors::HttpError;
///
/// fn log_http_error(error: &HttpError) {
/// match error {
/// HttpError::RequestFailed { url, reason } => {
/// log::error!("HTTP request failed: url={}, reason={}", url, reason);
/// }
/// HttpError::Timeout { url, seconds } => {
/// log::warn!("HTTP request timeout: url={}, duration={}s", url, seconds);
/// }
/// HttpError::RateLimited { retry_after_seconds } => {
/// log::info!("HTTP rate limited: retry_after={}s", retry_after_seconds);
/// }
/// _ => {
/// log::error!("HTTP error: {}", error);
/// }
/// }
/// }
/// ```
///
/// [`ClientCreation`]: HttpError::ClientCreation
/// [`RequestFailed`]: HttpError::RequestFailed
/// [`Timeout`]: HttpError::Timeout
/// [`InvalidResponse`]: HttpError::InvalidResponse
/// [`RateLimited`]: HttpError::RateLimited
/// Cache-related errors for token and data caching operations.
///
/// This enum provides detailed error classification for caching operations
/// throughout the application, particularly for authentication token caching
/// and other temporary data storage. Each error variant includes relevant
/// context to aid in cache management and error recovery.
///
/// # Error Categories
///
/// ## Cache Entry Lifecycle Errors
/// - [`Expired`] - Cache entry has exceeded its time-to-live
/// - [`Miss`] - Requested cache entry doesn't exist
///
/// ## Cache Capacity and Management Errors
/// - [`Full`] - Cache has reached capacity limits
/// - [`OperationFailed`] - General cache operation failures
///
/// # Examples
///
/// ## Token Cache Error Handling
/// ```no_run
/// use quetty_server::common::errors::CacheError;
///
/// async fn handle_token_cache_error(error: CacheError, token_key: &str) {
/// match error {
/// CacheError::Expired { key } => {
/// println!("Token expired for key: {}", key);
/// // Trigger token refresh
/// refresh_token(&key).await;
/// }
/// CacheError::Miss { key } => {
/// println!("Token not found in cache: {}", key);
/// // Authenticate and cache new token
/// authenticate_and_cache(&key).await;
/// }
/// CacheError::Full { key } => {
/// println!("Cache full, cannot store token for: {}", key);
/// // Implement cache eviction strategy
/// evict_oldest_entries().await;
/// retry_cache_operation(&key).await;
/// }
/// CacheError::OperationFailed { reason } => {
/// eprintln!("Cache operation failed: {}", reason);
/// // Log error and use alternative storage
/// fallback_to_memory_cache(&token_key).await;
/// }
/// }
/// }
/// ```
///
/// ## Cache Management Patterns
/// ```no_run
/// use quetty_server::common::errors::CacheError;
///
/// async fn get_or_create_cached_item<T>(
/// cache_key: &str,
/// create_fn: impl Fn() -> Result<T, String>
/// ) -> Result<T, CacheError> {
/// // Try to get from cache first
/// match get_from_cache(cache_key).await {
/// Ok(item) => Ok(item),
/// Err(CacheError::Miss { .. }) => {
/// // Cache miss - create and cache the item
/// match create_fn() {
/// Ok(item) => {
/// // Attempt to cache the new item
/// if let Err(cache_err) = cache_item(cache_key, &item).await {
/// // Log cache failure but return the item anyway
/// log::warn!("Failed to cache item: {}", cache_err);
/// }
/// Ok(item)
/// }
/// Err(create_error) => {
/// Err(CacheError::OperationFailed {
/// reason: format!("Item creation failed: {}", create_error)
/// })
/// }
/// }
/// }
/// Err(CacheError::Expired { key }) => {
/// // Cache expired - remove and recreate
/// remove_from_cache(&key).await;
/// create_fn().map_err(|e| CacheError::OperationFailed {
/// reason: format!("Recreation after expiry failed: {}", e)
/// })
/// }
/// Err(other) => Err(other),
/// }
/// }
/// ```
///
/// ## Cache Health Monitoring
/// ```no_run
/// use quetty_server::common::errors::CacheError;
///
/// struct CacheMetrics {
/// hits: u64,
/// misses: u64,
/// expirations: u64,
/// failures: u64,
/// }
///
/// fn update_cache_metrics(error: &CacheError, metrics: &mut CacheMetrics) {
/// match error {
/// CacheError::Miss { .. } => {
/// metrics.misses += 1;
/// log::debug!("Cache miss recorded");
/// }
/// CacheError::Expired { .. } => {
/// metrics.expirations += 1;
/// log::debug!("Cache expiration recorded");
/// }
/// CacheError::Full { .. } | CacheError::OperationFailed { .. } => {
/// metrics.failures += 1;
/// log::warn!("Cache failure recorded: {}", error);
/// }
/// }
/// }
///
/// fn calculate_cache_hit_rate(metrics: &CacheMetrics) -> f64 {
/// let total_requests = metrics.hits + metrics.misses;
/// if total_requests == 0 {
/// 0.0
/// } else {
/// metrics.hits as f64 / total_requests as f64
/// }
/// }
/// ```
///
/// ## Integration with Authentication
/// ```no_run
/// use quetty_server::common::errors::CacheError;
/// use quetty_server::auth::TokenRefreshError;
///
/// async fn get_valid_token(user_id: &str) -> Result<String, TokenRefreshError> {
/// match get_cached_token(user_id).await {
/// Ok(token) => Ok(token),
/// Err(CacheError::Miss { .. }) | Err(CacheError::Expired { .. }) => {
/// // Cache miss or expiry - refresh token
/// let new_token = refresh_user_token(user_id).await?;
///
/// // Attempt to cache the new token
/// if let Err(cache_err) = cache_token(user_id, &new_token).await {
/// log::warn!("Failed to cache refreshed token: {}", cache_err);
/// // Continue anyway - token is still valid
/// }
///
/// Ok(new_token)
/// }
/// Err(CacheError::OperationFailed { reason }) => {
/// // Cache operation failed - try refresh anyway
/// log::error!("Cache operation failed: {}", reason);
/// refresh_user_token(user_id).await
/// }
/// Err(CacheError::Full { .. }) => {
/// // Cache full - evict and retry
/// evict_expired_tokens().await;
/// match get_cached_token(user_id).await {
/// Ok(token) => Ok(token),
/// Err(_) => refresh_user_token(user_id).await,
/// }
/// }
/// }
/// }
/// ```
///
/// # Cache Strategies
///
/// ## Error-Based Cache Management
/// - **Miss**: Create and cache new data
/// - **Expired**: Remove expired entry and recreate
/// - **Full**: Implement LRU or TTL-based eviction
/// - **Operation Failed**: Fall back to direct data access
///
/// ## Performance Considerations
/// - Cache errors should not block critical operations
/// - Implement graceful degradation when cache is unavailable
/// - Monitor cache hit rates and error frequencies
/// - Use appropriate TTL values to balance freshness and performance
///
/// [`Expired`]: CacheError::Expired
/// [`Miss`]: CacheError::Miss
/// [`Full`]: CacheError::Full
/// [`OperationFailed`]: CacheError::OperationFailed
/// Helper trait for adding context to errors