qubit-retry 0.2.0

Retry module, providing a feature-complete, type-safe retry management system with support for multiple delay strategies and event listeners
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
/*******************************************************************************
 *
 *    Copyright (c) 2025 - 2026.
 *    Haixing Hu, Qubit Co. Ltd.
 *
 *    All rights reserved.
 *
 ******************************************************************************/
//! # Failure Event
//!
//! Event triggered when an operation ultimately fails.
//!
//! # Author
//!
//! Haixing Hu

use std::error::Error as StdError;
use std::time::Duration;

use qubit_function::BoxConsumer;

/// Failure event
///
/// Event triggered when an operation ultimately fails, indicating
/// all retry attempts have been exhausted.
///
/// # Features
///
/// - Stores the error or result from the last failure
/// - Records total attempt count
/// - Tracks total time from start to failure
///
/// # Generic Parameters
///
/// * `T` - The return value type of the operation
///
/// # Use Cases
///
/// Used in failure listeners for logging failures, sending alerts,
/// or performing fault handling.
///
/// # Construction
///
/// This event must be constructed using the builder pattern via
/// `FailureEventBuilder`. The builder pattern provides a more
/// readable and flexible way to create failure events with named
/// parameters:
///
/// ```rust
/// use qubit_retry::event::failure_event::FailureEvent;
/// use std::time::Duration;
/// use std::io::{Error, ErrorKind};
///
/// let error = Error::new(
///     ErrorKind::TimedOut,
///     "All retries timed out"
/// );
///
/// // Using builder pattern - recommended approach
/// let event = FailureEvent::<String>::builder()
///     .last_error(Some(Box::new(error)))
///     .attempt_count(3)
///     .total_duration(Duration::from_secs(5))
///     .build();
/// ```
///
/// # Author
///
/// Haixing Hu
#[derive(Debug)]
pub struct FailureEvent<T> {
    /// Last error
    last_error: Option<Box<dyn StdError + Send + Sync>>,
    /// Last result
    last_result: Option<T>,
    /// Total attempt count
    attempt_count: u32,
    /// Total execution time
    total_duration: Duration,
}

impl<T> FailureEvent<T> {
    /// Create a builder for constructing `FailureEvent`
    ///
    /// # Returns
    ///
    /// Returns a new `FailureEventBuilder` instance
    ///
    /// # Example
    ///
    /// ```rust
    /// use qubit_retry::event::failure_event::FailureEvent;
    /// use std::time::Duration;
    ///
    /// let event = FailureEvent::<String>::builder()
    ///     .last_result(Some(String::from("Failed")))
    ///     .attempt_count(3)
    ///     .total_duration(Duration::from_secs(3))
    ///     .build();
    /// assert_eq!(event.attempt_count(), 3);
    /// ```
    pub fn builder() -> FailureEventBuilder<T> {
        FailureEventBuilder::new()
    }

    /// Get last error
    ///
    /// # Returns
    ///
    /// Returns reference to the error if last failure was due to
    /// error, None otherwise
    ///
    /// # Example
    ///
    /// ```rust
    /// use qubit_retry::event::failure_event::FailureEvent;
    /// use std::time::Duration;
    /// use std::io::{Error, ErrorKind};
    ///
    /// let error = Error::new(ErrorKind::TimedOut, "Timeout");
    /// let event = FailureEvent::<i32>::builder()
    ///     .last_error(Some(Box::new(error)))
    ///     .attempt_count(3)
    ///     .total_duration(Duration::from_secs(3))
    ///     .build();
    /// assert!(event.last_error().is_some());
    /// ```
    pub fn last_error(&self) -> Option<&(dyn StdError + Send + Sync)> {
        self.last_error.as_ref().map(|e| e.as_ref())
    }

    /// Get last result
    ///
    /// # Returns
    ///
    /// Returns reference to the result if last failure had a return
    /// value, None otherwise
    ///
    /// # Example
    ///
    /// ```rust
    /// use qubit_retry::event::failure_event::FailureEvent;
    /// use std::time::Duration;
    ///
    /// let event = FailureEvent::builder()
    ///     .last_result(Some(String::from("Failed")))
    ///     .attempt_count(3)
    ///     .total_duration(Duration::from_secs(3))
    ///     .build();
    /// assert_eq!(
    ///     event.last_result(),
    ///     Some(&String::from("Failed"))
    /// );
    /// ```
    pub fn last_result(&self) -> Option<&T> {
        self.last_result.as_ref()
    }

    /// Get total attempt count
    ///
    /// # Returns
    ///
    /// Returns the total attempt count before failure
    ///
    /// # Example
    ///
    /// ```rust
    /// use qubit_retry::event::failure_event::FailureEvent;
    /// use std::time::Duration;
    ///
    /// let event = FailureEvent::<i32>::builder()
    ///     .attempt_count(5)
    ///     .total_duration(Duration::from_secs(5))
    ///     .build();
    /// assert_eq!(event.attempt_count(), 5);
    /// ```
    pub fn attempt_count(&self) -> u32 {
        self.attempt_count
    }

    /// Get total execution time
    ///
    /// # Returns
    ///
    /// Returns the total time from the first attempt until failure
    ///
    /// # Example
    ///
    /// ```rust
    /// use qubit_retry::event::failure_event::FailureEvent;
    /// use std::time::Duration;
    ///
    /// let duration = Duration::from_secs(10);
    /// let event = FailureEvent::<i32>::builder()
    ///     .attempt_count(3)
    ///     .total_duration(duration)
    ///     .build();
    /// assert_eq!(event.total_duration(), duration);
    /// ```
    pub fn total_duration(&self) -> Duration {
        self.total_duration
    }
}

