//! Rendered HTML and git answers kept in memory, keyed by immutable object ids.
use std::collections::{BTreeMap, HashMap};
use std::sync::{Arc, Condvar, LazyLock, Mutex};
/// Rendered HTML and git answers keyed by immutable object ids, so repeat views skip the
/// expensive work. Keys for anything that contains links include the repository, since the
/// same content in two repositories links differently. When full, the entries used least
/// recently make room, so pages people keep viewing stay cached.
pub(crate) struct Cache {
budget: usize,
/// Each key's value and when it was last used.
entries: HashMap, u64)>,
/// Keys by when they were last used, oldest first.
by_use: BTreeMap,
clock: u64,
bytes: usize,
}
pub(crate) static CACHE: LazyLock> = LazyLock::new(|| Mutex::new(Cache::new(CACHE_BUDGET)));
pub(crate) const CACHE_BUDGET: usize = 32 << 20;
impl Cache {
pub(crate) fn new(budget: usize) -> Cache {
Cache { budget, entries: HashMap::new(), by_use: BTreeMap::new(), clock: 0, bytes: 0 }
}
fn tick(&mut self) -> u64 {
self.clock += 1;
self.clock
}
/// The value for `key`, which now counts as just used.
pub(crate) fn get(&mut self, key: &str) -> Option> {
let now = self.tick();
let (value, used) = self.entries.get_mut(key)?;
let key = self.by_use.remove(used).unwrap_or_else(|| key.to_string());
*used = now;
let value = Arc::clone(value);
self.by_use.insert(now, key);
Some(value)
}
/// Keep `value` under `key`, making room by dropping the least recently used entries.
/// Anything over a quarter of the budget would push out much of everything else, so it
/// isn't kept.
pub(crate) fn insert(&mut self, key: String, value: Arc) {
let size = key.len() + value.len();
if size > self.budget / 4 {
return;
}
// Two requests can render the same key at once; the second replaces the first.
self.remove(&key);
while self.bytes + size > self.budget {
let Some((_, oldest)) = self.by_use.pop_first() else { break };
if let Some((old, _)) = self.entries.remove(&oldest) {
self.bytes -= oldest.len() + old.len();
}
}
let now = self.tick();
self.by_use.insert(now, key.clone());
self.entries.insert(key, (value, now));
self.bytes += size;
}
fn remove(&mut self, key: &str) {
if let Some((old, used)) = self.entries.remove(key) {
self.by_use.remove(&used);
self.bytes -= key.len() + old.len();
}
}
}
/// The cached value for `key`, or `make`'s. A failure (`None`) is never cached, so a git
/// command that timed out is retried next time instead of leaving a blank forever.
///
/// Only one request makes a missing value at a time: others asking for the same key meanwhile
/// wait for its answer (failure included) instead of running the same git work alongside it.
/// They wait at most [`gitv_core::GIT_TIMEOUT`], the longest the first can take.
pub(crate) fn cached(key: String, make: impl FnOnce() -> Option) -> Option> {
if let Some(hit) = lock(&CACHE).get(&key) {
return Some(hit);
}
let flight = {
let mut pending = lock(&PENDING);
match pending.get(&key) {
Some(flight) => Err(Arc::clone(flight)),
None => {
let flight = Arc::new(Flight::default());
pending.insert(key.clone(), Arc::clone(&flight));
Ok(flight)
}
}
};
let mut landing = match flight {
Err(flight) => return flight.wait(),
Ok(flight) => Landing { key, flight, value: None },
};
// Another request may have made it between the first look and joining the pending list.
// (Bound first, so the cache's lock is released before any git work starts.)
let made_meanwhile = lock(&CACHE).get(&landing.key);
landing.value = made_meanwhile.or_else(|| {
let value: Arc = make()?.into();
lock(&CACHE).insert(landing.key.clone(), Arc::clone(&value));
Some(value)
});
landing.value.clone()
}
/// Keys being made now, and how their waiters hear the answer.
static PENDING: LazyLock>>> = LazyLock::new(Mutex::default);
/// One value being made: `None` until it is done, then its answer.
#[derive(Default)]
struct Flight {
answer: Mutex