mockforge-grpc 0.3.107

gRPC protocol support for MockForge
Documentation
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
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
//! Error handling and retry mechanisms for the reflection proxy

use serde::{Deserialize, Serialize};
use std::time::Duration;
use tokio::time::sleep;
use tonic::Status;
use tracing::{debug, error, warn};

/// Configuration for error handling and retries
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ErrorConfig {
    /// Maximum number of retries for failed requests
    pub max_retries: u32,
    /// Base delay between retries (in milliseconds)
    pub base_delay_ms: u64,
    /// Maximum delay between retries (in milliseconds)
    pub max_delay_ms: u64,
    /// Whether to enable exponential backoff
    pub exponential_backoff: bool,
}

impl Default for ErrorConfig {
    fn default() -> Self {
        Self {
            max_retries: 3,
            base_delay_ms: 100,
            max_delay_ms: 5000,
            exponential_backoff: true,
        }
    }
}

/// Handle errors with retry logic
pub async fn handle_with_retry<F, Fut, T>(
    mut operation: F,
    config: &ErrorConfig,
) -> Result<T, Status>
where
    F: FnMut() -> Fut,
    Fut: std::future::Future<Output = Result<T, Status>>,
{
    let mut attempts = 0;
    let mut delay = Duration::from_millis(config.base_delay_ms);

    loop {
        match operation().await {
            Ok(result) => return Ok(result),
            Err(status) => {
                attempts += 1;

                // If we've reached the maximum retries, return the error
                if attempts > config.max_retries {
                    error!("Operation failed after {} attempts: {}", attempts, status);
                    return Err(status);
                }

                // For certain types of errors, we might not want to retry
                match status.code() {
                    // Don't retry these errors
                    tonic::Code::InvalidArgument
                    | tonic::Code::NotFound
                    | tonic::Code::AlreadyExists
                    | tonic::Code::PermissionDenied
                    | tonic::Code::FailedPrecondition
                    | tonic::Code::Aborted
                    | tonic::Code::OutOfRange
                    | tonic::Code::Unimplemented => {
                        error!("Non-retryable error: {}", status);
                        return Err(status);
                    }
                    // Retry all other errors
                    _ => {
                        warn!(
                            "Attempt {} failed: {}. Retrying in {:?}...",
                            attempts, status, delay
                        );

                        // Wait before retrying
                        sleep(delay).await;

                        // Calculate next delay with exponential backoff
                        if config.exponential_backoff {
                            delay = Duration::from_millis(
                                (delay.as_millis() * 2).min(config.max_delay_ms as u128) as u64,
                            );
                        }
                    }
                }
            }
        }
    }
}

/// Simulate various error conditions for testing
pub fn simulate_error(error_rate: f64) -> Result<(), Status> {
    use rand::Rng;

    let mut rng = rand::rng();
    let random: f64 = rng.random();

    if random < error_rate {
        // Simulate different types of errors
        let error_type: u32 = rng.random_range(0..5);
        match error_type {
            0 => Err(Status::unavailable("Simulated service unavailable")),
            1 => Err(Status::deadline_exceeded("Simulated timeout")),
            2 => Err(Status::internal("Simulated internal error")),
            3 => Err(Status::resource_exhausted("Simulated resource exhausted")),
            _ => Err(Status::unknown("Simulated unknown error")),
        }
    } else {
        Ok(())
    }
}