/// Failure event listener type
///
/// Callback function type for listening to failure events, called
/// when all retry attempts have failed.
///
/// Uses `BoxConsumer` from `qubit-function` to provide
/// readonly event consumption with single ownership.
///
/// # Generic Parameters
///
/// * `T` - The return value type of the operation
///
/// # Example
///
/// ```rust
/// use qubit_retry::event::failure_event::{
///     FailureEvent,
///     FailureEventListener
/// };
/// use qubit_function::BoxConsumer;
///
/// let listener: FailureEventListener<i32> =
///     BoxConsumer::new(|event: &FailureEvent<i32>| {
///         println!(
///             "Operation failed, attempted {} times",
///             event.attempt_count()
///         );
///     });
/// ```
pub type FailureEventListener<T> = BoxConsumer<FailureEvent<T>>;

/// Builder for constructing `FailureEvent`
///
/// Provides a fluent interface for building failure events with
/// optional error and result fields.
///
/// # Generic Parameters
///
/// * `T` - The return value type of the operation
///
/// # Example
///
/// ```rust
/// use qubit_retry::event::failure_event::FailureEvent;
/// use std::time::Duration;
///
/// let event = FailureEvent::<String>::builder()
///     .attempt_count(3)
///     .total_duration(Duration::from_secs(5))
///     .build();
/// ```
///
/// # Author
///
/// Haixing Hu
#[derive(Debug)]
#[allow(clippy::new_without_default)]
pub struct FailureEventBuilder<T> {
    last_error: Option<Box<dyn StdError + Send + Sync>>,
    last_result: Option<T>,
    attempt_count: u32,
    total_duration: Duration,
}

impl<T> FailureEventBuilder<T> {
    /// Create a new builder with default values
    ///
    /// # Returns
    ///
    /// Returns a new `FailureEventBuilder` instance
    ///
    /// # Example
    ///
    /// ```rust
    /// use qubit_retry::event::failure_event::FailureEventBuilder;
    ///
    /// let builder = FailureEventBuilder::<i32>::new();
    /// ```
    #[allow(clippy::new_without_default)]
    pub fn new() -> Self {
        Self {
            last_error: None,
            last_result: None,
            attempt_count: 0,
            total_duration: Duration::default(),
        }
    }

    /// Set the error from last failure
    ///
    /// # Parameters
    ///
    /// * `last_error` - Optional error from the last failure
    ///
    /// # Returns
    ///
    /// Returns self for method chaining
    ///
    /// # Example
    ///
    /// ```rust
    /// use qubit_retry::event::failure_event::FailureEvent;
    /// use std::io::{Error, ErrorKind};
    ///
    /// let error = Error::new(ErrorKind::TimedOut, "Timeout");
    /// let builder = FailureEvent::<i32>::builder()
    ///     .last_error(Some(Box::new(error)));
    /// ```
    pub fn last_error(mut self, last_error: Option<Box<dyn StdError + Send + Sync>>) -> Self {
        self.last_error = last_error;
        self
    }

    /// Set the result from last failure
    ///
    /// # Parameters
    ///
    /// * `last_result` - Optional result from the last failure
    ///
    /// # Returns
    ///
    /// Returns self for method chaining
    ///
    /// # Example
    ///
    /// ```rust
    /// use qubit_retry::event::failure_event::FailureEvent;
    ///
    /// let builder = FailureEvent::builder()
    ///     .last_result(Some(String::from("Failed")));
    /// ```
    pub fn last_result(mut self, last_result: Option<T>) -> Self {
        self.last_result = last_result;
        self
    }

    /// Set the total attempt count
    ///
    /// # Parameters
    ///
    /// * `attempt_count` - Total number of attempts before failure
    ///
    /// # Returns
    ///
    /// Returns self for method chaining
    ///
    /// # Example
    ///
    /// ```rust
    /// use qubit_retry::event::failure_event::FailureEvent;
    ///
    /// let builder = FailureEvent::<i32>::builder()
    ///     .attempt_count(5);
    /// ```
    pub fn attempt_count(mut self, attempt_count: u32) -> Self {
        self.attempt_count = attempt_count;
        self
    }

    /// Set the total execution time
    ///
    /// # Parameters
    ///
    /// * `total_duration` - Total time from start to failure
    ///
    /// # Returns
    ///
    /// Returns self for method chaining
    ///
    /// # Example
    ///
    /// ```rust
    /// use qubit_retry::event::failure_event::FailureEvent;
    /// use std::time::Duration;
    ///
    /// let builder = FailureEvent::<i32>::builder()
    ///     .total_duration(Duration::from_secs(10));
    /// ```
    pub fn total_duration(mut self, total_duration: Duration) -> Self {
        self.total_duration = total_duration;
        self
    }

    /// Build the `FailureEvent`
    ///
    /// Consumes the builder and creates a new `FailureEvent`
    /// instance with the configured values.
    ///
    /// # Returns
    ///
    /// Returns a newly constructed `FailureEvent` instance
    ///
    /// # Example
    ///
    /// ```rust
    /// use qubit_retry::event::failure_event::FailureEvent;
    /// use std::time::Duration;
    ///
    /// let event = FailureEvent::<String>::builder()
    ///     .attempt_count(3)
    ///     .total_duration(Duration::from_secs(5))
    ///     .build();
    /// ```
    pub fn build(self) -> FailureEvent<T> {
        FailureEvent {
            last_error: self.last_error,
            last_result: self.last_result,
            attempt_count: self.attempt_count,
            total_duration: self.total_duration,
        }
    }
}