OXYGENHUB

Coverage / crates/oxy-core/src/repo/gc.rs 92.9%

143 of 154 lines run, 7 of 14 functions · run #325 on main · run missed

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).
2816×
    pub fn gc(&self, now: bool) -> Result<GcReport> {
2988×
        self.gc_with(now, &mut |_| {})
3016×
    }
31
32
    /// [`Repo::gc`], reporting each phase and the packing's progress
33
    /// (oxygen#66), for a spinner or a log.
3417×
    pub fn gc_with(&self, now: bool, progress: crate::store::Progress) -> Result<GcReport> {
3517×
        self.gc_keeping(now, &[], progress)
3617×
    }
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).
4218×
    pub fn gc_keeping(
4318×
        &self,
4418×
        now: bool,
4518×
        extra: &[ObjectRef],
4618×
        progress: crate::store::Progress,
4718×
    ) -> Result<GcReport> {
4818×
        progress("finding what is reachable");
4918×
        let mut keep = self.reachable()?;
5018×
        for r in extra {
511×
            if !self.store.has(r) || !keep.insert(*r) {
520×
                continue;
531×
            }
541×
            if let Ok(body) = self.store.get_typed(r, ObjectType::Blob) {
551×
                if let Ok(blob) = Blob::decode(&body) {
561×
                    keep.extend(blob.chunks);
571×
                }
580×
            }
59
        }
6018×
        let grace = if now {
6116×
            std::time::Duration::ZERO
62
        } else {
632×
            std::time::Duration::from_secs(self.config.gc_grace_days * 86_400)
64
        };
6518×
        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.
6818×
        let (packed, merged_packs) = self
6918×
            .store
7018×
            .repack_all_with(crate::store::REPACK_ZSTD_LEVEL, progress)?;
7118×
        Ok(GcReport {
7218×
            packed,
7318×
            pruned,
7418×
            reachable: keep.len(),
7518×
            merged_packs,
7618×
        })
7718×
    }
78
79
    /// Every object that must survive garbage collection.
