use std::time::Duration;
use rskit_errors::AppResult;
use crate::Accumulator;
pub trait Trigger<V>: Send + Sync
where
V: Clone + Send + Sync + 'static,
{
fn should_flush(&self, accumulator: &Accumulator<V>) -> AppResult<bool>;
fn name(&self) -> &'static str;
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct SizeTrigger {
pub threshold: usize,
}
impl SizeTrigger {
#[must_use]
pub fn new(threshold: usize) -> Self {
Self { threshold }
}
}
impl<V> Trigger<V> for SizeTrigger
where
V: Clone + Send + Sync + 'static,
{
fn should_flush(&self, accumulator: &Accumulator<V>) -> AppResult<bool> {
Ok(accumulator.size()? >= self.threshold)
}
fn name(&self) -> &'static str {
"size"
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ByteSizeTrigger {
pub threshold: usize,
}
impl ByteSizeTrigger {
#[must_use]
pub fn new(threshold: usize) -> Self {
Self { threshold }
}
}
impl<V> Trigger<V> for ByteSizeTrigger
where
V: Clone + Send + Sync + 'static,
{
fn should_flush(&self, accumulator: &Accumulator<V>) -> AppResult<bool> {
Ok(accumulator.measure()? >= self.threshold)
}
fn name(&self) -> &'static str {
"byte_size"
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct TimeTrigger {
pub interval: Duration,
}
impl TimeTrigger {
#[must_use]
pub fn new(interval: Duration) -> Self {
Self { interval }
}
}
impl<V> Trigger<V> for TimeTrigger
where
V: Clone + Send + Sync + 'static,
{
fn should_flush(&self, accumulator: &Accumulator<V>) -> AppResult<bool> {
Ok(accumulator.elapsed_since_flush() >= self.interval)
}
fn name(&self) -> &'static str {
"time"
}
}