use std::collections::HashMap;
use std::sync::Arc;
use std::sync::Mutex as StdMutex;
use std::sync::atomic::{AtomicU64, Ordering};
use std::time::{Duration, Instant};
use tokio::sync::{Mutex, RwLock};
use super::key::JsonWebKeySet;
struct CacheEntry {
key_set: JsonWebKeySet,
expires_at: Option<Instant>,
last_access: AtomicU64,
}
pub(crate) struct Cache {
entries: RwLock<HashMap<String, CacheEntry>>,
last_refresh: RwLock<HashMap<String, Instant>>,
max_entries: usize,
access_counter: AtomicU64,
in_flight: StdMutex<HashMap<String, Arc<Mutex<()>>>>,
}
impl Cache {
pub(crate) fn new(max_entries: usize) -> Self {
Self {
entries: RwLock::new(HashMap::new()),
last_refresh: RwLock::new(HashMap::new()),
max_entries,
access_counter: AtomicU64::new(0),
in_flight: StdMutex::new(HashMap::new()),
}
}
fn next_tick(&self) -> u64 {
self.access_counter.fetch_add(1, Ordering::Relaxed)
}
pub(crate) async fn get(&self, key: &str) -> Option<JsonWebKeySet> {
let entries = self.entries.read().await;
let entry = entries.get(key)?;
if entry.expires_at.is_none_or(|at| Instant::now() < at) {
entry.last_access.store(self.next_tick(), Ordering::Relaxed);
Some(entry.key_set.clone())
} else {
None
}
}
pub(crate) async fn put(&self, key: String, key_set: JsonWebKeySet, ttl: Duration) {
let expires_at = Instant::now().checked_add(ttl);
let mut entries = self.entries.write().await;
let tick = self.next_tick();
entries.insert(
key,
CacheEntry {
key_set,
expires_at,
last_access: AtomicU64::new(tick),
},
);
let evicted = self.evict_lru(&mut entries);
if !evicted.is_empty() {
let mut last_refresh = self.last_refresh.write().await;
for key in &evicted {
last_refresh.remove(key);
}
}
}
fn evict_lru(&self, entries: &mut HashMap<String, CacheEntry>) -> Vec<String> {
let mut evicted = Vec::new();
if self.max_entries == 0 {
return evicted;
}
while entries.len() > self.max_entries {
let lru_key = entries
.iter()
.min_by_key(|(_, entry)| entry.last_access.load(Ordering::Relaxed))
.map(|(key, _)| key.clone());
match lru_key {
Some(key) => {
entries.remove(&key);
evicted.push(key);
}
None => break,
}
}
evicted
}
pub(crate) async fn invalidate(&self, key: &str) {
self.entries.write().await.remove(key);
}
pub(crate) async fn mark_refresh(&self, key: &str) {
let mut last_refresh = self.last_refresh.write().await;
last_refresh.insert(key.to_string(), Instant::now());
if self.max_entries == 0 {
return;
}
while last_refresh.len() > self.max_entries {
let oldest = last_refresh
.iter()
.min_by_key(|(_, instant)| **instant)
.map(|(key, _)| key.clone());
match oldest {
Some(key) => {
last_refresh.remove(&key);
}
None => break,
}
}
}
pub(crate) async fn refresh_throttled(&self, key: &str, cooldown: Duration) -> bool {
if cooldown.is_zero() {
return false;
}
let last_refresh = self.last_refresh.read().await;
match last_refresh.get(key) {
Some(&last) => last.elapsed() < cooldown,
None => false,
}
}
pub(crate) fn flight_gate(&self, key: &str) -> FlightGuard<'_> {
let gate = {
let mut in_flight = self.in_flight.lock().expect("in-flight gate map poisoned");
in_flight
.entry(key.to_string())
.or_insert_with(|| Arc::new(Mutex::new(())))
.clone()
};
FlightGuard {
cache: self,
key: key.to_string(),
gate,
}
}
pub(crate) fn release_flight(&self, key: &str, gate: &Arc<Mutex<()>>) {
let mut in_flight = self.in_flight.lock().expect("in-flight gate map poisoned");
let is_same = in_flight
.get(key)
.is_some_and(|existing| Arc::ptr_eq(existing, gate));
if is_same {
in_flight.remove(key);
}
}
#[cfg(test)]
pub(crate) async fn entry_count(&self) -> usize {
self.entries.read().await.len()
}
#[cfg(test)]
pub(crate) async fn refresh_record_count(&self) -> usize {
self.last_refresh.read().await.len()
}
#[cfg(test)]
pub(crate) fn flight_gate_count(&self) -> usize {
self.in_flight
.lock()
.expect("in-flight gate map poisoned")
.len()
}
}
pub(crate) struct FlightGuard<'a> {
cache: &'a Cache,
key: String,
gate: Arc<Mutex<()>>,
}
impl FlightGuard<'_> {
pub(crate) fn gate(&self) -> &Arc<Mutex<()>> {
&self.gate
}
}
impl Drop for FlightGuard<'_> {
fn drop(&mut self) {
self.cache.release_flight(&self.key, &self.gate);
}
}
#[cfg(test)]
mod tests {
use super::*;
fn key_set() -> JsonWebKeySet {
JsonWebKeySet { keys: Vec::new() }
}
const TTL: Duration = Duration::from_secs(60);
#[tokio::test]
async fn size_never_exceeds_cap() {
let cache = Cache::new(3);
for i in 0..25 {
cache
.put(format!("https://p/{i}/jwks"), key_set(), TTL)
.await;
assert!(
cache.entry_count().await <= 3,
"size exceeded cap after inserting entry {i}"
);
}
assert_eq!(cache.entry_count().await, 3);
}
#[tokio::test]
async fn evicts_least_recently_used_and_read_refreshes_recency() {
let cache = Cache::new(2);
cache.put("a".to_string(), key_set(), TTL).await;
cache.put("b".to_string(), key_set(), TTL).await;
assert!(cache.get("a").await.is_some());
cache.put("c".to_string(), key_set(), TTL).await;
assert!(cache.get("a").await.is_some(), "recently-read a survives");
assert!(cache.get("c").await.is_some(), "newest c present");
assert!(
cache.get("b").await.is_none(),
"least-recently-used b evicted"
);
assert_eq!(cache.entry_count().await, 2);
}
#[tokio::test]
async fn eviction_prunes_refresh_cooldown_sidecar() {
let cache = Cache::new(2);
cache.put("a".to_string(), key_set(), TTL).await;
cache.mark_refresh("a").await;
cache.put("b".to_string(), key_set(), TTL).await;
cache.mark_refresh("b").await;
assert_eq!(cache.refresh_record_count().await, 2);
assert!(cache.refresh_throttled("a", TTL).await);
cache.put("c".to_string(), key_set(), TTL).await;
assert!(cache.get("a").await.is_none(), "a evicted");
assert_eq!(
cache.refresh_record_count().await,
1,
"sidecar record for evicted a pruned"
);
assert!(
cache.refresh_throttled("b", TTL).await,
"b's cooldown intact"
);
assert!(
!cache.refresh_throttled("a", TTL).await,
"a's cooldown pruned, no longer throttled"
);
}
#[tokio::test]
async fn zero_cap_is_unbounded() {
let cache = Cache::new(0);
for i in 0..100 {
cache.put(format!("uri-{i}"), key_set(), TTL).await;
}
assert_eq!(cache.entry_count().await, 100, "cap 0 evicts nothing");
}
#[tokio::test]
async fn expired_entry_is_not_served() {
let cache = Cache::new(8);
cache
.put("a".to_string(), key_set(), Duration::from_millis(10))
.await;
assert!(cache.get("a").await.is_some(), "fresh before TTL");
tokio::time::sleep(Duration::from_millis(30)).await;
assert!(cache.get("a").await.is_none(), "expired after TTL");
}
#[tokio::test]
async fn max_ttl_never_expires() {
let cache = Cache::new(8);
cache.put("a".to_string(), key_set(), Duration::MAX).await;
assert!(cache.get("a").await.is_some(), "max-ttl entry stays fresh");
}
#[tokio::test]
async fn flight_gate_is_released() {
let cache = Cache::new(8);
let guard = cache.flight_gate("u");
assert_eq!(cache.flight_gate_count(), 1);
let guard2 = cache.flight_gate("u");
assert!(Arc::ptr_eq(guard.gate(), guard2.gate()));
assert_eq!(cache.flight_gate_count(), 1);
drop(guard);
assert_eq!(
cache.flight_gate_count(),
0,
"gate pruned when a holder drops"
);
drop(guard2);
assert_eq!(cache.flight_gate_count(), 0);
}
#[tokio::test]
async fn refresh_sidecar_is_bounded_independently() {
let cache = Cache::new(3);
for i in 0..50 {
cache.mark_refresh(&format!("https://p/{i}/jwks")).await;
assert!(
cache.refresh_record_count().await <= 3,
"cooldown sidecar exceeded cap after marking entry {i}"
);
}
}
}