go_zoom_kinesis/retry/
mod.rs

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
//! Retry and backoff functionality for the Kinesis processor

pub mod backoff;
pub mod error;

pub use backoff::{Backoff, ExponentialBackoff};
pub use error::RetryError;

use std::time::Duration;
use tokio::select;
use tracing::{debug, trace, warn};

/// Configuration for retry behavior
#[derive(Debug, Clone)]
pub struct RetryConfig {
    /// Maximum number of retry attempts (None for infinite)
    pub max_retries: Option<u32>,
    /// Initial backoff duration
    pub initial_backoff: Duration,
    /// Maximum backoff duration
    pub max_backoff: Duration,
    /// Jitter factor (0.0 to 1.0)
    pub jitter_factor: f64,
}

impl Default for RetryConfig {
    fn default() -> Self {
        Self {
            max_retries: None, // Infinite retries
            initial_backoff: Duration::from_millis(100),
            max_backoff: Duration::from_secs(30),
            jitter_factor: 0.1,
        }
    }
}

/// Helper for retrying operations with backoff
pub struct RetryHandle<B: Backoff> {
    config: RetryConfig,
    backoff: B,
    attempts: u32,
}

impl<B: Backoff> RetryHandle<B> {
    pub fn new(config: RetryConfig, backoff: B) -> Self {
        Self {
            config,
            backoff,
            attempts: 0,
        }
    }

    /// Retry an operation with backoff
    pub async fn retry<F, Fut, T, E>(
        &mut self,
        mut operation: F,
        shutdown: &mut tokio::sync::watch::Receiver<bool>,
    ) -> Result<T, RetryError>
    where
        F: FnMut() -> Fut,
        Fut: std::future::Future<Output = Result<T, E>>,
        E: std::fmt::Display,
    {
        loop {
            self.attempts += 1;
            trace!(attempt = self.attempts, "Executing operation");

            select! {
                result = operation() => {
                    match result {
                        Ok(value) => {
                            debug!(attempts = self.attempts, "Operation succeeded");
                            return Ok(value);
                        }
                        Err(e) => {
                            if let Some(max) = self.config.max_retries {
                                if self.attempts >= max {
                                    warn!(
                                        attempts = self.attempts,
                                        error = %e,
                                        "Maximum retry attempts exceeded"
                                    );
                                    return Err(RetryError::MaxRetriesExceeded(self.attempts, e.to_string()));
                                }
                            }

                            let delay = self.backoff.next_delay(self.attempts);
                            warn!(
                                attempt = self.attempts,
                                delay_ms = ?delay.as_millis(),
                                error = %e,
                                "Operation failed, retrying after delay"
                            );

                            select! {
                                _ = tokio::time::sleep(delay) => continue,
                                _ = shutdown.changed() => {
                                    debug!("Retry interrupted by shutdown signal");
                                    return Err(RetryError::Interrupted);
                                }
                            }
                        }
                    }
                }
                _ = shutdown.changed() => {
                    debug!("Operation interrupted by shutdown signal");
                    return Err(RetryError::Interrupted);
                }
            }
        }
    }

    /// Reset the retry counter
    pub fn reset(&mut self) {
        self.attempts = 0;
        self.backoff.reset();
    }

