Skip to content

Commit

Permalink
refactor: use governor for rate limiting
Browse files Browse the repository at this point in the history
Signed-off-by: Wenxuan Zhang <wenxuangm@gmail.com>
  • Loading branch information
wfxr committed Apr 23, 2024
1 parent d068be1 commit 8b23af0
Show file tree
Hide file tree
Showing 4 changed files with 174 additions and 88 deletions.
127 changes: 127 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 2 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,8 @@ tui-logger = { version = "0.11", optional = true }
log = { version = "0.4", optional = true }
cfg-if = "1"
parking_lot = "0.12"
governor = "0.6"
nonzero_ext = "0.3"

[dev-dependencies]
tokio = { version = "1.36", features = ["rt-multi-thread"] }
Expand Down
23 changes: 16 additions & 7 deletions src/clock.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,9 @@ use parking_lot::Mutex;
use tokio::time::{self, Duration, Instant};

/// A logical clock that can be paused
#[derive(Debug, Clone, Default)]
#[derive(Debug, Clone)]
pub struct Clock {
start: Instant,
inner: Arc<Mutex<InnerClock>>,
}

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

impl Clock {
pub fn start_at(instant: Instant) -> Self {
let inner = InnerClock {
status: Status::Running(instant),
elapsed: Duration::default(),
};
Self { inner: Arc::new(Mutex::new(inner)) }
pub fn start_at(start: Instant) -> Self {
let inner = InnerClock { status: Status::Running(start), elapsed: Duration::default() };
Self { start, inner: Arc::new(Mutex::new(inner)) }
}

pub fn resume(&mut self) {
Expand Down Expand Up @@ -79,6 +77,17 @@ impl Clock {
}
}

impl governor::clock::Clock for Clock {
type Instant = std::time::Instant;

fn now(&self) -> Self::Instant {
let elapsed = self.elapsed();
self.start.into_std() + elapsed
}
}

impl governor::clock::ReasonablyRealtime for Clock {}

/// A ticker that ticks at a fixed logical interval
#[derive(Debug, Clone)]
pub struct Ticker {
Expand Down
Loading

0 comments on commit 8b23af0

Please sign in to comment.