OXYGENHUB
# 99e3e0af08df oxygen / crates / oxy-core / src / repo / gc.rs
5.5 KiB · Rust · last changed Unbound hosted repositories adopt the first pusher's id 1 month ago source blame history raw
1
//! Garbage collection (spec §21): pack loose objects, then delete objects
2
//! nothing reachable refers to.
3
//!
4
//! Roots: the current view, the views of every operation newer than
5
//! `core.op-retention`, reference attestations, and the policy. Operation
6
//! objects are always kept so the log stays walkable, but an operation older
7
//! than the retention window no longer keeps its states alive, so undoing
8
//! that far back may fail once its objects are gone.
9
10
use super::*;
11
use crate::store::{PackReport, PruneReport};
12
use std::collections::HashSet;
13
14
#[derive(Debug, Clone, Default, PartialEq, Eq)]
15
pub struct GcReport {
16
    pub packed: PackReport,
17
    pub pruned: PruneReport,
18
    pub reachable: usize,
19
    /// Packs folded into one because there were more than `MAX_PACKS`.
20
    pub merged_packs: usize,
21
}
22
23
impl Repo {
24
    /// Pack loose objects and prune unreachable ones older than the grace
25
    /// period (`now` ignores the grace period).
26
    pub fn gc(&self, now: bool) -> Result<GcReport> {
27
        let packed = self.store.pack_loose()?;
28
        let keep = self.reachable()?;
29
        let grace = if now {
30
            std::time::Duration::ZERO
31
        } else {
32
            std::time::Duration::from_secs(self.config.gc_grace_days * 86_400)
33
        };
34
        let pruned = self.store.prune(&keep, grace)?;
35
        let merged_packs = self.store.merge_packs()?;
36
        Ok(GcReport {
37
            packed,
38
            pruned,
39
            reachable: keep.len(),
40
            merged_packs,
41
        })
42
    }
43
44
    /// Every object that must survive garbage collection.
45
    pub fn reachable(&self) -> Result<HashSet<ObjectRef>> {
46
        let mut keep: HashSet<ObjectRef> = HashSet::new();
47
        let mut states: Vec<ObjectRef> = Vec::new();
48
        let mut changes: Vec<ChangeHash> = Vec::new();
49
        let mut attests: Vec<ObjectRef> = Vec::new();
50
        let mut policies: Vec<ObjectRef> = Vec::new();
51
52
        // Operations: always kept; views within retention are roots.
53
        let cutoff = Hlc::now()
54
            .wall_ms
55
            .saturating_sub(self.config.op_retention_days * 86_400_000);
56
        for (i, (r, op)) in self.op_log()?.into_iter().enumerate() {
57
            keep.insert(r);
58
            if i == 0 || op.hlc.wall_ms >= cutoff {
59
                states.extend(op.view.bookmarks.values().copied());
60
                states.extend(op.view.remotes.values().flat_map(|b| b.values().copied()));
61
                changes.extend(op.view.workspaces.values().copied());
62
                policies.extend(op.view.policy);
63
            }
64
        }
65
        // Checkpoints: the object, its payload blob, and the blob's chunks.
66
        for r in self.checkpoint_refs()? {
67
            if let Ok(bytes) = self.store.get_typed(&r, ObjectType::Checkpoint) {
68
                keep.insert(r);
69
                let cp = crate::objects::Checkpoint::decode(&bytes)?;
70
                keep.insert(cp.payload);
71
                if let Ok(b) = self.store.get_typed(&cp.payload, ObjectType::Blob) {
72
                    keep.extend(Blob::decode(&b)?.chunks);
73
                }
74
            }
75
        }
76
        // Tags: their states and attestations.
77
        let view_now = self.view()?;
78
        states.extend(view_now.tags.values().copied());
79
        for name in view_now.tags.keys() {
80
            if let Some((r, _)) = self.tag_attest(name)? {
81
                attests.push(r);
82
            }
83
        }
84
        // Reference attestations.
85
        for name in self.view()?.bookmarks.keys() {
86
            if let Some((r, _)) = self.latest_ref_attest(name)? {
87
                attests.push(r);
88
            }
89
        }
90
        for st in states {
91
            if keep.insert(st) {
92
                changes.extend(self.store.get_state(&st)?.heads);
93
            }
94
        }
95
        for p in policies {
96
            if keep.insert(p) {
97
                let policy = crate::policy::Policy::decode(&self.store.get_typed(&p, ObjectType::Policy)?)?;
98
                for id in &policy.identities {
99
                    keep.insert(id.hash());
100
                }
101
                for sig in self.store.signatures(&p)? {
102
                    keep.insert(sig.key);
103
                }
104
            }
105
        }
106
        // Changes: their closure, identities, blobs, chunks, seals.
107
        let mut stack = changes;
108
        while let Some(h) = stack.pop() {
109
            if !keep.insert(h) {
110
                continue;
111
            }
112
            // Beyond the shallow boundary there is nothing to keep.
113
            let c = match self.store.get_change(&h) {
114
                Ok(c) => c,
115
                Err(StoreError::NotFound(_)) => continue,
116
                Err(e) => return Err(e.into()),
117
            };
118
            stack.extend(c.deps.iter().copied());
119
            if !c.author.is_zero() {
120
                keep.insert(c.author);
121
            }
122
            for sig in self.store.signatures(&h)? {
123
                keep.insert(sig.key);
124
            }
125
            for e in &c.edits {
126
                if let Edit::Replace { old, new, .. } = e {
127
                    for b in [old, new].into_iter().flatten() {
128
                        if keep.insert(*b) {
129
                            if let Ok(bytes) = self.store.get_typed(b, ObjectType::Blob) {
130
                                keep.extend(Blob::decode(&bytes)?.chunks);
131
                            }
132
                        }
133
                    }
134
                }
135
            }
136
            attests.extend(self.store.seals_for(&h)?);
137
        }
138
        for a in attests {
139
            if keep.insert(a) {
140
                for sig in self.store.signatures(&a)? {
141
                    keep.insert(sig.key);
142
                }
143
            }
144
        }
145
        Ok(keep)
146
    }
147
}