Skip to content

Commit

Permalink
Fix cache strategy related logics
Browse files Browse the repository at this point in the history
  • Loading branch information
marshallku committed Jan 21, 2024
1 parent 39a234f commit 48078df
Showing 1 changed file with 18 additions and 21 deletions.
39 changes: 18 additions & 21 deletions src/cache.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,12 @@ where
F: Fn() -> R + Send + Sync + 'static,
R: std::future::Future<Output = Result<MealData, Error>> + Send,
{
if state.fetch_in_progress.load(Ordering::SeqCst) {
let should_fetch_data =
state
.fetch_in_progress
.compare_exchange(false, true, Ordering::SeqCst, Ordering::SeqCst);

if !should_fetch_data.is_ok() {
let cached_data = state.cache.lock().unwrap();
return Ok(cached_data.clone());
}
Expand All @@ -24,27 +29,19 @@ where

drop(cache);

// Only spawn a new fetch if one isn't already in progress
let fetch_in_progress =
state
.fetch_in_progress
.compare_exchange(false, true, Ordering::SeqCst, Ordering::SeqCst);

if fetch_in_progress.is_ok() {
spawn(async move {
state.fetch_in_progress.store(true, Ordering::SeqCst);
match fetch_fn().await {
Ok(new_data) => {
let mut cache = state.cache.lock().unwrap();
*cache = new_data;
}
Err(e) => {
error!("Error fetching data: {:?}", e);
}
spawn(async move {
state.fetch_in_progress.store(true, Ordering::SeqCst);
match fetch_fn().await {
Ok(new_data) => {
let mut cache = state.cache.lock().unwrap();
*cache = new_data;
}
state.fetch_in_progress.store(false, Ordering::SeqCst);
});
}
Err(e) => {
error!("Error fetching data: {:?}", e);
}
}
state.fetch_in_progress.store(false, Ordering::SeqCst);
});

Ok(cached_data)
}
Expand Down

0 comments on commit 48078df

Please sign in to comment.