OXYGENHUB
# f53cbe7a204e oxygen / crates / oxy-core / src / repo / gc.rs
7.4 KiB · Rust · last changed The issuer countersigns when it accepted a certified update (keyless step 4c) 19 days ago source blame history raw
1
//! Garbage collection (spec §21): 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; receipts
6
//! live as long as the changes of their state. Operation
7
//! objects are always kept so the log stays walkable, but an operation older
8
//! than the retention window no longer keeps its states alive, so undoing
9
//! that far back may fail once its objects are gone.
10
11
use super::*;
12
use crate::store::{PackReport, PruneReport};
13
use std::collections::HashSet;
14
15
#[derive(Debug, Clone, Default, PartialEq, Eq)]
16
pub struct GcReport {
17
    pub packed: PackReport,
18
    pub pruned: PruneReport,
19
    pub reachable: usize,
20
    /// Packs folded into the one a full repack writes.
21
    pub merged_packs: usize,
22
}
23
24
impl Repo {
25
    /// Prune unreachable objects older than the grace period (`now`
26
    /// ignores it), then repack everything into one pack (spec §13.4).
27
    pub fn gc(&self, now: bool) -> Result<GcReport> {
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
        // Then everything left in one pack, compressed harder than a
36
        // commit's (spec §13.4), as `git gc` repacks.
37
        let (packed, merged_packs) = self.store.repack_all(crate::store::REPACK_ZSTD_LEVEL)?;
38
        Ok(GcReport {
39
            packed,
40
            pruned,
41
            reachable: keep.len(),
42
            merged_packs,
43
        })
44
    }
45
46
    /// Every object that must survive garbage collection.
47
    pub fn reachable(&self) -> Result<HashSet<ObjectRef>> {
48
        let mut keep: HashSet<ObjectRef> = HashSet::new();
49
        let mut states: Vec<ObjectRef> = Vec::new();
50
        let mut changes: Vec<ChangeHash> = Vec::new();
51
        let mut attests: Vec<ObjectRef> = Vec::new();
52
        let mut policies: Vec<ObjectRef> = Vec::new();
53
54
        // Operations: always kept; views within retention are roots.
55
        let cutoff = Hlc::now()
56
            .wall_ms
57
            .saturating_sub(self.config.op_retention_days * 86_400_000);
58
        for (i, (r, op)) in self.op_log()?.into_iter().enumerate() {
59
            keep.insert(r);
60
            if i == 0 || op.hlc.wall_ms >= cutoff {
61
                states.extend(op.view.bookmarks.values().copied());
62
                states.extend(op.view.remotes.values().flat_map(|b| b.values().copied()));
63
                changes.extend(op.view.workspaces.values().copied());
64
                policies.extend(op.view.policy);
65
            }
66
        }
67
        // Checkpoints: the object, its payload blob, and the blob's chunks.
68
        for r in self.checkpoint_refs()? {
69
            if let Ok(bytes) = self.store.get_typed(&r, ObjectType::Checkpoint) {
70
                keep.insert(r);
71
                let cp = crate::objects::Checkpoint::decode(&bytes)?;
72
                keep.insert(cp.payload);
73
                if let Ok(b) = self.store.get_typed(&cp.payload, ObjectType::Blob) {
74
                    keep.extend(Blob::decode(&b)?.chunks);
75
                }
76
                // A version 2 payload's graph blobs and their chunks.
77
                for g in self.checkpoint_graph_blobs(&cp).unwrap_or_default() {
78
                    keep.insert(g);
79
                    if let Ok(b) = self.store.get_typed(&g, ObjectType::Blob) {
80
                        keep.extend(Blob::decode(&b)?.chunks);
81
                    }
82
                }
83
            }
84
        }
85
        // Tags: their states and attestations.
86
        let view_now = self.view()?;
87
        states.extend(view_now.tags.values().copied());
88
        for name in view_now.tags.keys() {
89
            if let Some((r, _)) = self.tag_attest(name)? {
90
                attests.push(r);
91
            }
92
        }
93
        // Reference attestations.
94
        for name in self.view()?.bookmarks.keys() {
95
            if let Some((r, _)) = self.latest_ref_attest(name)? {
96
                // With a host's acceptance of it (spec §14.7).
97
                if let Some(acc) = self.acceptance_of(&r)? {
98
                    attests.push(acc.attest.hash());
99
                }
100
                attests.push(r);
101
            }
102
        }
103
        // A historical view may name objects pruned under an earlier, shorter
104
        // retention; there is nothing to keep for those.
105
        for st in states {
106
            if keep.insert(st) {
107
                match self.store.get_state(&st) {
108
                    Ok(s) => changes.extend(s.heads),
109
                    Err(StoreError::NotFound(_)) => continue,
110
                    Err(e) => return Err(e.into()),
111
                }
112
            }
113
        }
114
        for p in policies {
115
            if keep.insert(p) {
116
                let bytes = match self.store.get_typed(&p, ObjectType::Policy) {
117
                    Ok(b) => b,
118
                    Err(StoreError::NotFound(_)) => continue,
119
                    Err(e) => return Err(e.into()),
120
                };
121
                let policy = crate::policy::Policy::decode(&bytes)?;
122
                for id in &policy.identities {
123
                    keep.insert(id.hash());
124
                }
125
                for sig in self.store.signatures(&p)? {
126
                    keep.insert(sig.key);
127
                }
128
            }
129
        }
130
        // Changes: their closure, identities, blobs, chunks, seals.
131
        let mut stack = changes;
132
        while let Some(h) = stack.pop() {
133
            if !keep.insert(h) {
134
                continue;
135
            }
136
            // Beyond the shallow boundary, or pruned under an earlier
137
            // retention, there is nothing to keep.
138
            let c = match self.store.get_change_parts(&h) {
139
                Ok((c, texts)) => {
140
                    keep.extend(texts);
141
                    c
142
                }
143
                Err(StoreError::NotFound(_)) => continue,
144
                Err(e) => return Err(e.into()),
145
            };
146
            stack.extend(c.deps.iter().copied());
147
            if !c.author.is_zero() {
148
                keep.insert(c.author);
149
            }
150
            for sig in self.store.signatures(&h)? {
151
                self.keep_signer(&mut keep, sig.key)?;
152
            }
153
            for e in &c.edits {
154
                if let Edit::Replace { old, new, .. } = e {
155
                    for b in [old, new].into_iter().flatten() {
156
                        if keep.insert(*b) {
157
                            if let Ok(bytes) = self.store.get_typed(b, ObjectType::Blob) {
158
                                keep.extend(Blob::decode(&bytes)?.chunks);
159
                            }
160
                        }
161
                    }
162
                }
163
            }
164
            attests.extend(self.store.seals_for(&h)?);
165
        }
166
        self.reachable_receipts(&mut keep)?;
167
        for a in attests {
168
            if keep.insert(a) {
169
                for sig in self.store.signatures(&a)? {
170
                    self.keep_signer(&mut keep, sig.key)?;
171
                }
172
            }
173
        }
174
        Ok(keep)
175
    }
176
177
    /// Keep a signer's identity and, for a short-lived key, its
178
    /// certificate and the certificate's issuer (spec §14.7).
179
    pub(crate) fn keep_signer(&self, keep: &mut HashSet<ObjectRef>, key: ObjectRef) -> Result<()> {
180
        keep.insert(key);
181
        if let Some(c) = self.store.certificate_of(&key)? {
182
            keep.insert(c);
183
            if let Ok(cert) = self.store.get_certificate(&c) {
184
                keep.insert(cert.cert.issuer);
185
            }
186
        }
187
        Ok(())
188
    }
189
}