use crate::Reduction;
use chrono::{TimeDelta, Utc};
use std::fmt::Debug;
pub trait CachingPolicy<A>: Debug + Send + Sync + 'static {
fn should_cache(&self, reduction: &Reduction<A>) -> bool;
}
#[derive(Debug, Default)]
pub struct LogLengthPolicy {
min_length: u32,
max_length: u32,
}
impl LogLengthPolicy {
pub fn at_least(min_length: u32) -> Self {
Self {
min_length,
max_length: u32::MAX,
}
}
pub fn until(max_length: u32) -> Self {
Self {
min_length: 0,
max_length,
}
}
pub fn between(min_length: u32, max_length: u32) -> Self {
Self {
min_length,
max_length,
}
}
}
impl<A> CachingPolicy<A> for LogLengthPolicy {
fn should_cache(&self, reduction: &Reduction<A>) -> bool {
let length = reduction.through_index() + 1;
length >= self.min_length && length <= self.max_length
}
}
#[derive(Debug, Default)]
pub struct LogAgePolicy {
min_age: TimeDelta,
max_age: TimeDelta,
}
impl LogAgePolicy {
pub fn starting_at(min_age: TimeDelta) -> Self {
Self {
min_age,
max_age: TimeDelta::MAX,
}
}
pub fn until(max_age: TimeDelta) -> Self {
Self {
min_age: TimeDelta::MIN,
max_age,
}
}
pub fn between(min_age: TimeDelta, max_age: TimeDelta) -> Self {
Self { min_age, max_age }
}
}
impl<A> CachingPolicy<A> for LogAgePolicy {
fn should_cache(&self, reduction: &Reduction<A>) -> bool {
let age = Utc::now() - reduction.log_id().created_at();
age >= self.min_age && age <= self.max_age
}
}
#[derive(Debug, Default)]
pub struct NoPolicy;
impl<A> CachingPolicy<A> for NoPolicy {
fn should_cache(&self, _reduction: &Reduction<A>) -> bool {
true
}
}