| 1 | |
| 2 | |
| 3 | |
| 4 | use std::path::Path; |
| 5 | use std::time::{Duration, SystemTime}; |
| 6 | |
| 7 | use forge_git::browse::reachable_commits; |
| 8 | use forge_git::maintenance::{PRUNE_AFTER_GRACE, prune_due, prune_unreachable}; |
| 9 | use tokio::time::MissedTickBehavior; |
| 10 | |
| 11 | use crate::state::AppState; |
| 12 | |
| 13 | |
| 14 | const SWEEP_EVERY: Duration = Duration::from_secs(5 * 60); |
| 15 | |
| 16 | |
| 17 | pub fn spawn(state: AppState) { |
| 18 | tokio::spawn(run(state)); |
| 19 | } |
| 20 | |
| 21 | async fn run(state: AppState) { |
| 22 | let mut tick = tokio::time::interval(SWEEP_EVERY); |
| 23 | tick.set_missed_tick_behavior(MissedTickBehavior::Delay); |
| 24 | loop { |
| 25 | tick.tick().await; |
| 26 | sweep(&state).await; |
| 27 | } |
| 28 | } |
| 29 | |
| 30 | async fn sweep(state: &AppState) { |
| 31 | let ids = match state.store.all_repo_ids().await { |
| 32 | Ok(ids) => ids, |
| 33 | Err(e) => { |
| 34 | tracing::error!(error = %e, "prune: listing repos failed"); |
| 35 | return; |
| 36 | } |
| 37 | }; |
| 38 | for id in ids { |
| 39 | let Ok(dir) = forge_git::repo::repo_path(&state.git.data_dir, &id) else { |
| 40 | continue; |
| 41 | }; |
| 42 | if !dir.is_dir() || !prune_due(&dir, SystemTime::now()) { |
| 43 | continue; |
| 44 | } |
| 45 | match prune_unreachable(&state.git, &dir, PRUNE_AFTER_GRACE).await { |
| 46 | Ok(()) => { |
| 47 | |
| 48 | crate::replication::enqueue_repo(state, &id); |
| 49 | blank_unreachable_messages(state, &id, &dir).await; |
| 50 | } |
| 51 | Err(e) => tracing::error!(error = %e, repo_id = %id, "prune failed"), |
| 52 | } |
| 53 | } |
| 54 | } |
| 55 | |
| 56 | |
| 57 | |
| 58 | async fn blank_unreachable_messages(state: &AppState, repo_id: &str, dir: &Path) { |
| 59 | if let Err(e) = blank_unreachable_inner(state, repo_id, dir).await { |
| 60 | tracing::error!(error = %e, repo_id = %repo_id, "prune: blanking commit messages failed"); |
| 61 | } |
| 62 | } |
| 63 | |
| 64 | async fn blank_unreachable_inner( |
| 65 | state: &AppState, |
| 66 | repo_id: &str, |
| 67 | dir: &Path, |
| 68 | ) -> Result<(), String> { |
| 69 | let oids = state |
| 70 | .store |
| 71 | .coauthored_oids(repo_id) |
| 72 | .await |
| 73 | .map_err(|e| e.to_string())?; |
| 74 | if oids.is_empty() { |
| 75 | return Ok(()); |
| 76 | } |
| 77 | let repo = dir.to_path_buf(); |
| 78 | let check = oids.clone(); |
| 79 | let reachable = tokio::task::spawn_blocking(move || reachable_commits(&repo, &check)) |
| 80 | .await |
| 81 | .map_err(|e| e.to_string())? |
| 82 | .map_err(|e| e.to_string())?; |
| 83 | let gone: Vec<String> = oids |
| 84 | .into_iter() |
| 85 | .filter(|oid| !reachable.contains(oid)) |
| 86 | .collect(); |
| 87 | if gone.is_empty() { |
| 88 | return Ok(()); |
| 89 | } |
| 90 | state |
| 91 | .store |
| 92 | .blank_coauthored(repo_id, &gone) |
| 93 | .await |
| 94 | .map_err(|e| e.to_string()) |
| 95 | } |