use crate::error::Result;
use async_trait::async_trait;
use std::time::Duration;
use std::time::SystemTime;
use uuid::Uuid;
pub const MAX_BUCKET_BYTES: usize = 128;
pub const MAX_KEY_BYTES: usize = 512;
pub const MAX_UNITS: u32 = i32::MAX as u32;
pub const MAX_RESERVATION_TTL: Duration = Duration::from_secs(60 * 60);
pub fn parse_reservation_id(value: &str) -> Result<Uuid> {
Uuid::parse_str(value).map_err(|_| crate::ForgeError::invalid("reservation id must be a UUID"))
}
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum Algo {
#[default]
TokenBucket,
SlidingWindow,
}
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum FailMode {
#[default]
Default,
Open,
Closed,
}
#[non_exhaustive]
#[derive(Debug, Clone, Copy)]
pub struct Limit {
pub max: u32,
pub per: Duration,
pub algo: Algo,
}
impl Limit {
pub const fn per_duration(max: u32, per: Duration) -> Self {
Self {
max,
per,
algo: Algo::TokenBucket,
}
}
pub const fn with_algo(mut self, algo: Algo) -> Self {
self.algo = algo;
self
}
}
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Decision {
pub allowed: bool,
pub limit: u32,
pub remaining: u32,
pub reset_after: Duration,
pub retry_after: Option<Duration>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ReservationState {
Pending,
Committed,
Released,
Expired,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Reservation {
pub id: Uuid,
pub reserved_units: u32,
pub expires_at: SystemTime,
pub state: ReservationState,
pub committed_units: Option<u32>,
}
impl Decision {
pub fn new(
allowed: bool,
limit: u32,
remaining: u32,
reset_after: Duration,
retry_after: Option<Duration>,
) -> Self {
Self {
allowed,
limit,
remaining,
reset_after,
retry_after,
}
}
}
#[async_trait]
pub trait RateLimit: Send + Sync {
async fn check(&self, bucket: &str, key: &str, limit: Limit) -> Result<Decision> {
self.check_with(bucket, key, limit, FailMode::Default).await
}
async fn check_with(
&self,
bucket: &str,
key: &str,
limit: Limit,
fail: FailMode,
) -> Result<Decision> {
self.check_cost_with(bucket, key, limit, 1, fail).await
}
async fn check_cost(
&self,
bucket: &str,
key: &str,
limit: Limit,
cost: u32,
) -> Result<Decision> {
self.check_cost_with(bucket, key, limit, cost, FailMode::Default)
.await
}
async fn check_cost_with(
&self,
bucket: &str,
key: &str,
limit: Limit,
cost: u32,
fail: FailMode,
) -> Result<Decision>;
async fn reserve(
&self,
bucket: &str,
key: &str,
limit: Limit,
units: u32,
ttl: Duration,
) -> Result<Option<Reservation>>;
async fn commit(&self, reservation_id: Uuid, actual_units: u32) -> Result<Reservation>;
async fn release(&self, reservation_id: Uuid) -> Result<Reservation>;
}
mod algo;
mod memory;
mod postgres;
pub(crate) use memory::MemRateLimit;
pub(crate) use postgres::PgRateLimit;