use std::time::Duration;
use wordval::prelude::*;
use wordval_cache::{LocalCache, SharedCache};
#[wordval::cache_evict(key = "product:{id}", delay_ms = 100)]
async fn update_product(id: u64) -> ResResult<()> {
Ok(Res::ok(()))
}
#[wordval::cache_evict(key = "product0:{id}", delay_ms = 0)]
async fn update_product_no_delay(id: u64) -> ResResult<()> {
Ok(Res::ok(()))
}
#[wordval::cache_evict(key = "product_def:{id}")]
async fn update_product_default(id: u64) -> ResResult<()> {
Ok(Res::ok(()))
}
#[wordval::cache_evict_pattern(pattern = "dict:{id}:*", delay_ms = 100)]
async fn refresh_dict(id: u64) -> ResResult<()> {
Ok(Res::ok(()))
}
fn init_cache() -> &'static SharedCache {
wordval::set_cache(SharedCache::Local(LocalCache::new(100, 0))).ok();
wordval::cache()
}
#[tokio::test]
async fn double_delete_cleans_refill_window() {
let c = init_cache();
c.set("product:1", &"old").await.unwrap();
update_product(1).await.unwrap();
assert!(!c.exists("product:1").await.unwrap());
c.set("product:1", &"stale").await.unwrap();
assert!(c.exists("product:1").await.unwrap());
tokio::time::sleep(Duration::from_millis(400)).await;
assert!(!c.exists("product:1").await.unwrap());
}
#[tokio::test]
async fn zero_delay_disables_second_delete() {
let c = init_cache();
c.set("product0:1", &"old").await.unwrap();
update_product_no_delay(1).await.unwrap();
assert!(!c.exists("product0:1").await.unwrap());
c.set("product0:1", &"stale").await.unwrap();
tokio::time::sleep(Duration::from_millis(400)).await;
assert!(c.exists("product0:1").await.unwrap());
}
#[tokio::test]
async fn default_delay_enables_double_delete() {
let c = init_cache();
c.set("product_def:1", &"old").await.unwrap();
update_product_default(1).await.unwrap();
assert!(!c.exists("product_def:1").await.unwrap());
c.set("product_def:1", &"stale").await.unwrap();
tokio::time::sleep(Duration::from_millis(1000)).await;
assert!(!c.exists("product_def:1").await.unwrap());
}
#[tokio::test]
async fn pattern_evict_double_delete() {
let c = init_cache();
c.set("dict:1:en", &"v1").await.unwrap();
c.set("dict:1:zh", &"v2").await.unwrap();
refresh_dict(1).await.unwrap();
assert!(!c.exists("dict:1:en").await.unwrap());
c.set("dict:1:en", &"stale").await.unwrap();
tokio::time::sleep(Duration::from_millis(400)).await;
assert!(!c.exists("dict:1:en").await.unwrap());
assert!(!c.exists("dict:1:zh").await.unwrap());
}