OXYGENHUB
# 4597750166e7 oxygenhub / crates / hub / src / maintenance.rs
3.8 KiB · Rust · last changed The nightly gc keeps Flow's artifacts 26 days ago source blame history raw
1
//! Housekeeping that runs on its own (hub spec §17.2): the nightly
2
//! garbage collection of every repository, one at a time under its
3
//! write lock, so a push never races a repack. `oxygenhub gc` runs the
4
//! same pass by hand.
5
6
use crate::db;
7
use crate::repos::RepoName;
8
use crate::Shared;
9
10
/// What one repository's gc did, for the log and `oxygenhub gc`.
11
#[derive(Clone, Debug)]
12
pub struct Done {
13
    pub repo: String,
14
    pub failed: bool,
15
    pub summary: String,
16
}
17
18
impl std::fmt::Display for Done {
19
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
20
        write!(f, "{}: {}", self.repo, self.summary)
21
    }
22
}
23
24
/// Garbage-collect every repository, in turn. A repository that fails is
25
/// reported and the rest still run.
26
pub async fn gc_all(app: &Shared) -> Vec<Done> {
27
    let rows = match db::repos::list(&app.db).await {
28
        Ok(rows) => rows,
29
        Err(e) => {
30
            tracing::warn!("gc: listing repositories: {e}");
31
            return Vec::new();
32
        }
33
    };
34
    let mut done = Vec::with_capacity(rows.len());
35
    for row in rows {
36
        let slug = format!("{}/{}", row.owner, row.name);
37
        let Some(name) = RepoName::new(&row.owner, &row.name) else { continue };
38
        if !app.repos.exists(&name) {
39
            continue;
40
        }
41
        let label = slug.clone();
42
        // Flow's artifacts are named only in the database: kept as roots,
43
        // or gc would prune them after the grace period (#126). A listing
44
        // that fails skips this repository rather than risk them.
45
        let keep: Vec<oxy_core::hash::ObjectRef> = match db::flow::artifact_blobs(&app.db, row.id).await {
46
            Ok(blobs) => blobs.iter().filter_map(|b| oxy_core::hash::ObjectRef::from_hex(b)).collect(),
47
            Err(e) => {
48
                tracing::warn!("gc: {slug}: listing its artifacts: {e}; skipped");
49
                continue;
50
            }
51
        };
52
        let started = std::time::Instant::now();
53
        let result = app
54
            .repos
55
            .write(&name, move |repo, _| Ok(repo.gc_keeping(false, &keep, &mut |phase| tracing::debug!("gc {label}: {phase}"))?))
56
            .await;
57
        let d = match result {
58
            Ok(r) => Done {
59
                summary: format!(
60
                    "{} reachable; pruned {} ({} bytes){}; packed {} into one pack in {:.1} s",
61
                    r.reachable,
62
                    r.pruned.objects,
63
                    r.pruned.bytes,
64
                    if r.pruned.deferred > 0 { format!(", {} deferred by the grace period", r.pruned.deferred) } else { String::new() },
65
                    r.packed.objects,
66
                    started.elapsed().as_secs_f64()
67
                ),
68
                repo: slug,
69
                failed: false,
70
            },
71
            Err(e) => Done { summary: format!("failed: {e}"), repo: slug, failed: true },
72
        };
73
        if d.failed {
74
            tracing::warn!("gc {}", d);
75
        } else {
76
            tracing::info!("gc {}", d);
77
        }
78
        done.push(d);
79
    }
80
    done
81
}
82
83
/// Run [`gc_all`] once a day at `retention.gc_hour` UTC.
84
pub async fn nightly(app: Shared) {
85
    let hour = app.config.retention.gc_hour;
86
    if hour >= 24 {
87
        tracing::info!("gc: the nightly run is off (retention.gc_hour = {hour})");
88
        return;
89
    }
90
    let mut last_day = None;
91
    loop {
92
        tokio::time::sleep(std::time::Duration::from_secs(60)).await;
93
        let now = time::OffsetDateTime::now_utc();
94
        if u32::from(now.hour()) != hour {
95
            continue;
96
        }
97
        let day = now.date();
98
        if last_day == Some(day) {
99
            continue;
100
        }
101
        last_day = Some(day);
102
        let done = gc_all(&app).await;
103
        tracing::info!("gc: nightly run over {} repositories, {} failed", done.len(), done.iter().filter(|d| d.failed).count());
104
    }
105
}