use fibre_cache::CacheBuilder;
use std::sync::{
atomic::{AtomicUsize, Ordering},
Arc,
};
use std::thread;
use std::time::Duration;
#[test]
fn test_sync_stale_while_revalidate() {
let load_count = Arc::new(AtomicUsize::new(0));
let cache = CacheBuilder::default()
.capacity(10)
.time_to_live(Duration::from_millis(100))
.stale_while_revalidate(Duration::from_millis(500))
.loader({
let load_count = load_count.clone();
move |key: i32| {
let count = load_count.fetch_add(1, Ordering::SeqCst);
(key + (count as i32 * 100), 1)
}
})
.build()
.unwrap();
let value1 = cache.fetch_with(&5);
assert_eq!(*value1, 5);
assert_eq!(load_count.load(Ordering::Relaxed), 1);
thread::sleep(Duration::from_millis(150));
let value2 = cache.fetch_with(&5);
assert_eq!(*value2, 5, "Should return stale value immediately");
thread::sleep(Duration::from_millis(50));
assert_eq!(
load_count.load(Ordering::Relaxed),
2,
"Background refresh should have run"
);
let value3 = cache.fetch_with(&5);
assert_eq!(*value3, 105);
assert_eq!(
load_count.load(Ordering::Relaxed),
2,
"Loader should not be called again"
);
}