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)] #![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#[derive(Debug, Clone)]
77pub struct RetryError<E> {
78 doing: String,
80 errors: Vec<(Attempt, E, Instant)>,
82 n_errors: usize,
87 first_error_at: Option<SystemTime>,
101}
102
103#[derive(Debug, Clone)]
105enum Attempt {
106 Single(usize),
108 Range(usize, usize),
110}
111
112impl<E: Debug + AsRef<dyn Error>> Error for RetryError<E> {}
115
116impl<E> RetryError<E> {
117 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 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 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 pub fn sources(&self) -> impl Iterator<Item = &E> {
190 self.errors.iter().map(|(.., e, _)| e)
191 }
192
193 pub fn len(&self) -> usize {
195 self.errors.len()
196 }
197
198 pub fn is_empty(&self) -> bool {
200 self.errors.is_empty()
201 }
202
203 #[allow(clippy::disallowed_methods)] 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 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 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 pub fn dedup(&mut self) {
280 self.dedup_by(PartialEq::eq);
281 }
282}
283
284impl Attempt {
285 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 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 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
398struct 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
410struct 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 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
428fn 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
463pub fn fmt_error_with_sources(mut e: &dyn Error, f: &mut fmt::Formatter) -> fmt::Result {
504 let mut last = String::new();
509 let mut sep = iter::once("").chain(iter::repeat(": "));
510
511 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#[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#[cfg(not(all(target_arch = "wasm32", target_os = "unknown")))]
543fn current_system_time() -> SystemTime {
544 #![allow(clippy::disallowed_methods)]
545 SystemTime::now()
546}
547
548fn current_instant() -> Instant {
552 #![allow(clippy::disallowed_methods)]
553 Instant::now()
554}
555
556#[cfg(test)]
557mod test {
558 #![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)] #![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")); }
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")); 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")); }
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 assert!(err1.first_error_at.is_none());
716
717 err1.extend_from_retry_error(err2);
718
719 assert_eq!(err1.len(), 2);
720 assert_eq!(err1.errors[0].2, n1);
722 assert_eq!(err1.errors[1].2, n2);
723
724 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 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 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 err2.dedup_by(|e1, e2| e1.to_string() == e2.to_string());
748 assert_eq!(err2.len(), 1); match err2.errors[0].0 {
750 Attempt::Range(1, 3) => {}
751 _ => panic!("Expected range 1..3"),
752 }
753
754 err1.extend_from_retry_error(err2);
756
757 assert_eq!(err1.len(), 3); assert_eq!(err1.n_errors, 5); 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 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 err2.push_timed(anyhow::Error::msg(message), n1, None);
781 err2.push_timed(anyhow::Error::msg(message), n1, None);
782
783 err2.dedup_by(|e1, e2| e1.to_string() == e2.to_string());
785 assert_eq!(err2.len(), 1); match err2.errors[0].0 {
787 Attempt::Range(1, 2) => {}
788 _ => panic!("Expected range 1..2"),
789 }
790
791 err1.extend_from_retry_error(err2);
793 assert_eq!(err1.len(), 2); assert_eq!(err1.n_errors, 3); err1.dedup_by(|e1, e2| e1.to_string() == e2.to_string());
798 assert_eq!(err1.len(), 1); assert_eq!(err1.n_errors, 3); match err1.errors[0].0 {
803 Attempt::Range(1, 3) => {}
804 ref x => panic!("Expected range 1..3, got {:?}", x),
805 }
806 }
807}