OXYGENHUB
# 028545dfa7a4 oxygen / crates / oxy-core / src / repo / gc.rs
8.6 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
        self.gc_with(now, &mut |_| {})
29
    }
30
31
    /// [`Repo::gc`], reporting each phase and the packing's progress
32
    /// (oxygen#66), for a spinner or a log.
33
    pub fn gc_with(&self, now: bool, progress: crate::store::Progress) -> Result<GcReport> {
34
        self.gc_keeping(now, &[], progress)
35
    }
36
37
    /// [`Repo::gc_with`], keeping `extra` blobs and their chunks as well:
38
    /// objects a host stored for itself and names from outside the
39
    /// repository's history, such as a forge's job artifacts
40
    /// (oxygenhub#126).
41
    pub fn gc_keeping(
42
        &self,
43
        now: bool,
44
        extra: &[ObjectRef],
45
        progress: crate::store::Progress,
46
    ) -> Result<GcReport> {
47
        progress("finding what is reachable");
48
        let mut keep = self.reachable()?;
49
        for r in extra {
50
            if !self.store.has(r) || !keep.insert(*r) {
51
                continue;
52
            }
53
            if let Ok(body) = self.store.get_typed(r, ObjectType::Blob) {
54
                if let Ok(blob) = Blob::decode(&body) {
55
                    keep.extend(blob.chunks);
56
                }
57
            }
58
        }
59
        let grace = if now {
60
            std::time::Duration::ZERO
61
        } else {
62
            std::time::Duration::from_secs(self.config.gc_grace_days * 86_400)
63
        };
64
        let pruned = self.store.prune_with(&keep, grace, progress)?;
65
        // Then everything left in one pack, compressed harder than a
66
        // commit's (spec §13.4), as `git gc` repacks.
67
        let (packed, merged_packs) = self
68
            .store
69
            .repack_all_with(crate::store::REPACK_ZSTD_LEVEL, progress)?;
70
        Ok(GcReport {
71
            packed,
72
            pruned,
73
            reachable: keep.len(),
74
            merged_packs,
75
        })
76
    }
77
78
    /// Every object that must survive garbage collection.
