use std::sync::Arc;
use crate::RateLimiter;
#[cfg(any(feature = "redis-tokio", feature = "redis-smol"))]
use std::future::Future;
pub fn unique_key() -> String {
let n: u64 = rand::random();
format!("dt_{n}")
}
#[cfg(any(feature = "redis-tokio", feature = "redis-smol"))]
fn redis_url() -> String {
std::env::var("REDIS_URL").unwrap_or_else(|_| "redis://127.0.0.1:6379".to_string())
}
#[cfg(not(any(feature = "redis-tokio", feature = "redis-smol")))]
pub fn rate_limiter() -> Arc<RateLimiter> {
RateLimiter::builder().build().unwrap()
}
#[cfg(feature = "redis-tokio")]
pub fn rate_limiter() -> Arc<RateLimiter> {
tokio::runtime::Runtime::new().unwrap().block_on(async {
let conn = redis::Client::open(redis_url())
.unwrap()
.get_connection_manager()
.await
.unwrap();
RateLimiter::builder(conn).build().unwrap()
})
}
#[cfg(feature = "redis-tokio")]
pub fn with_redis_rate_limiter<F, Fut, T>(f: F) -> T
where
F: FnOnce(Arc<RateLimiter>) -> Fut,
Fut: Future<Output = T>,
{
tokio::runtime::Runtime::new()
.unwrap()
.block_on(async move {
let conn = redis::Client::open(redis_url())
.unwrap()
.get_connection_manager()
.await
.unwrap();
let rl = RateLimiter::builder(conn).build().unwrap();
f(rl).await
})
}
#[cfg(feature = "redis-smol")]
pub fn rate_limiter() -> Arc<RateLimiter> {
smol::block_on(async {
let conn = redis::Client::open(redis_url())
.unwrap()
.get_connection_manager()
.await
.unwrap();
RateLimiter::builder(conn).build().unwrap()
})
}
#[cfg(feature = "redis-smol")]
pub fn with_redis_rate_limiter<F, Fut, T>(f: F) -> T
where
F: FnOnce(Arc<RateLimiter>) -> Fut,
Fut: Future<Output = T>,
{
smol::block_on(async move {
let conn = redis::Client::open(redis_url())
.unwrap()
.get_connection_manager()
.await
.unwrap();
let rl = RateLimiter::builder(conn).build().unwrap();
f(rl).await
})
}
#[cfg(feature = "redis-tokio")]
pub fn block_on<F, T>(f: F) -> T
where
F: std::future::Future<Output = T>,
{
tokio::runtime::Runtime::new().unwrap().block_on(f)
}
#[cfg(feature = "redis-smol")]
pub fn block_on<F, T>(f: F) -> T
where
F: std::future::Future<Output = T>,
{
smol::block_on(f)
}