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