Skip to content

Commit 8b23af0

Browse files
committed
refactor: use governor for rate limiting
Signed-off-by: Wenxuan Zhang <[email protected]>
1 parent d068be1 commit 8b23af0

File tree

4 files changed

+174
-88
lines changed

4 files changed

+174
-88
lines changed

Cargo.lock

Lines changed: 127 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

Cargo.toml

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -46,6 +46,8 @@ tui-logger = { version = "0.11", optional = true }
4646
log = { version = "0.4", optional = true }
4747
cfg-if = "1"
4848
parking_lot = "0.12"
49+
governor = "0.6"
50+
nonzero_ext = "0.3"
4951

5052
[dev-dependencies]
5153
tokio = { version = "1.36", features = ["rt-multi-thread"] }

src/clock.rs

Lines changed: 16 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -4,8 +4,9 @@ use parking_lot::Mutex;
44
use tokio::time::{self, Duration, Instant};
55

66
/// A logical clock that can be paused
7-
#[derive(Debug, Clone, Default)]
7+
#[derive(Debug, Clone)]
88
pub struct Clock {
9+
start: Instant,
910
inner: Arc<Mutex<InnerClock>>,
1011
}
1112

@@ -23,12 +24,9 @@ pub(crate) enum Status {
2324
}
2425

2526
impl Clock {
26-
pub fn start_at(instant: Instant) -> Self {
27-
let inner = InnerClock {
28-
status: Status::Running(instant),
29-
elapsed: Duration::default(),
30-
};
31-
Self { inner: Arc::new(Mutex::new(inner)) }
27+
pub fn start_at(start: Instant) -> Self {
28+
let inner = InnerClock { status: Status::Running(start), elapsed: Duration::default() };
29+
Self { start, inner: Arc::new(Mutex::new(inner)) }
3230
}
3331

3432
pub fn resume(&mut self) {
@@ -79,6 +77,17 @@ impl Clock {
7977
}
8078
}
8179

80+
impl governor::clock::Clock for Clock {
81+
type Instant = std::time::Instant;
82+
83+
fn now(&self) -> Self::Instant {
84+
let elapsed = self.elapsed();
85+
self.start.into_std() + elapsed
86+
}
87+
}
88+
89+
impl governor::clock::ReasonablyRealtime for Clock {}
90+
8291
/// A ticker that ticks at a fixed logical interval
8392
#[derive(Debug, Clone)]
8493
pub struct Ticker {

0 commit comments

Comments
 (0)