use aspect_core::{Aspect, AspectError, ProceedingJoinPoint};
use std::any::Any;
use std::time::Duration;
#[derive(Clone)]
pub struct CachingAspect {
max_size: usize,
ttl: Option<Duration>,
}
impl CachingAspect {
pub fn new() -> Self {
Self {
max_size: usize::MAX,
ttl: None,
}
}
pub fn with_max_size(mut self, max_size: usize) -> Self {
self.max_size = max_size;
self
}
pub fn with_ttl(mut self, ttl: Duration) -> Self {
self.ttl = Some(ttl);
self
}
}
impl Default for CachingAspect {
fn default() -> Self {
Self::new()
}
}
impl Aspect for CachingAspect {
fn around(&self, pjp: ProceedingJoinPoint) -> Result<Box<dyn Any>, AspectError> {
println!("[CACHE] Checking cache for {}", pjp.context().function_name);
pjp.proceed()
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_caching_aspect() {
let aspect = CachingAspect::new()
.with_max_size(100)
.with_ttl(Duration::from_secs(60));
assert_eq!(aspect.max_size, 100);
assert_eq!(aspect.ttl, Some(Duration::from_secs(60)));
}
}