Skip to main content

retry_error/
lib.rs

1#![cfg_attr(docsrs, feature(doc_cfg))]
2#![doc = include_str!("../README.md")]
3// @@ begin lint list maintained by maint/add_warning @@
4#![allow(renamed_and_removed_lints)] // @@REMOVE_WHEN(ci_arti_stable)
5#![allow(unknown_lints)] // @@REMOVE_WHEN(ci_arti_nightly)
6#![warn(missing_docs)]
7#![warn(noop_method_call)]
8#![warn(unreachable_pub)]
9#![warn(clippy::all)]
10#![deny(clippy::await_holding_lock)]
11#![deny(clippy::cargo_common_metadata)]
12#![deny(clippy::cast_lossless)]
13#![deny(clippy::checked_conversions)]
14#![allow(clippy::cognitive_complexity)] // See arti#2556
15#![deny(clippy::debug_assert_with_mut_call)]
16#![deny(clippy::exhaustive_enums)]
17#![deny(clippy::exhaustive_structs)]
18#![deny(clippy::expl_impl_clone_on_copy)]
19#![deny(clippy::fallible_impl_from)]
20#![deny(clippy::implicit_clone)]
21#![deny(clippy::large_stack_arrays)]
22#![warn(clippy::manual_ok_or)]
23#![deny(clippy::missing_docs_in_private_items)]
24#![warn(clippy::needless_borrow)]
25#![warn(clippy::needless_pass_by_value)]
26#![warn(clippy::option_option)]
27#![warn(clippy::or_fun_call)]
28#![deny(clippy::print_stderr)]
29#![deny(clippy::print_stdout)]
30#![warn(clippy::rc_buffer)]
31#![deny(clippy::ref_option_ref)]
32#![warn(clippy::semicolon_if_nothing_returned)]
33#![warn(clippy::trait_duplication_in_bounds)]
34#![deny(clippy::unchecked_time_subtraction)]
35#![deny(clippy::unnecessary_wraps)]
36#![warn(clippy::unseparated_literal_suffix)]
37#![deny(clippy::unwrap_used)]
38#![deny(clippy::mod_module_files)]
39#![allow(clippy::let_unit_value)] // This can reasonably be done for explicitness
40#![allow(clippy::uninlined_format_args)]
41#![allow(clippy::significant_drop_in_scrutinee)] // arti/-/merge_requests/588/#note_2812945
42#![allow(clippy::result_large_err)] // temporary workaround for arti#587
43#![allow(clippy::needless_raw_string_hashes)] // complained-about code is fine, often best
44#![allow(clippy::needless_lifetimes)] // See arti#1765
45#![allow(mismatched_lifetime_syntaxes)] // temporary workaround for arti#2060
46#![allow(clippy::collapsible_if)] // See arti#2342
47#![deny(clippy::unused_async)]
48#![deny(clippy::string_slice)] // See arti#2571
49//! <!-- @@ end lint list maintained by maint/add_warning @@ -->
50
51// TODO: add to the list maintained by maint/add_warning once it's available on all crates
52#![warn(unnameable_types)]
53
54use std::error::Error;
55use std::fmt::{self, Debug, Display, Error as FmtError, Formatter};
56use std::iter;
57use std::time::{Duration, SystemTime};
58
59#[cfg(all(target_arch = "wasm32", target_os = "unknown"))]
60use web_time::Instant;
61
62#[cfg(not(all(target_arch = "wasm32", target_os = "unknown")))]
63use std::time::Instant;
64
65/// An error type for use when we're going to do something a few times,
66/// and they might all fail.
67///
68/// To use this error type, initialize a new RetryError before you
69/// start trying to do whatever it is.  Then, every time the operation
70/// fails, use [`RetryError::push()`] to add a new error to the list
71/// of errors.  If the operation fails too many times, you can use
72/// RetryError as an [`Error`] itself.
73///
74/// This type now tracks timestamps for each error occurrence, allowing
75/// users to see when errors occurred and how long the retry process took.
76#[derive(Debug, Clone)]
77pub struct RetryError<E> {
78    /// The operation we were trying to do.
79    doing: String,
80    /// The errors that we encountered when doing the operation.
81    errors: Vec<(Attempt, E, Instant)>,
82    /// The total number of errors we encountered.
83    ///
84    /// This can differ from errors.len() if the errors have been
85    /// deduplicated.
86    n_errors: usize,
87    /// The wall-clock time when the first error occurred.
88    ///
89    /// This is used for human-readable display of absolute timestamps.
90    ///
91    /// We store both types because they serve different purposes:
92    /// - `Instant` (in the errors vec): Monotonic clock for reliable duration calculations.
93    ///   Immune to clock adjustments, but can't be displayed as wall-clock time.
94    /// - `SystemTime` (here): Wall-clock time for displaying when the first error occurred
95    ///   in a human-readable format (e.g., "2025-12-09T10:24:02Z").
96    ///
97    /// We only store `SystemTime` for the first error to show users *when* the problem
98    /// started. Subsequent errors are displayed relative to the first ("+2m 30s"),
99    /// using the reliable `Instant` timestamps.
100    first_error_at: Option<SystemTime>,
101}
102
103/// Represents which attempts, in sequence, failed to complete.
104#[derive(Debug, Clone)]
105enum Attempt {
106    /// A single attempt that failed.
107    Single(usize),
108    /// A range of consecutive attempts that failed.
109    Range(usize, usize),
110}
111
112// TODO: Should we declare that some error is the 'source' of this one?
113// If so, should it be the first failure?  The last?
114impl<E: Debug + AsRef<dyn Error>> Error for RetryError<E> {}
115
116impl<E> RetryError<E> {
117    /// Create a new RetryError, with no failed attempts.
118    ///
119    /// The provided `doing` argument is a short string that describes
120    /// what we were trying to do when we failed too many times.  It
121    /// will be used to format the final error message; it should be a
122    /// phrase that can go after "while trying to".
123    ///
124    /// This RetryError should not be used as-is, since when no
125    /// [`Error`]s have been pushed into it, it doesn't represent an
126    /// actual failure.
127    pub fn in_attempt_to<T: Into<String>>(doing: T) -> Self {
128        RetryError {
129            doing: doing.into(),
130            errors: Vec::new(),
131            n_errors: 0,
132            first_error_at: None,
133        }
134    }
135    /// Add an error to this RetryError with explicit timestamps.
136    ///
137    /// You should call this method when an attempt at the underlying operation
138    /// has failed.
139    ///
140    /// The `instant` parameter should be the monotonic time when the error
141    /// occurred, typically obtained from a runtime's `now()` method.
142    ///
143    /// The `wall_clock` parameter is the wall-clock time when the error occurred,
144    /// used for human-readable display. Pass `None` to skip wall-clock tracking,
145    /// or `Some(SystemTime::now())` for the current time.
146    ///
147    /// # Example
148    /// ```
149    /// # #![allow(clippy::disallowed_methods)]
150    /// # use retry_error::RetryError;
151    /// # use std::time::{Instant, SystemTime};
152    /// let mut retry_err: RetryError<&str> = RetryError::in_attempt_to("connect");
153    /// let now = Instant::now();
154    /// retry_err.push_timed("connection failed", now, Some(SystemTime::now()));
155    /// ```
156    pub fn push_timed<T>(&mut self, err: T, instant: Instant, wall_clock: Option<SystemTime>)
157    where
158        T: Into<E>,
159    {
160        if self.n_errors < usize::MAX {
161            self.n_errors += 1;
162            let attempt = Attempt::Single(self.n_errors);
163
164            if self.first_error_at.is_none() {
165                self.first_error_at = wall_clock;
166            }
167
168            self.errors.push((attempt, err.into(), instant));
169        }
170    }
171
172    /// Add an error to this RetryError using the current time.
173    ///
174    /// You should call this method when an attempt at the underlying operation
175    /// has failed.
176    ///
177    /// This is a convenience wrapper around [`push_timed()`](Self::push_timed)
178    /// that uses `Instant::now()` and `SystemTime::now()` for the timestamps.
179    /// For code that needs mockable time (such as in tests), prefer `push_timed()`.
180    pub fn push<T>(&mut self, err: T)
181    where
182        T: Into<E>,
183    {
184        self.push_timed(err, current_instant(), Some(current_system_time()));
185    }
186
187    /// Return an iterator over all of the reasons that the attempt
188    /// behind this RetryError has failed.
189    pub fn sources(&self) -> impl Iterator<Item = &E> {
190        self.errors.iter().map(|(.., e, _)| e)
191    }
192
193    /// Return the number of underlying errors.
194    pub fn len(&self) -> usize {
195        self.errors.len()
196    }
197
198    /// Return true if no underlying errors have been added.
199    pub fn is_empty(&self) -> bool {
200        self.errors.is_empty()
201    }
202
203    /// Add multiple errors to this RetryError using the current time.
204    ///
205    /// This method uses [`push()`](Self::push) internally, which captures
206    /// `SystemTime::now()`. For code that needs mockable time (such as in tests),
207    /// iterate manually and call [`push_timed()`](Self::push_timed) instead.
208    ///
209    /// # Example
210    /// ```
211    /// # use retry_error::RetryError;
212    /// let mut err: RetryError<anyhow::Error> = RetryError::in_attempt_to("parse");
213    /// let errors = vec!["error1", "error2"].into_iter().map(anyhow::Error::msg);
214    /// err.extend(errors);
215    /// ```
216    #[allow(clippy::disallowed_methods)] // This method intentionally uses push()
217    pub fn extend<T>(&mut self, iter: impl IntoIterator<Item = T>)
218    where
219        T: Into<E>,
220    {
221        for item in iter {
222            self.push(item);
223        }
224    }
225
226    /// Group up consecutive errors of the same kind, for easier display.
227    ///
228    /// Two errors have "the same kind" if they return `true` when passed
229    /// to the provided `same_err` function.
230    pub fn dedup_by<F>(&mut self, same_err: F)
231    where
232        F: Fn(&E, &E) -> bool,
233    {
234        let mut old_errs = Vec::new();
235        std::mem::swap(&mut old_errs, &mut self.errors);
236
237        for (attempt, err, timestamp) in old_errs {
238            if let Some((last_attempt, last_err, ..)) = self.errors.last_mut() {
239                if same_err(last_err, &err) {
240                    last_attempt.grow(attempt.count());
241                } else {
242                    self.errors.push((attempt, err, timestamp));
243                }
244            } else {
245                self.errors.push((attempt, err, timestamp));
246            }
247        }
248    }
249
250    /// Add multiple errors to this RetryError, preserving their original timestamps.
251    ///
252    /// The errors from other will be added to this RetryError, with their original
253    /// timestamps retained. The `Attempt` counters will be updated to continue from
254    /// the current state of this RetryError. `Attempt::Range` entries are preserved as ranges
255    pub fn extend_from_retry_error(&mut self, other: RetryError<E>) {
256        if self.first_error_at.is_none() {
257            self.first_error_at = other.first_error_at;
258        }
259
260        for (attempt, err, timestamp) in other.errors {
261            let Some(new_n_errors) = self.n_errors.checked_add(attempt.count()) else {
262                break;
263            };
264
265            let new_attempt = match attempt {
266                Attempt::Single(_) => Attempt::Single(new_n_errors),
267                Attempt::Range(_, _) => Attempt::Range(self.n_errors + 1, new_n_errors),
268            };
269
270            self.errors.push((new_attempt, err, timestamp));
271            self.n_errors = new_n_errors;
272        }
273    }
274}
275
276impl<E: PartialEq<E>> RetryError<E> {
277    /// Group up consecutive errors of the same kind, according to the
278    /// `PartialEq` implementation.
279    pub fn dedup(&mut self) {
280        self.dedup_by(PartialEq::eq);
281    }
282}
283
284impl Attempt {
285    /// Extend this attempt by additional failures.
286    fn grow(&mut self, count: usize) {
287        *self = match *self {
288            Attempt::Single(idx) => Attempt::Range(idx, idx + count),
289            Attempt::Range(first, last) => Attempt::Range(first, last + count),
290        };
291    }
292
293    /// Return amount of failures.
294    fn count(&self) -> usize {
295        match *self {
296            Attempt::Single(_) => 1,
297            Attempt::Range(first, last) => last - first + 1,
298        }
299    }
300}
301
302impl<E> IntoIterator for RetryError<E> {
303    type Item = E;
304    type IntoIter = std::vec::IntoIter<E>;
305    #[allow(clippy::needless_collect)]
306    // TODO We have to use collect/into_iter here for now, since
307    // the actual Map<> type can't be named.  Once Rust lets us say
308    // `type IntoIter = impl Iterator<Item=E>` then we fix the code
309    // and turn the Clippy warning back on.
310    fn into_iter(self) -> Self::IntoIter {
311        self.errors
312            .into_iter()
313            .map(|(.., e, _)| e)
314            .collect::<Vec<_>>()
315            .into_iter()
316    }
317}
318
319impl Display for Attempt {
320    fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), FmtError> {
321        match self {
322            Attempt::Single(idx) => write!(f, "Attempt {}", idx),
323            Attempt::Range(first, last) => write!(f, "Attempts {}..{}", first, last),
324        }
325    }
326}
327
328impl<E: AsRef<dyn Error>> Display for RetryError<E> {
329    fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), FmtError> {
330        let show_timestamps = f.alternate();
331
332        match self.n_errors {
333            0 => write!(f, "Unable to {}. (No errors given)", self.doing),
334            1 => {
335                write!(f, "Unable to {}", self.doing)?;
336
337                if show_timestamps {
338                    if let (Some((.., timestamp)), Some(first_at)) =
339                        (self.errors.first(), self.first_error_at)
340                    {
341                        write!(
342                            f,
343                            " at {} ({})",
344                            humantime::format_rfc3339(first_at),
345                            FormatTimeAgo(timestamp.elapsed())
346                        )?;
347                    }
348                }
349
350                write!(f, ": ")?;
351                fmt_error_with_sources(self.errors[0].1.as_ref(), f)
352            }
353            n => {
354                write!(
355                    f,
356                    "Tried to {} {} times, but all attempts failed",
357                    self.doing, n
358                )?;
359
360                if show_timestamps {
361                    if let (Some(first_at), Some((.., first_ts)), Some((.., last_ts))) =
362                        (self.first_error_at, self.errors.first(), self.errors.last())
363                    {
364                        let duration = last_ts.saturating_duration_since(*first_ts);
365
366                        write!(f, " (from {} ", humantime::format_rfc3339(first_at))?;
367
368                        if duration.as_secs() > 0 {
369                            write!(f, "to {}", humantime::format_rfc3339(first_at + duration))?;
370                        }
371
372                        write!(f, ", {})", FormatTimeAgo(last_ts.elapsed()))?;
373                    }
374                }
375
376                let first_ts = self.errors.first().map(|(.., ts)| ts);
377                for (attempt, e, timestamp) in &self.errors {
378                    write!(f, "\n{}", attempt)?;
379
380                    if show_timestamps {
381                        if let Some(first_ts) = first_ts {
382                            let offset = timestamp.saturating_duration_since(*first_ts);
383                            if offset.as_secs() > 0 {
384                                write!(f, " (+{})", FormatDuration(offset))?;
385                            }
386                        }
387                    }
388
389                    write!(f, ": ")?;
390                    fmt_error_with_sources(e.as_ref(), f)?;
391                }
392                Ok(())
393            }
394        }
395    }
396}
397
398/// A wrapper for formatting a [`Duration`] in a human-readable way.
399/// Produces output like "2m 30s", "5h 12m", "45s", "500ms".
400///
401/// We use this instead of `humantime::format_duration` because humantime tends to produce overly verbose output.
402struct FormatDuration(Duration);
403
404impl Display for FormatDuration {
405    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
406        fmt_duration_impl(self.0, f)
407    }
408}
409
410/// A wrapper for formatting a [`Duration`] with "ago" suffix.
411struct FormatTimeAgo(Duration);
412
413impl Display for FormatTimeAgo {
414    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
415        let secs = self.0.as_secs();
416        let millis = self.0.as_millis();
417
418        // Special case: very recent times show as "just now" rather than "0s ago" or "0ms ago"
419        if secs == 0 && millis == 0 {
420            return write!(f, "just now");
421        }
422
423        fmt_duration_impl(self.0, f)?;
424        write!(f, " ago")
425    }
426}
427
428/// Internal helper to format a duration.
429///
430/// This function contains the actual formatting logic to avoid duplication
431/// between `FormatDuration` and `FormatTimeAgo`.
432fn fmt_duration_impl(duration: Duration, f: &mut Formatter<'_>) -> fmt::Result {
433    let secs = duration.as_secs();
434
435    if secs == 0 {
436        let millis = duration.as_millis();
437        if millis == 0 {
438            write!(f, "0s")
439        } else {
440            write!(f, "{}ms", millis)
441        }
442    } else if secs < 60 {
443        write!(f, "{}s", secs)
444    } else if secs < 3600 {
445        let mins = secs / 60;
446        let rem_secs = secs % 60;
447        if rem_secs == 0 {
448            write!(f, "{}m", mins)
449        } else {
450            write!(f, "{}m {}s", mins, rem_secs)
451        }
452    } else {
453        let hours = secs / 3600;
454        let mins = (secs % 3600) / 60;
455        if mins == 0 {
456            write!(f, "{}h", hours)
457        } else {
458            write!(f, "{}h {}m", hours, mins)
459        }
460    }
461}
462
463/// Helper: formats a [`std::error::Error`] and its sources (as `"error: source"`)
464///
465/// Avoids duplication in messages by not printing messages which are
466/// wholly-contained (textually) within already-printed messages.
467///
468/// Offered as a `fmt` function:
469/// this is for use in more-convenient higher-level error handling functionality,
470/// rather than directly in application/functional code.
471///
472/// This is used by `RetryError`'s impl of `Display`,
473/// but will be useful for other error-handling situations.
474///
475/// # Example
476///
477/// ```
478/// use std::fmt::{self, Display};
479///
480/// #[derive(Debug, thiserror::Error)]
481/// #[error("some pernickety problem")]
482/// struct Pernickety;
483///
484/// #[derive(Debug, thiserror::Error)]
485/// enum ApplicationError {
486///     #[error("everything is terrible")]
487///     Terrible(#[source] Pernickety),
488/// }
489///
490/// struct Wrapper(Box<dyn std::error::Error>);
491/// impl Display for Wrapper {
492///     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
493///         retry_error::fmt_error_with_sources(&*self.0, f)
494///     }
495/// }
496///
497/// let bad = Pernickety;
498/// let err = ApplicationError::Terrible(bad);
499///
500/// let printed = Wrapper(err.into()).to_string();
501/// assert_eq!(printed, "everything is terrible: some pernickety problem");
502/// ```
503pub fn fmt_error_with_sources(mut e: &dyn Error, f: &mut fmt::Formatter) -> fmt::Result {
504    // We deduplicate the errors here under the assumption that the `Error` trait is poorly defined
505    // and contradictory, and that some error types will duplicate error messages. This is
506    // controversial, and since there isn't necessarily agreement, we should stick with the status
507    // quo here and avoid changing this behaviour without further discussion.
508    let mut last = String::new();
509    let mut sep = iter::once("").chain(iter::repeat(": "));
510
511    // Note that this loop does not use tor_basic_utils::ErrorSources.  We can't, because `e` is not
512    // `Error + 'static`.  But we shouldn't use ErrorSources here, since io::Error will format
513    // its inner by_ref() error, and so it's desirable that `source` skips over it.
514    loop {
515        let this = e.to_string();
516        if !last.contains(&this) {
517            write!(f, "{}{}", sep.next().expect("repeat ended"), this)?;
518        }
519        last = this;
520
521        if let Some(ne) = e.source() {
522            e = ne;
523        } else {
524            break;
525        }
526    }
527    Ok(())
528}
529
530/// Return the current system time.
531///
532/// (This is a separate method for compatibility with wasm32.)
533#[cfg(all(target_arch = "wasm32", target_os = "unknown"))]
534fn current_system_time() -> SystemTime {
535    use web_time::web::SystemTimeExt as _;
536    web_time::SystemTime::now().to_std()
537}
538
539/// Return the current system time.
540///
541/// (This is a separate method for compatibility with wasm32.)
542#[cfg(not(all(target_arch = "wasm32", target_os = "unknown")))]
543fn current_system_time() -> SystemTime {
544    #![allow(clippy::disallowed_methods)]
545    SystemTime::now()
546}
547
548/// Return the current Instant.
549///
550/// (This is a separate method for compatibility with wasm32.)
551fn current_instant() -> Instant {
552    #![allow(clippy::disallowed_methods)]
553    Instant::now()
554}
555
556#[cfg(test)]
557mod test {
558    // @@ begin test lint list maintained by maint/add_warning @@
559    #![allow(clippy::bool_assert_comparison)]
560    #![allow(clippy::clone_on_copy)]
561    #![allow(clippy::dbg_macro)]
562    #![allow(clippy::mixed_attributes_style)]
563    #![allow(clippy::print_stderr)]
564    #![allow(clippy::print_stdout)]
565    #![allow(clippy::single_char_pattern)]
566    #![allow(clippy::unwrap_used)]
567    #![allow(clippy::unchecked_time_subtraction)]
568    #![allow(clippy::useless_vec)]
569    #![allow(clippy::needless_pass_by_value)]
570    #![allow(clippy::string_slice)] // See arti#2571
571    //! <!-- @@ end test lint list maintained by maint/add_warning @@ -->
572    #![allow(clippy::disallowed_methods)]
573    use super::*;
574    use derive_more::From;
575
576    #[test]
577    fn bad_parse1() {
578        let mut err: RetryError<anyhow::Error> = RetryError::in_attempt_to("convert some things");
579        if let Err(e) = "maybe".parse::<bool>() {
580            err.push(e);
581        }
582        if let Err(e) = "a few".parse::<u32>() {
583            err.push(e);
584        }
585        if let Err(e) = "the_g1b50n".parse::<std::net::IpAddr>() {
586            err.push(e);
587        }
588
589        let disp = format!("{}", err);
590        assert_eq!(
591            disp,
592            "\
593Tried to convert some things 3 times, but all attempts failed
594Attempt 1: provided string was not `true` or `false`
595Attempt 2: invalid digit found in string
596Attempt 3: invalid IP address syntax"
597        );
598
599        let disp_alt = format!("{:#}", err);
600        assert!(disp_alt.contains("Tried to convert some things 3 times, but all attempts failed"));
601        assert!(disp_alt.contains("(from 20")); // Year prefix for timestamp
602    }
603
604    #[test]
605    fn no_problems() {
606        let empty: RetryError<anyhow::Error> =
607            RetryError::in_attempt_to("immanentize the eschaton");
608        let disp = format!("{}", empty);
609        assert_eq!(
610            disp,
611            "Unable to immanentize the eschaton. (No errors given)"
612        );
613    }
614
615    #[test]
616    fn one_problem() {
617        let mut err: RetryError<anyhow::Error> =
618            RetryError::in_attempt_to("connect to torproject.org");
619        if let Err(e) = "the_g1b50n".parse::<std::net::IpAddr>() {
620            err.push(e);
621        }
622        let disp = format!("{}", err);
623        assert_eq!(
624            disp,
625            "Unable to connect to torproject.org: invalid IP address syntax"
626        );
627
628        let disp_alt = format!("{:#}", err);
629        assert!(disp_alt.contains("Unable to connect to torproject.org at 20")); // Year prefix
630        assert!(disp_alt.contains("invalid IP address syntax"));
631    }
632
633    #[test]
634    fn operations() {
635        use std::num::ParseIntError;
636
637        #[derive(From, Clone, Debug, Eq, PartialEq)]
638        struct Wrapper(ParseIntError);
639
640        impl AsRef<dyn Error + 'static> for Wrapper {
641            fn as_ref(&self) -> &(dyn Error + 'static) {
642                &self.0
643            }
644        }
645
646        let mut err: RetryError<Wrapper> = RetryError::in_attempt_to("parse some integers");
647        assert!(err.is_empty());
648        assert_eq!(err.len(), 0);
649        err.extend(
650            vec!["not", "your", "number"]
651                .iter()
652                .filter_map(|s| s.parse::<u16>().err())
653                .map(Wrapper),
654        );
655        assert!(!err.is_empty());
656        assert_eq!(err.len(), 3);
657
658        let cloned = err.clone();
659        for (s1, s2) in err.sources().zip(cloned.sources()) {
660            assert_eq!(s1, s2);
661        }
662
663        err.dedup();
664
665        let disp = format!("{}", err);
666        assert_eq!(
667            disp,
668            "\
669Tried to parse some integers 3 times, but all attempts failed
670Attempts 1..3: invalid digit found in string"
671        );
672
673        let disp_alt = format!("{:#}", err);
674        assert!(disp_alt.contains("Tried to parse some integers 3 times, but all attempts failed"));
675        assert!(disp_alt.contains("(from 20")); // Year prefix for timestamp
676    }
677
678    #[test]
679    fn overflow() {
680        use std::num::ParseIntError;
681        let mut err: RetryError<ParseIntError> =
682            RetryError::in_attempt_to("parse too many integers");
683        assert!(err.is_empty());
684        let mut errors: Vec<ParseIntError> = vec!["no", "numbers"]
685            .iter()
686            .filter_map(|s| s.parse::<u16>().err())
687            .collect();
688        err.n_errors = usize::MAX;
689        err.errors.push((
690            Attempt::Range(1, err.n_errors),
691            errors.pop().expect("parser did not fail"),
692            Instant::now(),
693        ));
694        assert!(err.n_errors == usize::MAX);
695        assert!(err.len() == 1);
696
697        err.push(errors.pop().expect("parser did not fail"));
698        assert!(err.n_errors == usize::MAX);
699        assert!(err.len() == 1);
700    }
701
702    #[test]
703    fn extend_from_retry_preserve_timestamps() {
704        let n1 = Instant::now();
705        let n2 = n1 + Duration::from_secs(10);
706        let n3 = n1 + Duration::from_secs(20);
707
708        let mut err1: RetryError<anyhow::Error> = RetryError::in_attempt_to("do first thing");
709        let mut err2: RetryError<anyhow::Error> = RetryError::in_attempt_to("do second thing");
710
711        err2.push_timed(anyhow::Error::msg("e1"), n1, None);
712        err2.push_timed(anyhow::Error::msg("e2"), n2, None);
713
714        // err1 is empty initially
715        assert!(err1.first_error_at.is_none());
716
717        err1.extend_from_retry_error(err2);
718
719        assert_eq!(err1.len(), 2);
720        // The timestamps should be preserved
721        assert_eq!(err1.errors[0].2, n1);
722        assert_eq!(err1.errors[1].2, n2);
723
724        // Add another error to err1 to ensure mixed sources work
725        err1.push_timed(anyhow::Error::msg("e3"), n3, None);
726        assert_eq!(err1.len(), 3);
727        assert_eq!(err1.errors[2].2, n3);
728    }
729
730    #[test]
731    fn extend_from_retry_preserve_ranges() {
732        let n1 = Instant::now();
733        let mut err1: RetryError<anyhow::Error> = RetryError::in_attempt_to("do thing 1");
734
735        // Push 2 errors
736        err1.push(anyhow::Error::msg("e1"));
737        err1.push(anyhow::Error::msg("e2"));
738        assert_eq!(err1.n_errors, 2);
739
740        let mut err2: RetryError<anyhow::Error> = RetryError::in_attempt_to("do thing 2");
741        // Push 3 identical errors to create a range
742        err2.push_timed(anyhow::Error::msg("repeated"), n1, None);
743        err2.push_timed(anyhow::Error::msg("repeated"), n1, None);
744        err2.push_timed(anyhow::Error::msg("repeated"), n1, None);
745
746        // Dedup err2 so it has a range
747        err2.dedup_by(|e1, e2| e1.to_string() == e2.to_string());
748        assert_eq!(err2.len(), 1); // collapsed to 1 entry
749        match err2.errors[0].0 {
750            Attempt::Range(1, 3) => {}
751            _ => panic!("Expected range 1..3"),
752        }
753
754        // Extend err1 with err2
755        err1.extend_from_retry_error(err2);
756
757        assert_eq!(err1.len(), 3); // 2 singles + 1 range
758        assert_eq!(err1.n_errors, 5); // 2 + 3 = 5 total attempts
759
760        // Check the range indices
761        match err1.errors[2].0 {
762            Attempt::Range(3, 5) => {}
763            ref x => panic!("Expected range 3..5, got {:?}", x),
764        }
765    }
766
767    #[test]
768    fn dedup_after_extend_same_doing() {
769        let doing = "do thing";
770        let message = "error";
771        let n1 = Instant::now();
772        let mut err1: RetryError<anyhow::Error> = RetryError::in_attempt_to(doing);
773
774        // Push 1 error
775        err1.push(anyhow::Error::msg(message));
776        assert_eq!(err1.n_errors, 1);
777
778        let mut err2: RetryError<anyhow::Error> = RetryError::in_attempt_to(doing);
779        // Push 2 identical errors to create a range
780        err2.push_timed(anyhow::Error::msg(message), n1, None);
781        err2.push_timed(anyhow::Error::msg(message), n1, None);
782
783        // Dedup err2 so it has a range
784        err2.dedup_by(|e1, e2| e1.to_string() == e2.to_string());
785        assert_eq!(err2.len(), 1); // collapsed to 1 entry
786        match err2.errors[0].0 {
787            Attempt::Range(1, 2) => {}
788            _ => panic!("Expected range 1..2"),
789        }
790
791        // Extend err1 with err2
792        err1.extend_from_retry_error(err2);
793        assert_eq!(err1.len(), 2); // 1 single + 1 range
794        assert_eq!(err1.n_errors, 3); // 1 + 2 = 3 total attempts
795
796        // Dedup err1 so it has only one range
797        err1.dedup_by(|e1, e2| e1.to_string() == e2.to_string());
798        assert_eq!(err1.len(), 1); // collapsed to 1 entry
799        assert_eq!(err1.n_errors, 3); // 3 total attempts
800
801        // Check the range indices
802        match err1.errors[0].0 {
803            Attempt::Range(1, 3) => {}
804            ref x => panic!("Expected range 1..3, got {:?}", x),
805        }
806    }
807}