Get cache updates time.

This commit is contained in:
Jeff Baskin 2022-12-24 10:28:49 -05:00
parent 56005a5e47
commit fe29841ffe

View File

@ -139,13 +139,17 @@ impl MoreThanText {
}
async fn get_entry(&self, id: &str) -> Result<CacheEntry, DBError> {
let cache = self.cache.lock().await;
match cache.get(id) {
Some(id) => Ok(id.clone()),
let mut cache = self.cache.lock().await;
match cache.get_mut(id) {
Some(entry) => {
entry.touch();
Ok(entry.clone())
}
None => match read(Path::new(&self.dir).join(&id)).await {
Ok(content) => {
let data = CacheType::from_bytes(content);
Ok(CacheEntry::new(data))
let data = CacheEntry::new(CacheType::from_bytes(content));
cache.insert(id.to_string(), data.clone());
Ok(data)
}
Err(_) => Err(DBError::new("cache entry not found")),
},
@ -272,6 +276,28 @@ mod cache {
assert_eq!(content, expected.to_bytes());
}
#[async_std::test]
async fn get_entry_uodates_time() {
let mtt = MTT::new().await;
let id = "something";
let holder = CacheEntry {
data: CacheType::Raw("old".to_string()),
last_used: Instant::now() - Duration::from_secs(200),
};
let mut cache = mtt.db.cache.lock().await;
cache.insert(id.to_string(), holder);
drop(cache);
mtt.db.get_entry(&id).await.unwrap();
let cache = mtt.db.cache.lock().await;
let entry = cache.get(id).unwrap();
let held = entry.elapsed();
assert!(
Duration::from_secs(1) > held,
"Duration was {:?}, should have been close to 0s.",
held
);
}
#[async_std::test]
async fn retrieve_from_disk() {
let mtt = MTT::new().await;
@ -282,6 +308,9 @@ mod cache {
.unwrap();
let output = mtt.db.get_entry(id).await.unwrap();
assert_eq!(output.to_string(), data.to_string());
let cache = mtt.db.cache.lock().await;
let stored = cache.get(id);
assert!(stored.is_some(), "Did not store entry in the cache.");
}
#[async_std::test]
@ -312,16 +341,28 @@ mod cache {
#[async_std::test]
async fn update_cache_entry() {
let mtt = MTT::new().await;
let id = mtt
.db
.add_entry(CacheType::Raw("same".to_string()))
.await
.unwrap();
let id = "updateable";
let holder = CacheEntry {
data: CacheType::Raw("elder".to_string()),
last_used: Instant::now() - Duration::from_secs(500),
};
let mut cache = mtt.db.cache.lock().await;
cache.insert(id.to_string(), holder);
drop(cache);
let expected = "different";
let expect = CacheType::Raw(expected.to_string());
mtt.db.update_entry(&id, expect.clone()).await.unwrap();
let output = mtt.db.get_entry(&id).await.unwrap();
mtt.db.update_entry(id, expect.clone()).await.unwrap();
let output = mtt.db.get_entry(id).await.unwrap();
assert_eq!(output.to_string(), expected);
let cache = mtt.db.cache.lock().await;
let entry = cache.get(id).unwrap();
let held = entry.elapsed();
assert!(
Duration::from_secs(1) > held,
"Duration was {:?}, should have been close to 0s.",
held
);
drop(cache);
let content = read(mtt.dir.path().join(DATA).join(id)).await.unwrap();
assert_eq!(content, expect.to_bytes());
}