79
    pub fn reachable(&self) -> Result<HashSet<ObjectRef>> {
80
        let mut keep: HashSet<ObjectRef> = HashSet::new();
81
        let mut states: Vec<ObjectRef> = Vec::new();
82
        let mut changes: Vec<ChangeHash> = Vec::new();
83
        let mut attests: Vec<ObjectRef> = Vec::new();
84
        let mut policies: Vec<ObjectRef> = Vec::new();
85
86
        // Operations: always kept; views within retention are roots.
87
        let cutoff = Hlc::now()
88
            .wall_ms
89
            .saturating_sub(self.config.op_retention_days * 86_400_000);
90
        for (i, (r, op)) in self.op_log()?.into_iter().enumerate() {
91
            keep.insert(r);
92
            if i == 0 || op.hlc.wall_ms >= cutoff {
93
                states.extend(op.view.bookmarks.values().copied());
94
                states.extend(op.view.remotes.values().flat_map(|b| b.values().copied()));
95
                changes.extend(op.view.workspaces.values().copied());
96
                policies.extend(op.view.policy);
97
            }
98
        }
99
        // Checkpoints: the object, its payload blob, and the blob's chunks.
100
        for r in self.checkpoint_refs()? {
101
            if let Ok(bytes) = self.store.get_typed(&r, ObjectType::Checkpoint) {
102
                keep.insert(r);
103
                let cp = crate::objects::Checkpoint::decode(&bytes)?;
104
                keep.insert(cp.payload);
105
                if let Ok(b) = self.store.get_typed(&cp.payload, ObjectType::Blob) {
106
                    keep.extend(Blob::decode(&b)?.chunks);
107
                }
108
                // A version 2 payload's graph blobs and their chunks.
109
                for g in self.checkpoint_graph_blobs(&cp).unwrap_or_default() {
110
                    keep.insert(g);
111
                    if let Ok(b) = self.store.get_typed(&g, ObjectType::Blob) {
112
                        keep.extend(Blob::decode(&b)?.chunks);
113
                    }
114
                }
115
            }
116
        }
117
        // Tags: their states and attestations.
118
        let view_now = self.view()?;
119
        states.extend(view_now.tags.values().copied());
120
        for name in view_now.tags.keys() {
121
            if let Some((r, _)) = self.tag_attest(name)? {
122
                attests.push(r);
123
            }
124
        }
125
        // Reference attestations.
126
        for name in self.view()?.bookmarks.keys() {
127
            if let Some((r, _)) = self.latest_ref_attest(name)? {
128
                // With a host's acceptance of it (spec §14.7).
129
                if let Some(acc) = self.acceptance_of(&r)? {
130
                    attests.push(acc.attest.hash());
131
                }
132
                attests.push(r);
133
            }
134
        }
135
        // A historical view may name objects pruned under an earlier, shorter
136
        // retention; there is nothing to keep for those.
137
        for st in states {
138
            if keep.insert(st) {
139
                match self.store.get_state(&st) {
140
                    Ok(s) => changes.extend(s.heads),
141
                    Err(StoreError::NotFound(_)) => continue,
142
                    Err(e) => return Err(e.into()),
143
                }
144
            }
145
        }
146
        for p in policies {
147
            if keep.insert(p) {
148
                let bytes = match self.store.get_typed(&p, ObjectType::Policy) {
149
                    Ok(b) => b,
150
                    Err(StoreError::NotFound(_)) => continue,
151
                    Err(e) => return Err(e.into()),
152
                };
153
                let policy = crate::policy::Policy::decode(&bytes)?;
154
                for id in &policy.identities {
155
                    keep.insert(id.hash());
156
                }
157
                for sig in self.store.signatures(&p)? {
158
                    keep.insert(sig.key);
159
                }
160
            }
161
        }
162
        // Changes: their closure, identities, blobs, chunks, seals.
163
        let mut stack = changes;
164
        while let Some(h) = stack.pop() {
165
            if !keep.insert(h) {
166
                continue;
167
            }
168
            // Beyond the shallow boundary, or pruned under an earlier
169
            // retention, there is nothing to keep.
170
            let c = match self.store.get_change_parts(&h) {
171
                Ok((c, texts)) => {
172
                    keep.extend(texts);
173
                    c
174
                }
175
                Err(StoreError::NotFound(_)) => continue,
176
                Err(e) => return Err(e.into()),
177
            };
178
            stack.extend(c.deps.iter().copied());
179
            if !c.author.is_zero() {
180
                keep.insert(c.author);
181
            }
182
            for sig in self.store.signatures(&h)? {
183
                self.keep_signer(&mut keep, sig.key)?;
184
            }
185
            for e in &c.edits {
186
                if let Edit::Replace { old, new, .. } = e {
187
                    for b in [old, new].into_iter().flatten() {
188
                        if keep.insert(*b) {
189
                            if let Ok(bytes) = self.store.get_typed(b, ObjectType::Blob) {
190
                                keep.extend(Blob::decode(&bytes)?.chunks);
191
                            }
192
                        }
193
                    }
194
                }
195
            }
196
            attests.extend(self.store.seals_for(&h)?);
197
        }
198
        self.reachable_receipts(&mut keep)?;
199
        for a in attests {
200
            if keep.insert(a) {
201
                for sig in self.store.signatures(&a)? {
202
                    self.keep_signer(&mut keep, sig.key)?;
203
                }
204
            }
205
        }
206
        Ok(keep)
207
    }
208
209
    /// Keep a signer's identity and, for a short-lived key, its
210
    /// certificate and the certificate's issuer (spec §14.7).
211
    pub(crate) fn keep_signer(&self, keep: &mut HashSet<ObjectRef>, key: ObjectRef) -> Result<()> {
212
        keep.insert(key);
213
        if let Some(c) = self.store.certificate_of(&key)? {
214
            keep.insert(c);
215
            if let Ok(cert) = self.store.get_certificate(&c) {
216
                keep.insert(cert.cert.issuer);
217
            }
218
        }
219
        Ok(())
220
    }
221
}