use std::borrow::{Borrow, ToOwned};
use std::boxed::Box;
use std::collections::HashMap;
use std::hash::{BuildHasher, Hash, RandomState};
use std::num::NonZeroUsize;
use std::sync::{Mutex, MutexGuard, PoisonError};
use std::time::Duration;
use std::vec::Vec;
use crate::{Gate, Gcra, GcraPolicy, Refusal};
const DEFAULT_SHARDS: NonZeroUsize = NonZeroUsize::MIN.saturating_add(15);
const DEFAULT_MAX_KEYS_PER_SHARD: NonZeroUsize = NonZeroUsize::MIN.saturating_add(4095);
const DEFAULT_EVICT_AT: usize = 4096;
const SWEEP_BATCH: usize = 8;
#[derive(Debug)]
struct Shard<K> {
tats: HashMap<K, Duration>,
next_sweep: Option<Duration>,
}
impl<K> Shard<K> {
fn sweep_open(&self, now: Duration) -> bool {
self.next_sweep.is_none_or(|deadline| deadline <= now)
}
fn sweep_due(&mut self, now: Duration) {
if self.sweep_open(now) {
self.sweep(now);
}
}
fn reclaimable(&self, now: Duration) -> bool {
self.sweep_open(now) && self.tats.values().any(|tat| *tat <= now)
}
fn sweep(&mut self, now: Duration) {
self.tats.retain(|_, tat| *tat > now);
let mut tats: Vec<Duration> = self.tats.values().copied().collect();
self.next_sweep = (!tats.is_empty()).then(|| {
let batch = (tats.len() / SWEEP_BATCH).max(1);
*tats.select_nth_unstable(batch - 1).1
});
}
}
enum Seen {
Tracked(Duration),
Full(Option<Duration>),
Room,
}
#[derive(Debug)]
pub struct KeyedGcra<K, S = RandomState> {
policy: GcraPolicy,
shards: Box<[Mutex<Shard<K>>]>,
hasher: S,
evict_at: usize,
max_keys_per_shard: NonZeroUsize,
}
impl<K: Hash + Eq> KeyedGcra<K> {
#[must_use]
pub fn new(policy: GcraPolicy) -> Self {
Self::with_hasher(
policy,
DEFAULT_SHARDS,
DEFAULT_MAX_KEYS_PER_SHARD,
RandomState::new(),
)
}
}
impl<K: Hash + Eq, S: BuildHasher> KeyedGcra<K, S> {
#[must_use]
pub fn with_hasher(
policy: GcraPolicy,
shards: NonZeroUsize,
max_keys_per_shard: NonZeroUsize,
hasher: S,
) -> Self {
Self {
policy,
shards: (0..shards.get())
.map(|_| {
Mutex::new(Shard {
tats: HashMap::new(),
next_sweep: None,
})
})
.collect(),
hasher,
evict_at: DEFAULT_EVICT_AT,
max_keys_per_shard,
}
}
#[must_use]
pub const fn evict_at(mut self, evict_at: usize) -> Self {
self.evict_at = evict_at;
self
}
#[must_use]
pub const fn policy(&self) -> GcraPolicy {
self.policy
}
pub fn check<Q>(&self, key: &Q, now: Duration) -> Result<u64, Refusal>
where
K: Borrow<Q>,
Q: Hash + Eq + ToOwned<Owned = K> + ?Sized,
{
self.check_with_retry_after(key, now)
.map_err(|(reason, _)| reason)
}
pub fn check_with_retry_after<Q>(
&self,
key: &Q,
now: Duration,
) -> Result<u64, (Refusal, Duration)>
where
K: Borrow<Q>,
Q: Hash + Eq + ToOwned<Owned = K> + ?Sized,
{
let admit = |gcra: &mut Gcra| {
gcra.check(now)
.map_err(|reason| (reason, gcra.retry_after(now)))
};
let mut shard = self.shard(key);
let left = if let Some(tat) = shard.tats.get_mut(key) {
let mut gcra = Gcra::restored(self.policy, *tat);
let left = admit(&mut gcra)?;
*tat = gcra.tat();
left
} else {
if shard.tats.len() >= self.max_keys_per_shard.get() {
shard.sweep_due(now);
if shard.tats.len() >= self.max_keys_per_shard.get() {
let delay = shard
.next_sweep
.map_or(Duration::ZERO, |at| at.saturating_sub(now));
return Err((Refusal::Full, delay));
}
}
let mut gcra = Gcra::new(self.policy);
let left = admit(&mut gcra)?;
shard.tats.insert(key.to_owned(), gcra.tat());
left
};
if shard.tats.len() >= self.evict_at {
shard.sweep_due(now);
}
drop(shard);
Ok(left)
}
pub fn peek<Q>(&self, key: &Q, now: Duration) -> Result<u64, Refusal>
where
K: Borrow<Q>,
Q: Hash + Eq + ?Sized,
{
match self.seen(key, now) {
Seen::Tracked(tat) => Gcra::restored(self.policy, tat).peek(now),
Seen::Full(_) => Err(Refusal::Full),
Seen::Room => Gcra::new(self.policy).peek(now),
}
}
pub fn retry_after<Q>(&self, key: &Q, now: Duration) -> Duration
where
K: Borrow<Q>,
Q: Hash + Eq + ?Sized,
{
match self.seen(key, now) {
Seen::Tracked(tat) => Gcra::restored(self.policy, tat).retry_after(now),
Seen::Full(next_sweep) => {
next_sweep.map_or(Duration::ZERO, |deadline| deadline.saturating_sub(now))
}
Seen::Room => Gcra::new(self.policy).retry_after(now),
}
}
pub fn refund<Q>(&self, key: &Q, now: Duration)
where
K: Borrow<Q>,
Q: Hash + Eq + ?Sized,
{
let mut shard = self.shard(key);
let Some(tat) = shard.tats.get_mut(key) else {
return;
};
let mut gcra = Gcra::restored(self.policy, *tat);
gcra.refund();
*tat = gcra.tat();
if *tat <= now {
shard.tats.remove(key);
}
}
pub fn evict(&self, now: Duration) -> usize {
self.shards
.iter()
.map(|shard| {
let mut shard = lock(shard);
let before = shard.tats.len();
shard.sweep(now);
before - shard.tats.len()
})
.sum()
}
pub fn len(&self) -> usize {
self.shards.iter().map(|shard| lock(shard).tats.len()).sum()
}
pub fn is_empty(&self) -> bool {
self.shards.iter().all(|shard| lock(shard).tats.is_empty())
}
fn seen<Q>(&self, key: &Q, now: Duration) -> Seen
where
K: Borrow<Q>,
Q: Hash + Eq + ?Sized,
{
let shard = self.shard(key);
let seen = match shard.tats.get(key) {
Some(tat) => Seen::Tracked(*tat),
None if shard.tats.len() >= self.max_keys_per_shard.get()
&& !shard.reclaimable(now) =>
{
Seen::Full(shard.next_sweep)
}
None => Seen::Room,
};
drop(shard);
seen
}
fn shard<Q: Hash + ?Sized>(&self, key: &Q) -> MutexGuard<'_, Shard<K>> {
let count = self.shards.len() as u64;
let index = usize::try_from(self.hasher.hash_one(key) % count).unwrap_or(0);
#[allow(
clippy::indexing_slicing,
reason = "index < count = shards.len(): reduced modulo the length just above"
)]
let shard = &self.shards[index];
lock(shard)
}
}
fn lock<T>(mutex: &Mutex<T>) -> MutexGuard<'_, T> {
mutex.lock().unwrap_or_else(PoisonError::into_inner)
}
#[cfg(test)]
mod tests;