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
use std::{
collections::HashMap,
time::{Duration, Instant},
};
use parking_lot::RwLock;
pub mod msgs {
pub const ACCOUNTS: Option<&str> =
Some("Account management is being phased out see #9997 for alternatives.");
}
type MethodName = &'static str;
const PRINT_INTERVAL: Duration = Duration::from_secs(60);
pub struct DeprecationNotice<T = fn() -> Instant> {
now: T,
next_warning_at: RwLock<HashMap<String, Instant>>,
printer: Box<dyn Fn(MethodName, Option<&str>) + Send + Sync>,
}
impl Default for DeprecationNotice {
fn default() -> Self {
Self::new(Instant::now, |method, more| {
let more = more
.map(|x| format!(": {}", x))
.unwrap_or_else(|| ".".into());
warn!(target: "rpc", "{} is deprecated and will be removed in future versions{}", method, more);
})
}
}
impl<N: Fn() -> Instant> DeprecationNotice<N> {
pub fn new<T>(now: N, printer: T) -> Self
where
T: Fn(MethodName, Option<&str>) + Send + Sync + 'static,
{
DeprecationNotice {
now,
next_warning_at: Default::default(),
printer: Box::new(printer),
}
}
pub fn print<'a, T: Into<Option<&'a str>>>(&self, method: MethodName, details: T) {
let now = (self.now)();
match self.next_warning_at.read().get(method) {
Some(next) if *next > now => return,
_ => {}
}
self.next_warning_at
.write()
.insert(method.to_owned(), now + PRINT_INTERVAL);
(self.printer)(method, details.into());
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::sync::Arc;
#[test]
fn should_throttle_printing() {
let saved = Arc::new(RwLock::new(None));
let s = saved.clone();
let printer = move |method: MethodName, more: Option<&str>| {
*s.write() = Some((method, more.map(|s| s.to_owned())));
};
let now = Arc::new(RwLock::new(Instant::now()));
let n = now.clone();
let get_now = || n.read().clone();
let notice = DeprecationNotice::new(get_now, printer);
let details = Some("See issue #123456");
notice.print("eth_test", details.clone());
notice.print("eth_test", None);
assert_eq!(
saved.read().clone().unwrap(),
("eth_test", details.as_ref().map(|x| x.to_string()))
);
notice.print("eth_test2", None);
assert_eq!(saved.read().clone().unwrap(), ("eth_test2", None));
*now.write() = Instant::now() + PRINT_INTERVAL;
notice.print("eth_test", None);
assert_eq!(saved.read().clone().unwrap(), ("eth_test", None));
}
}