2022-09-11 01:02:54 +02:00
|
|
|
use std::{borrow::Cow, sync::Arc, time::Duration};
|
2022-03-20 01:40:34 +01:00
|
|
|
|
2022-09-11 01:02:54 +02:00
|
|
|
#[cfg(feature = "session")]
|
|
|
|
use actix_session::SessionExt as _;
|
|
|
|
use actix_web::dev::ServiceRequest;
|
2022-03-20 01:40:34 +01:00
|
|
|
use redis::Client;
|
|
|
|
|
2022-09-11 01:02:54 +02:00
|
|
|
use crate::{errors::Error, GetArcBoxKeyFn, Limiter};
|
2022-03-20 01:40:34 +01:00
|
|
|
|
2022-07-11 03:05:22 +02:00
|
|
|
/// Rate limiter builder.
|
2022-03-20 01:40:34 +01:00
|
|
|
#[derive(Debug)]
|
2022-07-11 03:05:22 +02:00
|
|
|
pub struct Builder {
|
|
|
|
pub(crate) redis_url: String,
|
2022-03-20 01:40:34 +01:00
|
|
|
pub(crate) limit: usize,
|
|
|
|
pub(crate) period: Duration,
|
2022-09-11 01:02:54 +02:00
|
|
|
pub(crate) get_key_fn: Option<GetArcBoxKeyFn>,
|
2022-03-20 01:40:34 +01:00
|
|
|
pub(crate) cookie_name: Cow<'static, str>,
|
2022-09-11 01:02:54 +02:00
|
|
|
#[cfg(feature = "session")]
|
2022-03-20 01:40:34 +01:00
|
|
|
pub(crate) session_key: Cow<'static, str>,
|
|
|
|
}
|
|
|
|
|
2022-07-11 03:05:22 +02:00
|
|
|
impl Builder {
|
2022-03-20 01:40:34 +01:00
|
|
|
/// Set upper limit.
|
|
|
|
pub fn limit(&mut self, limit: usize) -> &mut Self {
|
|
|
|
self.limit = limit;
|
|
|
|
self
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Set limit window/period.
|
|
|
|
pub fn period(&mut self, period: Duration) -> &mut Self {
|
|
|
|
self.period = period;
|
|
|
|
self
|
|
|
|
}
|
|
|
|
|
2022-09-11 01:02:54 +02:00
|
|
|
/// Sets rate limit key derivation function.
|
|
|
|
///
|
|
|
|
/// Should not be used in combination with `cookie_name` or `session_key` as they conflict.
|
|
|
|
pub fn key_by<F>(&mut self, resolver: F) -> &mut Self
|
|
|
|
where
|
|
|
|
F: Fn(&ServiceRequest) -> Option<String> + Send + Sync + 'static,
|
|
|
|
{
|
|
|
|
self.get_key_fn = Some(Arc::new(resolver));
|
|
|
|
self
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Sets name of cookie to be sent.
|
|
|
|
///
|
|
|
|
/// This method should not be used in combination of `key_by` as they conflict.
|
|
|
|
#[deprecated = "Prefer `key_by`."]
|
2022-03-20 01:40:34 +01:00
|
|
|
pub fn cookie_name(&mut self, cookie_name: impl Into<Cow<'static, str>>) -> &mut Self {
|
2022-09-11 01:02:54 +02:00
|
|
|
if self.get_key_fn.is_some() {
|
|
|
|
panic!("This method should not be used in combination of get_key as they overwrite each other")
|
|
|
|
}
|
2022-03-20 01:40:34 +01:00
|
|
|
self.cookie_name = cookie_name.into();
|
|
|
|
self
|
|
|
|
}
|
|
|
|
|
2022-09-11 01:02:54 +02:00
|
|
|
/// Sets session key to be used in backend.
|
|
|
|
///
|
|
|
|
/// This method should not be used in combination of `key_by` as they conflict.
|
|
|
|
#[deprecated = "Prefer `key_by`."]
|
|
|
|
#[cfg(feature = "session")]
|
2022-03-20 01:40:34 +01:00
|
|
|
pub fn session_key(&mut self, session_key: impl Into<Cow<'static, str>>) -> &mut Self {
|
2022-09-11 01:02:54 +02:00
|
|
|
if self.get_key_fn.is_some() {
|
|
|
|
panic!("This method should not be used in combination of get_key as they overwrite each other")
|
|
|
|
}
|
2022-03-20 01:40:34 +01:00
|
|
|
self.session_key = session_key.into();
|
|
|
|
self
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Finalizes and returns a `Limiter`.
|
|
|
|
///
|
|
|
|
/// Note that this method will connect to the Redis server to test its connection which is a
|
|
|
|
/// **synchronous** operation.
|
2022-09-11 01:02:54 +02:00
|
|
|
pub fn build(&mut self) -> Result<Limiter, Error> {
|
|
|
|
let get_key = if let Some(resolver) = self.get_key_fn.clone() {
|
|
|
|
resolver
|
|
|
|
} else {
|
|
|
|
let cookie_name = self.cookie_name.clone();
|
|
|
|
|
|
|
|
#[cfg(feature = "session")]
|
|
|
|
let session_key = self.session_key.clone();
|
|
|
|
|
|
|
|
let closure: GetArcBoxKeyFn = Arc::new(Box::new(move |req: &ServiceRequest| {
|
|
|
|
#[cfg(feature = "session")]
|
|
|
|
let res = req
|
|
|
|
.get_session()
|
|
|
|
.get(&session_key)
|
|
|
|
.unwrap_or_else(|_| req.cookie(&cookie_name).map(|c| c.to_string()));
|
|
|
|
|
|
|
|
#[cfg(not(feature = "session"))]
|
|
|
|
let res = req.cookie(&cookie_name).map(|c| c.to_string());
|
|
|
|
|
|
|
|
res
|
|
|
|
}));
|
|
|
|
closure
|
|
|
|
};
|
|
|
|
|
2022-03-20 01:40:34 +01:00
|
|
|
Ok(Limiter {
|
2022-07-11 03:05:22 +02:00
|
|
|
client: Client::open(self.redis_url.as_str())?,
|
2022-03-20 01:40:34 +01:00
|
|
|
limit: self.limit,
|
|
|
|
period: self.period,
|
2022-09-11 01:02:54 +02:00
|
|
|
get_key_fn: get_key,
|
2022-03-20 01:40:34 +01:00
|
|
|
})
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
#[cfg(test)]
|
|
|
|
mod tests {
|
|
|
|
use super::*;
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn test_create_builder() {
|
|
|
|
let redis_url = "redis://127.0.0.1";
|
|
|
|
let period = Duration::from_secs(10);
|
|
|
|
let builder = Builder {
|
2022-07-11 03:05:22 +02:00
|
|
|
redis_url: redis_url.to_owned(),
|
2022-03-20 01:40:34 +01:00
|
|
|
limit: 100,
|
|
|
|
period,
|
2022-09-11 01:02:54 +02:00
|
|
|
get_key_fn: Some(Arc::new(|_| None)),
|
2022-03-20 01:40:34 +01:00
|
|
|
cookie_name: Cow::Owned("session".to_string()),
|
2022-09-11 01:02:54 +02:00
|
|
|
#[cfg(feature = "session")]
|
2022-03-20 01:40:34 +01:00
|
|
|
session_key: Cow::Owned("rate-api".to_string()),
|
|
|
|
};
|
|
|
|
|
|
|
|
assert_eq!(builder.redis_url, redis_url);
|
|
|
|
assert_eq!(builder.limit, 100);
|
|
|
|
assert_eq!(builder.period, period);
|
2022-09-11 01:02:54 +02:00
|
|
|
#[cfg(feature = "session")]
|
2022-03-20 01:40:34 +01:00
|
|
|
assert_eq!(builder.session_key, "rate-api");
|
|
|
|
assert_eq!(builder.cookie_name, "session");
|
|
|
|
}
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn test_create_limiter() {
|
|
|
|
let redis_url = "redis://127.0.0.1";
|
|
|
|
let period = Duration::from_secs(20);
|
|
|
|
let mut builder = Builder {
|
2022-07-11 03:05:22 +02:00
|
|
|
redis_url: redis_url.to_owned(),
|
2022-03-20 01:40:34 +01:00
|
|
|
limit: 100,
|
|
|
|
period: Duration::from_secs(10),
|
2022-09-11 01:02:54 +02:00
|
|
|
get_key_fn: Some(Arc::new(|_| None)),
|
2022-03-20 01:40:34 +01:00
|
|
|
cookie_name: Cow::Borrowed("sid"),
|
2022-09-11 01:02:54 +02:00
|
|
|
#[cfg(feature = "session")]
|
|
|
|
session_key: Cow::Borrowed("key"),
|
2022-03-20 01:40:34 +01:00
|
|
|
};
|
|
|
|
|
2022-09-11 01:02:54 +02:00
|
|
|
let limiter = builder.limit(200).period(period).build().unwrap();
|
2022-03-20 01:40:34 +01:00
|
|
|
|
|
|
|
assert_eq!(limiter.limit, 200);
|
|
|
|
assert_eq!(limiter.period, period);
|
|
|
|
}
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
#[should_panic = "Redis URL did not parse"]
|
|
|
|
fn test_create_limiter_error() {
|
|
|
|
let redis_url = "127.0.0.1";
|
|
|
|
let period = Duration::from_secs(20);
|
|
|
|
let mut builder = Builder {
|
2022-07-11 03:05:22 +02:00
|
|
|
redis_url: redis_url.to_owned(),
|
2022-03-20 01:40:34 +01:00
|
|
|
limit: 100,
|
|
|
|
period: Duration::from_secs(10),
|
2022-09-11 01:02:54 +02:00
|
|
|
get_key_fn: Some(Arc::new(|_| None)),
|
2022-03-20 01:40:34 +01:00
|
|
|
cookie_name: Cow::Borrowed("sid"),
|
2022-09-11 01:02:54 +02:00
|
|
|
#[cfg(feature = "session")]
|
|
|
|
session_key: Cow::Borrowed("key"),
|
2022-03-20 01:40:34 +01:00
|
|
|
};
|
|
|
|
|
|
|
|
builder.limit(200).period(period).build().unwrap();
|
|
|
|
}
|
|
|
|
}
|