1//! The state for a single backend for a basic log_ratelim().
23use std::{error::Error as StdError, fmt, time::Duration};
45/// A type-erased error type with the minimum features we need.
6type DynError = Box<dyn StdError + Send + 'static>;
78/// The state for a single rate-limited log message.
9///
10/// This type is used as a common implementation helper for the
11/// [`log_ratelim!()`](crate::log_ratelim) macro.
12///
13/// Its role is to track successes and failures,
14/// to remember some error information,
15/// and produce Display-able messages when a [RateLim](crate::ratelim::RateLim)
16/// decides that it is time to log.
17///
18/// This type has to be `pub`, but it is hidden:
19/// using it directly will void your semver guarantees.
20pub struct LogState {
21/// How many times has the activity failed since we last reset()?
22n_fail: usize,
23/// How many times has the activity succeeded since we last reset()?
24n_ok: usize,
25/// A string representing the activity itself.
26activity: String,
27/// If present, a message that we will along with `error`.
28error_message: Option<String>,
29/// If present, an error that we will log when reporting an error.
30error: Option<DynError>,
31}
32impl LogState {
33/// Create a new LogState with no recorded errors or successes.
34pub fn new(activity: String) -> Self {
35Self {
36 n_fail: 0,
37 n_ok: 0,
38 activity,
39 error_message: None,
40 error: None,
41 }
42 }
43/// Discard all success and failure information in this LogState.
44pub fn reset(&mut self) {
45*self = Self::new(std::mem::take(&mut self.activity));
46 }
47/// Record a single failure in this LogState.
48 ///
49 /// If this is the _first_ recorded failure, invoke `msg_fn` to get an
50 /// optional failure message and an optional error to be reported as an
51 /// example of the types of failures we are seeing.
52pub fn note_fail(&mut self, msg_fn: impl FnOnce() -> (Option<String>, Option<DynError>)) {
53if self.n_fail == 0 {
54let (m, e) = msg_fn();
55self.error_message = m;
56self.error = e;
57 }
58self.n_fail = self.n_fail.saturating_add(1);
59 }
60/// Record a single success in this LogState.
61pub fn note_ok(&mut self) {
62self.n_ok = self.n_ok.saturating_add(1);
63 }
64/// Check whether there is any activity to report from this LogState.
65pub fn activity(&self) -> crate::Activity {
66if self.n_fail == 0 {
67crate::Activity::Dormant
68 } else {
69crate::Activity::Active
70 }
71 }
72/// Return a wrapper type for reporting that we have observed problems in
73 /// this LogState.
74pub fn display_problem(&self, dur: Duration) -> impl fmt::Display + '_ {
75 DispProblem(self, dur)
76 }
77/// Return a wrapper type for reporting that we have not observed problems in
78 /// this LogState.
79pub fn display_recovery(&self, dur: Duration) -> impl fmt::Display + '_ {
80 DispWorking(self, dur)
81 }
82}
8384/// Helper: wrapper for reporting problems via Display.
85struct DispProblem<'a>(&'a LogState, Duration);
86impl<'a> fmt::Display for DispProblem<'a> {
87fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
88write!(f, "{}: error", self.0.activity)?;
89let n_total = self.0.n_fail.saturating_add(self.0.n_ok);
90write!(
91 f,
92" (problem occurred {}/{} times in the last {})",
93self.0.n_fail,
94 n_total,
95 humantime::format_duration(self.1)
96 )?;
97if let Some(msg) = self.0.error_message.as_ref() {
98write!(f, ": {}", msg)?;
99 }
100if let Some(err) = self.0.error.as_ref() {
101let err = Adaptor(err);
102write!(f, ": {}", tor_error::Report(&err))?;
103 }
104Ok(())
105 }
106}
107/// Helper: wrapper for reporting a lack of problems via Display.
108struct DispWorking<'a>(&'a LogState, Duration);
109impl<'a> fmt::Display for DispWorking<'a> {
110fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
111write!(f, "{}: now working", self.0.activity)?;
112write!(
113 f,
114" (problem occurred 0/{} times in the last {})",
115self.0.n_ok,
116 humantime::format_duration(self.1)
117 )?;
118Ok(())
119 }
120}
121/// Helper struct to make Report work correctly.
122///
123/// We can't use ErrorReport since our `Box<>`ed error is not only `dyn Error`, but also `Send`.
124#[derive(Debug)]
125struct Adaptor<'a>(&'a DynError);
126impl<'a> AsRef<dyn StdError + 'static> for Adaptor<'a> {
127fn as_ref(&self) -> &(dyn StdError + 'static) {
128self.0.as_ref()
129 }
130}
131132#[cfg(test)]
133mod tests {
134135#![allow(clippy::redundant_closure)]
136use super::*;
137use crate::Activity;
138use std::time::Duration;
139use thiserror::Error;
140141#[derive(Debug, Error)]
142 #[error("TestError is here!")]
143struct TestError {
144 source: TestErrorBuddy,
145 }
146147#[derive(Debug, Error)]
148 #[error("TestErrorBuddy is here!")]
149struct TestErrorBuddy;
150151#[test]
152fn display_problem() {
153let duration = Duration::from_millis(10);
154let mut ls: LogState = LogState::new("test".to_string());
155let mut activity: Activity = ls.activity();
156assert_eq!(Activity::Dormant, activity);
157assert_eq!(ls.n_fail, 0);
158fn err_msg() -> (Option<String>, Option<DynError>) {
159 (
160Some("test".to_string()),
161Some(Box::new(TestError {
162 source: TestErrorBuddy,
163 })),
164 )
165 }
166 ls.note_fail(|| err_msg());
167assert_eq!(ls.n_fail, 1);
168let problem = ls.display_problem(duration);
169let expected_problem = String::from(
170"test: error (problem occurred 1/1 times in the last 10ms): test: error: TestError is here!: TestErrorBuddy is here!"
171);
172let str_problem = format!("{problem}");
173assert_eq!(expected_problem, str_problem);
174 activity = ls.activity();
175assert_eq!(Activity::Active, activity);
176 }
177178#[test]
179fn display_recovery() {
180let duration = Duration::from_millis(10);
181let mut ls = LogState::new("test".to_string());
182 ls.note_ok();
183assert_eq!(ls.n_ok, 1);
184 {
185let recovery = ls.display_recovery(duration);
186let expected_recovery =
187 String::from("test: now working (problem occurred 0/1 times in the last 10ms)");
188let str_recovery = format!("{recovery}");
189assert_eq!(expected_recovery, str_recovery);
190 }
191 ls.reset();
192assert_eq!(ls.n_ok, 0);
193 }
194}