OXYGENHUB
# f7bcee49bf24 oxygenhub / crates / hub / src / repos / cache.rs
15.2 KiB · Rust · last changed Keep bookmark briefs across restarts, and log slow requests 24 days ago source blame history raw
9ff27da5 Andy McCall ↶ 1
//! Loaded states cached by their heads (hub spec §16.3). A state is a pure
2
//! function of its heads, so entries never go stale; the cache is only
3
//! bounded. Shared across threads because `oxy_core::state::State` is
4
//! `Send + Sync`.
5
6
use oxy_core::hash::ChangeHash;
7
use oxy_core::repo::Repo;
8
use oxy_core::state::{Snapshot, State};
9
use std::collections::HashMap;
39442b00 Andy McCall ↶ 10
use std::path::{Path, PathBuf};
9ff27da5 Andy McCall ↶ 11
use std::sync::{Arc, Mutex};
12
13
/// A state and its materialised snapshot.
14
pub struct Loaded {
15
    pub heads: Vec<ChangeHash>,
16
    pub state: State,
17
    pub snapshot: Snapshot,
18
}
19
20
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
21
struct Key {
22
    repo: [u8; 16],
23
    heads: Vec<ChangeHash>,
24
}
25
26
struct Entry {
27
    loaded: Arc<Loaded>,
28
    last_used: u64,
736ae87e Andy McCall ↶ 29
    /// Its estimated size in bytes (`weight`).
30
    weight: usize,
9ff27da5 Andy McCall ↶ 31
}
32
736ae87e Andy McCall ↶ 33
/// A loaded state's estimated size: its rendered text three times over (the
34
/// text, and the line graphs it was rendered from), plus a kilobyte per
35
/// change. Rough, but proportional: a repository of large files weighs
36
/// more than one of small ones.
37
fn weight(l: &Loaded) -> usize {
38
    let text: usize = l
39
        .snapshot
40
        .files
41
        .values()
42
        .map(|f| match &f.content {
43
            oxy_core::state::FileContent::Text { bytes, .. } => bytes.len(),
44
            _ => 64,
45
        })
46
        .sum();
47
    text.saturating_mul(3).saturating_add(l.state.len().saturating_mul(1024))
48
}
49
50
/// What the state cache may hold, in bytes: OXYHUB_STATE_CACHE_MB, else
51
/// 3 GiB. A count alone let a few large repositories' states grow the hub
52
/// to 17 GB.
53
fn budget() -> usize {
54
    std::env::var("OXYHUB_STATE_CACHE_MB").ok().and_then(|v| v.parse::<usize>().ok()).unwrap_or(3 * 1024).saturating_mul(1 << 20)
55
}
56
2e640ffa Andy McCall ↶ 57
/// What the bookmark lists and a change's "in bookmarks" need of a state:
58
/// small, so many are kept, and computed without filling the state cache.
59
/// A repository with more bookmarks than the state cache holds otherwise
60
/// cycled through it on every such page, so nothing stayed cached
61
/// (metalgear's 128 bookmarks: 7.7 s per change page, and every page of
62
/// every repository slower after it).
63
pub struct Summary {
64
    pub changes: std::collections::HashSet<ChangeHash>,
65
    pub latest_ms: u64,
66
    pub conflicted: bool,
67
}
68
39442b00 Andy McCall ↶ 69
impl Summary {
70
    pub fn brief(&self) -> Brief {
71
        Brief { changes: self.changes.len(), latest_ms: self.latest_ms, conflicted: self.conflicted }
72
    }
73
}
74
75
/// What a bookmark list and the overview show of a state (#145): how many
76
/// changes, the latest, and whether it is conflicted. A pure function of
77
/// the heads, so it is kept on disk as well and a restart costs nothing:
78
/// metalgear's 162 bookmarks took ~31 s to summarise again after one.
79
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
80
pub struct Brief {
81
    pub changes: usize,
82
    pub latest_ms: u64,
83
    pub conflicted: bool,
84
}
85
2e640ffa Andy McCall ↶ 86
/// Summaries kept; each is the state's change set, a few hundred kilobytes
87
/// for a long history.
88
const SUMMARIES: usize = 2048;
39442b00 Andy McCall ↶ 89
/// Most summaries computed at once when a page needs many.
90
const PARALLEL: usize = 4;
2e640ffa Andy McCall ↶ 91
92
/// Summaries by heads, each with when it was last used, and the clock.
93
type Summaries = (HashMap<Key, (Arc<Summary>, u64)>, u64);
94
9ff27da5 Andy McCall ↶ 95
/// A bounded least-recently-used cache of loaded states.
96
pub struct StateCache {
97
    capacity: usize,
736ae87e Andy McCall ↶ 98
    /// Bytes of estimated state it may hold (`budget`).
99
    budget: usize,
9ff27da5 Andy McCall ↶ 100
    inner: Mutex<(HashMap<Key, Entry>, u64)>,
2e640ffa Andy McCall ↶ 101
    summaries: Mutex<Summaries>,
39442b00 Andy McCall ↶ 102
    /// Where briefs are kept on disk, when anywhere.
103
    briefs: Option<PathBuf>,
9ff27da5 Andy McCall ↶ 104
}
105
106
impl StateCache {
107
    pub fn new(capacity: usize) -> StateCache {
736ae87e Andy McCall ↶ 108
        StateCache::with_budget(capacity, budget())
109
    }
110
111
    pub fn with_budget(capacity: usize, budget: usize) -> StateCache {
39442b00 Andy McCall ↶ 112
        StateCache {
113
            capacity: capacity.max(1),
114
            budget,
115
            inner: Mutex::new((HashMap::new(), 0)),
116
            summaries: Mutex::new((HashMap::new(), 0)),
117
            briefs: None,
118
        }
119
    }
120
121
    /// Keep briefs on disk under `dir`, one small file per state.
122
    pub fn with_briefs(mut self, dir: PathBuf) -> StateCache {
123
        self.briefs = Some(dir);
124
        self
125
    }
126
127
    fn brief_path(&self, key: &Key) -> Option<PathBuf> {
128
        let dir = self.briefs.as_ref()?;
129
        let mut h = blake3::Hasher::new();
130
        for c in &key.heads {
131
            h.update(&c.0);
132
        }
133
        Some(dir.join(hex::encode(key.repo)).join(h.finalize().to_hex().as_str()))
134
    }
135
136
    fn known_brief(&self, key: &Key) -> Option<Brief> {
137
        if let Some((s, _)) = self.summaries.lock().unwrap().0.get(key) {
138
            return Some(s.brief());
139
        }
140
        read_brief(&self.brief_path(key)?)
141
    }
142
143
    /// The brief of the state with these heads: from memory, from disk, or
144
    /// worked out and kept.
145
    pub fn brief(&self, repo: &Repo, heads: &[ChangeHash]) -> Result<Brief, oxy_core::repo::RepoError> {
146
        Ok(self.briefs(repo, &[heads.to_vec()])?[0])
147
    }
148
149
    /// The briefs of many states, those not yet known worked out a few at
150
    /// a time in parallel.
151
    pub fn briefs(&self, repo: &Repo, all: &[Vec<ChangeHash>]) -> Result<Vec<Brief>, oxy_core::repo::RepoError> {
152
        let id = repo.id()?;
153
        let mut out: Vec<Option<Brief>> = all.iter().map(|h| self.known_brief(&Key { repo: id, heads: sorted(h) })).collect();
154
        let missing: Vec<usize> = (0..all.len()).filter(|&i| out[i].is_none()).collect();
155
        if missing.is_empty() {
156
            return Ok(out.into_iter().map(|b| b.expect("known")).collect());
157
        }
158
        let next = Mutex::new(missing.iter());
159
        let found: Mutex<Vec<(usize, Result<Brief, oxy_core::repo::RepoError>)>> = Mutex::new(Vec::new());
160
        let threads = PARALLEL.min(missing.len()).min(std::thread::available_parallelism().map(|n| n.get()).unwrap_or(1));
161
        // A `Repo` stays on its thread, so each worker opens its own.
162
        let root = repo.root().to_path_buf();
163
        std::thread::scope(|s| {
164
            for _ in 0..threads {
165
                s.spawn(|| {
166
                    let mine = Repo::open(&root);
167
                    loop {
168
                        let Some(&i) = next.lock().unwrap().next() else { break };
169
                        let b = match &mine {
170
                            Ok(r) => self.summary(r, &all[i]).map(|s| s.brief()),
171
                            Err(e) => Err(oxy_core::repo::RepoError::Msg(format!("open {}: {e}", root.display()))),
172
                        };
173
                        found.lock().unwrap().push((i, b));
174
                    }
175
                });
176
            }
177
        });
178
        for (i, b) in found.into_inner().unwrap() {
179
            out[i] = Some(b?);
180
        }
181
        Ok(out.into_iter().map(|b| b.expect("worked out")).collect())
2e640ffa Andy McCall ↶ 182
    }
183
184
    /// The summary of the state with these heads: from the state cache when
185
    /// it holds the state, else loaded and dropped, the state cache left as
186
    /// it was.
187
    pub fn summary(&self, repo: &Repo, heads: &[ChangeHash]) -> Result<Arc<Summary>, oxy_core::repo::RepoError> {
39442b00 Andy McCall ↶ 188
        let sorted = sorted(heads);
2e640ffa Andy McCall ↶ 189
        let key = Key { repo: repo.id()?, heads: sorted.clone() };
190
        {
191
            let mut guard = self.summaries.lock().unwrap();
192
            let (map, tick) = &mut *guard;
193
            *tick += 1;
194
            if let Some(e) = map.get_mut(&key) {
195
                e.1 = *tick;
196
                return Ok(e.0.clone());
197
            }
198
        }
199
        let held = self.inner.lock().unwrap().0.get(&key).map(|e| e.loaded.clone());
200
        let summary = Arc::new(match held {
201
            Some(l) => summarise(&l.state, &l.snapshot),
202
            None => {
203
                let state = repo.load_state(&sorted)?;
204
                let snapshot = state.materialize();
205
                summarise(&state, &snapshot)
206
            }
207
        });
39442b00 Andy McCall ↶ 208
        if let Some(path) = self.brief_path(&key) {
209
            write_brief(&path, summary.brief());
210
        }
2e640ffa Andy McCall ↶ 211
        let mut guard = self.summaries.lock().unwrap();
212
        let (map, tick) = &mut *guard;
213
        if map.len() >= SUMMARIES {
214
            if let Some(oldest) = map.iter().min_by_key(|(_, e)| e.1).map(|(k, _)| k.clone()) {
215
                map.remove(&oldest);
216
            }
217
        }
218
        map.insert(key, (summary.clone(), *tick));
219
        Ok(summary)
9ff27da5 Andy McCall ↶ 220
    }
221
222
    /// The state with these heads, loaded once per hub process.
223
    pub fn load(&self, repo: &Repo, heads: &[ChangeHash]) -> Result<Arc<Loaded>, oxy_core::repo::RepoError> {
224
        let mut sorted = heads.to_vec();
225
        sorted.sort();
226
        sorted.dedup();
227
        let key = Key { repo: repo.id()?, heads: sorted.clone() };
228
        {
229
            let mut guard = self.inner.lock().unwrap();
230
            let (map, tick) = &mut *guard;
231
            *tick += 1;
232
            if let Some(e) = map.get_mut(&key) {
233
                e.last_used = *tick;
234
                return Ok(e.loaded.clone());
235
            }
236
        }
237
        let state = repo.load_state(&sorted)?;
238
        let snapshot = state.materialize();
239
        let loaded = Arc::new(Loaded { heads: sorted, state, snapshot });
736ae87e Andy McCall ↶ 240
        let w = weight(&loaded);
9ff27da5 Andy McCall ↶ 241
        let mut guard = self.inner.lock().unwrap();
242
        let (map, tick) = &mut *guard;
736ae87e Andy McCall ↶ 243
        // The oldest go until it fits by count and by size; the new one
244
        // stays even when it alone is over the budget.
245
        let budget = self.budget;
246
        let mut total: usize = map.values().map(|e| e.weight).sum::<usize>() + w;
247
        while !map.is_empty() && (map.len() >= self.capacity || total > budget) {
248
            let Some(oldest) = map.iter().min_by_key(|(_, e)| e.last_used).map(|(k, _)| k.clone()) else {
249
                break;
250
            };
251
            if let Some(e) = map.remove(&oldest) {
252
                total -= e.weight;
9ff27da5 Andy McCall ↶ 253
            }
254
        }
736ae87e Andy McCall ↶ 255
        map.insert(key, Entry { loaded: loaded.clone(), last_used: *tick, weight: w });
9ff27da5 Andy McCall ↶ 256
        Ok(loaded)
257
    }
258
259
    pub fn len(&self) -> usize {
260
        self.inner.lock().unwrap().0.len()
261
    }
262
263
    pub fn is_empty(&self) -> bool {
264
        self.len() == 0
39442b00 Andy McCall ↶ 265
    }
266
}
267
268
fn sorted(heads: &[ChangeHash]) -> Vec<ChangeHash> {
269
    let mut v = heads.to_vec();
270
    v.sort();
271
    v.dedup();
272
    v
273
}
274
275
/// A brief on disk: `changes latest_ms conflicted`.
276
fn read_brief(path: &Path) -> Option<Brief> {
277
    let text = std::fs::read_to_string(path).ok()?;
278
    let mut f = text.split_whitespace();
279
    Some(Brief { changes: f.next()?.parse().ok()?, latest_ms: f.next()?.parse().ok()?, conflicted: f.next()? == "1" })
280
}
281
282
/// Kept when it can be; a brief that is not kept is only worked out again.
283
fn write_brief(path: &Path, b: Brief) {
284
    let Some(dir) = path.parent() else { return };
285
    if std::fs::create_dir_all(dir).is_err() {
286
        return;
287
    }
288
    let tmp = path.with_extension(format!("tmp{}", std::process::id()));
289
    if std::fs::write(&tmp, format!("{} {} {}", b.changes, b.latest_ms, u8::from(b.conflicted))).is_ok() {
290
        std::fs::rename(&tmp, path).ok();
9ff27da5 Andy McCall ↶ 291
    }
292
}
293
2e640ffa Andy McCall ↶ 294
fn summarise(state: &State, snapshot: &Snapshot) -> Summary {
295
    Summary {
296
        changes: state.changes().map(|(h, _)| *h).collect(),
297
        latest_ms: state.changes().map(|(_, m)| m.hlc.wall_ms).max().unwrap_or(0),
298
        conflicted: snapshot.is_conflicted(),
299
    }
300
}
301
9ff27da5 Andy McCall ↶ 302
#[cfg(test)]
303
mod tests {
304
    use super::*;
305
306
    #[test]
307
    fn caches_by_heads_and_evicts_the_oldest() {
308
        let dir = tempfile::tempdir().unwrap();
309
        let repo = Repo::init_bare(dir.path()).unwrap();
310
        let cache = StateCache::new(2);
311
        let a = cache.load(&repo, &[]).unwrap();
312
        let b = cache.load(&repo, &[]).unwrap();
313
        assert!(Arc::ptr_eq(&a, &b), "same heads, same entry");
314
        assert_eq!(cache.len(), 1);
315
        let h1 = oxy_core::hash::ObjectRef([1; 32]);
316
        let h2 = oxy_core::hash::ObjectRef([2; 32]);
317
        // Unknown heads fail to load and are not cached.
318
        assert!(cache.load(&repo, &[h1]).is_err());
319
        assert_eq!(cache.len(), 1);
320
        let _ = (h2, dir);
2e640ffa Andy McCall ↶ 321
    }
322
323
    #[test]
324
    fn summaries_leave_the_state_cache_alone() {
325
        let dir = tempfile::tempdir().unwrap();
326
        let repo = Repo::init_bare(dir.path()).unwrap();
327
        let cache = StateCache::new(2);
328
        let a = cache.summary(&repo, &[]).unwrap();
329
        assert_eq!(cache.len(), 0, "a summary does not fill the state cache");
330
        assert!(Arc::ptr_eq(&a, &cache.summary(&repo, &[]).unwrap()), "kept");
331
        assert!(a.changes.is_empty() && !a.conflicted);
332
        assert!(cache.summary(&repo, &[oxy_core::hash::ObjectRef([3; 32])]).is_err());
736ae87e Andy McCall ↶ 333
    }
334
335
    #[test]
336
    fn a_size_budget_evicts_the_oldest_and_keeps_the_newest() {
337
        let dir = tempfile::tempdir().unwrap();
338
        let repo = Repo::init(dir.path()).unwrap();
339
        std::fs::write(dir.path().join("a.txt"), "a\n".repeat(1000)).unwrap();
340
        let one = repo.commit("one", &[]).unwrap();
341
        std::fs::write(dir.path().join("b.txt"), "b\n".repeat(1000)).unwrap();
342
        let two = repo.commit("two", &[]).unwrap();
343
        // Room for nothing: each load stays, the one before goes.
344
        let cache = StateCache::with_budget(64, 0);
345
        cache.load(&repo, &[one]).unwrap();
346
        assert_eq!(cache.len(), 1, "kept though over the budget");
347
        cache.load(&repo, &[two]).unwrap();
348
        assert_eq!(cache.len(), 1, "the older one went");
349
        // Room for plenty: both stay.
350
        let roomy = StateCache::with_budget(64, 1 << 30);
351
        roomy.load(&repo, &[one]).unwrap();
352
        roomy.load(&repo, &[two]).unwrap();
353
        assert_eq!(roomy.len(), 2);
39442b00 Andy McCall ↶ 354
    }
355
356
    #[test]
357
    fn briefs_are_worked_out_in_parallel_and_survive_a_restart() {
358
        let dir = tempfile::tempdir().unwrap();
359
        let repo = Repo::init(dir.path()).unwrap();
360
        std::fs::write(dir.path().join("a.txt"), "a\n").unwrap();
361
        let one = repo.commit("one", &[]).unwrap();
362
        std::fs::write(dir.path().join("b.txt"), "b\n").unwrap();
363
        let two = repo.commit("two", &[]).unwrap();
364
        let kept = tempfile::tempdir().unwrap();
365
        let cache = StateCache::new(8).with_briefs(kept.path().to_path_buf());
366
        let got = cache.briefs(&repo, &[vec![one], vec![one, two], vec![]]).unwrap();
367
        assert_eq!(got.iter().map(|b| b.changes).collect::<Vec<_>>(), vec![1, 2, 0]);
368
        assert!(got[1].latest_ms >= got[0].latest_ms && !got[1].conflicted);
369
        // A new cache (a restarted hub) reads them back without loading a
370
        // state: a repository that no longer has the changes still answers.
371
        let gone = tempfile::tempdir().unwrap();
372
        let empty = Repo::init(gone.path()).unwrap();
373
        let empty_id = empty.id().unwrap();
374
        for f in std::fs::read_dir(kept.path()).unwrap() {
375
            let f = f.unwrap().path();
376
            std::fs::rename(&f, kept.path().join(hex::encode(empty_id))).unwrap();
377
        }
378
        let restarted = StateCache::new(8).with_briefs(kept.path().to_path_buf());
379
        assert_eq!(restarted.brief(&empty, &[two, one]).unwrap(), got[1], "from disk, whatever the heads' order");
380
        assert!(StateCache::new(8).brief(&empty, &[one, two]).is_err(), "without the disk it would have to load");
381
        // Unknown heads are an error, not a guess.
382
        assert!(cache.briefs(&repo, &[vec![one], vec![oxy_core::hash::ObjectRef([9; 32])]]).is_err());
383
        // A bare repository, as the hub keeps them, works across threads too.
384
        let bare_dir = tempfile::tempdir().unwrap();
385
        let bare = Repo::init_bare(bare_dir.path()).unwrap();
386
        assert_eq!(cache.briefs(&bare, &[vec![], vec![]]).unwrap().len(), 2);
9ff27da5 Andy McCall ↶ 387
    }
388
}