web3-proxy/redis-rate-limiter/src/lib.rs

112 lines
3.6 KiB
Rust
Raw Normal View History

//#![warn(missing_docs)]
use anyhow::Context;
use std::ops::Add;
use std::time::{SystemTime, UNIX_EPOCH};
use tokio::time::{Duration, Instant};
use tracing::{debug, trace};
2022-09-14 09:18:13 +03:00
pub use deadpool_redis::redis;
2022-09-15 20:57:24 +03:00
pub use deadpool_redis::{
Config as RedisConfig, Connection as RedisConnection, Manager as RedisManager,
Pool as RedisPool, Runtime as DeadpoolRuntime,
};
2022-09-15 20:57:24 +03:00
#[derive(Clone)]
pub struct RedisRateLimiter {
key_prefix: String,
2022-08-30 23:01:42 +03:00
/// The default maximum requests allowed in a period.
2022-09-15 20:57:24 +03:00
pub max_requests_per_period: u64,
2022-08-30 23:01:42 +03:00
/// seconds
2022-09-15 20:57:24 +03:00
pub period: f32,
pool: RedisPool,
}
2022-09-15 20:57:24 +03:00
pub enum RedisRateLimitResult {
Allowed(u64),
RetryAt(Instant, u64),
RetryNever,
}
2022-09-15 20:57:24 +03:00
impl RedisRateLimiter {
pub fn new(
app: &str,
label: &str,
2022-08-30 23:01:42 +03:00
max_requests_per_period: u64,
period: f32,
2022-09-15 20:57:24 +03:00
pool: RedisPool,
) -> Self {
let key_prefix = format!("{}:rrl:{}", app, label);
Self {
pool,
key_prefix,
2022-08-30 23:01:42 +03:00
max_requests_per_period,
period,
}
}
2022-08-30 23:01:42 +03:00
/// label might be an ip address or a user_key id.
/// if setting max_per_period, be sure to keep the period the same for all requests to this label
pub async fn throttle_label(
&self,
label: &str,
max_per_period: Option<u64>,
count: u64,
2022-09-15 20:57:24 +03:00
) -> anyhow::Result<RedisRateLimitResult> {
2022-08-30 23:01:42 +03:00
let max_per_period = max_per_period.unwrap_or(self.max_requests_per_period);
if max_per_period == 0 {
2022-09-15 20:57:24 +03:00
return Ok(RedisRateLimitResult::RetryNever);
}
let now = SystemTime::now()
.duration_since(UNIX_EPOCH)
.context("cannot tell the time")?
2022-08-30 23:01:42 +03:00
.as_secs_f32();
// if self.period is 60, period_id will be the minute of the current time
let period_id = (now / self.period) % self.period;
2022-09-15 20:57:24 +03:00
// TODO: include max per period in the throttle key?
let throttle_key = format!("{}:{}:{}", self.key_prefix, label, period_id);
2022-09-14 09:41:34 +03:00
let mut conn = self.pool.get().await.context("throttle")?;
// TODO: at high concurency, i think this is giving errors
// TODO: i'm starting to think that bb8 has a bug
2022-09-15 20:57:24 +03:00
let x: Vec<u64> = redis::pipe()
// we could get the key first, but that means an extra redis call for every check. this seems better
.incr(&throttle_key, count)
// set expiration each time we set the key. ignore the result
2022-08-30 23:01:42 +03:00
.expire(&throttle_key, self.period as usize)
// TODO: NX will make it only set the expiration the first time. works in redis, but not elasticache
// .arg("NX")
.ignore()
// do the query
.query_async(&mut *conn)
.await
.context("increment rate limit")?;
2022-09-15 20:57:24 +03:00
// TODO: is there a better way to do this?
let new_count = *x.first().context("check rate limit result")?;
2022-09-15 20:57:24 +03:00
if new_count > max_per_period {
2022-08-30 23:01:42 +03:00
let seconds_left_in_period = self.period - (now % self.period);
2022-08-30 23:01:42 +03:00
let retry_at = Instant::now().add(Duration::from_secs_f32(seconds_left_in_period));
debug!(%label, ?retry_at, "rate limited: {}/{}", new_count, max_per_period);
2022-09-15 20:57:24 +03:00
Ok(RedisRateLimitResult::RetryAt(retry_at, new_count))
} else {
trace!(%label, "NOT rate limited: {}/{}", new_count, max_per_period);
2022-09-15 20:57:24 +03:00
Ok(RedisRateLimitResult::Allowed(new_count))
}
}
#[inline]
2022-09-15 20:57:24 +03:00
pub async fn throttle(&self) -> anyhow::Result<RedisRateLimitResult> {
self.throttle_label("", None, 1).await
}
}