use core::num::NonZeroU64;
use core::time::Duration;
use crate::{Gate, Refusal};
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct FixedWindowPolicy {
window: Duration,
limit: NonZeroU64,
}
impl FixedWindowPolicy {
#[must_use]
pub const fn new(window: Duration, limit: NonZeroU64) -> Option<Self> {
if window.is_zero() {
return None;
}
Some(Self { window, limit })
}
#[must_use]
pub const fn window(&self) -> Duration {
self.window
}
#[must_use]
pub const fn limit(&self) -> NonZeroU64 {
self.limit
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct FixedWindow {
policy: FixedWindowPolicy,
count: u64,
window_start: Duration,
}
impl FixedWindow {
#[must_use]
pub const fn new(policy: FixedWindowPolicy) -> Self {
Self {
policy,
count: 0,
window_start: Duration::ZERO,
}
}
#[must_use]
pub const fn restored(
policy: FixedWindowPolicy,
count: u64,
window_start: Duration,
) -> Option<Self> {
if count > policy.limit.get() {
return None;
}
Some(Self {
policy,
count,
window_start,
})
}
#[must_use]
pub const fn policy(&self) -> FixedWindowPolicy {
self.policy
}
#[must_use]
pub const fn count(&self) -> u64 {
self.count
}
#[must_use]
pub const fn window_start(&self) -> Duration {
self.window_start
}
const fn window_end(&self) -> Option<Duration> {
self.window_start.checked_add(self.policy.window)
}
fn current(&self, now: Duration) -> (u64, Duration) {
if self.window_end().is_some_and(|end| now >= end) {
(0, now)
} else {
(self.count, self.window_start)
}
}
const fn left(&self, admitted: u64) -> Result<u64, Refusal> {
match self.policy.limit.get().checked_sub(admitted) {
Some(0) | None => Err(Refusal::Throttled),
Some(left) => Ok(left),
}
}
}
impl Gate for FixedWindow {
fn check(&mut self, now: Duration) -> Result<u64, Refusal> {
let (count, window_start) = self.current(now);
let left = self.left(count)?;
self.count = count + 1;
self.window_start = window_start;
Ok(left - 1)
}
fn peek(&self, now: Duration) -> Result<u64, Refusal> {
self.left(self.current(now).0)
}
fn retry_after(&self, now: Duration) -> Duration {
let (count, window_start) = self.current(now);
if self.left(count).is_ok() {
return Duration::ZERO;
}
window_start
.checked_add(self.policy.window)
.map_or(Duration::MAX, |end| end.saturating_sub(now))
}
fn refund(&mut self) {
self.count = self.count.saturating_sub(1);
}
}
#[cfg(test)]
mod tests;