use crate::Result;
use crate::cache::models::CacheEntry;
use crate::cache::utils::log_hit;
use chrono::Utc;
use std::time::Duration;
pub trait Cache {
fn get_all_urls(&self) -> Vec<String>;
fn get_all(&self, url: &str) -> Vec<&CacheEntry>;
fn get(&self, url: &str) -> Option<&CacheEntry> {
self.get_all(url)
.into_iter()
.max_by(|a, b| a.created.cmp(&b.created))
.inspect(|entry| log_hit(url, entry))
}
fn get_younger_than(
&self,
url: &str,
max_age: Duration,
) -> Option<&CacheEntry> {
let now = Utc::now();
let min_created = now - max_age;
self.get_all(url)
.into_iter()
.filter(|entry| entry.created >= min_created)
.max_by(|a, b| a.created.cmp(&b.created))
.inspect(|entry| log_hit(url, entry))
}
fn insert(&mut self, url: String, text: String);
fn save(&self) -> Result<()>;
fn size_bytes(&self) -> Result<u64>;
fn remove(&mut self, url: &str) -> Vec<CacheEntry>;
fn prune(&mut self, keep: &Vec<String>) -> Vec<String> {
let remove: Vec<String> = self
.get_all_urls()
.iter()
.filter(|url| !keep.contains(url))
.map(|s| s.to_string())
.collect();
for url in remove.iter() {
self.remove(url);
}
remove
}
fn clear(&mut self);
}