use std::fmt;
use std::sync::Arc;
use std::time::{Duration, SystemTime};
use super::allowance::Allowance;
use super::buffer::{Buffer, Change, Live};
use super::path::Key;
use super::scope::{Kind, Scope};
use crate::engine::Home;
use crate::{Error, Result, Store, unix_millis, unix_nanos};
const FLUSH: Duration = Duration::from_secs(1);
#[must_use = "a rate limit opens with open()"]
pub struct RateLimitBuilder {
store: Store,
name: String,
rate: Option<(u64, Duration)>,
burst: Option<u64>,
}
impl Store {
pub fn rate_limit(&self, name: &str) -> RateLimitBuilder {
RateLimitBuilder { store: self.clone(), name: name.to_owned(), rate: None, burst: None }
}
}
impl RateLimitBuilder {
pub fn rate(mut self, count: u64, per: Duration) -> Self {
self.rate = Some((count, per));
self
}
pub fn burst(mut self, burst: u64) -> Self {
self.burst = Some(burst);
self
}
pub fn open(self) -> Result<RateLimit> {
let (interval, burst) =
check_rate(self.rate, self.burst).map_err(|error| error.within(format!("kv rate limit {}", self.name)))?;
let scope = Scope::open(&Home::Store(self.store.clone()), &self.name, Kind::RateLimit)?;
let buffer =
scope.kv.buffer(scope.id, Some(FLUSH), &scope.shown()).map_err(|error| error.within(scope.shown()))?;
let buffer = buffer.ok_or_else(|| Error::internal("a rate limit without its memory").within(scope.shown()))?;
Ok(RateLimit { scope, buffer, interval, burst })
}
}
pub struct RateLimit {
pub(crate) scope: Scope,
pub(crate) buffer: Arc<Buffer>,
interval: i64,
burst: i64,
}
impl RateLimit {
pub fn under(&self, owner: impl Key) -> RateLimit {
RateLimit { scope: self.scope.under(owner), ..self.clone() }
}
pub fn allow(&self, key: impl Key) -> Result<Allowance> {
self.allow_n(key, 1)
}
pub fn allow_n(&self, key: impl Key, n: u64) -> Result<Allowance> {
let key = key.text();
#[cfg(feature = "replication")]
if self.scope.kv.file().is_copy() {
return super::forward::allowance(&self.pass_on(&key, &super::forward::Call::Allow(n))?);
}
let shown = || self.scope.shown_key(&key);
if n == 0 {
return Err(Error::invalid("no requests at once: ask for one at least").within(shown()));
}
let asked = i64::try_from(n).ok().filter(|&n| n <= self.burst).ok_or_else(|| {
Error::invalid(format!("{n} requests at once, past a burst of {}", self.burst)).within(shown())
})?;
let path = self.scope.path(&key)?;
let now = self.scope.kv.clock().now();
let step = |live: Option<Live>| {
let due = live.map_or(0, |live| live.value);
let (allowance, next) = self.decide(due, now, asked);
let change = if allowance.ok {
Change::Set(Live { value: next, expires: Some(millis_after(next)) })
} else {
Change::Leave
};
Ok((change, allowance))
};
self.buffer.step(&self.scope.kv, &path, unix_millis(now), step).map_err(|error| error.within(shown()))
}
pub fn peek(&self, key: impl Key) -> Result<Allowance> {
let key = key.text();
let path = self.scope.path(&key)?;
let now = self.scope.kv.clock().now();
let live = self.buffer.get(&self.scope.kv, &path, unix_millis(now));
let due = live.map_err(|error| error.within(self.scope.shown_key(&key)))?.map_or(0, |live| live.value);
Ok(self.decide(due, now, 1).0)
}
pub fn reset(&self, key: impl Key) -> Result<()> {
let key = key.text();
#[cfg(feature = "replication")]
if self.scope.kv.file().is_copy() {
return self.pass_on(&key, &super::forward::Call::Reset).map(drop);
}
let path = self.scope.path(&key)?;
let now = unix_millis(self.scope.kv.clock().now());
let step = |live: Option<Live>| Ok((if live.is_some() { Change::Remove } else { Change::Leave }, ()));
self.buffer.step(&self.scope.kv, &path, now, step).map_err(|error| error.within(self.scope.shown_key(&key)))
}
#[cfg(feature = "async")]
pub(crate) fn on_a_copy(&self) -> bool {
#[cfg(feature = "replication")]
return self.scope.kv.file().is_copy();
#[cfg(not(feature = "replication"))]
false
}
#[cfg(feature = "replication")]
fn pass_on(&self, key: &str, call: &super::forward::Call) -> Result<Vec<u8>> {
let handle = super::forward::Handle::RateLimit {
name: self.scope.name().to_owned(),
interval: self.interval,
burst: self.burst,
};
self.scope.pass_on(&handle, key, call)
}
fn decide(&self, due: i64, now: SystemTime, n: i64) -> (Allowance, i64) {
let nanos = unix_nanos(now);
let start = due.max(nanos);
let (next, limit) = (start + n * self.interval, nanos + self.burst * self.interval);
if next > limit {
let wait = Duration::from_nanos((next - limit).unsigned_abs());
let left = ((limit - start).max(0) / self.interval).unsigned_abs();
return (Allowance { ok: false, left, retry_at: Some(now + wait), windows: Vec::new() }, due);
}
let left = ((limit - next) / self.interval).unsigned_abs();
(Allowance { ok: true, left, retry_at: None, windows: Vec::new() }, next)
}
}
impl Clone for RateLimit {
fn clone(&self) -> Self {
RateLimit {
scope: self.scope.clone(),
buffer: Arc::clone(&self.buffer),
interval: self.interval,
burst: self.burst,
}
}
}
impl fmt::Debug for RateLimit {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "RateLimit({:?})", self.scope)
}
}
impl fmt::Debug for RateLimitBuilder {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "RateLimitBuilder({})", self.name)
}
}
fn check_rate(rate: Option<(u64, Duration)>, burst: Option<u64>) -> Result<(i64, i64)> {
let Some((count, per)) = rate else {
return Err(Error::invalid("a rate limit needs a rate: .rate(100, Duration::from_secs(1))"));
};
let per_nanos = i64::try_from(per.as_nanos()).unwrap_or(i64::MAX);
let count_most = i64::try_from(count).unwrap_or(i64::MAX);
if count == 0 || per.is_zero() {
return Err(Error::invalid("a rate of at least one request every positive span"));
}
if per_nanos < count_most {
return Err(Error::invalid(format!("a rate of {count} every {per:?} is past one a nanosecond")));
}
let interval = per_nanos / count_most;
let burst = i64::try_from(burst.unwrap_or(count)).unwrap_or(i64::MAX);
if burst < 1 {
return Err(Error::invalid("a burst of 0"));
}
if burst > i64::MAX / 4 / interval {
return Err(Error::invalid(format!("a burst of {burst} at {interval} ns a request is past what a time holds")));
}
Ok((interval, burst))
}
fn millis_after(nanos: i64) -> i64 {
nanos.div_euclid(1_000_000) + i64::from(nanos.rem_euclid(1_000_000) != 0)
}
#[cfg(test)]
#[path = "rate_limit_tests.rs"]
mod tests;