use std::collections::VecDeque;
use std::future::Future;
use std::sync::{Arc, Mutex};
use super::Row;
pub const MAX_ENTRIES: usize = 100;
pub(crate) type Rows = Arc<[Row]>;
#[derive(Default)]
struct Cache {
entries: VecDeque<(String, Rows)>,
}
tokio::task_local! {
static CACHE: Arc<Mutex<Cache>>;
static UNCACHED: bool;
}
fn with_cache<T>(f: impl FnOnce(&mut Cache) -> T) -> Option<T> {
CACHE
.try_with(|cache| f(&mut cache.lock().unwrap_or_else(|e| e.into_inner())))
.ok()
}
fn enabled() -> bool {
!UNCACHED.try_with(|off| *off).unwrap_or(false)
}
pub(crate) async fn scope<F: Future>(fut: F) -> F::Output {
CACHE.scope(Arc::default(), fut).await
}
pub async fn uncached<F: Future>(fut: F) -> F::Output {
UNCACHED.scope(true, fut).await
}
pub(crate) fn get(key: &str) -> Option<Rows> {
if !enabled() {
return None;
}
with_cache(|cache| {
let at = cache.entries.iter().position(|(k, _)| k == key)?;
let entry = cache.entries.remove(at)?;
let rows = entry.1.clone();
cache.entries.push_back(entry);
Some(rows)
})
.flatten()
}
pub(crate) fn put(key: String, rows: Rows) {
if !enabled() {
return;
}
with_cache(|cache| {
cache.entries.retain(|(k, _)| *k != key);
if cache.entries.len() == MAX_ENTRIES {
cache.entries.pop_front();
}
cache.entries.push_back((key, rows));
});
}
pub(crate) fn active() -> bool {
enabled() && CACHE.try_with(|_| ()).is_ok()
}
pub(crate) fn clear() {
with_cache(|cache| cache.entries.clear());
}
#[cfg(test)]
fn len() -> usize {
with_cache(|cache| cache.entries.len()).unwrap_or(0)
}
#[cfg(test)]
mod tests {
use super::*;
fn rows() -> Rows {
Arc::from(Vec::new())
}
#[tokio::test]
async fn keeps_reads_in_a_request_only() {
put("a".into(), rows());
assert!(get("a").is_none(), "outside a request");
scope(async {
put("a".into(), rows());
assert!(get("a").is_some());
clear();
assert!(get("a").is_none());
})
.await;
}
#[tokio::test]
async fn uncached_work_neither_reads_nor_keeps() {
scope(async {
put("a".into(), rows());
uncached(async {
assert!(!active());
assert!(get("a").is_none());
put("b".into(), rows());
clear();
})
.await;
assert!(get("b").is_none());
assert!(get("a").is_none(), "a write inside still empties it");
})
.await;
}
#[tokio::test]
async fn drops_the_least_recently_used_beyond_the_limit() {
scope(async {
for i in 0..MAX_ENTRIES {
put(i.to_string(), rows());
}
assert!(get("0").is_some(), "0 is now the most recent");
put("new".into(), rows());
assert_eq!(len(), MAX_ENTRIES);
assert!(get("1").is_none(), "the oldest went");
assert!(get("0").is_some());
assert!(get("new").is_some());
})
.await;
}
}