2023-05-30 03:19:05 +03:00
|
|
|
use log::{log_enabled, trace};
|
2023-05-15 20:48:59 +03:00
|
|
|
use quick_cache::sync::KQCache;
|
|
|
|
use quick_cache::{PlaceholderGuard, Weighter};
|
2023-05-30 01:48:22 +03:00
|
|
|
use std::convert::Infallible;
|
2023-05-30 03:19:05 +03:00
|
|
|
use std::fmt::Debug;
|
2023-05-15 20:48:59 +03:00
|
|
|
use std::future::Future;
|
|
|
|
use std::hash::{BuildHasher, Hash};
|
2023-05-30 01:48:22 +03:00
|
|
|
use std::num::NonZeroU32;
|
2023-05-15 20:48:59 +03:00
|
|
|
use std::sync::Arc;
|
|
|
|
use std::time::Duration;
|
|
|
|
use tokio::task::JoinHandle;
|
|
|
|
use tokio::time::{sleep_until, Instant};
|
|
|
|
|
|
|
|
pub struct KQCacheWithTTL<Key, Qey, Val, We, B> {
|
2023-05-18 23:34:22 +03:00
|
|
|
cache: Arc<KQCache<Key, Qey, Val, We, B>>,
|
2023-05-30 01:48:22 +03:00
|
|
|
max_item_weight: NonZeroU32,
|
2023-05-30 03:19:05 +03:00
|
|
|
name: &'static str,
|
2023-05-15 20:48:59 +03:00
|
|
|
ttl: Duration,
|
2023-05-18 23:34:22 +03:00
|
|
|
tx: flume::Sender<(Instant, Key, Qey)>,
|
2023-05-30 01:48:22 +03:00
|
|
|
weighter: We,
|
|
|
|
|
|
|
|
pub task_handle: JoinHandle<()>,
|
2023-05-15 20:48:59 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
struct KQCacheWithTTLTask<Key, Qey, Val, We, B> {
|
|
|
|
cache: Arc<KQCache<Key, Qey, Val, We, B>>,
|
2023-05-30 03:19:05 +03:00
|
|
|
name: &'static str,
|
2023-05-15 20:48:59 +03:00
|
|
|
rx: flume::Receiver<(Instant, Key, Qey)>,
|
|
|
|
}
|
|
|
|
|
|
|
|
pub struct PlaceholderGuardWithTTL<'a, Key, Qey, Val, We, B> {
|
2023-05-30 03:19:05 +03:00
|
|
|
name: &'a str,
|
2023-05-15 20:48:59 +03:00
|
|
|
inner: PlaceholderGuard<'a, Key, Qey, Val, We, B>,
|
|
|
|
key: Key,
|
|
|
|
qey: Qey,
|
|
|
|
ttl: Duration,
|
|
|
|
tx: &'a flume::Sender<(Instant, Key, Qey)>,
|
|
|
|
}
|
|
|
|
|
|
|
|
impl<
|
2023-05-30 03:19:05 +03:00
|
|
|
Key: Clone + Debug + Eq + Hash + Send + Sync + 'static,
|
|
|
|
Qey: Clone + Debug + Eq + Hash + Send + Sync + 'static,
|
2023-05-15 20:48:59 +03:00
|
|
|
Val: Clone + Send + Sync + 'static,
|
|
|
|
We: Weighter<Key, Qey, Val> + Clone + Send + Sync + 'static,
|
|
|
|
B: BuildHasher + Clone + Send + Sync + 'static,
|
|
|
|
> KQCacheWithTTL<Key, Qey, Val, We, B>
|
|
|
|
{
|
2023-05-30 01:48:22 +03:00
|
|
|
pub async fn new_with_options(
|
2023-05-30 03:19:05 +03:00
|
|
|
name: &'static str,
|
2023-05-15 20:48:59 +03:00
|
|
|
estimated_items_capacity: usize,
|
2023-05-30 01:48:22 +03:00
|
|
|
max_item_weight: NonZeroU32,
|
2023-05-15 20:48:59 +03:00
|
|
|
weight_capacity: u64,
|
|
|
|
weighter: We,
|
|
|
|
hash_builder: B,
|
|
|
|
ttl: Duration,
|
|
|
|
) -> Self {
|
|
|
|
let (tx, rx) = flume::unbounded();
|
|
|
|
|
|
|
|
let cache = KQCache::with(
|
|
|
|
estimated_items_capacity,
|
|
|
|
weight_capacity,
|
2023-05-30 01:48:22 +03:00
|
|
|
weighter.clone(),
|
2023-05-15 20:48:59 +03:00
|
|
|
hash_builder,
|
|
|
|
);
|
|
|
|
|
|
|
|
let cache = Arc::new(cache);
|
|
|
|
|
|
|
|
let task = KQCacheWithTTLTask {
|
|
|
|
cache: cache.clone(),
|
2023-05-30 03:19:05 +03:00
|
|
|
name,
|
2023-05-15 20:48:59 +03:00
|
|
|
rx,
|
|
|
|
};
|
|
|
|
|
|
|
|
let task_handle = tokio::spawn(task.run());
|
|
|
|
|
|
|
|
Self {
|
|
|
|
cache,
|
2023-05-30 01:48:22 +03:00
|
|
|
max_item_weight,
|
2023-05-30 03:19:05 +03:00
|
|
|
name,
|
2023-05-15 20:48:59 +03:00
|
|
|
task_handle,
|
|
|
|
ttl,
|
|
|
|
tx,
|
2023-05-30 01:48:22 +03:00
|
|
|
weighter,
|
2023-05-15 20:48:59 +03:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-05-18 23:34:22 +03:00
|
|
|
#[inline]
|
|
|
|
pub fn get(&self, key: &Key, qey: &Qey) -> Option<Val> {
|
|
|
|
self.cache.get(key, qey)
|
|
|
|
}
|
|
|
|
|
2023-05-15 20:48:59 +03:00
|
|
|
#[inline]
|
2023-05-30 01:48:22 +03:00
|
|
|
pub async fn get_or_insert_async<Fut>(&self, key: &Key, qey: &Qey, f: Fut) -> Val
|
|
|
|
where
|
|
|
|
Fut: Future<Output = Val>,
|
|
|
|
{
|
2023-05-30 03:19:05 +03:00
|
|
|
self.try_get_or_insert_async::<Infallible, _>(key, qey, async move { Ok(f.await) })
|
2023-05-30 01:48:22 +03:00
|
|
|
.await
|
|
|
|
.expect("infallible")
|
|
|
|
}
|
|
|
|
|
|
|
|
#[inline]
|
|
|
|
pub async fn try_get_or_insert_async<E, Fut>(
|
|
|
|
&self,
|
|
|
|
key: &Key,
|
|
|
|
qey: &Qey,
|
|
|
|
f: Fut,
|
|
|
|
) -> Result<Val, E>
|
2023-05-15 20:48:59 +03:00
|
|
|
where
|
|
|
|
Fut: Future<Output = Result<Val, E>>,
|
|
|
|
{
|
2023-05-30 03:19:05 +03:00
|
|
|
self.cache
|
|
|
|
.get_or_insert_async(key, qey, async move {
|
|
|
|
let x = f.await;
|
|
|
|
|
|
|
|
if x.is_ok() {
|
|
|
|
let expire_at = Instant::now() + self.ttl;
|
|
|
|
|
|
|
|
trace!(
|
|
|
|
"{}, {:?}, {:?} expiring in {}s",
|
|
|
|
self.name,
|
|
|
|
&key,
|
|
|
|
&qey,
|
|
|
|
expire_at.duration_since(Instant::now()).as_secs_f32()
|
|
|
|
);
|
|
|
|
|
|
|
|
self.tx.send((expire_at, key.clone(), qey.clone())).unwrap();
|
|
|
|
}
|
|
|
|
|
|
|
|
x
|
|
|
|
})
|
|
|
|
.await
|
2023-05-15 20:48:59 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
#[inline]
|
|
|
|
pub async fn get_value_or_guard_async(
|
|
|
|
&self,
|
|
|
|
key: Key,
|
|
|
|
qey: Qey,
|
|
|
|
) -> Result<Val, PlaceholderGuardWithTTL<'_, Key, Qey, Val, We, B>> {
|
|
|
|
match self.cache.get_value_or_guard_async(&key, &qey).await {
|
|
|
|
Ok(x) => Ok(x),
|
|
|
|
Err(inner) => Err(PlaceholderGuardWithTTL {
|
2023-05-30 03:19:05 +03:00
|
|
|
name: self.name,
|
2023-05-15 20:48:59 +03:00
|
|
|
inner,
|
|
|
|
key,
|
|
|
|
qey,
|
|
|
|
ttl: self.ttl,
|
|
|
|
tx: &self.tx,
|
|
|
|
}),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-05-30 01:48:22 +03:00
|
|
|
#[inline]
|
|
|
|
pub fn hits(&self) -> u64 {
|
|
|
|
self.cache.hits()
|
|
|
|
}
|
|
|
|
|
|
|
|
/// if the item was too large to insert, it is returned with the error
|
2023-05-30 03:19:05 +03:00
|
|
|
/// IMPORTANT! Inserting the same key multiple times does NOT reset the TTL!
|
2023-05-30 01:48:22 +03:00
|
|
|
#[inline]
|
|
|
|
pub fn try_insert(&self, key: Key, qey: Qey, val: Val) -> Result<(), (Key, Qey, Val)> {
|
2023-05-15 20:48:59 +03:00
|
|
|
let expire_at = Instant::now() + self.ttl;
|
|
|
|
|
2023-05-30 01:48:22 +03:00
|
|
|
let weight = self.weighter.weight(&key, &qey, &val);
|
|
|
|
|
|
|
|
if weight <= self.max_item_weight {
|
|
|
|
self.cache.insert(key.clone(), qey.clone(), val);
|
|
|
|
|
2023-05-30 03:19:05 +03:00
|
|
|
trace!(
|
|
|
|
"{}, {:?}, {:?} expiring in {}s",
|
|
|
|
self.name,
|
|
|
|
&key,
|
|
|
|
&qey,
|
|
|
|
expire_at.duration_since(Instant::now()).as_secs_f32()
|
|
|
|
);
|
|
|
|
|
2023-05-30 01:48:22 +03:00
|
|
|
self.tx.send((expire_at, key, qey)).unwrap();
|
|
|
|
|
|
|
|
Ok(())
|
|
|
|
} else {
|
|
|
|
Err((key, qey, val))
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
#[inline]
|
|
|
|
pub fn misses(&self) -> u64 {
|
|
|
|
self.cache.misses()
|
|
|
|
}
|
2023-05-15 20:48:59 +03:00
|
|
|
|
2023-05-30 01:48:22 +03:00
|
|
|
#[inline]
|
|
|
|
pub fn peek(&self, key: &Key, qey: &Qey) -> Option<Val> {
|
|
|
|
self.cache.peek(key, qey)
|
2023-05-15 20:48:59 +03:00
|
|
|
}
|
|
|
|
|
2023-05-30 01:48:22 +03:00
|
|
|
#[inline]
|
2023-05-15 20:48:59 +03:00
|
|
|
pub fn remove(&self, key: &Key, qey: &Qey) -> bool {
|
|
|
|
self.cache.remove(key, qey)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl<
|
2023-05-30 03:19:05 +03:00
|
|
|
Key: Debug + Eq + Hash,
|
|
|
|
Qey: Debug + Eq + Hash,
|
2023-05-15 20:48:59 +03:00
|
|
|
Val: Clone,
|
|
|
|
We: Weighter<Key, Qey, Val> + Clone,
|
|
|
|
B: BuildHasher + Clone,
|
|
|
|
> KQCacheWithTTLTask<Key, Qey, Val, We, B>
|
|
|
|
{
|
|
|
|
async fn run(self) {
|
2023-05-30 03:19:05 +03:00
|
|
|
trace!("watching for expirations on {}", self.name);
|
|
|
|
|
2023-05-15 20:48:59 +03:00
|
|
|
while let Ok((expire_at, key, qey)) = self.rx.recv_async().await {
|
2023-05-30 03:19:05 +03:00
|
|
|
let now = Instant::now();
|
|
|
|
if expire_at > now {
|
|
|
|
if log_enabled!(log::Level::Trace) {
|
|
|
|
trace!(
|
|
|
|
"{}, {:?}, {:?} sleeping for {}ms.",
|
|
|
|
self.name,
|
|
|
|
key,
|
|
|
|
qey,
|
|
|
|
expire_at.duration_since(now).as_millis(),
|
|
|
|
);
|
|
|
|
}
|
|
|
|
|
|
|
|
sleep_until(expire_at).await;
|
|
|
|
|
|
|
|
trace!("{}, {:?}, {:?} done sleeping", self.name, key, qey);
|
|
|
|
} else {
|
|
|
|
trace!("no need to sleep!");
|
|
|
|
}
|
2023-05-15 20:48:59 +03:00
|
|
|
|
2023-05-30 03:19:05 +03:00
|
|
|
if self.cache.remove(&key, &qey) {
|
|
|
|
trace!("removed {}, {:?}, {:?}", self.name, key, qey);
|
|
|
|
} else {
|
|
|
|
trace!("empty {}, {:?}, {:?}", self.name, key, qey);
|
|
|
|
};
|
2023-05-15 20:48:59 +03:00
|
|
|
}
|
2023-05-30 03:19:05 +03:00
|
|
|
|
|
|
|
trace!("watching for expirations on {}", self.name)
|
2023-05-15 20:48:59 +03:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl<
|
|
|
|
'a,
|
2023-05-30 03:19:05 +03:00
|
|
|
Key: Clone + Debug + Hash + Eq,
|
|
|
|
Qey: Clone + Debug + Hash + Eq,
|
2023-05-15 20:48:59 +03:00
|
|
|
Val: Clone,
|
|
|
|
We: Weighter<Key, Qey, Val>,
|
|
|
|
B: BuildHasher,
|
|
|
|
> PlaceholderGuardWithTTL<'a, Key, Qey, Val, We, B>
|
|
|
|
{
|
|
|
|
pub fn insert(self, val: Val) {
|
|
|
|
let expire_at = Instant::now() + self.ttl;
|
|
|
|
|
|
|
|
self.inner.insert(val);
|
|
|
|
|
2023-05-30 03:19:05 +03:00
|
|
|
if log_enabled!(log::Level::Trace) {
|
|
|
|
trace!(
|
|
|
|
"{}, {:?}, {:?} expiring in {}s",
|
|
|
|
self.name,
|
|
|
|
self.key,
|
|
|
|
self.qey,
|
|
|
|
expire_at.duration_since(Instant::now()).as_secs_f32()
|
|
|
|
);
|
|
|
|
}
|
|
|
|
|
2023-05-15 20:48:59 +03:00
|
|
|
self.tx.send((expire_at, self.key, self.qey)).unwrap();
|
|
|
|
}
|
|
|
|
}
|