🔥 remove: overwritten and deleted history is gone: a hash that no branch, tag or pull request reaches gets a 404 on every page and in the API at once, and its objects are deleted 15 minutes later, so it cannot be fetched by hash either; every repo is also pruned once on boot and then weekly
Browse files at this commit046e0947d83bbf6bd8bf1e068ffd95f742c51c2bParent: 6b26e8213 changed files +321 -34
- crates/forge-git/src/browse.rs +45 -2
- crates/forge-git/src/maintenance.rs +123 -2
- crates/forge-git/src/pulls.rs +1 -0
- crates/forge-git/src/tags.rs +4 -16
- crates/forge-web/src/api/mod.rs +4 -4
- crates/forge-web/src/boot.rs +1 -0
- crates/forge-web/src/internal.rs +22 -0
- crates/forge-web/src/main.rs +1 -0
- crates/forge-web/src/pages/repo_scrub.rs +5 -0
- crates/forge-web/src/prune.rs +47 -0
- crates/forge-web/src/release_ops.rs +9 -10
- crates/forge-web/tests/e2e/git_e2e.rs +55 -0
- docs/architecture.md +4 -0
crates/forge-git/src/browse.rsmodified+45 -2
| @@ -216,9 +216,52 @@ fn resolve_hex(repo: &gix::Repository, hex: &str) -> Result<Option<String>> { | |||
| 216 | let prefix = gix::hash::Prefix::from_hex(&lower).map_err(gerr)?; | 216 | let prefix = gix::hash::Prefix::from_hex(&lower).map_err(gerr)?; |
| 217 | let outcome = repo.objects.lookup_prefix(prefix, None).map_err(gerr)?; | 217 | let outcome = repo.objects.lookup_prefix(prefix, None).map_err(gerr)?; |
| 218 | match outcome { | 218 | match outcome { |
| 219 | - Some(Ok(id)) if is_commit(repo, id)? => Ok(Some(id.to_hex().to_string())), | 219 | + Some(Ok(id)) if is_commit(repo, id)? && reachable(repo, id)? => { |
| 220 | - _ => Ok(None), // missing, ambiguous, or not a commit | 220 | + Ok(Some(id.to_hex().to_string())) |
| 221 | + } | ||
| 222 | + _ => Ok(None), // missing, ambiguous, overwritten, or not a commit | ||
| 223 | + } | ||
| 224 | +} | ||
| 225 | + | ||
| 226 | +/// The refs whose history is public. A commit no ref here reaches was overwritten or deleted. | ||
| 227 | +const VISIBLE_REFS: [&str; 3] = ["refs/heads/", "refs/tags/", "refs/pull/"]; | ||
| 228 | + | ||
| 229 | +/// True when a branch, tag or pull request reaches `id`. Other commits stay on disk until | ||
| 230 | +/// `maintenance::prune_unreachable` runs, and must not be served by hash until then. | ||
| 231 | +fn reachable(repo: &gix::Repository, id: gix::ObjectId) -> Result<bool> { | ||
| 232 | + let refs = repo.references().map_err(gerr)?; | ||
| 233 | + let mut tips = Vec::new(); | ||
| 234 | + for prefix in VISIBLE_REFS { | ||
| 235 | + for reference in refs.prefixed(prefix).map_err(gerr)? { | ||
| 236 | + let mut reference = reference.map_err(gerr)?; | ||
| 237 | + // A ref that does not peel to a commit reaches nothing. | ||
| 238 | + if let Ok(tip) = reference.peel_to_id() { | ||
| 239 | + let tip = tip.detach(); | ||
| 240 | + if tip == id { | ||
| 241 | + return Ok(true); | ||
| 242 | + } | ||
| 243 | + if is_commit(repo, tip)? { | ||
| 244 | + tips.push(tip); | ||
| 245 | + } | ||
| 246 | + } | ||
| 247 | + } | ||
| 248 | + } | ||
| 249 | + if tips.is_empty() { | ||
| 250 | + return Ok(false); | ||
| 251 | + } | ||
| 252 | + for info in repo.rev_walk(tips).all().map_err(gerr)? { | ||
| 253 | + if info.map_err(gerr)?.id == id { | ||
| 254 | + return Ok(true); | ||
| 255 | + } | ||
| 221 | } | 256 | } |
| 257 | + Ok(false) | ||
| 258 | +} | ||
| 259 | + | ||
| 260 | +/// True when `oid` is a full commit id that a branch, tag or pull request reaches. | ||
| 261 | +pub fn commit_reachable(repo: &Path, oid: &str) -> Result<bool> { | ||
| 262 | + let repo = open(repo)?; | ||
| 263 | + let id = parse_oid(oid)?; | ||
| 264 | + Ok(is_commit(&repo, id)? && reachable(&repo, id)?) | ||
| 222 | } | 265 | } |
| 223 | 266 | ||
| 224 | /// Split `"feature/x/src/main.rs"` into `("feature/x", commit, "src/main.rs")`. The longest existing | 267 | /// Split `"feature/x/src/main.rs"` into `("feature/x", commit, "src/main.rs")`. The longest existing |
crates/forge-git/src/maintenance.rsmodified+123 -2
| @@ -1,13 +1,28 @@ | |||
| 1 | -//! Post-push housekeeping for a bare repository: commit-graph refresh and `git maintenance --auto`. | 1 | +//! Post-push housekeeping for a bare repository: commit-graph refresh and `git maintenance --auto`, |
| 2 | +//! and removing what a force push or a deleted ref left behind. | ||
| 2 | 3 | ||
| 4 | +use std::fs; | ||
| 3 | use std::path::Path; | 5 | use std::path::Path; |
| 4 | -use std::time::Duration; | 6 | +use std::time::{Duration, SystemTime}; |
| 5 | 7 | ||
| 6 | use crate::command::{GitCommand, GitEnv}; | 8 | use crate::command::{GitCommand, GitEnv}; |
| 7 | use crate::error::{Error, Result}; | 9 | use crate::error::{Error, Result}; |
| 8 | 10 | ||
| 9 | /// Upper bound for each git invocation. The child is killed when the timeout fires. | 11 | /// Upper bound for each git invocation. The child is killed when the timeout fires. |
| 10 | const STEP_TIMEOUT: Duration = Duration::from_secs(120); | 12 | const STEP_TIMEOUT: Duration = Duration::from_secs(120); |
| 13 | +/// Upper bound for one prune, which repacks the repo. | ||
| 14 | +const PRUNE_TIMEOUT: Duration = Duration::from_secs(30 * 60); | ||
| 15 | +/// Written in the bare repo when history was overwritten or deleted. A file, so a restart keeps it. | ||
| 16 | +const PRUNE_MARK: &str = "forge-prune-due"; | ||
| 17 | +/// Touched after each prune. | ||
| 18 | +const PRUNE_STAMP: &str = "forge-pruned"; | ||
| 19 | +/// A push's objects are unreachable for a moment before its ref lands, so only objects at least | ||
| 20 | +/// this old are removed. The mark waits this long too, so everything it stands for qualifies. | ||
| 21 | +const PRUNE_GRACE: Duration = Duration::from_secs(15 * 60); | ||
| 22 | +/// The `git gc` flag for [`PRUNE_GRACE`]. | ||
| 23 | +pub const PRUNE_AFTER_GRACE: &str = "--prune=900.seconds.ago"; | ||
| 24 | +/// Every repo is pruned this often, for what no mark covers: mirrors and a fork's old pull heads. | ||
| 25 | +const PRUNE_EVERY: Duration = Duration::from_secs(7 * 24 * 60 * 60); | ||
| 11 | 26 | ||
| 12 | /// Refreshes the commit-graph (with changed-path filters) and runs the auto maintenance tasks | 27 | /// Refreshes the commit-graph (with changed-path filters) and runs the auto maintenance tasks |
| 13 | /// for the bare repo at `repo`. Each step is bounded by [`STEP_TIMEOUT`]. | 28 | /// 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<()> { | |||
| 27 | run_bounded(maintenance).await | 42 | run_bounded(maintenance).await |
| 28 | } | 43 | } |
| 29 | 44 | ||
| 45 | +/// Records that `repo` has overwritten or deleted history to remove. Best effort: a missed mark | ||
| 46 | +/// waits for the weekly prune. | ||
| 47 | +pub fn mark_prune_due(repo: &Path) { | ||
| 48 | + let _ = fs::write(repo.join(PRUNE_MARK), b""); | ||
| 49 | +} | ||
| 50 | + | ||
| 51 | +/// True when `repo` should be pruned now: its mark is past the grace period, or it was not pruned | ||
| 52 | +/// in the last week, which includes never. | ||
| 53 | +pub fn prune_due(repo: &Path, now: SystemTime) -> bool { | ||
| 54 | + let age = |name: &str| { | ||
| 55 | + let modified = fs::metadata(repo.join(name)) | ||
| 56 | + .and_then(|m| m.modified()) | ||
| 57 | + .ok()?; | ||
| 58 | + Some(now.duration_since(modified).unwrap_or_default()) | ||
| 59 | + }; | ||
| 60 | + age(PRUNE_MARK).is_some_and(|mark| mark >= PRUNE_GRACE) | ||
| 61 | + || age(PRUNE_STAMP).is_none_or(|stamp| stamp >= PRUNE_EVERY) | ||
| 62 | +} | ||
| 63 | + | ||
| 64 | +/// Deletes the objects no ref reaches, of the age `prune` names. A hash overwritten by a force push | ||
| 65 | +/// or left by a deleted ref can then no longer be fetched, which git would otherwise allow. | ||
| 66 | +pub async fn prune_unreachable(env: &GitEnv, repo: &Path, prune: &'static str) -> Result<()> { | ||
| 67 | + let marked = fs::metadata(repo.join(PRUNE_MARK)).and_then(|m| m.modified()); | ||
| 68 | + let gc = GitCommand::new(env, "gc") | ||
| 69 | + .git_dir(repo) | ||
| 70 | + .arg("--quiet") | ||
| 71 | + .arg(prune); | ||
| 72 | + match tokio::time::timeout(PRUNE_TIMEOUT, gc.status()).await { | ||
| 73 | + Ok(result) => result?, | ||
| 74 | + Err(_) => { | ||
| 75 | + return Err(Error::Failed(format!( | ||
| 76 | + "timed out after {}s", | ||
| 77 | + PRUNE_TIMEOUT.as_secs() | ||
| 78 | + ))); | ||
| 79 | + } | ||
| 80 | + } | ||
| 81 | + fs::write(repo.join(PRUNE_STAMP), b"")?; | ||
| 82 | + // A mark written during the prune stays for the next pass. | ||
| 83 | + if let Ok(marked) = marked | ||
| 84 | + && fs::metadata(repo.join(PRUNE_MARK)) | ||
| 85 | + .and_then(|m| m.modified()) | ||
| 86 | + .ok() | ||
| 87 | + == Some(marked) | ||
| 88 | + { | ||
| 89 | + let _ = fs::remove_file(repo.join(PRUNE_MARK)); | ||
| 90 | + } | ||
| 91 | + Ok(()) | ||
| 92 | +} | ||
| 93 | + | ||
| 30 | /// Runs `cmd` with [`STEP_TIMEOUT`]. Dropping the future on timeout drops the child, | 94 | /// Runs `cmd` with [`STEP_TIMEOUT`]. Dropping the future on timeout drops the child, |
| 31 | /// which `GitCommand` spawns with `kill_on_drop`, so the process is killed. | 95 | /// which `GitCommand` spawns with `kill_on_drop`, so the process is killed. |
| 32 | async fn run_bounded(cmd: GitCommand) -> Result<()> { | 96 | async fn run_bounded(cmd: GitCommand) -> Result<()> { |
| @@ -101,4 +165,61 @@ mod tests { | |||
| 101 | // A second run on an unchanged repo must also succeed. | 165 | // A second run on an unchanged repo must also succeed. |
| 102 | after_push(&env, &bare).await.expect("second after_push"); | 166 | after_push(&env, &bare).await.expect("second after_push"); |
| 103 | } | 167 | } |
| 168 | + | ||
| 169 | + #[tokio::test] | ||
| 170 | + async fn overwritten_commits_stop_resolving_then_are_removed() { | ||
| 171 | + use crate::browse::{commit_reachable, resolve_commit}; | ||
| 172 | + | ||
| 173 | + let tmp = tempfile::tempdir().expect("tempdir"); | ||
| 174 | + let env = env_for(tmp.path()); | ||
| 175 | + let bare = tmp.path().join("repo.git"); | ||
| 176 | + init_bare(&env, &bare, "main").await.expect("init bare"); | ||
| 177 | + let work = tmp.path().join("work"); | ||
| 178 | + std::fs::create_dir(&work).expect("mkdir work"); | ||
| 179 | + git(&work, &["init", "-b", "main"]); | ||
| 180 | + let bare_str = bare.to_str().expect("utf8 path"); | ||
| 181 | + for text in ["one", "two"] { | ||
| 182 | + std::fs::write(work.join("file.txt"), text).expect("write"); | ||
| 183 | + git(&work, &["add", "file.txt"]); | ||
| 184 | + git(&work, &["commit", "-m", text]); | ||
| 185 | + } | ||
| 186 | + git(&work, &["push", bare_str, "main"]); | ||
| 187 | + let rev = |name: &str| { | ||
| 188 | + let out = std::process::Command::new("git") | ||
| 189 | + .arg("-C") | ||
| 190 | + .arg(&work) | ||
| 191 | + .args(["rev-parse", name]) | ||
| 192 | + .output() | ||
| 193 | + .expect("rev-parse"); | ||
| 194 | + String::from_utf8_lossy(&out.stdout).trim().to_owned() | ||
| 195 | + }; | ||
| 196 | + let old = rev("HEAD"); | ||
| 197 | + assert_eq!(resolve_commit(&bare, &old[..8]).unwrap(), Some(old.clone())); | ||
| 198 | + | ||
| 199 | + git(&work, &["reset", "--hard", "HEAD~1"]); | ||
| 200 | + git(&work, &["push", "--force", bare_str, "main"]); | ||
| 201 | + assert_eq!(resolve_commit(&bare, &old).unwrap(), None); | ||
| 202 | + assert!(!commit_reachable(&bare, &old).unwrap()); | ||
| 203 | + | ||
| 204 | + // A pull request's ref keeps its commit visible and on disk. | ||
| 205 | + git(&bare, &["update-ref", "refs/pull/1/head", &old]); | ||
| 206 | + assert_eq!(resolve_commit(&bare, &old).unwrap(), Some(old.clone())); | ||
| 207 | + git(&bare, &["update-ref", "-d", "refs/pull/1/head"]); | ||
| 208 | + | ||
| 209 | + mark_prune_due(&bare); | ||
| 210 | + assert!(prune_due(&bare, SystemTime::now() + PRUNE_GRACE)); | ||
| 211 | + prune_unreachable(&env, &bare, "--prune=now") | ||
| 212 | + .await | ||
| 213 | + .expect("prune"); | ||
| 214 | + assert!(!prune_due(&bare, SystemTime::now() + PRUNE_GRACE)); | ||
| 215 | + | ||
| 216 | + let gone = std::process::Command::new("git") | ||
| 217 | + .arg("-C") | ||
| 218 | + .arg(&bare) | ||
| 219 | + .args(["cat-file", "-e", &old]) | ||
| 220 | + .status() | ||
| 221 | + .expect("cat-file"); | ||
| 222 | + assert!(!gone.success(), "the overwritten commit is still on disk"); | ||
| 223 | + assert_eq!(resolve_commit(&bare, "main").unwrap(), Some(rev("HEAD"))); | ||
| 224 | + } | ||
| 104 | } | 225 | } |
crates/forge-git/src/pulls.rsmodified+1 -0
| @@ -396,6 +396,7 @@ pub async fn update_ref_cas( | |||
| 396 | .user_arg(old)?; | 396 | .user_arg(old)?; |
| 397 | let out = run_raw(cmd, None).await?; | 397 | let out = run_raw(cmd, None).await?; |
| 398 | if out.status.success() { | 398 | if out.status.success() { |
| 399 | + crate::maintenance::mark_prune_due(repo); | ||
| 399 | return Ok(()); | 400 | return Ok(()); |
| 400 | } | 401 | } |
| 401 | let stderr = String::from_utf8_lossy(&out.stderr); | 402 | let stderr = String::from_utf8_lossy(&out.stderr); |
crates/forge-git/src/tags.rsmodified+4 -16
| @@ -75,6 +75,10 @@ pub async fn move_lightweight_tag( | |||
| 75 | { | 75 | { |
| 76 | Err(Error::RefMoved(refname)) | 76 | Err(Error::RefMoved(refname)) |
| 77 | } | 77 | } |
| 78 | + Ok(()) => { | ||
| 79 | + crate::maintenance::mark_prune_due(repo); | ||
| 80 | + Ok(()) | ||
| 81 | + } | ||
| 78 | other => other, | 82 | other => other, |
| 79 | } | 83 | } |
| 80 | } | 84 | } |
| @@ -111,22 +115,6 @@ pub async fn previous_tag( | |||
| 111 | Ok(Some((name, commit))) | 115 | Ok(Some((name, commit))) |
| 112 | } | 116 | } |
| 113 | 117 | ||
| 114 | -/// True when `oid` is a full object id that names a commit in the repo. A malformed id or a | ||
| 115 | -/// missing object is `false`, so this is safe to use on user input. | ||
| 116 | -pub async fn commit_exists(env: &GitEnv, repo: &Path, oid: &str) -> bool { | ||
| 117 | - if validate_oid(oid).is_err() { | ||
| 118 | - return false; | ||
| 119 | - } | ||
| 120 | - match git(env, "cat-file") | ||
| 121 | - .git_dir(repo) | ||
| 122 | - .arg("-e") | ||
| 123 | - .user_arg(&format!("{oid}^{{commit}}")) | ||
| 124 | - { | ||
| 125 | - Ok(cmd) => cmd.status().await.is_ok(), | ||
| 126 | - Err(_) => false, | ||
| 127 | - } | ||
| 128 | -} | ||
| 129 | - | ||
| 130 | #[cfg(test)] | 118 | #[cfg(test)] |
| 131 | mod tests { | 119 | mod tests { |
| 132 | use super::valid_tag_name; | 120 | use super::valid_tag_name; |
crates/forge-web/src/api/mod.rsmodified+4 -4
| @@ -211,13 +211,13 @@ pub fn repo_dir(state: &AppState, repo: &Repo) -> Result<PathBuf, Refusal> { | |||
| 211 | forge_git::repo::repo_path(&state.config.data_dir, &repo.id).map_err(internal) | 211 | forge_git::repo::repo_path(&state.config.data_dir, &repo.id).map_err(internal) |
| 212 | } | 212 | } |
| 213 | 213 | ||
| 214 | -/// True when `sha` names a commit in the repo. Runs the git read off the async runtime. | 214 | +/// True when `sha` names a commit a branch, tag or pull request reaches. Runs the git read off the |
| 215 | +/// async runtime. | ||
| 215 | pub async fn commit_exists(path: PathBuf, sha: String) -> Result<bool, Refusal> { | 216 | pub async fn commit_exists(path: PathBuf, sha: String) -> Result<bool, Refusal> { |
| 216 | - let found = tokio::task::spawn_blocking(move || browse::read_commit(&path, &sha)) | 217 | + tokio::task::spawn_blocking(move || browse::commit_reachable(&path, &sha)) |
| 217 | .await | 218 | .await |
| 218 | .map_err(internal)? | 219 | .map_err(internal)? |
| 219 | - .map_err(internal)?; | 220 | + .map_err(internal) |
| 220 | - Ok(found.is_some()) | ||
| 221 | } | 221 | } |
| 222 | 222 | ||
| 223 | /// Lowercases a full commit id. `None` unless it is 40 or 64 hex characters. | 223 | /// Lowercases a full commit id. `None` unless it is 40 or 64 hex characters. |
crates/forge-web/src/boot.rsmodified+1 -0
| @@ -161,6 +161,7 @@ pub async fn serve( | |||
| 161 | } | 161 | } |
| 162 | crate::alerts::on_boot(&state).await; | 162 | crate::alerts::on_boot(&state).await; |
| 163 | crate::ci::reaper::spawn(state.clone()); | 163 | crate::ci::reaper::spawn(state.clone()); |
| 164 | + crate::prune::spawn(state.clone()); | ||
| 164 | crate::pages::admin_health::spawn_repo_size(state.clone()); | 165 | crate::pages::admin_health::spawn_repo_size(state.clone()); |
| 165 | crate::ci::scheduled::spawn(state.clone()); | 166 | crate::ci::scheduled::spawn(state.clone()); |
| 166 | 167 | ||
crates/forge-web/src/internal.rsmodified+22 -0
| @@ -506,6 +506,27 @@ pub fn trigger_maintenance(git: &Arc<GitEnv>, repo_id: &str) { | |||
| 506 | }); | 506 | }); |
| 507 | } | 507 | } |
| 508 | 508 | ||
| 509 | +/// Marks the repo for pruning when the push deleted a ref or moved one to a commit that does not | ||
| 510 | +/// contain its old one: that history is now unreachable. | ||
| 511 | +async fn mark_rewrites(state: &AppState, req: &HookRequest) { | ||
| 512 | + let Ok(repo_dir) = forge_git::repo::repo_path(&state.git.data_dir, &req.repo_id) else { | ||
| 513 | + return; | ||
| 514 | + }; | ||
| 515 | + for update in &req.updates { | ||
| 516 | + if is_zero_oid(&update.old) { | ||
| 517 | + continue; | ||
| 518 | + } | ||
| 519 | + let kept = !is_zero_oid(&update.new) | ||
| 520 | + && forge_git::pulls::is_ancestor(&state.git, &repo_dir, &update.old, &update.new) | ||
| 521 | + .await | ||
| 522 | + .unwrap_or(false); | ||
| 523 | + if !kept { | ||
| 524 | + forge_git::maintenance::mark_prune_due(&repo_dir); | ||
| 525 | + return; | ||
| 526 | + } | ||
| 527 | + } | ||
| 528 | +} | ||
| 529 | + | ||
| 509 | /// Runs `post_update::after_ref_update` for every ref the push updated. Errors are logged; the | 530 | /// Runs `post_update::after_ref_update` for every ref the push updated. Errors are logged; the |
| 510 | /// push itself is already accepted at this point. | 531 | /// push itself is already accepted at this point. |
| 511 | async fn after_push_refs(state: &AppState, req: &HookRequest) { | 532 | async fn after_push_refs(state: &AppState, req: &HookRequest) { |
| @@ -517,6 +538,7 @@ async fn after_push_refs(state: &AppState, req: &HookRequest) { | |||
| 517 | return; | 538 | return; |
| 518 | } | 539 | } |
| 519 | }; | 540 | }; |
| 541 | + mark_rewrites(state, req).await; | ||
| 520 | for update in &req.updates { | 542 | for update in &req.updates { |
| 521 | if let Err(e) = after_ref_update( | 543 | if let Err(e) = after_ref_update( |
| 522 | state, | 544 | state, |
crates/forge-web/src/main.rsmodified+1 -0
| @@ -45,6 +45,7 @@ mod package_ops; | |||
| 45 | mod packages_live; | 45 | mod packages_live; |
| 46 | mod pages; | 46 | mod pages; |
| 47 | mod post_update; | 47 | mod post_update; |
| 48 | +mod prune; | ||
| 48 | mod pulls_sync; | 49 | mod pulls_sync; |
| 49 | mod raw; | 50 | mod raw; |
| 50 | mod release_ops; | 51 | mod release_ops; |
crates/forge-web/src/pages/repo_scrub.rsmodified+5 -0
| @@ -109,6 +109,11 @@ fn cache_put(repo: &RepoRow, oid: &str, lang: Lang, parts: Arc<Parts>) { | |||
| 109 | /// The parts for `oid`, from the cache or built now. None when the commit does not exist. | 109 | /// The parts for `oid`, from the cache or built now. None when the commit does not exist. |
| 110 | async fn scrub_parts(state: &AppState, ctx: &RepoCtx, oid: &str) -> Result<Option<Arc<Parts>>> { | 110 | async fn scrub_parts(state: &AppState, ctx: &RepoCtx, oid: &str) -> Result<Option<Arc<Parts>>> { |
| 111 | let repo = &ctx.repo; | 111 | let repo = &ctx.repo; |
| 112 | + let path: PathBuf = ctx.path.clone(); | ||
| 113 | + let commit = oid.to_owned(); | ||
| 114 | + if !tokio::task::spawn_blocking(move || browse::commit_reachable(&path, &commit)).await?? { | ||
| 115 | + return Ok(None); | ||
| 116 | + } | ||
| 112 | if let Some(hit) = cache_get(repo, oid, ctx.lang) { | 117 | if let Some(hit) = cache_get(repo, oid, ctx.lang) { |
| 113 | return Ok(Some(hit)); | 118 | return Ok(Some(hit)); |
| 114 | } | 119 | } |
crates/forge-web/src/prune.rsadded+47 -0
| @@ -0,0 +1,47 @@ | |||
| 1 | +//! Removes overwritten and deleted history. Pages stop serving such a hash at once; this deletes | ||
| 2 | +//! the objects themselves, one repo at a time, once the grace period has passed. | ||
| 3 | + | ||
| 4 | +use std::time::{Duration, SystemTime}; | ||
| 5 | + | ||
| 6 | +use forge_git::maintenance::{PRUNE_AFTER_GRACE, prune_due, prune_unreachable}; | ||
| 7 | +use tokio::time::MissedTickBehavior; | ||
| 8 | + | ||
| 9 | +use crate::state::AppState; | ||
| 10 | + | ||
| 11 | +/// How often repos are checked for a due prune. | ||
| 12 | +const SWEEP_EVERY: Duration = Duration::from_secs(5 * 60); | ||
| 13 | + | ||
| 14 | +/// Starts the prune task. It runs until the process exits. | ||
| 15 | +pub fn spawn(state: AppState) { | ||
| 16 | + tokio::spawn(run(state)); | ||
| 17 | +} | ||
| 18 | + | ||
| 19 | +async fn run(state: AppState) { | ||
| 20 | + let mut tick = tokio::time::interval(SWEEP_EVERY); | ||
| 21 | + tick.set_missed_tick_behavior(MissedTickBehavior::Delay); | ||
| 22 | + loop { | ||
| 23 | + tick.tick().await; | ||
| 24 | + sweep(&state).await; | ||
| 25 | + } | ||
| 26 | +} | ||
| 27 | + | ||
| 28 | +async fn sweep(state: &AppState) { | ||
| 29 | + let ids = match state.store.all_repo_ids().await { | ||
| 30 | + Ok(ids) => ids, | ||
| 31 | + Err(e) => { | ||
| 32 | + tracing::error!(error = %e, "prune: listing repos failed"); | ||
| 33 | + return; | ||
| 34 | + } | ||
| 35 | + }; | ||
| 36 | + for id in ids { | ||
| 37 | + let Ok(dir) = forge_git::repo::repo_path(&state.git.data_dir, &id) else { | ||
| 38 | + continue; | ||
| 39 | + }; | ||
| 40 | + if !dir.is_dir() || !prune_due(&dir, SystemTime::now()) { | ||
| 41 | + continue; | ||
| 42 | + } | ||
| 43 | + if let Err(e) = prune_unreachable(&state.git, &dir, PRUNE_AFTER_GRACE).await { | ||
| 44 | + tracing::error!(error = %e, repo_id = %id, "prune failed"); | ||
| 45 | + } | ||
| 46 | + } | ||
| 47 | +} | ||
crates/forge-web/src/release_ops.rsmodified+9 -10
| @@ -19,9 +19,7 @@ use forge_core::webhooks::WebhookEvent; | |||
| 19 | use forge_core::{Repo, User}; | 19 | use forge_core::{Repo, User}; |
| 20 | use forge_git::browse::{self, RefInfo, RefKind}; | 20 | use forge_git::browse::{self, RefInfo, RefKind}; |
| 21 | use forge_git::repo::repo_path; | 21 | use forge_git::repo::repo_path; |
| 22 | -use forge_git::tags::{ | 22 | +use forge_git::tags::{create_lightweight_tag, move_lightweight_tag, valid_tag_name}; |
| 23 | - commit_exists, create_lightweight_tag, move_lightweight_tag, valid_tag_name, | ||
| 24 | -}; | ||
| 25 | use futures_util::{Stream, StreamExt}; | 23 | use futures_util::{Stream, StreamExt}; |
| 26 | use http::StatusCode; | 24 | use http::StatusCode; |
| 27 | 25 | ||
| @@ -147,9 +145,8 @@ fn tag_oid(refs: &[RefInfo], tag: &str) -> Option<String> { | |||
| 147 | .map(|r| r.target.clone()) | 145 | .map(|r| r.target.clone()) |
| 148 | } | 146 | } |
| 149 | 147 | ||
| 150 | -/// The commit a target names: a branch of the repo, or a full commit id that exists. | 148 | +/// The commit a target names: a branch of the repo, or a full commit id that a ref reaches. |
| 151 | async fn resolve_target( | 149 | async fn resolve_target( |
| 152 | - state: &AppState, | ||
| 153 | path: &Path, | 150 | path: &Path, |
| 154 | refs: &[RefInfo], | 151 | refs: &[RefInfo], |
| 155 | target: &str, | 152 | target: &str, |
| @@ -160,7 +157,9 @@ async fn resolve_target( | |||
| 160 | { | 157 | { |
| 161 | return Ok(branch.target.clone()); | 158 | return Ok(branch.target.clone()); |
| 162 | } | 159 | } |
| 163 | - if commit_exists(&state.git, path, target).await { | 160 | + let (repo, oid) = (path.to_owned(), target.to_owned()); |
| 161 | + let reachable = tokio::task::spawn_blocking(move || browse::commit_reachable(&repo, &oid)); | ||
| 162 | + if matches!(reachable.await, Ok(Ok(true))) { | ||
| 164 | return Ok(target.to_owned()); | 163 | return Ok(target.to_owned()); |
| 165 | } | 164 | } |
| 166 | Err(ReleaseError::Invalid(format!( | 165 | Err(ReleaseError::Invalid(format!( |
| @@ -271,7 +270,7 @@ pub async fn create( | |||
| 271 | .as_deref() | 270 | .as_deref() |
| 272 | .filter(|t| !t.is_empty()) | 271 | .filter(|t| !t.is_empty()) |
| 273 | .unwrap_or(&repo.default_branch); | 272 | .unwrap_or(&repo.default_branch); |
| 274 | - let oid = resolve_target(state, &path, &refs, target).await?; | 273 | + let oid = resolve_target(&path, &refs, target).await?; |
| 275 | create_lightweight_tag(&state.git, &path, &input.tag, &oid).await?; | 274 | create_lightweight_tag(&state.git, &path, &input.tag, &oid).await?; |
| 276 | fire_tag_hook(state, repo, actor, &input.tag, &zero_oid(oid.len()), &oid).await; | 275 | fire_tag_hook(state, repo, actor, &input.tag, &zero_oid(oid.len()), &oid).await; |
| 277 | oid | 276 | oid |
| @@ -335,7 +334,7 @@ pub async fn update( | |||
| 335 | match tag_oid(&refs, &new_tag) { | 334 | match tag_oid(&refs, &new_tag) { |
| 336 | Some(existing) => { | 335 | Some(existing) => { |
| 337 | if let Some(target) = wanted | 336 | if let Some(target) = wanted |
| 338 | - && resolve_target(state, &path, &refs, target).await? != existing | 337 | + && resolve_target(&path, &refs, target).await? != existing |
| 339 | { | 338 | { |
| 340 | return Err(ReleaseError::Invalid(format!( | 339 | return Err(ReleaseError::Invalid(format!( |
| 341 | "the tag {new_tag} already exists at another commit" | 340 | "the tag {new_tag} already exists at another commit" |
| @@ -345,7 +344,7 @@ pub async fn update( | |||
| 345 | } | 344 | } |
| 346 | None => { | 345 | None => { |
| 347 | let oid = match wanted { | 346 | let oid = match wanted { |
| 348 | - Some(target) => resolve_target(state, &path, &refs, target).await?, | 347 | + Some(target) => resolve_target(&path, &refs, target).await?, |
| 349 | None => release.target_oid.clone(), | 348 | None => release.target_oid.clone(), |
| 350 | }; | 349 | }; |
| 351 | create_lightweight_tag(&state.git, &path, &new_tag, &oid).await?; | 350 | create_lightweight_tag(&state.git, &path, &new_tag, &oid).await?; |
| @@ -359,7 +358,7 @@ pub async fn update( | |||
| 359 | "published release tags can't be moved; pick a new tag".to_owned(), | 358 | "published release tags can't be moved; pick a new tag".to_owned(), |
| 360 | )); | 359 | )); |
| 361 | } | 360 | } |
| 362 | - let oid = resolve_target(state, &path, &refs, target).await?; | 361 | + let oid = resolve_target(&path, &refs, target).await?; |
| 363 | match tag_oid(&refs, &release.tag) { | 362 | match tag_oid(&refs, &release.tag) { |
| 364 | Some(current) if current == oid => {} | 363 | Some(current) if current == oid => {} |
| 365 | Some(current) => { | 364 | Some(current) => { |
crates/forge-web/tests/e2e/git_e2e.rsmodified+55 -0
| @@ -127,6 +127,15 @@ fn head_sha(repo: &Path) -> String { | |||
| 127 | String::from_utf8_lossy(&out.stdout).trim().to_owned() | 127 | String::from_utf8_lossy(&out.stdout).trim().to_owned() |
| 128 | } | 128 | } |
| 129 | 129 | ||
| 130 | +/// True when a file called `name` exists anywhere under `dir`. | ||
| 131 | +fn find_file(dir: &Path, name: &str) -> bool { | ||
| 132 | + std::fs::read_dir(dir).is_ok_and(|entries| { | ||
| 133 | + entries.flatten().any(|entry| { | ||
| 134 | + entry.file_name() == name || (entry.path().is_dir() && find_file(&entry.path(), name)) | ||
| 135 | + }) | ||
| 136 | + }) | ||
| 137 | +} | ||
| 138 | + | ||
| 130 | fn read(path: PathBuf) -> String { | 139 | fn read(path: PathBuf) -> String { |
| 131 | fs::read_to_string(&path).unwrap_or_else(|e| panic!("read {}: {e}", path.display())) | 140 | fs::read_to_string(&path).unwrap_or_else(|e| panic!("read {}: {e}", path.display())) |
| 132 | } | 141 | } |
| @@ -384,6 +393,52 @@ async fn git_end_to_end() { | |||
| 384 | "main moved after rejected pushes: {remote_main}" | 393 | "main moved after rejected pushes: {remote_main}" |
| 385 | ); | 394 | ); |
| 386 | 395 | ||
| 396 | + // A force push to another branch takes the old commit's page down and marks it for removal. | ||
| 397 | + ok( | ||
| 398 | + &git( | ||
| 399 | + &pub_verify, | ||
| 400 | + &["push", "origin", "HEAD:refs/heads/scratch"], | ||
| 401 | + &[], | ||
| 402 | + ), | ||
| 403 | + "push scratch", | ||
| 404 | + ); | ||
| 405 | + let overwritten = head_sha(&pub_verify); | ||
| 406 | + let page = format!("/tahinli/pub/commit/{overwritten}"); | ||
| 407 | + assert_eq!( | ||
| 408 | + http.get(&page, None).await.status, | ||
| 409 | + 200, | ||
| 410 | + "commit on a branch" | ||
| 411 | + ); | ||
| 412 | + ok( | ||
| 413 | + &git( | ||
| 414 | + &pub_verify, | ||
| 415 | + &[ | ||
| 416 | + "-c", | ||
| 417 | + "commit.gpgsign=false", | ||
| 418 | + "commit", | ||
| 419 | + "--amend", | ||
| 420 | + "-q", | ||
| 421 | + "-m", | ||
| 422 | + "rewritten again", | ||
| 423 | + ], | ||
| 424 | + &[], | ||
| 425 | + ), | ||
| 426 | + "amend again", | ||
| 427 | + ); | ||
| 428 | + ok( | ||
| 429 | + &git(&pub_verify, &["push", "-f", "origin", "HEAD:scratch"], &[]), | ||
| 430 | + "force-push scratch", | ||
| 431 | + ); | ||
| 432 | + assert_eq!( | ||
| 433 | + http.get(&page, None).await.status, | ||
| 434 | + 404, | ||
| 435 | + "overwritten commit" | ||
| 436 | + ); | ||
| 437 | + assert!( | ||
| 438 | + find_file(&dir, "forge-prune-due"), | ||
| 439 | + "the force push marks the repo for pruning" | ||
| 440 | + ); | ||
| 441 | + | ||
| 387 | // Negative: an SSH key that is not registered is refused. | 442 | // Negative: an SSH key that is not registered is refused. |
| 388 | let rogue = dir.join("rogue"); | 443 | let rogue = dir.join("rogue"); |
| 389 | gen_key(&rogue); | 444 | gen_key(&rogue); |
docs/architecture.mdmodified+4 -0
| @@ -347,6 +347,10 @@ Written at boot by `write_managed_gitconfig()`. Keys: | |||
| 347 | - `protocol.file.allow=user` | 347 | - `protocol.file.allow=user` |
| 348 | - Later: `uploadpack.hideRefs` and `transfer.hideRefs` for internal refs (`refs/pull/*` as needed) | 348 | - Later: `uploadpack.hideRefs` and `transfer.hideRefs` for internal refs (`refs/pull/*` as needed) |
| 349 | 349 | ||
| 350 | +### 7.2.1 Overwritten and deleted history | ||
| 351 | + | ||
| 352 | +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. | ||
| 353 | + | ||
| 350 | ### 7.3 Repo path layout | 354 | ### 7.3 Repo path layout |
| 351 | 355 | ||
| 352 | `<data_dir>/repos/<id[0..2]>/<id[2..4]>/<id>.git`, where `<id>` 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. | 356 | `<data_dir>/repos/<id[0..2]>/<id[2..4]>/<id>.git`, where `<id>` 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. |