Make each missing cached value once, however many ask at once
Browse filesSimultaneous first requests for the same value (a commit's diff, a branch's commit count) each ran the same git work. Now the first makes it and the rest wait for its answer, failure included, for at most the git timeout. A maker that panics still answers its waiters, and a failure still isn't cached. A poisoned cache lock no longer silently turns the cache off. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- Author
- Um9i vulgarmessiah@gmail.com
- Date
- 22 Nov 2026, 22:12
- Commit
- 0f4caaa32882
- Parent
- 4f9e91e
1 file changed +115−6
| @@ -1,7 +1,7 @@ | ||
| //! Rendered HTML and git answers kept in memory, keyed by immutable object ids. | ||
| use std::collections::{BTreeMap, HashMap}; | ||
| use std::sync::{Arc, LazyLock, Mutex}; | ||
| 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 | ||
| @@ -73,15 +73,81 @@ impl Cache { | ||
| /// 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<String>) -> Option<Arc<str>> { | ||
| if let Some(hit) = CACHE.lock().ok().and_then(|mut c| c.get(&key)) { | ||
| if let Some(hit) = lock(&CACHE).get(&key) { | ||
| return Some(hit); | ||
| } | ||
| let value: Arc<str> = make()?.into(); | ||
| if let Ok(mut cache) = CACHE.lock() { | ||
| cache.insert(key, Arc::clone(&value)); | ||
| 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<str> = 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<Mutex<HashMap<String, Arc<Flight>>>> = LazyLock::new(Mutex::default); | ||
| /// One value being made: `None` until it is done, then its answer. | ||
| #[derive(Default)] | ||
| struct Flight { | ||
| answer: Mutex<Option<Option<Arc<str>>>>, | ||
| done: Condvar, | ||
| } | ||
| impl Flight { | ||
| fn wait(&self) -> Option<Arc<str>> { | ||
| let answer = lock(&self.answer); | ||
| let (answer, _) = self | ||
| .done | ||
| .wait_timeout_while(answer, gitv_core::GIT_TIMEOUT, |a| a.is_none()) | ||
| .unwrap_or_else(|e| e.into_inner()); | ||
| answer.clone().flatten() | ||
| } | ||
| } | ||
| /// The request making a value. Dropping it, whether the value was made or `make` panicked, | ||
| /// answers every waiter and clears the key from [`PENDING`], so nobody waits forever. | ||
| struct Landing { | ||
| key: String, | ||
| flight: Arc<Flight>, | ||
| value: Option<Arc<str>>, | ||
| } | ||
| impl Drop for Landing { | ||
| fn drop(&mut self) { | ||
| lock(&PENDING).remove(&self.key); | ||
| *lock(&self.flight.answer) = Some(self.value.take()); | ||
| self.flight.done.notify_all(); | ||
| } | ||
| Some(value) | ||
| } | ||
| /// A lock that a panic elsewhere doesn't disable: the cache holds no invariant a panic | ||
| /// could break half way, so carrying on is safe. | ||
| fn lock<T>(mutex: &Mutex<T>) -> std::sync::MutexGuard<'_, T> { | ||
| mutex.lock().unwrap_or_else(|e| e.into_inner()) | ||
| } | ||
| #[cfg(test)] | ||
| @@ -92,6 +158,49 @@ mod tests { | ||
| text.into() | ||
| } | ||
| #[test] | ||
| fn requests_for_one_missing_value_make_it_once() { | ||
| use std::sync::atomic::{AtomicUsize, Ordering}; | ||
| static MADE: AtomicUsize = AtomicUsize::new(0); | ||
| let key = format!("test-single-flight:{}", std::process::id()); | ||
| let threads: Vec<_> = (0..8) | ||
| .map(|_| { | ||
| let key = key.clone(); | ||
| std::thread::spawn(move || { | ||
| cached(key, || { | ||
| MADE.fetch_add(1, Ordering::SeqCst); | ||
| std::thread::sleep(std::time::Duration::from_millis(200)); | ||
| Some("made".into()) | ||
| }) | ||
| }) | ||
| }) | ||
| .collect(); | ||
| for thread in threads { | ||
| assert_eq!(thread.join().unwrap().as_deref(), Some("made")); | ||
| } | ||
| assert_eq!(MADE.load(Ordering::SeqCst), 1, "the value was made more than once"); | ||
| } | ||
| #[test] | ||
| fn a_maker_that_panics_leaves_nobody_waiting() { | ||
| let key = format!("test-panic:{}", std::process::id()); | ||
| let maker = { | ||
| let key = key.clone(); | ||
| std::thread::spawn(move || { | ||
| cached(key, || { | ||
| std::thread::sleep(std::time::Duration::from_millis(200)); | ||
| panic!("render failed") | ||
| }) | ||
| }) | ||
| }; | ||
| std::thread::sleep(std::time::Duration::from_millis(50)); | ||
| let started = std::time::Instant::now(); | ||
| assert_eq!(cached(key.clone(), || Some("unused".into())), None, "the waiter hears the failure"); | ||
| assert!(started.elapsed() < std::time::Duration::from_secs(5), "the waiter wasn't released"); | ||
| assert!(maker.join().is_err()); | ||
| assert_eq!(cached(key, || Some("retried".into())).as_deref(), Some("retried"), "a failure isn't cached"); | ||
| } | ||
| #[test] | ||
| fn the_least_recently_used_entries_make_room() { | ||
| // Room for four entries of 2 bytes of key and 8 of value. | ||