diff --git a/crates/forge-git/src/browse.rs b/crates/forge-git/src/browse.rs index 52b06dc..9d8b12b 100644 --- a/crates/forge-git/src/browse.rs +++ b/crates/forge-git/src/browse.rs @@ -216,9 +216,52 @@ fn resolve_hex(repo: &gix::Repository, hex: &str) -> Result> { let prefix = gix::hash::Prefix::from_hex(&lower).map_err(gerr)?; let outcome = repo.objects.lookup_prefix(prefix, None).map_err(gerr)?; match outcome { - Some(Ok(id)) if is_commit(repo, id)? => Ok(Some(id.to_hex().to_string())), - _ => Ok(None), // missing, ambiguous, or not a commit + Some(Ok(id)) if is_commit(repo, id)? && reachable(repo, id)? => { + Ok(Some(id.to_hex().to_string())) + } + _ => Ok(None), // missing, ambiguous, overwritten, or not a commit + } +} + +/// The refs whose history is public. A commit no ref here reaches was overwritten or deleted. +const VISIBLE_REFS: [&str; 3] = ["refs/heads/", "refs/tags/", "refs/pull/"]; + +/// True when a branch, tag or pull request reaches `id`. Other commits stay on disk until +/// `maintenance::prune_unreachable` runs, and must not be served by hash until then. +fn reachable(repo: &gix::Repository, id: gix::ObjectId) -> Result { + let refs = repo.references().map_err(gerr)?; + let mut tips = Vec::new(); + for prefix in VISIBLE_REFS { + for reference in refs.prefixed(prefix).map_err(gerr)? { + let mut reference = reference.map_err(gerr)?; + // A ref that does not peel to a commit reaches nothing. + if let Ok(tip) = reference.peel_to_id() { + let tip = tip.detach(); + if tip == id { + return Ok(true); + } + if is_commit(repo, tip)? { + tips.push(tip); + } + } + } + } + if tips.is_empty() { + return Ok(false); + } + for info in repo.rev_walk(tips).all().map_err(gerr)? { + if info.map_err(gerr)?.id == id { + return Ok(true); + } } + Ok(false) +} + +/// True when `oid` is a full commit id that a branch, tag or pull request reaches. +pub fn commit_reachable(repo: &Path, oid: &str) -> Result { + let repo = open(repo)?; + let id = parse_oid(oid)?; + Ok(is_commit(&repo, id)? && reachable(&repo, id)?) } /// Split `"feature/x/src/main.rs"` into `("feature/x", commit, "src/main.rs")`. The longest existing diff --git a/crates/forge-git/src/maintenance.rs b/crates/forge-git/src/maintenance.rs index 7c5500e..15d7359 100644 --- a/crates/forge-git/src/maintenance.rs +++ b/crates/forge-git/src/maintenance.rs @@ -1,13 +1,28 @@ -//! Post-push housekeeping for a bare repository: commit-graph refresh and `git maintenance --auto`. +//! Post-push housekeeping for a bare repository: commit-graph refresh and `git maintenance --auto`, +//! and removing what a force push or a deleted ref left behind. +use std::fs; use std::path::Path; -use std::time::Duration; +use std::time::{Duration, SystemTime}; use crate::command::{GitCommand, GitEnv}; use crate::error::{Error, Result}; /// Upper bound for each git invocation. The child is killed when the timeout fires. const STEP_TIMEOUT: Duration = Duration::from_secs(120); +/// Upper bound for one prune, which repacks the repo. +const PRUNE_TIMEOUT: Duration = Duration::from_secs(30 * 60); +/// Written in the bare repo when history was overwritten or deleted. A file, so a restart keeps it. +const PRUNE_MARK: &str = "forge-prune-due"; +/// Touched after each prune. +const PRUNE_STAMP: &str = "forge-pruned"; +/// A push's objects are unreachable for a moment before its ref lands, so only objects at least +/// this old are removed. The mark waits this long too, so everything it stands for qualifies. +const PRUNE_GRACE: Duration = Duration::from_secs(15 * 60); +/// The `git gc` flag for [`PRUNE_GRACE`]. +pub const PRUNE_AFTER_GRACE: &str = "--prune=900.seconds.ago"; +/// Every repo is pruned this often, for what no mark covers: mirrors and a fork's old pull heads. +const PRUNE_EVERY: Duration = Duration::from_secs(7 * 24 * 60 * 60); /// Refreshes the commit-graph (with changed-path filters) and runs the auto maintenance tasks /// for the bare repo at `repo`. Each step is bounded by [`STEP_TIMEOUT`]. @@ -27,6 +42,55 @@ pub async fn after_push(env: &GitEnv, repo: &Path) -> Result<()> { run_bounded(maintenance).await } +/// Records that `repo` has overwritten or deleted history to remove. Best effort: a missed mark +/// waits for the weekly prune. +pub fn mark_prune_due(repo: &Path) { + let _ = fs::write(repo.join(PRUNE_MARK), b""); +} + +/// True when `repo` should be pruned now: its mark is past the grace period, or it was not pruned +/// in the last week, which includes never. +pub fn prune_due(repo: &Path, now: SystemTime) -> bool { + let age = |name: &str| { + let modified = fs::metadata(repo.join(name)) + .and_then(|m| m.modified()) + .ok()?; + Some(now.duration_since(modified).unwrap_or_default()) + }; + age(PRUNE_MARK).is_some_and(|mark| mark >= PRUNE_GRACE) + || age(PRUNE_STAMP).is_none_or(|stamp| stamp >= PRUNE_EVERY) +} + +/// Deletes the objects no ref reaches, of the age `prune` names. A hash overwritten by a force push +/// or left by a deleted ref can then no longer be fetched, which git would otherwise allow. +pub async fn prune_unreachable(env: &GitEnv, repo: &Path, prune: &'static str) -> Result<()> { + let marked = fs::metadata(repo.join(PRUNE_MARK)).and_then(|m| m.modified()); + let gc = GitCommand::new(env, "gc") + .git_dir(repo) + .arg("--quiet") + .arg(prune); + match tokio::time::timeout(PRUNE_TIMEOUT, gc.status()).await { + Ok(result) => result?, + Err(_) => { + return Err(Error::Failed(format!( + "timed out after {}s", + PRUNE_TIMEOUT.as_secs() + ))); + } + } + fs::write(repo.join(PRUNE_STAMP), b"")?; + // A mark written during the prune stays for the next pass. + if let Ok(marked) = marked + && fs::metadata(repo.join(PRUNE_MARK)) + .and_then(|m| m.modified()) + .ok() + == Some(marked) + { + let _ = fs::remove_file(repo.join(PRUNE_MARK)); + } + Ok(()) +} + /// Runs `cmd` with [`STEP_TIMEOUT`]. Dropping the future on timeout drops the child, /// which `GitCommand` spawns with `kill_on_drop`, so the process is killed. async fn run_bounded(cmd: GitCommand) -> Result<()> { @@ -101,4 +165,61 @@ mod tests { // A second run on an unchanged repo must also succeed. after_push(&env, &bare).await.expect("second after_push"); } + + #[tokio::test] + async fn overwritten_commits_stop_resolving_then_are_removed() { + use crate::browse::{commit_reachable, resolve_commit}; + + let tmp = tempfile::tempdir().expect("tempdir"); + let env = env_for(tmp.path()); + let bare = tmp.path().join("repo.git"); + init_bare(&env, &bare, "main").await.expect("init bare"); + let work = tmp.path().join("work"); + std::fs::create_dir(&work).expect("mkdir work"); + git(&work, &["init", "-b", "main"]); + let bare_str = bare.to_str().expect("utf8 path"); + for text in ["one", "two"] { + std::fs::write(work.join("file.txt"), text).expect("write"); + git(&work, &["add", "file.txt"]); + git(&work, &["commit", "-m", text]); + } + git(&work, &["push", bare_str, "main"]); + let rev = |name: &str| { + let out = std::process::Command::new("git") + .arg("-C") + .arg(&work) + .args(["rev-parse", name]) + .output() + .expect("rev-parse"); + String::from_utf8_lossy(&out.stdout).trim().to_owned() + }; + let old = rev("HEAD"); + assert_eq!(resolve_commit(&bare, &old[..8]).unwrap(), Some(old.clone())); + + git(&work, &["reset", "--hard", "HEAD~1"]); + git(&work, &["push", "--force", bare_str, "main"]); + assert_eq!(resolve_commit(&bare, &old).unwrap(), None); + assert!(!commit_reachable(&bare, &old).unwrap()); + + // A pull request's ref keeps its commit visible and on disk. + git(&bare, &["update-ref", "refs/pull/1/head", &old]); + assert_eq!(resolve_commit(&bare, &old).unwrap(), Some(old.clone())); + git(&bare, &["update-ref", "-d", "refs/pull/1/head"]); + + mark_prune_due(&bare); + assert!(prune_due(&bare, SystemTime::now() + PRUNE_GRACE)); + prune_unreachable(&env, &bare, "--prune=now") + .await + .expect("prune"); + assert!(!prune_due(&bare, SystemTime::now() + PRUNE_GRACE)); + + let gone = std::process::Command::new("git") + .arg("-C") + .arg(&bare) + .args(["cat-file", "-e", &old]) + .status() + .expect("cat-file"); + assert!(!gone.success(), "the overwritten commit is still on disk"); + assert_eq!(resolve_commit(&bare, "main").unwrap(), Some(rev("HEAD"))); + } } diff --git a/crates/forge-git/src/pulls.rs b/crates/forge-git/src/pulls.rs index cbccb1e..4530fb4 100644 --- a/crates/forge-git/src/pulls.rs +++ b/crates/forge-git/src/pulls.rs @@ -396,6 +396,7 @@ pub async fn update_ref_cas( .user_arg(old)?; let out = run_raw(cmd, None).await?; if out.status.success() { + crate::maintenance::mark_prune_due(repo); return Ok(()); } let stderr = String::from_utf8_lossy(&out.stderr); diff --git a/crates/forge-git/src/tags.rs b/crates/forge-git/src/tags.rs index a4d3286..a04fe95 100644 --- a/crates/forge-git/src/tags.rs +++ b/crates/forge-git/src/tags.rs @@ -75,6 +75,10 @@ pub async fn move_lightweight_tag( { Err(Error::RefMoved(refname)) } + Ok(()) => { + crate::maintenance::mark_prune_due(repo); + Ok(()) + } other => other, } } @@ -111,22 +115,6 @@ pub async fn previous_tag( Ok(Some((name, commit))) } -/// True when `oid` is a full object id that names a commit in the repo. A malformed id or a -/// missing object is `false`, so this is safe to use on user input. -pub async fn commit_exists(env: &GitEnv, repo: &Path, oid: &str) -> bool { - if validate_oid(oid).is_err() { - return false; - } - match git(env, "cat-file") - .git_dir(repo) - .arg("-e") - .user_arg(&format!("{oid}^{{commit}}")) - { - Ok(cmd) => cmd.status().await.is_ok(), - Err(_) => false, - } -} - #[cfg(test)] mod tests { use super::valid_tag_name; diff --git a/crates/forge-web/src/api/mod.rs b/crates/forge-web/src/api/mod.rs index 95a4b4a..3de7b17 100644 --- a/crates/forge-web/src/api/mod.rs +++ b/crates/forge-web/src/api/mod.rs @@ -211,13 +211,13 @@ pub fn repo_dir(state: &AppState, repo: &Repo) -> Result { forge_git::repo::repo_path(&state.config.data_dir, &repo.id).map_err(internal) } -/// True when `sha` names a commit in the repo. Runs the git read off the async runtime. +/// True when `sha` names a commit a branch, tag or pull request reaches. Runs the git read off the +/// async runtime. pub async fn commit_exists(path: PathBuf, sha: String) -> Result { - let found = tokio::task::spawn_blocking(move || browse::read_commit(&path, &sha)) + tokio::task::spawn_blocking(move || browse::commit_reachable(&path, &sha)) .await .map_err(internal)? - .map_err(internal)?; - Ok(found.is_some()) + .map_err(internal) } /// Lowercases a full commit id. `None` unless it is 40 or 64 hex characters. diff --git a/crates/forge-web/src/boot.rs b/crates/forge-web/src/boot.rs index 755cf04..6f396e5 100644 --- a/crates/forge-web/src/boot.rs +++ b/crates/forge-web/src/boot.rs @@ -161,6 +161,7 @@ pub async fn serve( } crate::alerts::on_boot(&state).await; crate::ci::reaper::spawn(state.clone()); + crate::prune::spawn(state.clone()); crate::pages::admin_health::spawn_repo_size(state.clone()); crate::ci::scheduled::spawn(state.clone()); diff --git a/crates/forge-web/src/internal.rs b/crates/forge-web/src/internal.rs index 22dc86c..0847357 100644 --- a/crates/forge-web/src/internal.rs +++ b/crates/forge-web/src/internal.rs @@ -506,6 +506,27 @@ pub fn trigger_maintenance(git: &Arc, repo_id: &str) { }); } +/// Marks the repo for pruning when the push deleted a ref or moved one to a commit that does not +/// contain its old one: that history is now unreachable. +async fn mark_rewrites(state: &AppState, req: &HookRequest) { + let Ok(repo_dir) = forge_git::repo::repo_path(&state.git.data_dir, &req.repo_id) else { + return; + }; + for update in &req.updates { + if is_zero_oid(&update.old) { + continue; + } + let kept = !is_zero_oid(&update.new) + && forge_git::pulls::is_ancestor(&state.git, &repo_dir, &update.old, &update.new) + .await + .unwrap_or(false); + if !kept { + forge_git::maintenance::mark_prune_due(&repo_dir); + return; + } + } +} + /// Runs `post_update::after_ref_update` for every ref the push updated. Errors are logged; the /// push itself is already accepted at this point. async fn after_push_refs(state: &AppState, req: &HookRequest) { @@ -517,6 +538,7 @@ async fn after_push_refs(state: &AppState, req: &HookRequest) { return; } }; + mark_rewrites(state, req).await; for update in &req.updates { if let Err(e) = after_ref_update( state, diff --git a/crates/forge-web/src/main.rs b/crates/forge-web/src/main.rs index 5df6f34..420689c 100644 --- a/crates/forge-web/src/main.rs +++ b/crates/forge-web/src/main.rs @@ -45,6 +45,7 @@ mod package_ops; mod packages_live; mod pages; mod post_update; +mod prune; mod pulls_sync; mod raw; mod release_ops; diff --git a/crates/forge-web/src/pages/repo_scrub.rs b/crates/forge-web/src/pages/repo_scrub.rs index d90260b..7c6052b 100644 --- a/crates/forge-web/src/pages/repo_scrub.rs +++ b/crates/forge-web/src/pages/repo_scrub.rs @@ -109,6 +109,11 @@ fn cache_put(repo: &RepoRow, oid: &str, lang: Lang, parts: Arc) { /// The parts for `oid`, from the cache or built now. None when the commit does not exist. async fn scrub_parts(state: &AppState, ctx: &RepoCtx, oid: &str) -> Result>> { let repo = &ctx.repo; + let path: PathBuf = ctx.path.clone(); + let commit = oid.to_owned(); + if !tokio::task::spawn_blocking(move || browse::commit_reachable(&path, &commit)).await?? { + return Ok(None); + } if let Some(hit) = cache_get(repo, oid, ctx.lang) { return Ok(Some(hit)); } diff --git a/crates/forge-web/src/prune.rs b/crates/forge-web/src/prune.rs new file mode 100644 index 0000000..d418d98 --- /dev/null +++ b/crates/forge-web/src/prune.rs @@ -0,0 +1,47 @@ +//! Removes overwritten and deleted history. Pages stop serving such a hash at once; this deletes +//! the objects themselves, one repo at a time, once the grace period has passed. + +use std::time::{Duration, SystemTime}; + +use forge_git::maintenance::{PRUNE_AFTER_GRACE, prune_due, prune_unreachable}; +use tokio::time::MissedTickBehavior; + +use crate::state::AppState; + +/// How often repos are checked for a due prune. +const SWEEP_EVERY: Duration = Duration::from_secs(5 * 60); + +/// Starts the prune task. It runs until the process exits. +pub fn spawn(state: AppState) { + tokio::spawn(run(state)); +} + +async fn run(state: AppState) { + let mut tick = tokio::time::interval(SWEEP_EVERY); + tick.set_missed_tick_behavior(MissedTickBehavior::Delay); + loop { + tick.tick().await; + sweep(&state).await; + } +} + +async fn sweep(state: &AppState) { + let ids = match state.store.all_repo_ids().await { + Ok(ids) => ids, + Err(e) => { + tracing::error!(error = %e, "prune: listing repos failed"); + return; + } + }; + for id in ids { + let Ok(dir) = forge_git::repo::repo_path(&state.git.data_dir, &id) else { + continue; + }; + if !dir.is_dir() || !prune_due(&dir, SystemTime::now()) { + continue; + } + if let Err(e) = prune_unreachable(&state.git, &dir, PRUNE_AFTER_GRACE).await { + tracing::error!(error = %e, repo_id = %id, "prune failed"); + } + } +} diff --git a/crates/forge-web/src/release_ops.rs b/crates/forge-web/src/release_ops.rs index 8a2df06..856727d 100644 --- a/crates/forge-web/src/release_ops.rs +++ b/crates/forge-web/src/release_ops.rs @@ -19,9 +19,7 @@ use forge_core::webhooks::WebhookEvent; use forge_core::{Repo, User}; use forge_git::browse::{self, RefInfo, RefKind}; use forge_git::repo::repo_path; -use forge_git::tags::{ - commit_exists, create_lightweight_tag, move_lightweight_tag, valid_tag_name, -}; +use forge_git::tags::{create_lightweight_tag, move_lightweight_tag, valid_tag_name}; use futures_util::{Stream, StreamExt}; use http::StatusCode; @@ -147,9 +145,8 @@ fn tag_oid(refs: &[RefInfo], tag: &str) -> Option { .map(|r| r.target.clone()) } -/// The commit a target names: a branch of the repo, or a full commit id that exists. +/// The commit a target names: a branch of the repo, or a full commit id that a ref reaches. async fn resolve_target( - state: &AppState, path: &Path, refs: &[RefInfo], target: &str, @@ -160,7 +157,9 @@ async fn resolve_target( { return Ok(branch.target.clone()); } - if commit_exists(&state.git, path, target).await { + let (repo, oid) = (path.to_owned(), target.to_owned()); + let reachable = tokio::task::spawn_blocking(move || browse::commit_reachable(&repo, &oid)); + if matches!(reachable.await, Ok(Ok(true))) { return Ok(target.to_owned()); } Err(ReleaseError::Invalid(format!( @@ -271,7 +270,7 @@ pub async fn create( .as_deref() .filter(|t| !t.is_empty()) .unwrap_or(&repo.default_branch); - let oid = resolve_target(state, &path, &refs, target).await?; + let oid = resolve_target(&path, &refs, target).await?; create_lightweight_tag(&state.git, &path, &input.tag, &oid).await?; fire_tag_hook(state, repo, actor, &input.tag, &zero_oid(oid.len()), &oid).await; oid @@ -335,7 +334,7 @@ pub async fn update( match tag_oid(&refs, &new_tag) { Some(existing) => { if let Some(target) = wanted - && resolve_target(state, &path, &refs, target).await? != existing + && resolve_target(&path, &refs, target).await? != existing { return Err(ReleaseError::Invalid(format!( "the tag {new_tag} already exists at another commit" @@ -345,7 +344,7 @@ pub async fn update( } None => { let oid = match wanted { - Some(target) => resolve_target(state, &path, &refs, target).await?, + Some(target) => resolve_target(&path, &refs, target).await?, None => release.target_oid.clone(), }; create_lightweight_tag(&state.git, &path, &new_tag, &oid).await?; @@ -359,7 +358,7 @@ pub async fn update( "published release tags can't be moved; pick a new tag".to_owned(), )); } - let oid = resolve_target(state, &path, &refs, target).await?; + let oid = resolve_target(&path, &refs, target).await?; match tag_oid(&refs, &release.tag) { Some(current) if current == oid => {} Some(current) => { diff --git a/crates/forge-web/tests/e2e/git_e2e.rs b/crates/forge-web/tests/e2e/git_e2e.rs index dcfba68..4279ac8 100644 --- a/crates/forge-web/tests/e2e/git_e2e.rs +++ b/crates/forge-web/tests/e2e/git_e2e.rs @@ -127,6 +127,15 @@ fn head_sha(repo: &Path) -> String { String::from_utf8_lossy(&out.stdout).trim().to_owned() } +/// True when a file called `name` exists anywhere under `dir`. +fn find_file(dir: &Path, name: &str) -> bool { + std::fs::read_dir(dir).is_ok_and(|entries| { + entries.flatten().any(|entry| { + entry.file_name() == name || (entry.path().is_dir() && find_file(&entry.path(), name)) + }) + }) +} + fn read(path: PathBuf) -> String { fs::read_to_string(&path).unwrap_or_else(|e| panic!("read {}: {e}", path.display())) } @@ -384,6 +393,52 @@ async fn git_end_to_end() { "main moved after rejected pushes: {remote_main}" ); + // A force push to another branch takes the old commit's page down and marks it for removal. + ok( + &git( + &pub_verify, + &["push", "origin", "HEAD:refs/heads/scratch"], + &[], + ), + "push scratch", + ); + let overwritten = head_sha(&pub_verify); + let page = format!("/tahinli/pub/commit/{overwritten}"); + assert_eq!( + http.get(&page, None).await.status, + 200, + "commit on a branch" + ); + ok( + &git( + &pub_verify, + &[ + "-c", + "commit.gpgsign=false", + "commit", + "--amend", + "-q", + "-m", + "rewritten again", + ], + &[], + ), + "amend again", + ); + ok( + &git(&pub_verify, &["push", "-f", "origin", "HEAD:scratch"], &[]), + "force-push scratch", + ); + assert_eq!( + http.get(&page, None).await.status, + 404, + "overwritten commit" + ); + assert!( + find_file(&dir, "forge-prune-due"), + "the force push marks the repo for pruning" + ); + // Negative: an SSH key that is not registered is refused. let rogue = dir.join("rogue"); gen_key(&rogue); diff --git a/docs/architecture.md b/docs/architecture.md index 4e20854..f7b2ac8 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -347,6 +347,10 @@ Written at boot by `write_managed_gitconfig()`. Keys: - `protocol.file.allow=user` - Later: `uploadpack.hideRefs` and `transfer.hideRefs` for internal refs (`refs/pull/*` as needed) +### 7.2.1 Overwritten and deleted history + +A commit is served by hash only if `refs/heads/*`, `refs/tags/*` or `refs/pull/*` reaches it (`browse::resolve_commit`, `browse::commit_reachable`). Protocol v2 fetches any object that exists, so the objects are removed too: a force push, a moved tag or a deleted ref writes `forge-prune-due` in the bare repo, and the `prune` task runs `git gc --prune` once the mark is 15 minutes old. The grace period protects a push whose objects landed before its ref. Every repo is also pruned weekly, which covers mirrors and a fork's old pull heads. + ### 7.3 Repo path layout `/repos///.git`, where `` is the lowercased ULID. Created with `git init --bare` through the builder. Renames are DB-only, because the path depends on the id, not the name.