OXYGENHUB
◆ switch-says oxygen / crates / oxy-core / src / repo / gc.rs
8.4 KiB · Rust · last changed Snapshots: large new files left out and named; past working copies expire 24 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
                attests.push(r);
137
            }
138
        }
139
        // A historical view may name objects pruned under an earlier, shorter
140
        // retention; there is nothing to keep for those.
141
        for st in states {
142
            if keep.insert(st) {
143
                match self.store.get_state(&st) {
144
                    Ok(s) => changes.extend(s.heads),
145
                    Err(StoreError::NotFound(_)) => continue,
146
                    Err(e) => return Err(e.into()),
147
                }
148
            }
149
        }
150
        for p in policies {
151
            if keep.insert(p) {
152
                let bytes = match self.store.get_typed(&p, ObjectType::Policy) {
153
                    Ok(b) => b,
154
                    Err(StoreError::NotFound(_)) => continue,
155
                    Err(e) => return Err(e.into()),
156
                };
157
                let policy = crate::policy::Policy::decode(&bytes)?;
158
                for id in &policy.identities {
159
                    keep.insert(id.hash());
160
                }
161
                for sig in self.store.signatures(&p)? {
162
                    keep.insert(sig.key);
163
                }
164
            }
165
        }
166
        // Changes: their closure, identities, blobs, chunks, seals.
167
        let mut stack = changes;
168
        while let Some(h) = stack.pop() {
169
            if !keep.insert(h) {
170
                continue;
171
            }
172
            // Beyond the shallow boundary, or pruned under an earlier
173
            // retention, there is nothing to keep.
174
            let c = match self.store.get_change_parts(&h) {
175
                Ok((c, texts)) => {
176
                    keep.extend(texts);
177
                    c
178
                }
179
                Err(StoreError::NotFound(_)) => continue,
180
                Err(e) => return Err(e.into()),
181
            };
182
            stack.extend(c.deps.iter().copied());
183
            if !c.author.is_zero() {
184
                keep.insert(c.author);
185
            }
186
            for sig in self.store.signatures(&h)? {
187
                keep.insert(sig.key);
188
            }
189
            for e in &c.edits {
190
                if let Edit::Replace { old, new, .. } = e {
191
                    for b in [old, new].into_iter().flatten() {
192
                        if keep.insert(*b) {
193
                            if let Ok(bytes) = self.store.get_typed(b, ObjectType::Blob) {
194
                                keep.extend(Blob::decode(&bytes)?.chunks);
195
                            }
196
                        }
197
                    }
198
                }
199
            }
200
            attests.extend(self.store.seals_for(&h)?);
201
        }
202
        self.reachable_receipts(&mut keep)?;
203
        for a in attests {
204
            if keep.insert(a) {
205
                for sig in self.store.signatures(&a)? {
206
                    keep.insert(sig.key);
207
                }
208
            }
209
        }
210
        Ok(keep)
211
    }
212
}