8018×
    pub fn reachable(&self) -> Result<HashSet<ObjectRef>> {
8118×
        let mut keep: HashSet<ObjectRef> = HashSet::new();
8218×
        let mut states: Vec<ObjectRef> = Vec::new();
8318×
        let mut changes: Vec<ChangeHash> = Vec::new();
8418×
        let mut attests: Vec<ObjectRef> = Vec::new();
8518×
        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.
9118×
        let now_ms = Hlc::now().wall_ms;
9218×
        let cutoff = now_ms.saturating_sub(self.config.op_retention_days * 86_400_000);
9318×
        let wc_cutoff = now_ms
9418×
            .saturating_sub(self.config.snapshot_retention_days * 86_400_000)
9518×
            .max(cutoff);
96124×
        for (i, (r, op)) in self.op_log()?.into_iter().enumerate() {
97124×
            keep.insert(r);
98124×
            if i == 0 || op.hlc.wall_ms >= cutoff {
9986×
                states.extend(op.view.bookmarks.values().copied());
10086×
                states.extend(op.view.remotes.values().flat_map(|b| b.values().copied()));
10186×
                policies.extend(op.view.policy);
10238×
            }
103124×
            if i == 0 || (self.config.snapshot_retention_days > 0 && op.hlc.wall_ms >= wc_cutoff) {
10483×
                changes.extend(op.view.workspaces.values().copied());
10583×
            }
106
        }
107
        // Checkpoints: the object, its payload blob, and the blob's chunks.
10818×
        for r in self.checkpoint_refs()? {
1092×
            if let Ok(bytes) = self.store.get_typed(&r, ObjectType::Checkpoint) {
1102×
                keep.insert(r);
1112×
                let cp = crate::objects::Checkpoint::decode(&bytes)?;
1122×
                keep.insert(cp.payload);
1132×
                if let Ok(b) = self.store.get_typed(&cp.payload, ObjectType::Blob) {
1142×
                    keep.extend(Blob::decode(&b)?.chunks);
1150×
                }
116
                // A version 2 payload's graph blobs and their chunks.
1172×
                for g in self.checkpoint_graph_blobs(&cp).unwrap_or_default() {
1181×
                    keep.insert(g);
1191×
                    if let Ok(b) = self.store.get_typed(&g, ObjectType::Blob) {
1201×
                        keep.extend(Blob::decode(&b)?.chunks);
1210×
                    }
122
                }
1230×
            }
124
        }
125
        // Tags: their states and attestations.
12618×
        let view_now = self.view()?;
12718×
        states.extend(view_now.tags.values().copied());
12818×
        for name in view_now.tags.keys() {
1293×
            if let Some((r, _)) = self.tag_attest(name)? {
1303×
                attests.push(r);
1313×
            }
132
        }
133
        // Reference attestations.
13418×
        for name in self.view()?.bookmarks.keys() {
13518×
            if let Some((r, _)) = self.latest_ref_attest(name)? {
136
                // With a host's acceptance of it (spec §14.7).
1371×
                if let Some(acc) = self.acceptance_of(&r)? {
1381×
                    attests.push(acc.attest.hash());
1391×
                }
1401×
                attests.push(r);
14117×
            }
142
        }
143
        // A historical view may name objects pruned under an earlier, shorter
144
        // retention; there is nothing to keep for those.
145105×
        for st in states {
146105×
            if keep.insert(st) {
14752×
                match self.store.get_state(&st) {
14849×
                    Ok(s) => changes.extend(s.heads),
1493×
                    Err(StoreError::NotFound(_)) => continue,
1500×
                    Err(e) => return Err(e.into()),
151
                }
15253×
            }
153
        }
15418×
        for p in policies {
1559×
            if keep.insert(p) {
1563×
                let bytes = match self.store.get_typed(&p, ObjectType::Policy) {
1573×
                    Ok(b) => b,
1580×
                    Err(StoreError::NotFound(_)) => continue,
1590×
                    Err(e) => return Err(e.into()),
160
                };
1613×
                let policy = crate::policy::Policy::decode(&bytes)?;
1624×
                for id in &policy.identities {
1634×
                    keep.insert(id.hash());
1644×
                }
1653×
                for sig in self.store.signatures(&p)? {
1663×
                    keep.insert(sig.key);
1673×
                }
1686×
            }
169
        }
170
        // Changes: their closure, identities, blobs, chunks, seals.
17118×
        let mut stack = changes;
172255×
        while let Some(h) = stack.pop() {
173237×
            if !keep.insert(h) {
174120×
                continue;
175117×
            }
176
            // Beyond the shallow boundary, or pruned under an earlier
177
            // retention, there is nothing to keep.
178117×
            let c = match self.store.get_change_parts(&h) {
179107×
                Ok((c, texts)) => {
180107×
                    keep.extend(texts);
181107×
                    c
182
                }
18310×
                Err(StoreError::NotFound(_)) => continue,
1840×
                Err(e) => return Err(e.into()),
185
            };
186107×
            stack.extend(c.deps.iter().copied());
187107×
            if !c.author.is_zero() {
18832×
                keep.insert(c.author);
18975×
            }
190107×
            for sig in self.store.signatures(&h)? {
19113×
                self.keep_signer(&mut keep, sig.key)?;
192
            }
193114×
            for e in &c.edits {
194114×
                if let Edit::Replace { old, new, .. } = e {
19518×
                    for b in [old, new].into_iter().flatten() {
19618×
                        if keep.insert(*b) {
19718×
                            if let Ok(bytes) = self.store.get_typed(b, ObjectType::Blob) {
19818×
                                keep.extend(Blob::decode(&bytes)?.chunks);
1990×
                            }
2000×
                        }
201
                    }
20296×
                }
203
            }
204107×
            attests.extend(self.store.seals_for(&h)?);
205
        }
20618×
        self.reachable_receipts(&mut keep)?;
20718×
        self.reachable_approvals(&mut keep)?;
20818×
        for a in attests {
2099×
            if keep.insert(a) {
2108×
                for sig in self.store.signatures(&a)? {
2118×
                    self.keep_signer(&mut keep, sig.key)?;
212
                }
2131×
            }
214
        }
21518×
        Ok(keep)
21618×
    }
217
218
    /// Keep a signer's identity and, for a short-lived key, its
219
    /// certificate and the certificate's issuer (spec §14.7).
22023×
    pub(crate) fn keep_signer(&self, keep: &mut HashSet<ObjectRef>, key: ObjectRef) -> Result<()> {
22123×
        keep.insert(key);
22223×
        if let Some(c) = self.store.certificate_of(&key)? {
2233×
            keep.insert(c);
2243×
            if let Ok(cert) = self.store.get_certificate(&c) {
2253×
                keep.insert(cert.cert.issuer);
2263×
            }
22720×
        }
22823×
        Ok(())
22923×
    }
230
}