/// Add latency to simulate network delays
pub async fn simulate_latency(latency_ms: u64) {
    if latency_ms > 0 {
        debug!("Simulating {}ms latency", latency_ms);
        sleep(Duration::from_millis(latency_ms)).await;
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    // ==================== ErrorConfig Tests ====================

    #[test]
    fn test_error_config_default() {
        let config = ErrorConfig::default();

        assert_eq!(config.max_retries, 3);
        assert_eq!(config.base_delay_ms, 100);
        assert_eq!(config.max_delay_ms, 5000);
        assert!(config.exponential_backoff);
    }

    #[test]
    fn test_error_config_custom_values() {
        let config = ErrorConfig {
            max_retries: 5,
            base_delay_ms: 200,
            max_delay_ms: 10000,
            exponential_backoff: false,
        };

        assert_eq!(config.max_retries, 5);
        assert_eq!(config.base_delay_ms, 200);
        assert_eq!(config.max_delay_ms, 10000);
        assert!(!config.exponential_backoff);
    }

    #[test]
    fn test_error_config_clone() {
        let config = ErrorConfig {
            max_retries: 4,
            base_delay_ms: 150,
            max_delay_ms: 8000,
            exponential_backoff: true,
        };

        let cloned = config.clone();

        assert_eq!(cloned.max_retries, config.max_retries);
        assert_eq!(cloned.base_delay_ms, config.base_delay_ms);
        assert_eq!(cloned.max_delay_ms, config.max_delay_ms);
        assert_eq!(cloned.exponential_backoff, config.exponential_backoff);
    }

    #[test]
    fn test_error_config_debug() {
        let config = ErrorConfig::default();
        let debug_str = format!("{:?}", config);

        assert!(debug_str.contains("max_retries"));
        assert!(debug_str.contains("base_delay_ms"));
        assert!(debug_str.contains("max_delay_ms"));
        assert!(debug_str.contains("exponential_backoff"));
    }

    #[test]
    fn test_error_config_serialization() {
        let config = ErrorConfig {
            max_retries: 5,
            base_delay_ms: 250,
            max_delay_ms: 15000,
            exponential_backoff: true,
        };

        let json = serde_json::to_string(&config).unwrap();
        let deserialized: ErrorConfig = serde_json::from_str(&json).unwrap();

        assert_eq!(deserialized.max_retries, config.max_retries);
        assert_eq!(deserialized.base_delay_ms, config.base_delay_ms);
        assert_eq!(deserialized.max_delay_ms, config.max_delay_ms);
        assert_eq!(deserialized.exponential_backoff, config.exponential_backoff);
    }

    #[test]
    fn test_error_config_deserialization() {
        let json = r#"{
            "max_retries": 10,
            "base_delay_ms": 500,
            "max_delay_ms": 30000,
            "exponential_backoff": false
        }"#;

        let config: ErrorConfig = serde_json::from_str(json).unwrap();

        assert_eq!(config.max_retries, 10);
        assert_eq!(config.base_delay_ms, 500);
        assert_eq!(config.max_delay_ms, 30000);
        assert!(!config.exponential_backoff);
    }

    #[test]
    fn test_error_config_zero_retries() {
        let config = ErrorConfig {
            max_retries: 0,
            base_delay_ms: 100,
            max_delay_ms: 1000,
            exponential_backoff: true,
        };

        assert_eq!(config.max_retries, 0);
    }

    #[test]
    fn test_error_config_high_retries() {
        let config = ErrorConfig {
            max_retries: 100,
            base_delay_ms: 10,
            max_delay_ms: 60000,
            exponential_backoff: true,
        };

        assert_eq!(config.max_retries, 100);
    }

    // ==================== simulate_error Tests ====================

    #[test]
    fn test_simulate_error_zero_rate() {
        // With 0% error rate, should always succeed
        for _ in 0..100 {
            let result = simulate_error(0.0);
            assert!(result.is_ok());
        }
    }

    #[test]
    fn test_simulate_error_full_rate() {
        // With 100% error rate, should always fail
        for _ in 0..100 {
            let result = simulate_error(1.0);
            assert!(result.is_err());
        }
    }

    #[test]
    fn test_simulate_error_produces_status() {
        // When error occurs, should return a tonic Status
        let result = simulate_error(1.0);
        assert!(result.is_err());

        let status = result.unwrap_err();
        // Status should have a valid code
        let code = status.code();
        assert!(matches!(
            code,
            tonic::Code::Unavailable
                | tonic::Code::DeadlineExceeded
                | tonic::Code::Internal
                | tonic::Code::ResourceExhausted
                | tonic::Code::Unknown
        ));
    }

    #[test]
    fn test_simulate_error_partial_rate() {
        // With 50% error rate, should have some successes and some failures
        let mut successes = 0;
        let mut failures = 0;

        for _ in 0..1000 {
            match simulate_error(0.5) {
                Ok(()) => successes += 1,
                Err(_) => failures += 1,
            }
        }

        // With 1000 samples, we should have both successes and failures
        assert!(successes > 0, "Expected some successes");
        assert!(failures > 0, "Expected some failures");
    }

    // ==================== simulate_latency Tests ====================

    #[tokio::test]
    async fn test_simulate_latency_zero() {
        let start = std::time::Instant::now();
        simulate_latency(0).await;
        let elapsed = start.elapsed();

        // Should complete almost instantly (allow 10ms margin)
        assert!(elapsed.as_millis() < 10);
    }

    #[tokio::test]
    async fn test_simulate_latency_short() {
        let start = std::time::Instant::now();
        simulate_latency(50).await;
        let elapsed = start.elapsed();

        // Should take at least 50ms (allow some margin)
        assert!(elapsed.as_millis() >= 45);
        // Should not take too long (allow 100ms margin for scheduling)
        assert!(elapsed.as_millis() < 150);
    }

    #[tokio::test]
    async fn test_simulate_latency_longer() {
        let start = std::time::Instant::now();
        simulate_latency(100).await;
        let elapsed = start.elapsed();

        // Should take at least 100ms
        assert!(elapsed.as_millis() >= 95);
    }

    // ==================== handle_with_retry Tests ====================

    #[tokio::test]
    async fn test_handle_with_retry_immediate_success() {
        let config = ErrorConfig::default();

        let result = handle_with_retry(|| async { Ok::<_, Status>("success") }, &config).await;

        assert!(result.is_ok());
        assert_eq!(result.unwrap(), "success");
    }

    #[tokio::test]
    async fn test_handle_with_retry_non_retryable_error() {
        let config = ErrorConfig::default();

        // InvalidArgument is a non-retryable error
        let result = handle_with_retry(
            || async { Err::<(), _>(Status::invalid_argument("bad argument")) },
            &config,
        )
        .await;

        assert!(result.is_err());
        assert_eq!(result.unwrap_err().code(), tonic::Code::InvalidArgument);
    }

    #[tokio::test]
    async fn test_handle_with_retry_not_found_no_retry() {
        let config = ErrorConfig::default();

        let result = handle_with_retry(
            || async { Err::<(), _>(Status::not_found("resource not found")) },
            &config,
        )
        .await;

        assert!(result.is_err());
        assert_eq!(result.unwrap_err().code(), tonic::Code::NotFound);
    }

    #[tokio::test]
    async fn test_handle_with_retry_already_exists_no_retry() {
        let config = ErrorConfig::default();

        let result = handle_with_retry(
            || async { Err::<(), _>(Status::already_exists("already exists")) },
            &config,
        )
        .await;

        assert!(result.is_err());
        assert_eq!(result.unwrap_err().code(), tonic::Code::AlreadyExists);
    }

    #[tokio::test]
    async fn test_handle_with_retry_permission_denied_no_retry() {
        let config = ErrorConfig::default();

        let result = handle_with_retry(
            || async { Err::<(), _>(Status::permission_denied("access denied")) },
            &config,
        )
        .await;

        assert!(result.is_err());
        assert_eq!(result.unwrap_err().code(), tonic::Code::PermissionDenied);
    }

    #[tokio::test]
    async fn test_handle_with_retry_unimplemented_no_retry() {
        let config = ErrorConfig::default();

        let result = handle_with_retry(
            || async { Err::<(), _>(Status::unimplemented("not implemented")) },
            &config,
        )
        .await;

        assert!(result.is_err());
        assert_eq!(result.unwrap_err().code(), tonic::Code::Unimplemented);
    }

    #[tokio::test]
    async fn test_handle_with_retry_retryable_error_eventual_success() {
        let config = ErrorConfig {
            max_retries: 3,
            base_delay_ms: 10,
            max_delay_ms: 100,
            exponential_backoff: false,
        };

        let counter = std::sync::Arc::new(std::sync::atomic::AtomicU32::new(0));
        let counter_clone = counter.clone();

        let result = handle_with_retry(
            || {
                let counter = counter_clone.clone();
                async move {
                    let count = counter.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
                    if count < 2 {
                        Err(Status::unavailable("service unavailable"))
                    } else {
                        Ok("success")
                    }
                }
            },
            &config,
        )
        .await;

        assert!(result.is_ok());
        assert_eq!(result.unwrap(), "success");
        // Should have been called 3 times (2 failures + 1 success)
        assert_eq!(counter.load(std::sync::atomic::Ordering::Relaxed), 3);
    }

    #[tokio::test]
    async fn test_handle_with_retry_max_retries_exceeded() {
        let config = ErrorConfig {
            max_retries: 2,
            base_delay_ms: 10,
            max_delay_ms: 100,
            exponential_backoff: false,
        };

        let counter = std::sync::Arc::new(std::sync::atomic::AtomicU32::new(0));
        let counter_clone = counter.clone();

        let result = handle_with_retry(
            || {
                let counter = counter_clone.clone();
                async move {
                    counter.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
                    Err::<(), _>(Status::unavailable("service unavailable"))
                }
            },
            &config,
        )
        .await;

        assert!(result.is_err());
        // Initial attempt + 2 retries = 3 total calls
        assert_eq!(counter.load(std::sync::atomic::Ordering::Relaxed), 3);
    }

    #[tokio::test]
    async fn test_handle_with_retry_zero_retries() {
        let config = ErrorConfig {
            max_retries: 0,
            base_delay_ms: 10,
            max_delay_ms: 100,
            exponential_backoff: false,
        };

        let counter = std::sync::Arc::new(std::sync::atomic::AtomicU32::new(0));
        let counter_clone = counter.clone();

        let result = handle_with_retry(
            || {
                let counter = counter_clone.clone();
                async move {
                    counter.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
                    Err::<(), _>(Status::unavailable("service unavailable"))
                }
            },
            &config,
        )
        .await;

        assert!(result.is_err());
        // With 0 retries, should only try once
        assert_eq!(counter.load(std::sync::atomic::Ordering::Relaxed), 1);
    }

    #[tokio::test]
    async fn test_handle_with_retry_deadline_exceeded_retryable() {
        let config = ErrorConfig {
            max_retries: 2,
            base_delay_ms: 10,
            max_delay_ms: 100,
            exponential_backoff: false,
        };

        let counter = std::sync::Arc::new(std::sync::atomic::AtomicU32::new(0));
        let counter_clone = counter.clone();

        let _ = handle_with_retry(
            || {
                let counter = counter_clone.clone();
                async move {
                    counter.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
                    Err::<(), _>(Status::deadline_exceeded("timeout"))
                }
            },
            &config,
        )
        .await;

        // DeadlineExceeded is retryable, so should try 3 times
        assert_eq!(counter.load(std::sync::atomic::Ordering::Relaxed), 3);
    }

    #[tokio::test]
    async fn test_handle_with_retry_internal_error_retryable() {
        let config = ErrorConfig {
            max_retries: 1,
            base_delay_ms: 10,
            max_delay_ms: 100,
            exponential_backoff: false,
        };

        let counter = std::sync::Arc::new(std::sync::atomic::AtomicU32::new(0));
        let counter_clone = counter.clone();

        let _ = handle_with_retry(
            || {
                let counter = counter_clone.clone();
                async move {
                    counter.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
                    Err::<(), _>(Status::internal("internal error"))
                }
            },
            &config,
        )
        .await;

        // Internal is retryable, should try 2 times (1 initial + 1 retry)
        assert_eq!(counter.load(std::sync::atomic::Ordering::Relaxed), 2);
    }

    // ==================== Edge Cases ====================

    #[test]
    fn test_error_config_json_roundtrip() {
        let config = ErrorConfig::default();
        let json = serde_json::to_string(&config).unwrap();
        let roundtrip: ErrorConfig = serde_json::from_str(&json).unwrap();

        assert_eq!(roundtrip.max_retries, config.max_retries);
        assert_eq!(roundtrip.base_delay_ms, config.base_delay_ms);
        assert_eq!(roundtrip.max_delay_ms, config.max_delay_ms);
        assert_eq!(roundtrip.exponential_backoff, config.exponential_backoff);
    }

    #[test]
    fn test_simulate_error_negative_rate_treated_as_zero() {
        // Negative error rate should effectively be 0%
        let result = simulate_error(-0.5);
        assert!(result.is_ok());
    }

    #[test]
    fn test_simulate_error_rate_above_one_always_fails() {
        // Error rate above 1.0 should always fail
        for _ in 0..10 {
            let result = simulate_error(1.5);
            assert!(result.is_err());
        }
    }
}