Skip to content

Commit 3091a02

Browse files
authored
Improve TTL caching and handling (#230)
- increase TTL cache duration to `3h` - update context fetching code to handle cache expired
1 parent 0dbb01e commit 3091a02

File tree

2 files changed

+17
-9
lines changed

2 files changed

+17
-9
lines changed

spotify_player/src/client/handlers.rs

Lines changed: 15 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -141,6 +141,10 @@ pub async fn start_player_event_watchers(
141141
// An event is categorized as "high-frequency" when
142142
// - we want to handle it "immediately" to prevent users from experiencing a noticable delay
143143
let refresh_duration = std::time::Duration::from_millis(200); // frequency = 5Hz
144+
145+
// This timer is used to avoid making multiple `GetContext` requests in a short period of time.
146+
let mut last_request_timer = std::time::Instant::now();
147+
144148
loop {
145149
tokio::time::sleep(refresh_duration).await;
146150

@@ -175,17 +179,21 @@ pub async fn start_player_event_watchers(
175179
*page_state = None;
176180
}
177181
}
182+
}
178183

179-
// request new context's data if not found in memory
180-
if let Some(id) = id {
181-
if !state.data.read().caches.context.contains_key(&id.uri()) {
182-
client_pub
183-
.send(ClientRequest::GetContext(id.clone()))
184-
.unwrap_or_default();
185-
}
184+
// request new context's data if not found in memory
185+
if let Some(id) = id {
186+
if !state.data.read().caches.context.contains_key(&id.uri())
187+
&& last_request_timer.elapsed() >= std::time::Duration::from_secs(1)
188+
{
189+
last_request_timer = std::time::Instant::now();
190+
client_pub
191+
.send(ClientRequest::GetContext(id.clone()))
192+
.unwrap_or_default();
186193
}
187194
}
188195
}
196+
189197
#[cfg(feature = "lyric-finder")]
190198
PageState::Lyric {
191199
track,

spotify_player/src/state/data.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -6,9 +6,9 @@ use super::model::*;
66

77
pub type DataReadGuard<'a> = parking_lot::RwLockReadGuard<'a, AppData>;
88

9-
// cache duration, which is default to be 1h
9+
// cache duration, which is default to be 3h
1010
pub static CACHE_DURATION: Lazy<std::time::Duration> =
11-
Lazy::new(|| std::time::Duration::from_secs(60 * 60));
11+
Lazy::new(|| std::time::Duration::from_secs(60 * 60 * 3));
1212

1313
#[derive(Default)]
1414
/// the application's data

0 commit comments

Comments
 (0)