use crate::{CanaryEvent, Sink};
use std::collections::VecDeque;
use std::fmt;
use std::sync::Mutex;
use std::time::{Duration, Instant};
pub struct RateLimitedSink<S> {
inner: S,
max_events: usize,
window: Duration,
timestamps: Mutex<VecDeque<Instant>>,
}
impl<S> RateLimitedSink<S> {
#[must_use]
pub fn inner(&self) -> &S {
&self.inner
}
#[must_use]
pub fn max_events(&self) -> usize {
self.max_events
}
#[must_use]
pub fn window(&self) -> Duration {
self.window
}
}
impl<S: Sink> RateLimitedSink<S> {
#[must_use]
pub fn new(inner: S, max_events: usize, window: Duration) -> Self {
Self {
inner,
max_events,
window,
timestamps: Mutex::new(VecDeque::new()),
}
}
#[must_use]
pub fn per_second(inner: S, max_events: usize) -> Self {
Self::new(inner, max_events, Duration::from_secs(1))
}
#[must_use]
pub fn per_minute(inner: S, max_events: usize) -> Self {
Self::new(inner, max_events, Duration::from_secs(60))
}
}
impl<S: Sink> Sink for RateLimitedSink<S> {
fn emit(&self, event: &CanaryEvent) {
let now = Instant::now();
let should_emit = {
let mut timestamps = self.timestamps.lock().expect("rate limit mutex poisoned");
while let Some(front) = timestamps.front() {
if now.duration_since(*front) >= self.window {
timestamps.pop_front();
} else {
break;
}
}
if timestamps.len() < self.max_events {
timestamps.push_back(now);
true
} else {
false
}
};
if should_emit {
self.inner.emit(event);
}
}
}
impl<S> fmt::Debug for RateLimitedSink<S> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("RateLimitedSink")
.field("max_events", &self.max_events)
.field("window", &self.window)
.finish_non_exhaustive()
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::{CanaryKind, TriggerSource};
use std::sync::Arc;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::time::SystemTime;
#[derive(Debug, Clone, Default)]
struct CountingSink {
count: Arc<AtomicUsize>,
}
impl Sink for CountingSink {
fn emit(&self, _event: &CanaryEvent) {
self.count.fetch_add(1, Ordering::SeqCst);
}
}
fn sample_event() -> CanaryEvent {
CanaryEvent {
token_id: "test-id".to_owned(),
token_name: "test".to_owned(),
kind: CanaryKind::Password,
source: TriggerSource::Reveal,
triggered_at: SystemTime::now(),
correlation_id: None,
thread_id: None,
}
}
#[test]
fn events_within_limit_are_delivered() {
let counter = CountingSink::default();
let count = counter.count.clone();
let sink = RateLimitedSink::per_second(counter, 5);
for _ in 0..5 {
sink.emit(&sample_event());
}
assert_eq!(count.load(Ordering::SeqCst), 5);
}
#[test]
fn events_exceeding_limit_are_suppressed() {
let counter = CountingSink::default();
let count = counter.count.clone();
let sink = RateLimitedSink::per_second(counter, 3);
for _ in 0..10 {
sink.emit(&sample_event());
}
assert_eq!(count.load(Ordering::SeqCst), 3);
}
#[test]
fn zero_max_events_suppresses_all() {
let counter = CountingSink::default();
let count = counter.count.clone();
let sink = RateLimitedSink::per_second(counter, 0);
sink.emit(&sample_event());
sink.emit(&sample_event());
assert_eq!(count.load(Ordering::SeqCst), 0);
}
#[test]
fn events_allowed_after_window_expires() {
let counter = CountingSink::default();
let count = counter.count.clone();
let sink = RateLimitedSink::new(counter, 2, Duration::from_millis(10));
sink.emit(&sample_event());
sink.emit(&sample_event());
assert_eq!(count.load(Ordering::SeqCst), 2);
sink.emit(&sample_event());
assert_eq!(count.load(Ordering::SeqCst), 2);
std::thread::sleep(Duration::from_millis(20));
sink.emit(&sample_event());
assert_eq!(count.load(Ordering::SeqCst), 3);
}
#[test]
fn accessors_return_configured_values() {
let sink = RateLimitedSink::new(CountingSink::default(), 10, Duration::from_secs(30));
assert_eq!(sink.max_events(), 10);
assert_eq!(sink.window(), Duration::from_secs(30));
}
#[test]
fn sink_is_send_and_sync() {
fn assert_send_sync<T: Send + Sync>() {}
assert_send_sync::<RateLimitedSink<CountingSink>>();
}
}