GITv
master
cache.rs231 lines, 8.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
//! 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<String, (Arc<str>, u64)>,
    /// Keys by when they were last used, oldest first.
    by_use: BTreeMap<u64, String>,
    clock: u64,
    bytes: usize,
}

pub(crate) static CACHE: LazyLock<Mutex<Cache>> = 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<Arc<str>> {
        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<str>) {
        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<String>) -> Option<Arc<str>> {
    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<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();
    }
}

/// 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)]
mod tests {
    use super::*;

    fn value(text: &str) -> Arc<str> {
        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.
        let mut cache = Cache::new(40);
        for key in ["k1", "k2", "k3", "k4"] {
            cache.insert(key.into(), value("12345678"));
        }
        assert!(cache.get("k1").is_some(), "k1 is used again, so k2 is now the oldest");
        cache.insert("k5".into(), value("12345678"));
        assert!(cache.get("k2").is_none(), "the least recently used went");
        for key in ["k1", "k3", "k4", "k5"] {
            assert!(cache.get(key).is_some(), "{key} stays");
        }
        assert_eq!(cache.bytes, 40);
    }

    #[test]
    fn replacing_a_key_counts_it_once_and_big_values_are_not_kept() {
        let mut cache = Cache::new(40);
        cache.insert("k1".into(), value("1234"));
        cache.insert("k1".into(), value("12345678"));
        assert_eq!(cache.bytes, 10);
        assert_eq!(cache.entries.len(), cache.by_use.len());
        cache.insert("big".into(), value("12345678901"));
        assert!(cache.get("big").is_none(), "over a quarter of the budget");
        assert_eq!(&*cache.get("k1").unwrap(), "12345678");
    }
}