1#![cfg_attr(docsrs, feature(doc_cfg))]
2#![doc = include_str!("../README.md")]
3#![allow(renamed_and_removed_lints)] #![allow(unknown_lints)] #![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)] #![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)] #![allow(clippy::uninlined_format_args)]
41#![allow(clippy::significant_drop_in_scrutinee)] #![allow(clippy::result_large_err)] #![allow(clippy::needless_raw_string_hashes)] #![allow(clippy::needless_lifetimes)] #![allow(mismatched_lifetime_syntaxes)] #![allow(clippy::collapsible_if)] #![deny(clippy::unused_async)]
48#![deny(clippy::string_slice)] #![allow(recursion_depth_exceeding_limit)] use std::error::Error;
53use std::fmt::{self, Debug, Display, Error as FmtError, Formatter};
54use std::iter;
55use std::time::{Duration, SystemTime};
56
57#[cfg(all(target_arch = "wasm32", target_os = "unknown"))]
58use web_time::Instant;
59
60#[cfg(not(all(target_arch = "wasm32", target_os = "unknown")))]
61use std::time::Instant;
62
63#[derive(Debug, Clone)]
75pub struct RetryError<E> {
76 doing: String,
78 errors: Vec<(Attempt, E, Instant)>,
80 n_errors: usize,
85 first_error_at: Option<SystemTime>,
99}
100
101#[derive(Debug, Clone)]
103enum Attempt {
104 Single(usize),
106 Range(usize, usize),
108}
109
110impl<E: Debug + AsRef<dyn Error>> Error for RetryError<E> {}
113
114impl<E> RetryError<E> {
115 pub fn in_attempt_to<T: Into<String>>(doing: T) -> Self {
126 RetryError {
127 doing: doing.into(),
128 errors: Vec::new(),
129 n_errors: 0,
130 first_error_at: None,
131 }
132 }
133 pub fn push_timed<T>(&mut self, err: T, instant: Instant, wall_clock: Option<SystemTime>)
155 where
156 T: Into<E>,
157 {
158 if self.n_errors < usize::MAX {
159 self.n_errors += 1;
160 let attempt = Attempt::Single(self.n_errors);
161
162 if self.first_error_at.is_none() {
163 self.first_error_at = wall_clock;
164 }
165
166 self.errors.push((attempt, err.into(), instant));
167 }
168 }
169
170 pub fn push<T>(&mut self, err: T)
179 where
180 T: Into<E>,
181 {
182 self.push_timed(err, current_instant(), Some(current_system_time()));
183 }
184
185 pub fn sources(&self) -> impl Iterator<Item = &E> {
188 self.errors.iter().map(|(.., e, _)| e)
189 }
190
191 pub fn len(&self) -> usize {
193 self.errors.len()
194 }
195
196 pub fn is_empty(&self) -> bool {
198 self.errors.is_empty()
199 }
200
201 #[allow(clippy::disallowed_methods)] pub fn extend<T>(&mut self, iter: impl IntoIterator<Item = T>)
216 where
217 T: Into<E>,
218 {
219 for item in iter {
220 self.push(item);
221 }
222 }
223
224 pub fn dedup_by<F>(&mut self, same_err: F)
229 where
230 F: Fn(&E, &E) -> bool,
231 {
232 let mut old_errs = Vec::new();
233 std::mem::swap(&mut old_errs, &mut self.errors);
234
235 for (attempt, err, timestamp) in old_errs {
236 if let Some((last_attempt, last_err, ..)) = self.errors.last_mut() {
237 if same_err(last_err, &err) {
238 last_attempt.grow(attempt.count());
239 } else {
240 self.errors.push((attempt, err, timestamp));
241 }
242 } else {
243 self.errors.push((attempt, err, timestamp));
244 }
245 }
246 }
247
248 pub fn extend_from_retry_error(&mut self, other: RetryError<E>) {
254 if self.first_error_at.is_none() {
255 self.first_error_at = other.first_error_at;
256 }
257
258 for (attempt, err, timestamp) in other.errors {
259 let Some(new_n_errors) = self.n_errors.checked_add(attempt.count()) else {
260 break;
261 };
262
263 let new_attempt = match attempt {
264 Attempt::Single(_) => Attempt::Single(new_n_errors),
265 Attempt::Range(_, _) => Attempt::Range(self.n_errors + 1, new_n_errors),
266 };
267
268 self.errors.push((new_attempt, err, timestamp));
269 self.n_errors = new_n_errors;
270 }
271 }
272}
273
274impl<E: PartialEq<E>> RetryError<E> {
275 pub fn dedup(&mut self) {
278 self.dedup_by(PartialEq::eq);
279 }
280}
281
282impl Attempt {
283 fn grow(&mut self, count: usize) {
285 *self = match *self {
286 Attempt::Single(idx) => Attempt::Range(idx, idx + count),
287 Attempt::Range(first, last) => Attempt::Range(first, last + count),
288 };
289 }
290
291 fn count(&self) -> usize {
293 match *self {
294 Attempt::Single(_) => 1,
295 Attempt::Range(first, last) => last - first + 1,
296 }
297 }
298}
299
300impl<E> IntoIterator for RetryError<E> {
301 type Item = E;
302 type IntoIter = std::vec::IntoIter<E>;
303 #[allow(clippy::needless_collect)]
304 fn into_iter(self) -> Self::IntoIter {
309 self.errors
310 .into_iter()
311 .map(|(.., e, _)| e)
312 .collect::<Vec<_>>()
313 .into_iter()
314 }
315}
316
317impl Display for Attempt {
318 fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), FmtError> {
319 match self {
320 Attempt::Single(idx) => write!(f, "Attempt {}", idx),
321 Attempt::Range(first, last) => write!(f, "Attempts {}..{}", first, last),
322 }
323 }
324}
325
326impl<E: AsRef<dyn Error>> Display for RetryError<E> {
327 fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), FmtError> {
328 let show_timestamps = f.alternate();
329
330 match self.n_errors {
331 0 => write!(f, "Unable to {}. (No errors given)", self.doing),
332 1 => {
333 write!(f, "Unable to {}", self.doing)?;
334
335 if show_timestamps {
336 if let (Some((.., timestamp)), Some(first_at)) =
337 (self.errors.first(), self.first_error_at)
338 {
339 write!(
340 f,
341 " at {} ({})",
342 humantime::format_rfc3339(first_at),
343 FormatTimeAgo(timestamp.elapsed())
344 )?;
345 }
346 }
347
348 write!(f, ": ")?;
349 fmt_error_with_sources(self.errors[0].1.as_ref(), f)
350 }
351 n => {
352 write!(
353 f,
354 "Tried to {} {} times, but all attempts failed",
355 self.doing, n
356 )?;
357
358 if show_timestamps {
359 if let (Some(first_at), Some((.., first_ts)), Some((.., last_ts))) =
360 (self.first_error_at, self.errors.first(), self.errors.last())
361 {
362 let duration = last_ts.saturating_duration_since(*first_ts);
363
364 write!(f, " (from {} ", humantime::format_rfc3339(first_at))?;
365
366 if duration.as_secs() > 0 {
367 write!(f, "to {}", humantime::format_rfc3339(first_at + duration))?;
368 }
369
370 write!(f, ", {})", FormatTimeAgo(last_ts.elapsed()))?;
371 }
372 }
373
374 let first_ts = self.errors.first().map(|(.., ts)| ts);
375 for (attempt, e, timestamp) in &self.errors {
376 write!(f, "\n{}", attempt)?;
377
378 if show_timestamps {
379 if let Some(first_ts) = first_ts {
380 let offset = timestamp.saturating_duration_since(*first_ts);
381 if offset.as_secs() > 0 {
382 write!(f, " (+{})", FormatDuration(offset))?;
383 }
384 }
385 }
386
387 write!(f, ": ")?;
388 fmt_error_with_sources(e.as_ref(), f)?;
389 }
390 Ok(())
391 }
392 }
393 }
394}
395
396struct FormatDuration(Duration);
401
402impl Display for FormatDuration {
403 fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
404 fmt_duration_impl(self.0, f)
405 }
406}
407
408struct FormatTimeAgo(Duration);
410
411impl Display for FormatTimeAgo {
412 fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
413 let secs = self.0.as_secs();
414 let millis = self.0.as_millis();
415
416 if secs == 0 && millis == 0 {
418 return write!(f, "just now");
419 }
420
421 fmt_duration_impl(self.0, f)?;
422 write!(f, " ago")
423 }
424}
425
426fn fmt_duration_impl(duration: Duration, f: &mut Formatter<'_>) -> fmt::Result {
431 let secs = duration.as_secs();
432
433 if secs == 0 {
434 let millis = duration.as_millis();
435 if millis == 0 {
436 write!(f, "0s")
437 } else {
438 write!(f, "{}ms", millis)
439 }
440 } else if secs < 60 {
441 write!(f, "{}s", secs)
442 } else if secs < 3600 {
443 let mins = secs / 60;
444 let rem_secs = secs % 60;
445 if rem_secs == 0 {
446 write!(f, "{}m", mins)
447 } else {
448 write!(f, "{}m {}s", mins, rem_secs)
449 }
450 } else {
451 let hours = secs / 3600;
452 let mins = (secs % 3600) / 60;
453 if mins == 0 {
454 write!(f, "{}h", hours)
455 } else {
456 write!(f, "{}h {}m", hours, mins)
457 }
458 }
459}
460
461pub fn fmt_error_with_sources(mut e: &dyn Error, f: &mut fmt::Formatter) -> fmt::Result {
502 let mut last = String::new();
507 let mut sep = iter::once("").chain(iter::repeat(": "));
508
509 loop {
513 let this = e.to_string();
514 if !last.contains(&this) {
515 write!(f, "{}{}", sep.next().expect("repeat ended"), this)?;
516 }
517 last = this;
518
519 if let Some(ne) = e.source() {
520 e = ne;
521 } else {
522 break;
523 }
524 }
525 Ok(())
526}
527
528#[cfg(all(target_arch = "wasm32", target_os = "unknown"))]
532fn current_system_time() -> SystemTime {
533 use web_time::web::SystemTimeExt as _;
534 web_time::SystemTime::now().to_std()
535}
536
537#[cfg(not(all(target_arch = "wasm32", target_os = "unknown")))]
541fn current_system_time() -> SystemTime {
542 #![allow(clippy::disallowed_methods)]
543 SystemTime::now()
544}
545
546fn current_instant() -> Instant {
550 #![allow(clippy::disallowed_methods)]
551 Instant::now()
552}
553
554#[cfg(test)]
555mod test {
556 #![allow(clippy::bool_assert_comparison)]
558 #![allow(clippy::clone_on_copy)]
559 #![allow(clippy::dbg_macro)]
560 #![allow(clippy::mixed_attributes_style)]
561 #![allow(clippy::print_stderr)]
562 #![allow(clippy::print_stdout)]
563 #![allow(clippy::single_char_pattern)]
564 #![allow(clippy::unwrap_used)]
565 #![allow(clippy::unchecked_time_subtraction)]
566 #![allow(clippy::useless_vec)]
567 #![allow(clippy::needless_pass_by_value)]
568 #![allow(clippy::string_slice)] #![allow(clippy::disallowed_methods)]
571 use super::*;
572 use derive_more::From;
573
574 #[test]
575 fn bad_parse1() {
576 let mut err: RetryError<anyhow::Error> = RetryError::in_attempt_to("convert some things");
577 if let Err(e) = "maybe".parse::<bool>() {
578 err.push(e);
579 }
580 if let Err(e) = "a few".parse::<u32>() {
581 err.push(e);
582 }
583 if let Err(e) = "the_g1b50n".parse::<std::net::IpAddr>() {
584 err.push(e);
585 }
586
587 let disp = format!("{}", err);
588 assert_eq!(
589 disp,
590 "\
591Tried to convert some things 3 times, but all attempts failed
592Attempt 1: provided string was not `true` or `false`
593Attempt 2: invalid digit found in string
594Attempt 3: invalid IP address syntax"
595 );
596
597 let disp_alt = format!("{:#}", err);
598 assert!(disp_alt.contains("Tried to convert some things 3 times, but all attempts failed"));
599 assert!(disp_alt.contains("(from 20")); }
601
602 #[test]
603 fn no_problems() {
604 let empty: RetryError<anyhow::Error> =
605 RetryError::in_attempt_to("immanentize the eschaton");
606 let disp = format!("{}", empty);
607 assert_eq!(
608 disp,
609 "Unable to immanentize the eschaton. (No errors given)"
610 );
611 }
612
613 #[test]
614 fn one_problem() {
615 let mut err: RetryError<anyhow::Error> =
616 RetryError::in_attempt_to("connect to torproject.org");
617 if let Err(e) = "the_g1b50n".parse::<std::net::IpAddr>() {
618 err.push(e);
619 }
620 let disp = format!("{}", err);
621 assert_eq!(
622 disp,
623 "Unable to connect to torproject.org: invalid IP address syntax"
624 );
625
626 let disp_alt = format!("{:#}", err);
627 assert!(disp_alt.contains("Unable to connect to torproject.org at 20")); assert!(disp_alt.contains("invalid IP address syntax"));
629 }
630
631 #[test]
632 fn operations() {
633 use std::num::ParseIntError;
634
635 #[derive(From, Clone, Debug, Eq, PartialEq)]
636 struct Wrapper(ParseIntError);
637
638 impl AsRef<dyn Error + 'static> for Wrapper {
639 fn as_ref(&self) -> &(dyn Error + 'static) {
640 &self.0
641 }
642 }
643
644 let mut err: RetryError<Wrapper> = RetryError::in_attempt_to("parse some integers");
645 assert!(err.is_empty());
646 assert_eq!(err.len(), 0);
647 err.extend(
648 vec!["not", "your", "number"]
649 .iter()
650 .filter_map(|s| s.parse::<u16>().err())
651 .map(Wrapper),
652 );
653 assert!(!err.is_empty());
654 assert_eq!(err.len(), 3);
655
656 let cloned = err.clone();
657 for (s1, s2) in err.sources().zip(cloned.sources()) {
658 assert_eq!(s1, s2);
659 }
660
661 err.dedup();
662
663 let disp = format!("{}", err);
664 assert_eq!(
665 disp,
666 "\
667Tried to parse some integers 3 times, but all attempts failed
668Attempts 1..3: invalid digit found in string"
669 );
670
671 let disp_alt = format!("{:#}", err);
672 assert!(disp_alt.contains("Tried to parse some integers 3 times, but all attempts failed"));
673 assert!(disp_alt.contains("(from 20")); }
675
676 #[test]
677 fn overflow() {
678 use std::num::ParseIntError;
679 let mut err: RetryError<ParseIntError> =
680 RetryError::in_attempt_to("parse too many integers");
681 assert!(err.is_empty());
682 let mut errors: Vec<ParseIntError> = vec!["no", "numbers"]
683 .iter()
684 .filter_map(|s| s.parse::<u16>().err())
685 .collect();
686 err.n_errors = usize::MAX;
687 err.errors.push((
688 Attempt::Range(1, err.n_errors),
689 errors.pop().expect("parser did not fail"),
690 Instant::now(),
691 ));
692 assert!(err.n_errors == usize::MAX);
693 assert!(err.len() == 1);
694
695 err.push(errors.pop().expect("parser did not fail"));
696 assert!(err.n_errors == usize::MAX);
697 assert!(err.len() == 1);
698 }
699
700 #[test]
701 fn extend_from_retry_preserve_timestamps() {
702 let n1 = Instant::now();
703 let n2 = n1 + Duration::from_secs(10);
704 let n3 = n1 + Duration::from_secs(20);
705
706 let mut err1: RetryError<anyhow::Error> = RetryError::in_attempt_to("do first thing");
707 let mut err2: RetryError<anyhow::Error> = RetryError::in_attempt_to("do second thing");
708
709 err2.push_timed(anyhow::Error::msg("e1"), n1, None);
710 err2.push_timed(anyhow::Error::msg("e2"), n2, None);
711
712 assert!(err1.first_error_at.is_none());
714
715 err1.extend_from_retry_error(err2);
716
717 assert_eq!(err1.len(), 2);
718 assert_eq!(err1.errors[0].2, n1);
720 assert_eq!(err1.errors[1].2, n2);
721
722 err1.push_timed(anyhow::Error::msg("e3"), n3, None);
724 assert_eq!(err1.len(), 3);
725 assert_eq!(err1.errors[2].2, n3);
726 }
727
728 #[test]
729 fn extend_from_retry_preserve_ranges() {
730 let n1 = Instant::now();
731 let mut err1: RetryError<anyhow::Error> = RetryError::in_attempt_to("do thing 1");
732
733 err1.push(anyhow::Error::msg("e1"));
735 err1.push(anyhow::Error::msg("e2"));
736 assert_eq!(err1.n_errors, 2);
737
738 let mut err2: RetryError<anyhow::Error> = RetryError::in_attempt_to("do thing 2");
739 err2.push_timed(anyhow::Error::msg("repeated"), n1, None);
741 err2.push_timed(anyhow::Error::msg("repeated"), n1, None);
742 err2.push_timed(anyhow::Error::msg("repeated"), n1, None);
743
744 err2.dedup_by(|e1, e2| e1.to_string() == e2.to_string());
746 assert_eq!(err2.len(), 1); match err2.errors[0].0 {
748 Attempt::Range(1, 3) => {}
749 _ => panic!("Expected range 1..3"),
750 }
751
752 err1.extend_from_retry_error(err2);
754
755 assert_eq!(err1.len(), 3); assert_eq!(err1.n_errors, 5); match err1.errors[2].0 {
760 Attempt::Range(3, 5) => {}
761 ref x => panic!("Expected range 3..5, got {:?}", x),
762 }
763 }
764
765 #[test]
766 fn dedup_after_extend_same_doing() {
767 let doing = "do thing";
768 let message = "error";
769 let n1 = Instant::now();
770 let mut err1: RetryError<anyhow::Error> = RetryError::in_attempt_to(doing);
771
772 err1.push(anyhow::Error::msg(message));
774 assert_eq!(err1.n_errors, 1);
775
776 let mut err2: RetryError<anyhow::Error> = RetryError::in_attempt_to(doing);
777 err2.push_timed(anyhow::Error::msg(message), n1, None);
779 err2.push_timed(anyhow::Error::msg(message), n1, None);
780
781 err2.dedup_by(|e1, e2| e1.to_string() == e2.to_string());
783 assert_eq!(err2.len(), 1); match err2.errors[0].0 {
785 Attempt::Range(1, 2) => {}
786 _ => panic!("Expected range 1..2"),
787 }
788
789 err1.extend_from_retry_error(err2);
791 assert_eq!(err1.len(), 2); assert_eq!(err1.n_errors, 3); err1.dedup_by(|e1, e2| e1.to_string() == e2.to_string());
796 assert_eq!(err1.len(), 1); assert_eq!(err1.n_errors, 3); match err1.errors[0].0 {
801 Attempt::Range(1, 3) => {}
802 ref x => panic!("Expected range 1..3, got {:?}", x),
803 }
804 }
805}