    /// Get the current attempt count
    pub fn attempts(&self) -> u32 {
        self.attempts
    }
}

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

    use std::sync::atomic::{AtomicU32, Ordering};
    use std::sync::Arc;

    #[tokio::test]
    async fn test_retry_success() -> anyhow::Result<()> {
        let config = RetryConfig::default();
        let backoff = ExponentialBackoff::new(config.initial_backoff, config.max_backoff);

        let mut retry = RetryHandle::new(config, backoff);
        let (shutdown_tx, mut shutdown_rx) = tokio::sync::watch::channel(false);

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

        let result = retry
            .retry(
                || {
                    let value = counter_clone.clone();
                    async move {
                        let attempts = value.fetch_add(1, Ordering::SeqCst);
                        if attempts < 2 {
                            Err("not yet")
                        } else {
                            Ok("success")
                        }
                    }
                },
                &mut shutdown_rx,
            )
            .await;

        assert!(result.is_ok());
        assert_eq!(counter.load(Ordering::SeqCst), 3);
        assert_eq!(retry.attempts(), 3);

        drop(shutdown_tx); // Prevent memory leak in test
        Ok(())
    }

    #[tokio::test]
    async fn test_retry_max_attempts() -> anyhow::Result<()> {
        let config = RetryConfig {
            max_retries: Some(2),
            ..Default::default()
        };

        let backoff = ExponentialBackoff::new(config.initial_backoff, config.max_backoff);

        let mut retry = RetryHandle::new(config, backoff);
        let (shutdown_tx, mut shutdown_rx) = tokio::sync::watch::channel(false);

        let result: Result<(), _> = retry
            .retry(|| async { Err("always fails") }, &mut shutdown_rx)
            .await;

        assert!(matches!(result, Err(RetryError::MaxRetriesExceeded(2, _))));

        drop(shutdown_tx);
        Ok(())
    }

    #[tokio::test]
    async fn test_retry_shutdown() -> anyhow::Result<()> {
        let config = RetryConfig::default();
        let backoff = ExponentialBackoff::new(config.initial_backoff, config.max_backoff);

        let mut retry = RetryHandle::new(config, backoff);
        let (shutdown_tx, mut shutdown_rx) = tokio::sync::watch::channel(false);

        let handle = tokio::spawn(async move {
            retry
                .retry(
                    || async {
                        tokio::time::sleep(Duration::from_secs(1)).await;
                        Err("never succeeds")
                    },
                    &mut shutdown_rx,
                )
                .await
        });

        tokio::time::sleep(Duration::from_millis(50)).await;
        shutdown_tx.send(true)?;

        let result: Result<(), _> = handle.await?;
        assert!(matches!(result, Err(RetryError::Interrupted)));

        Ok(())
    }

    #[tokio::test]
    async fn test_retry_with_backoff() -> anyhow::Result<()> {
        let config = RetryConfig {
            max_retries: Some(3),
            initial_backoff: Duration::from_millis(10),
            max_backoff: Duration::from_millis(100),
            jitter_factor: 0.1,
        };

        let backoff = ExponentialBackoff::new(config.initial_backoff, config.max_backoff);

        let mut retry = RetryHandle::new(config, backoff);
        let (tx, mut rx) = tokio::sync::watch::channel(false);

        let attempts = Arc::new(AtomicU32::new(0));
        let attempts_clone = attempts.clone();

        let start = std::time::Instant::now();

        let result: Result<(), RetryError> = retry
            .retry(
                || {
                    let attempts = attempts_clone.clone();
                    async move {
                        let current = attempts.fetch_add(1, Ordering::SeqCst);
                        if current < 2 {
                            Err("not ready")
                        } else {
                            Ok(())
                        }
                    }
                },
                &mut rx,
            )
            .await;

        let elapsed = start.elapsed();

        assert!(result.is_ok());
        assert_eq!(attempts.load(Ordering::SeqCst), 3);
        // Verify backoff timing
        assert!(elapsed >= Duration::from_millis(20)); // At least 2 backoffs

        drop(tx);
        Ok(())
    }

    #[tokio::test]
    async fn test_retry_max_retries_exceeded() -> anyhow::Result<()> {
        let config = RetryConfig {
            max_retries: Some(2),
            initial_backoff: Duration::from_millis(10),
            max_backoff: Duration::from_millis(100),
            jitter_factor: 0.1,
        };

        let backoff = ExponentialBackoff::new(config.initial_backoff, config.max_backoff);

        let mut retry = RetryHandle::new(config, backoff);
        let (tx, mut rx) = tokio::sync::watch::channel(false);

        let result: Result<(), RetryError> =
            retry.retry(|| async { Err("always fails") }, &mut rx).await;

        assert!(matches!(result, Err(RetryError::MaxRetriesExceeded(2, _))));

        drop(tx);
        Ok(())
    }
}