use std::collections::BTreeMap;
use std::fmt;
use std::sync::Arc;
use std::time::Duration;
use super::allowance::{Allowance, Window as WindowUse};
use super::bucket::Work;
use super::cells;
use super::engine::{Revision, next_version};
use super::path::Key;
use super::scope::{Kind, Scope};
use super::value::Raw;
use crate::clock::{from_unix_millis, millis};
use crate::engine::Home;
use crate::sqlite::Tx;
use crate::{Error, Result, Store};
const MOST_WINDOWS: usize = 8;
const ROW: usize = 2 << 10;
#[must_use = "a quota opens with open()"]
pub struct QuotaBuilder {
store: Store,
name: String,
windows: Vec<Window>,
}
impl Store {
pub fn quota(&self, name: &str) -> QuotaBuilder {
QuotaBuilder { store: self.clone(), name: name.to_owned(), windows: Vec::new() }
}
}
impl QuotaBuilder {
pub fn window(mut self, name: &str, limit: u64, span: Duration) -> Self {
self.windows.push(Window { name: name.to_owned(), limit, span: millis(span) });
self
}
pub fn open(self) -> Result<Quota> {
check_windows(&self.windows).map_err(|error| error.within(format!("kv quota {}", self.name)))?;
let least = self.windows.iter().map(|window| window.limit).min().unwrap_or(0);
let scope = Scope::open(&Home::Store(self.store.clone()), &self.name, Kind::Quota)?;
Ok(Quota { scope, windows: self.windows.into(), least })
}
}
pub struct Quota {
pub(crate) scope: Scope,
windows: Arc<[Window]>,
least: u64,
}
#[derive(Clone, Debug)]
struct Window {
name: String,
limit: u64,
span: i64,
}
type Held = BTreeMap<String, (u64, i64)>;
impl Quota {
pub fn under(&self, owner: impl Key) -> Quota {
Quota { scope: self.scope.under(owner), windows: Arc::clone(&self.windows), least: self.least }
}
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))?);
}
self.scope.write(&key, ROW, self.allow_work(&key, n)?)
}
#[cfg(any(feature = "wire", feature = "async"))]
pub(crate) fn allow_n_then(&self, key: &str, n: u64, done: impl FnOnce(Result<Allowance>) + Send + 'static) {
#[cfg(feature = "replication")]
if self.scope.kv.file().is_copy() {
let (quota, key) = (self.clone(), key.to_owned());
std::thread::spawn(move || done(quota.allow_n(key, n)));
return;
}
self.scope.submit_made(key, ROW, self.allow_work(key, n), done);
}
fn allow_work(&self, key: &str, n: u64) -> Result<impl Work<Allowance> + use<>> {
if n == 0 {
return Err(Error::invalid("none at once: ask for one at least").within(self.scope.shown_key(key)));
}
if n > self.least {
let message = format!("{n} at once, past the smallest window's limit of {}", self.least);
return Err(Error::invalid(message).within(self.scope.shown_key(key)));
}
let now = self.scope.now();
let (id, path, windows) = (self.scope.id, self.scope.path(key)?, Arc::clone(&self.windows));
Ok(move |tx: &Tx<'_>, revision: &Revision| {
let (held, spill) = held(tx, id, &path, now)?;
let (next, usage) = decide(&windows, &held, now, n);
if usage.ok {
keep(tx, revision, (id, &path), &next, spill)?;
}
Ok(usage)
})
}
pub fn peek(&self, key: impl Key) -> Result<Allowance> {
let key = key.text();
let (id, path, now) = (self.scope.id, self.scope.path(&key)?, self.scope.now());
let (held, _) = self.scope.read(&key, |connection| held(connection, id, &path, now))?;
Ok(decide(&self.windows, &held, now, 0).1)
}
pub fn refund(&self, key: impl Key) -> Result<()> {
self.refund_n(key, 1)
}
pub fn refund_n(&self, key: impl Key, n: u64) -> Result<()> {
let key = key.text();
#[cfg(feature = "replication")]
if self.scope.kv.file().is_copy() {
return self.pass_on(&key, &super::forward::Call::Refund(n)).map(drop);
}
self.scope.write(&key, ROW, self.refund_work(&key, n)?)
}
#[cfg(any(feature = "wire", feature = "async"))]
pub(crate) fn refund_n_then(&self, key: &str, n: u64, done: impl FnOnce(Result<()>) + Send + 'static) {
#[cfg(feature = "replication")]
if self.scope.kv.file().is_copy() {
let (quota, key) = (self.clone(), key.to_owned());
std::thread::spawn(move || done(quota.refund_n(key, n)));
return;
}
self.scope.submit_made(key, ROW, self.refund_work(key, n), done);
}
fn refund_work(&self, key: &str, n: u64) -> Result<impl Work<()> + use<>> {
let now = self.scope.now();
let (id, path) = (self.scope.id, self.scope.path(key)?);
Ok(move |tx: &Tx<'_>, revision: &Revision| {
let (held, spill) = held(tx, id, &path, now)?;
let next: Held = held
.into_iter()
.filter(|(_, (_, resets))| *resets > now)
.map(|(name, (used, resets))| (name, (used.saturating_sub(n), resets)))
.collect();
if next.is_empty() {
return Ok(());
}
keep(tx, revision, (id, &path), &next, spill)
})
}
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);
}
self.scope.write(&key, 0, self.reset_work(&key)?)
}
#[cfg(any(feature = "wire", feature = "async"))]
pub(crate) fn reset_then(&self, key: &str, done: impl FnOnce(Result<()>) + Send + 'static) {
#[cfg(feature = "replication")]
if self.scope.kv.file().is_copy() {
let (quota, key) = (self.clone(), key.to_owned());
std::thread::spawn(move || done(quota.reset(key)));
return;
}
self.scope.submit_made(key, 0, self.reset_work(key), done);
}
#[cfg(feature = "replication")]
fn pass_on(&self, key: &str, call: &super::forward::Call) -> Result<Vec<u8>> {
let windows = self.windows.iter().map(|window| (window.name.clone(), window.limit, window.span)).collect();
let handle = super::forward::Handle::Quota { name: self.scope.name().to_owned(), windows };
self.scope.pass_on(&handle, key, call)
}
fn reset_work(&self, key: &str) -> Result<impl Work<()> + use<>> {
let now = self.scope.now();
let (id, path) = (self.scope.id, self.scope.path(key)?);
Ok(move |tx: &Tx<'_>, _: &Revision| match cells::current(tx, id, &path, now)? {
Some(current) => cells::remove(tx, id, &path, current.spill),
None => Ok(()),
})
}
}
impl Clone for Quota {
fn clone(&self) -> Self {
Quota { scope: self.scope.clone(), windows: Arc::clone(&self.windows), least: self.least }
}
}
impl fmt::Debug for Quota {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "Quota({:?})", self.scope)
}
}
impl fmt::Debug for QuotaBuilder {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "QuotaBuilder({})", self.name)
}
}
fn decide(windows: &[Window], held: &Held, now: i64, n: u64) -> (Held, Allowance) {
let asked = n.max(1);
let mut kept: Vec<(u64, i64)> = windows.iter().map(|window| current(held, window, now)).collect();
let refusing: Vec<i64> = windows
.iter()
.zip(&kept)
.filter(|(window, (used, _))| used + asked > window.limit)
.map(|(_, (_, resets))| *resets)
.collect();
let ok = refusing.is_empty();
if ok && n > 0 {
for (window, (used, resets)) in windows.iter().zip(kept.iter_mut()) {
*used += n;
if *resets == 0 {
*resets = now.saturating_add(window.span);
}
}
}
let usage = Allowance {
ok,
left: windows
.iter()
.zip(&kept)
.map(|(window, (used, _))| window.limit.saturating_sub(*used))
.min()
.unwrap_or(0),
retry_at: refusing.into_iter().max().map(from_unix_millis),
windows: windows.iter().zip(&kept).map(|(window, kept)| shown(window, *kept)).collect(),
};
let next = windows.iter().zip(kept).map(|(window, kept)| (window.name.clone(), kept)).collect();
(next, usage)
}
fn current(held: &Held, window: &Window, now: i64) -> (u64, i64) {
match held.get(&window.name) {
Some(&(used, resets)) if resets > now => (used, resets),
_ => (0, 0),
}
}
fn shown(window: &Window, (used, resets): (u64, i64)) -> WindowUse {
WindowUse {
name: window.name.clone(),
used,
limit: window.limit,
left: window.limit.saturating_sub(used),
resets_at: (resets != 0).then(|| from_unix_millis(resets)),
}
}
fn held(connection: &rusqlite::Connection, id: i64, path: &[u8], now: i64) -> Result<(Held, Option<i64>)> {
let spill = cells::current(connection, id, path, now)?.and_then(|current| current.spill);
let Some(cell) = cells::live(connection, id, path, now)? else {
return Ok((Held::new(), spill));
};
let Raw::Bytes(bytes) = cell.raw else {
return Err(Error::corrupt("a quota's row is not the windows it wrote"));
};
let held =
serde_json::from_slice(&bytes).map_err(|_| Error::corrupt("a quota's row is not the windows it wrote"))?;
Ok((held, spill))
}
fn keep(tx: &Tx<'_>, revision: &Revision, (id, path): (i64, &[u8]), next: &Held, spill: Option<i64>) -> Result<()> {
let row = serde_json::to_vec(next).map_err(|error| Error::internal(format!("a quota's row: {error}")))?;
let expires = next.values().map(|(_, resets)| *resets).max();
let version = next_version(revision, tx)?;
cells::put(tx, id, path, (version, expires), &Raw::Bytes(row), spill)
}
fn check_windows(windows: &[Window]) -> Result<()> {
if windows.is_empty() || windows.len() > MOST_WINDOWS {
return Err(Error::invalid(format!("{} windows, not one to {MOST_WINDOWS}", windows.len())));
}
for (index, window) in windows.iter().enumerate() {
check_window(window)?;
if windows[..index].iter().any(|before| before.name == window.name) {
return Err(Error::invalid(format!("two windows named {:?}", window.name)));
}
}
Ok(())
}
fn check_window(window: &Window) -> Result<()> {
let bytes = window.name.as_bytes();
let named = bytes.first().is_some_and(u8::is_ascii_lowercase)
&& bytes.len() <= 32
&& bytes.iter().all(|&byte| byte.is_ascii_lowercase() || byte.is_ascii_digit() || byte == b'_');
if !named {
return Err(Error::invalid(format!(
"a window's name is a lowercase letter, then up to 31 of them, digits and '_', not {:?}",
window.name
)));
}
if window.limit == 0 || window.span < 1 {
return Err(Error::invalid(format!(
"window {:?} of {} every {} ms, not at least one every millisecond",
window.name, window.limit, window.span
)));
}
Ok(())
}
#[cfg(test)]
#[path = "quota_tests.rs"]
mod tests;