use crate::{CanaryEvent, Sink};
use std::collections::HashMap;
use std::fmt;
use std::sync::Mutex;
use std::time::{Duration, Instant};
pub struct DeduplicatingSink<S> {
inner: S,
seen: Mutex<HashMap<String, Instant>>,
window: Option<Duration>,
}
impl<S> DeduplicatingSink<S> {
#[must_use]
pub fn inner(&self) -> &S {
&self.inner
}
fn dedup_key(event: &CanaryEvent) -> String {
format!("{}:{}", event.token_id, event.source)
}
}
impl<S: Sink> DeduplicatingSink<S> {
#[must_use]
pub fn new(inner: S) -> Self {
Self {
inner,
seen: Mutex::new(HashMap::new()),
window: None,
}
}
#[must_use]
pub fn with_window(inner: S, window: Duration) -> Self {
Self {
inner,
seen: Mutex::new(HashMap::new()),
window: Some(window),
}
}
}
impl<S: Sink> Sink for DeduplicatingSink<S> {
fn emit(&self, event: &CanaryEvent) {
let key = Self::dedup_key(event);
let now = Instant::now();
let should_emit = {
let mut seen = self.seen.lock().expect("dedup sink mutex poisoned");
match self.window {
None => {
seen.insert(key, now).is_none()
}
Some(window) => {
match seen.get(&key) {
Some(last) if now.duration_since(*last) < window => {
false
}
_ => {
seen.insert(key, now);
true
}
}
}
}
};
if should_emit {
self.inner.emit(event);
}
}
}
impl<S> fmt::Debug for DeduplicatingSink<S> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("DeduplicatingSink")
.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(token_id: &str) -> CanaryEvent {
CanaryEvent {
token_id: token_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 first_event_is_delivered() {
let counter = CountingSink::default();
let count = counter.count.clone();
let sink = DeduplicatingSink::new(counter);
sink.emit(&sample_event("id-1"));
assert_eq!(count.load(Ordering::SeqCst), 1);
}
#[test]
fn duplicate_event_is_suppressed_permanently() {
let counter = CountingSink::default();
let count = counter.count.clone();
let sink = DeduplicatingSink::new(counter);
sink.emit(&sample_event("id-1"));
sink.emit(&sample_event("id-1"));
sink.emit(&sample_event("id-1"));
assert_eq!(count.load(Ordering::SeqCst), 1);
}
#[test]
fn different_tokens_are_not_duplicates() {
let counter = CountingSink::default();
let count = counter.count.clone();
let sink = DeduplicatingSink::new(counter);
sink.emit(&sample_event("id-1"));
sink.emit(&sample_event("id-2"));
assert_eq!(count.load(Ordering::SeqCst), 2);
}
#[test]
fn window_suppresses_within_duration() {
let counter = CountingSink::default();
let count = counter.count.clone();
let sink = DeduplicatingSink::with_window(counter, Duration::from_secs(60));
sink.emit(&sample_event("id-1"));
sink.emit(&sample_event("id-1"));
assert_eq!(count.load(Ordering::SeqCst), 1);
}
#[test]
fn window_allows_redelivery_after_expiry() {
let counter = CountingSink::default();
let count = counter.count.clone();
let sink = DeduplicatingSink::with_window(counter, Duration::from_millis(10));
sink.emit(&sample_event("id-1"));
assert_eq!(count.load(Ordering::SeqCst), 1);
sink.emit(&sample_event("id-1"));
assert_eq!(count.load(Ordering::SeqCst), 1);
std::thread::sleep(Duration::from_millis(20));
sink.emit(&sample_event("id-1"));
assert_eq!(count.load(Ordering::SeqCst), 2);
}
#[test]
fn sink_is_send_and_sync() {
fn assert_send_sync<T: Send + Sync>() {}
assert_send_sync::<DeduplicatingSink<CountingSink>>();
}
}