-
Notifications
You must be signed in to change notification settings - Fork 452
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
fix(rust): implement a throttler to prevent hitting the rate limit an…
…d being banned.
- Loading branch information
Showing
5 changed files
with
94 additions
and
24 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,35 @@ | ||
use std::{future::Future, sync::Arc}; | ||
|
||
use chrono::Utc; | ||
use tokio::sync::Mutex; | ||
|
||
#[derive(Clone)] | ||
pub struct Throttler { | ||
exec_ts: Arc<Mutex<Vec<i64>>>, | ||
rate_limit: usize, | ||
} | ||
|
||
impl Throttler { | ||
pub fn new(rate_limit: usize) -> Self { | ||
Self { | ||
exec_ts: Default::default(), | ||
rate_limit, | ||
} | ||
} | ||
|
||
pub async fn execute<Fut, T>(&mut self, fut: Fut) -> Option<T> | ||
where | ||
Fut: Future<Output = T>, | ||
{ | ||
let cur_ts = Utc::now().timestamp_nanos_opt().unwrap(); | ||
{ | ||
let mut exec_ts_ = self.exec_ts.lock().await; | ||
exec_ts_.retain(|ts| *ts > cur_ts - 60_000_000_000); | ||
if exec_ts_.len() > self.rate_limit { | ||
return None; | ||
} | ||
exec_ts_.push(cur_ts); | ||
} | ||
Some(fut.await) | ||
} | ||
} |