OXYGENHUB
◆ v0.4.5 oxygen / crates / oxy-core / src / repo / gc.rs
9.1 KiB · Rust · last changed The issuer countersigns when it accepted a certified update (keyless step 4c) 18 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` (their working copies only within the shorter
6
//! `core.snapshot-retention`), reference attestations, and the policy; receipts
7
//! live as long as the changes of their state. Operation
8
//! objects are always kept so the log stays walkable, but an operation older
9
//! than the retention window no longer keeps its states alive, so undoing
10
//! that far back may fail once its objects are gone.
11
12
use super::*;
13
use crate::store::{PackReport, PruneReport};
14
use std::collections::HashSet;
15
16
#[derive(Debug, Clone, Default, PartialEq, Eq)]
17
pub struct GcReport {
18
    pub packed: PackReport,
19
    pub pruned: PruneReport,
20
    pub reachable: usize,
21
    /// Packs folded into the one a full repack writes.
22
    pub merged_packs: usize,
23
}
24
25
impl Repo {
26
    /// Prune unreachable objects older than the grace period (`now`
27
    /// ignores it), then repack everything into one pack (spec §13.4).
28
    pub fn gc(&self, now: bool) -> Result<GcReport> {
29
        self.gc_with(now, &mut |_| {})
30
    }
31
32
    /// [`Repo::gc`], reporting each phase and the packing's progress
33
    /// (oxygen#66), for a spinner or a log.
34
    pub fn gc_with(&self, now: bool, progress: crate::store::Progress) -> Result<GcReport> {
35
        self.gc_keeping(now, &[], progress)
36
    }
37
38
    /// [`Repo::gc_with`], keeping `extra` blobs and their chunks as well:
39
    /// objects a host stored for itself and names from outside the
40
    /// repository's history, such as a forge's job artifacts
41
    /// (oxygenhub#126).
42
    pub fn gc_keeping(
43
        &self,
44
        now: bool,
45
        extra: &[ObjectRef],
46
        progress: crate::store::Progress,
47
    ) -> Result<GcReport> {
48
        progress("finding what is reachable");
49
        let mut keep = self.reachable()?;
50
        for r in extra {
51
            if !self.store.has(r) || !keep.insert(*r) {
52
                continue;
53
            }
54
            if let Ok(body) = self.store.get_typed(r, ObjectType::Blob) {
55
                if let Ok(blob) = Blob::decode(&body) {
56
                    keep.extend(blob.chunks);
57
                }
58
            }
59
        }
60
        let grace = if now {
61
            std::time::Duration::ZERO
62
        } else {
63
            std::time::Duration::from_secs(self.config.gc_grace_days * 86_400)
64
        };
65
        let pruned = self.store.prune_with(&keep, grace, progress)?;
66
        // Then everything left in one pack, compressed harder than a
67
        // commit's (spec §13.4), as `git gc` repacks.
68
        let (packed, merged_packs) = self
69
            .store
70
            .repack_all_with(crate::store::REPACK_ZSTD_LEVEL, progress)?;
71
        Ok(GcReport {
72
            packed,
73
            pruned,
74
            reachable: keep.len(),
75
            merged_packs,
76
        })
77
    }
78
79
    /// Every object that must survive garbage collection.
80
    pub fn reachable(&self) -> Result<HashSet<ObjectRef>> {
81
        let mut keep: HashSet<ObjectRef> = HashSet::new();
82
        let mut states: Vec<ObjectRef> = Vec::new();
83
        let mut changes: Vec<ChangeHash> = Vec::new();
84
        let mut attests: Vec<ObjectRef> = Vec::new();
85
        let mut policies: Vec<ObjectRef> = Vec::new();
86
87
        // Operations: always kept; views within retention are roots. Past
88
        // working copies only within the shorter `core.snapshot-retention`
89
        // (oxygen#98): a file only ever snapshotted, such as a build output
90
        // a status took in, goes once they expire.
91
        let now_ms = Hlc::now().wall_ms;
92
        let cutoff = now_ms.saturating_sub(self.config.op_retention_days * 86_400_000);
93
        let wc_cutoff = now_ms
94
            .saturating_sub(self.config.snapshot_retention_days * 86_400_000)
95
            .max(cutoff);
96
        for (i, (r, op)) in self.op_log()?.into_iter().enumerate() {
97
            keep.insert(r);
98
            if i == 0 || op.hlc.wall_ms >= cutoff {
99
                states.extend(op.view.bookmarks.values().copied());
100
                states.extend(op.view.remotes.values().flat_map(|b| b.values().copied()));
101
                policies.extend(op.view.policy);
102
            }
103
            if i == 0 || (self.config.snapshot_retention_days > 0 && op.hlc.wall_ms >= wc_cutoff) {
104
                changes.extend(op.view.workspaces.values().copied());
105
            }
106
        }
107
        // Checkpoints: the object, its payload blob, and the blob's chunks.
108
        for r in self.checkpoint_refs()? {
109
            if let Ok(bytes) = self.store.get_typed(&r, ObjectType::Checkpoint) {
110
                keep.insert(r);
111
                let cp = crate::objects::Checkpoint::decode(&bytes)?;
112
                keep.insert(cp.payload);
113
                if let Ok(b) = self.store.get_typed(&cp.payload, ObjectType::Blob) {
114
                    keep.extend(Blob::decode(&b)?.chunks);
115
                }
116
                // A version 2 payload's graph blobs and their chunks.
117
                for g in self.checkpoint_graph_blobs(&cp).unwrap_or_default() {
118
                    keep.insert(g);
119
                    if let Ok(b) = self.store.get_typed(&g, ObjectType::Blob) {
120
                        keep.extend(Blob::decode(&b)?.chunks);
121
                    }
122
                }
123
            }
124
        }
125
        // Tags: their states and attestations.
126
        let view_now = self.view()?;
127
        states.extend(view_now.tags.values().copied());
128
        for name in view_now.tags.keys() {
129
            if let Some((r, _)) = self.tag_attest(name)? {
130
                attests.push(r);
131
            }
132
        }
133
        // Reference attestations.
134
        for name in self.view()?.bookmarks.keys() {
135
            if let Some((r, _)) = self.latest_ref_attest(name)? {
136
                // With a host's acceptance of it (spec §14.7).
137
                if let Some(acc) = self.acceptance_of(&r)? {
138
                    attests.push(acc.attest.hash());
139
                }
140
                attests.push(r);
141
            }
142
        }
143
        // A historical view may name objects pruned under an earlier, shorter
144
        // retention; there is nothing to keep for those.
145
        for st in states {
146
            if keep.insert(st) {
147
                match self.store.get_state(&st) {
148
                    Ok(s) => changes.extend(s.heads),
149
                    Err(StoreError::NotFound(_)) => continue,
150
                    Err(e) => return Err(e.into()),
151
                }
152
            }
153
        }
154
        for p in policies {
155
            if keep.insert(p) {
156
                let bytes = match self.store.get_typed(&p, ObjectType::Policy) {
157
                    Ok(b) => b,
158
                    Err(StoreError::NotFound(_)) => continue,
159
                    Err(e) => return Err(e.into()),
160
                };
161
                let policy = crate::policy::Policy::decode(&bytes)?;
162
                for id in &policy.identities {
163
                    keep.insert(id.hash());
164
                }
165
                for sig in self.store.signatures(&p)? {
166
                    keep.insert(sig.key);
167
                }
168
            }
169
        }
170
        // Changes: their closure, identities, blobs, chunks, seals.
171
        let mut stack = changes;
172
        while let Some(h) = stack.pop() {
173
            if !keep.insert(h) {
174
                continue;
175
            }
176
            // Beyond the shallow boundary, or pruned under an earlier
177
            // retention, there is nothing to keep.
178
            let c = match self.store.get_change_parts(&h) {
179
                Ok((c, texts)) => {
180
                    keep.extend(texts);
181
                    c
182
                }
183
                Err(StoreError::NotFound(_)) => continue,
184
                Err(e) => return Err(e.into()),
185
            };
186
            stack.extend(c.deps.iter().copied());
187
            if !c.author.is_zero() {
188
                keep.insert(c.author);
189
            }
190
            for sig in self.store.signatures(&h)? {
191
                self.keep_signer(&mut keep, sig.key)?;
192
            }
193
            for e in &c.edits {
194
                if let Edit::Replace { old, new, .. } = e {
195
                    for b in [old, new].into_iter().flatten() {
196
                        if keep.insert(*b) {
197
                            if let Ok(bytes) = self.store.get_typed(b, ObjectType::Blob) {
198
                                keep.extend(Blob::decode(&bytes)?.chunks);
199
                            }
200
                        }
201
                    }
202
                }
203
            }
204
            attests.extend(self.store.seals_for(&h)?);
205
        }
206
        self.reachable_receipts(&mut keep)?;
207
        self.reachable_approvals(&mut keep)?;
208
        for a in attests {
209
            if keep.insert(a) {
210
                for sig in self.store.signatures(&a)? {
211
                    self.keep_signer(&mut keep, sig.key)?;
212
                }
213
            }
214
        }
215
        Ok(keep)
216
    }
217
218
    /// Keep a signer's identity and, for a short-lived key, its
219
    /// certificate and the certificate's issuer (spec §14.7).
220
    pub(crate) fn keep_signer(&self, keep: &mut HashSet<ObjectRef>, key: ObjectRef) -> Result<()> {
221
        keep.insert(key);
222
        if let Some(c) = self.store.certificate_of(&key)? {
223
            keep.insert(c);
224
            if let Ok(cert) = self.store.get_certificate(&c) {
225
                keep.insert(cert.cert.issuer);
226
            }
227
        }
228
        Ok(())
229
    }
230
}