From 9dd13264e08eec353ab367e5b6c8883aa10eca7f Mon Sep 17 00:00:00 2001 From: Yorgos Saslis Date: Tue, 1 Dec 2026 11:31:04 +0100 Subject: [PATCH] httpd: Bound the diff in commit and diff responses MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Commits with large or many files, like a vendored driver with 3,790 files, OOM-killed httpd at its 2 GiB limit. radicle-surf diffs every file twice and its rename detection loads whole blobs, so its output can't be bounded, and httpd now builds the diff itself. Files over 1 MiB or 50,000 lines, or past the per-response budgets, aren't diffed and come back as binary with `"tooLarge": true`. Files after the first 3,000 are left out. The diff is then `"truncated"` and takes its stats from `git diff --numstat`. This also fixes files shrunk from over the limit showing up as empty. `git2` becomes a direct dependency, at the version `radicle` already uses, for the diff types `radicle::git::raw` doesn't re-export. Co-authored-by: Rūdolfs Ošiņš --- explorer/CHANGELOG.md | 9 + explorer/Cargo.lock | 1 + explorer/crates/radicle-httpd/Cargo.toml | 3 + .../crates/radicle-httpd/src/api/v1/repos.rs | 526 +++++++++++++++++- explorer/docs/api-changes.md | 9 + 5 files changed, 539 insertions(+), 9 deletions(-) diff --git a/explorer/CHANGELOG.md b/explorer/CHANGELOG.md index d26b4703e..5ba085464 100644 --- a/explorer/CHANGELOG.md +++ b/explorer/CHANGELOG.md @@ -27,6 +27,15 @@ response's inlined blobs stay within 8 MiB. Both sides of a file are inlined, or neither. The explorer shows files without inlined content without syntax highlighting or image previews +- **Bounded diffs**: The commit and diff endpoints no longer diff a file with a + side over 1 MiB or 50,000 lines, and stop diffing files once a response holds + 32 MiB of blobs or 50,000 hunk lines. These files come back as + `{"type": "binary"}` with `"tooLarge": true`. Files after the first 3,000 are + left out. The diff then gets `"truncated": true`, and its stats come from + `git diff --numstat`, so they still count every file. Rename and copy + detection only matches identical files when the changed files exceed 1 MiB + each or 32 MiB in total. `git diff --numstat`, here and in + `/diff/:base/:oid/stats`, treats files over 1 MiB as binary ## radicle-httpd + radicle-search 0.31.0 diff --git a/explorer/Cargo.lock b/explorer/Cargo.lock index cded49f58..02aec20b7 100644 --- a/explorer/Cargo.lock +++ b/explorer/Cargo.lock @@ -2765,6 +2765,7 @@ dependencies = [ "base64 0.22.1", "chrono", "futures-util", + "git2", "hyper", "infer", "lexopt", diff --git a/explorer/crates/radicle-httpd/Cargo.toml b/explorer/crates/radicle-httpd/Cargo.toml index ec76f3d90..a255dd037 100644 --- a/explorer/crates/radicle-httpd/Cargo.toml +++ b/explorer/crates/radicle-httpd/Cargo.toml @@ -27,6 +27,9 @@ base64 = { version = "0.22.1" } chrono.workspace = true futures-util = { version = "0.3.32", default-features = false } hyper = { version = "1.6.0", default-features = false } +# The same version as `radicle` uses, for the diff types `radicle::git::raw` +# does not re-export. +git2 = { version = "0.21.0", default-features = false } infer = { version = "0.19.0" } lexopt.workspace = true lru = { version = "0.18.2" } diff --git a/explorer/crates/radicle-httpd/src/api/v1/repos.rs b/explorer/crates/radicle-httpd/src/api/v1/repos.rs index d73ba95f7..83198c189 100644 --- a/explorer/crates/radicle-httpd/src/api/v1/repos.rs +++ b/explorer/crates/radicle-httpd/src/api/v1/repos.rs @@ -2,7 +2,7 @@ mod job; #[cfg(feature = "artifacts")] mod releases; -use std::collections::{BTreeMap, HashMap}; +use std::collections::{BTreeMap, BTreeSet, HashMap}; use axum::extract::{DefaultBodyLimit, State}; use axum::http::header; @@ -511,7 +511,12 @@ async fn commit_handler( let repo = Repository::open(storage.path())?; let commit = repo.commit(sha)?; - let diff = repo.diff_commit(commit.id)?; + let diff = diff_commits( + &storage.backend, + commit.parents.first().copied(), + commit.id, + DiffLimits::DEFAULT, + )?; let glob = Glob::all_heads().branches().and(Glob::all_remotes()); let branches: Vec = repo .revision_branches(commit.id, glob)? @@ -525,10 +530,16 @@ async fn commit_handler( changed_blob_groups(&diff), InlineBlobLimits::DEFAULT, )?; + let diff_json = diff.to_json( + api::json::diff::Diff::new(&diff.diff).as_json(), + storage.path(), + commit.parents.first().copied(), + commit.id, + ); Ok::<_, Error>(json!({ "commit": api::json::commit::Commit::new(&commit).as_json(), - "diff": api::json::diff::Diff::new(&diff).as_json(), + "diff": diff_json, "files": files, "branches": branches })) @@ -549,7 +560,12 @@ async fn diff_handler( let repo = Repository::open(storage.path())?; let base = repo.commit(base)?; let commit = repo.commit(oid)?; - let diff = repo.diff(base.id, commit.id)?; + let diff = diff_commits( + &storage.backend, + Some(base.id), + commit.id, + DiffLimits::DEFAULT, + )?; let files = inline_blobs( &repo, &storage.backend, @@ -573,16 +589,277 @@ async fn diff_handler( .map(|c| api::json::commit::Commit::new(&c).as_json()) .collect::>(); - Ok::<_, Error>(json!({ "diff": diff, "files": files, "commits": commits })) + let diff_json = diff.to_json(json!(diff.diff), storage.path(), Some(base.id), commit.id); + + Ok::<_, Error>(json!({ "diff": diff_json, "files": files, "commits": commits })) }) .await?; Ok::<_, Error>(immutable_response(response)) } -fn changed_blob_groups(diff: &diff::Diff) -> Vec> { - diff.files() - .map(|file_diff| match file_diff { +/// Limits on the diff returned by the commit and diff endpoints. +#[derive(Debug, Clone, Copy)] +struct DiffLimits { + /// Files with a side larger than this are not diffed, in bytes. + per_file: usize, + /// The total size of the blobs diffed for one response, in bytes. Rename + /// and copy detection compares whole blobs, so it only matches identical + /// blobs when the changed blobs exceed this in total. + per_response: usize, + /// The total number of hunk lines in one response. Files with a side + /// that has more lines than this are not diffed. + lines_per_response: usize, + /// The number of files in one response. Files after it are left out. + files_per_response: usize, +} + +impl DiffLimits { + const DEFAULT: Self = Self { + per_file: 1024 * 1024, + per_response: 32 * 1024 * 1024, + lines_per_response: 50_000, + files_per_response: 3_000, + }; +} + +/// A diff in which files over the [`DiffLimits`] are returned as binary. +struct LimitedDiff { + diff: diff::Diff, + /// The positions in `diff.files()` of the files that were not diffed + /// because of their size. + too_large: BTreeSet, + /// Whether files after [`DiffLimits::files_per_response`] were left out. + files_left_out: bool, +} + +impl LimitedDiff { + /// Mark the files that were too large to diff in `diff_json`, the + /// serialized `self.diff`, with `tooLarge`, and the diff with + /// `truncated` if any file was not diffed or was left out. A truncated + /// diff takes its stats from `git diff --numstat`, which counts every + /// file. + fn to_json( + &self, + mut diff_json: serde_json::Value, + repo_dir: &std::path::Path, + base: Option, + head: Oid, + ) -> serde_json::Value { + if self.too_large.is_empty() && !self.files_left_out { + return diff_json; + } + if let Some(files) = diff_json["files"].as_array_mut() { + for index in &self.too_large { + if let Some(content) = files + .get_mut(*index) + .and_then(|file| file.get_mut("diff")) + .and_then(|content| content.as_object_mut()) + { + content.insert("tooLarge".to_string(), json!(true)); + } + } + } + diff_json["truncated"] = json!(true); + + let base = match base { + Some(base) => Some(base), + None => radicle::git::raw::Oid::hash_object(radicle::git::raw::ObjectType::Tree, &[]) + .ok() + .map(Oid::from), + }; + if let Some((files_changed, insertions, deletions)) = + base.and_then(|base| numstat(repo_dir, base, head)) + { + diff_json["stats"] = json!({ + "filesChanged": files_changed, + "insertions": insertions, + "deletions": deletions, + }); + } + diff_json + } +} + +fn surf_error(err: impl Into) -> Error { + radicle_surf::Error::from(err.into()).into() +} + +/// Diff `from` against `to`, or against the empty tree without `from`, +/// within `limits`. +/// +/// Blob sizes are read from the object headers before any blob is loaded. A +/// file that does not fit `limits` is returned as +/// [`diff::DiffContent::Binary`] without being loaded, and is listed in +/// [`LimitedDiff::too_large`]. +fn diff_commits( + backend: &radicle::git::raw::Repository, + from: Option, + to: Oid, + limits: DiffLimits, +) -> Result { + use git2 as raw; + + let new_tree = backend.find_commit(to.into())?.tree()?; + let old_tree = from + .map(|from| backend.find_commit(from.into()).and_then(|c| c.tree())) + .transpose()?; + + let mut opts = raw::DiffOptions::new(); + opts.max_size(i64::try_from(limits.per_file).unwrap_or(i64::MAX)); + let mut git_diff = + backend.diff_tree_to_tree(old_tree.as_ref(), Some(&new_tree), Some(&mut opts))?; + + let odb = backend.odb()?; + let mut sizes = HashMap::new(); + // A submodule's oid is a commit in another repository, and its diff is + // a single line. + let mut size = |file: &raw::DiffFile<'_>| -> usize { + let oid = file.id(); + if oid.is_zero() || file.mode() == raw::FileMode::Commit { + return 0; + } + *sizes.entry(oid).or_insert_with(|| { + odb.read_header(oid) + .map(|(size, _)| size) + .unwrap_or(usize::MAX) + }) + }; + + let line_count = |file: &raw::DiffFile<'_>| -> usize { + let oid = file.id(); + if oid.is_zero() || file.mode() == raw::FileMode::Commit { + return 0; + } + backend + .find_blob(oid) + .map(|blob| blob.content().iter().filter(|byte| **byte == b'\n').count()) + .unwrap_or(usize::MAX) + }; + + let mut changed = 0usize; + let mut oversized = false; + for delta in git_diff.deltas() { + for file in [delta.old_file(), delta.new_file()] { + let size = size(&file); + oversized |= size > limits.per_file; + changed = changed.saturating_add(size); + } + } + let mut find_opts = raw::DiffFindOptions::new(); + find_opts.renames(true); + find_opts.copies(true); + find_opts.exact_match_only(oversized || changed > limits.per_response); + git_diff.find_similar(Some(&mut find_opts))?; + + let mut result = LimitedDiff { + diff: diff::Diff::default(), + too_large: BTreeSet::new(), + files_left_out: false, + }; + let mut bytes = limits.per_response; + let mut lines = limits.lines_per_response; + for (index, delta) in git_diff.deltas().enumerate() { + if index >= limits.files_per_response { + result.files_left_out = true; + break; + } + let (old_file, new_file) = (delta.old_file(), delta.new_file()); + let path = |file: raw::DiffFile<'_>| { + file.path() + .map(|path| path.to_path_buf()) + .ok_or_else(|| surf_error(diff::git::error::Diff::PathUnavailable)) + }; + let file = |file: raw::DiffFile<'_>| diff::DiffFile::try_from(file).map_err(surf_error); + let unchanged = old_file.id() == new_file.id(); + let (old_size, new_size) = (size(&old_file), size(&new_file)); + + let content = if unchanged { + Some(diff::DiffContent::Empty) + } else if old_size.max(new_size) > limits.per_file + || old_size.saturating_add(new_size) > bytes + // Counted before diffing, as the patch holds every line of both + // sides. + || line_count(&old_file).max(line_count(&new_file)) > limits.lines_per_response + { + None + } else { + bytes -= old_size + new_size; + match raw::Patch::from_diff(&git_diff, index)? { + Some(patch) if patch.delta().flags().is_binary() => Some(diff::DiffContent::Binary), + Some(patch) => { + // Counted before converting, which copies every line. + let (context, additions, deletions) = patch.line_stats()?; + let count = context + additions + deletions; + if count > lines { + None + } else { + lines -= count; + Some(diff::DiffContent::try_from(patch).map_err(surf_error)?) + } + } + None => Some(diff::DiffContent::Empty), + } + }; + let content = content.unwrap_or_else(|| { + result.too_large.insert(index); + diff::DiffContent::Binary + }); + + let diff = &mut result.diff; + match delta.status() { + raw::Delta::Added => { + diff.insert_added(path(delta.new_file())?, content, file(delta.new_file())?) + } + raw::Delta::Deleted => { + diff.insert_deleted(path(delta.old_file())?, content, file(delta.old_file())?) + } + // A mode change keeps the blob, and has no hunks rather than no + // content. + raw::Delta::Modified if unchanged => diff.insert_modified( + path(delta.new_file())?, + diff::DiffContent::Plain { + hunks: Default::default(), + stats: Default::default(), + eof: diff::EofNewLine::NoneMissing, + }, + file(delta.old_file())?, + file(delta.new_file())?, + ), + raw::Delta::Modified => diff.insert_modified( + path(delta.new_file())?, + content, + file(delta.old_file())?, + file(delta.new_file())?, + ), + raw::Delta::Renamed => diff.insert_moved( + path(delta.old_file())?, + path(delta.new_file())?, + file(delta.old_file())?, + file(delta.new_file())?, + content, + ), + raw::Delta::Copied => diff.insert_copied( + path(delta.old_file())?, + path(delta.new_file())?, + file(delta.old_file())?, + file(delta.new_file())?, + content, + ), + status => return Err(surf_error(diff::git::error::Diff::DeltaUnhandled(status))), + } + } + Ok(result) +} + +/// The blobs of each changed file, except files that were too large to +/// diff, as the explorer does not show their content. +fn changed_blob_groups(diff: &LimitedDiff) -> Vec> { + diff.diff + .files() + .enumerate() + .filter(|(index, _)| !diff.too_large.contains(index)) + .map(|(_, file_diff)| match file_diff { diff::FileDiff::Added(added) => vec![added.new.oid], diff::FileDiff::Deleted(deleted) => vec![deleted.old.oid], diff::FileDiff::Modified(modified) => vec![modified.old.oid, modified.new.oid], @@ -757,9 +1034,19 @@ fn git_output(repo_dir: &std::path::Path, args: &[&str]) -> Option> { fn numstat(repo_dir: &std::path::Path, base: Oid, head: Oid) -> Option<(usize, usize, usize)> { let (base, head) = (base.to_string(), head.to_string()); + // Above `core.bigFileThreshold`, git treats files as binary and does not + // load them to count lines. + let threshold = format!("core.bigFileThreshold={}", DiffLimits::DEFAULT.per_file); let stdout = git_output( repo_dir, - &["diff", "--numstat", base.as_str(), head.as_str()], + &[ + "-c", + threshold.as_str(), + "diff", + "--numstat", + base.as_str(), + head.as_str(), + ], )?; let mut files_changed = 0; @@ -3098,4 +3385,225 @@ mod routes { } } } + + mod diff_commits { + use radicle_surf::{diff, Oid}; + use serde_json::json; + + use super::super::{changed_blob_groups, diff_commits, DiffLimits}; + + struct Fixture { + _dir: tempfile::TempDir, + backend: radicle::git::raw::Repository, + } + + impl Fixture { + fn new() -> Self { + let dir = tempfile::tempdir().unwrap(); + let backend = radicle::git::raw::Repository::init_bare(dir.path()).unwrap(); + Self { _dir: dir, backend } + } + + /// Commit `files`, each a path and its number of lines, on top + /// of `parent`. + fn commit(&self, parent: Option, files: &[(&str, usize)]) -> Oid { + let entries = files + .iter() + .map(|(path, lines)| { + let content = (0..*lines) + .map(|n| format!("line {n}\n")) + .collect::(); + let blob = self.backend.blob(content.as_bytes()).unwrap(); + (*path, blob, 0o100644) + }) + .collect::>(); + self.commit_entries(parent, &entries) + } + + /// Commit a submodule at `path` pointing to `commit`, on top of + /// `parent`. + fn commit_submodule(&self, parent: Option, path: &str, commit: &str) -> Oid { + let commit = radicle::git::raw::Oid::from_str(commit).unwrap(); + self.commit_entries(parent, &[(path, commit, 0o160000)]) + } + + fn commit_entries( + &self, + parent: Option, + entries: &[(&str, radicle::git::raw::Oid, i32)], + ) -> Oid { + let mut builder = self.backend.treebuilder(None).unwrap(); + for (path, oid, mode) in entries { + builder.insert(path, *oid, *mode).unwrap(); + } + let tree = self.backend.find_tree(builder.write().unwrap()).unwrap(); + let signature = + radicle::git::raw::Signature::now("Amy", "amy@radicle.xyz").unwrap(); + let parents = parent + .map(|parent| self.backend.find_commit(parent.into()).unwrap()) + .into_iter() + .collect::>(); + self.backend + .commit( + None, + &signature, + &signature, + "", + &tree, + &parents.iter().collect::>(), + ) + .unwrap() + .into() + } + } + + fn limits(per_file: usize, per_response: usize, lines_per_response: usize) -> DiffLimits { + DiffLimits { + per_file, + per_response, + lines_per_response, + files_per_response: usize::MAX, + } + } + + fn is_binary(file: &diff::FileDiff) -> bool { + matches!( + file, + diff::FileDiff::Added(diff::Added { + diff: diff::DiffContent::Binary, + .. + }) | diff::FileDiff::Modified(diff::Modified { + diff: diff::DiffContent::Binary, + .. + }) + ) + } + + #[test] + fn marks_a_file_shrunk_from_over_the_per_file_limit_too_large() { + let f = Fixture::new(); + let base = f.commit(None, &[("file", 1000)]); + let head = f.commit(Some(base), &[("file", 10)]); + let diff = + diff_commits(&f.backend, Some(base), head, limits(1000, 1 << 20, 1000)).unwrap(); + let files = diff.diff.files().collect::>(); + assert!(is_binary(files[0])); + assert_eq!(diff.too_large.into_iter().collect::>(), [0]); + } + + #[test] + fn skips_files_over_the_remaining_line_budget() { + let f = Fixture::new(); + let head = f.commit(None, &[("a", 6), ("b", 5), ("c", 4)]); + let diff = diff_commits(&f.backend, None, head, limits(1 << 20, 1 << 20, 10)).unwrap(); + let binary = diff.diff.files().map(is_binary).collect::>(); + assert_eq!(binary, [false, true, false]); + assert_eq!(diff.too_large.into_iter().collect::>(), [1]); + } + + #[test] + fn skips_files_with_a_side_over_the_line_limit() { + let f = Fixture::new(); + let base = f.commit(None, &[("a", 20)]); + let head = f.commit(Some(base), &[("a", 21)]); + let diff = + diff_commits(&f.backend, Some(base), head, limits(1 << 20, 1 << 20, 10)).unwrap(); + let files = diff.diff.files().collect::>(); + assert!(is_binary(files[0])); + assert_eq!(diff.too_large.into_iter().collect::>(), [0]); + } + + #[test] + fn leaves_out_the_blobs_of_files_not_diffed() { + let f = Fixture::new(); + let head = f.commit(None, &[("a", 5), ("b", 20)]); + let diff = diff_commits(&f.backend, None, head, limits(1 << 20, 1 << 20, 10)).unwrap(); + let a = diff.diff.files().next().unwrap(); + let diff::FileDiff::Added(a) = a else { + panic!("`a` is added"); + }; + assert_eq!(changed_blob_groups(&diff), [vec![a.new.oid]]); + } + + #[test] + fn skips_files_over_the_remaining_byte_budget() { + let f = Fixture::new(); + let head = f.commit(None, &[("a", 100), ("b", 100)]); + let diff = diff_commits(&f.backend, None, head, limits(1 << 20, 1000, 1000)).unwrap(); + let binary = diff.diff.files().map(is_binary).collect::>(); + assert_eq!(binary, [false, true]); + } + + #[test] + fn keeps_diffs_within_the_limits_complete() { + let f = Fixture::new(); + let base = f.commit(None, &[("a", 10), ("b", 10)]); + let head = f.commit(Some(base), &[("a", 12), ("c", 3)]); + let limited = diff_commits(&f.backend, Some(base), head, DiffLimits::DEFAULT).unwrap(); + assert!(limited.too_large.is_empty()); + + let repo = radicle_surf::Repository::open(f.backend.path()).unwrap(); + assert_eq!(limited.diff, repo.diff(base, head).unwrap()); + } + + #[test] + fn diffs_a_submodule_change() { + let f = Fixture::new(); + let base = f.commit_submodule(None, "sub", &"1".repeat(40)); + let head = f.commit_submodule(Some(base), "sub", &"2".repeat(40)); + let limited = diff_commits(&f.backend, Some(base), head, DiffLimits::DEFAULT).unwrap(); + assert!(limited.too_large.is_empty()); + + let repo = radicle_surf::Repository::open(f.backend.path()).unwrap(); + assert_eq!(limited.diff, repo.diff(base, head).unwrap()); + } + + #[test] + fn leaves_out_files_over_the_file_limit() { + let f = Fixture::new(); + let head = f.commit(None, &[("a", 1), ("b", 1), ("c", 1)]); + let limits = DiffLimits { + files_per_response: 2, + ..DiffLimits::DEFAULT + }; + let diff = diff_commits(&f.backend, None, head, limits).unwrap(); + assert_eq!(diff.diff.files().count(), 2); + assert!(diff.files_left_out); + } + + #[test] + fn marks_files_not_diffed_in_json_and_counts_every_file() { + let f = Fixture::new(); + let head = f.commit(None, &[("a", 10), ("b", 1000), ("c", 5)]); + let limits = DiffLimits { + per_file: 1000, + files_per_response: 2, + ..DiffLimits::DEFAULT + }; + let diff = diff_commits(&f.backend, None, head, limits).unwrap(); + let json = diff.to_json(json!(diff.diff), f.backend.path(), None, head); + + assert_eq!(json["truncated"], json!(true)); + assert_eq!(json["files"][0]["path"], json!("a")); + assert_eq!(json["files"][0]["diff"].get("tooLarge"), None); + assert_eq!(json["files"][1]["path"], json!("b")); + assert_eq!(json["files"][1]["diff"]["tooLarge"], json!(true)); + assert_eq!(json["files"].as_array().unwrap().len(), 2); + assert_eq!( + json["stats"], + json!({ "filesChanged": 3, "insertions": 1015, "deletions": 0 }) + ); + } + + #[test] + fn leaves_complete_diffs_unchanged_in_json() { + let f = Fixture::new(); + let base = f.commit(None, &[("a", 10)]); + let head = f.commit(Some(base), &[("a", 12)]); + let diff = diff_commits(&f.backend, Some(base), head, DiffLimits::DEFAULT).unwrap(); + let expected = json!(diff.diff); + let json = diff.to_json(expected.clone(), f.backend.path(), Some(base), head); + assert_eq!(json, expected); + } + } } diff --git a/explorer/docs/api-changes.md b/explorer/docs/api-changes.md index 66a517c77..86e6ce1eb 100644 --- a/explorer/docs/api-changes.md +++ b/explorer/docs/api-changes.md @@ -37,6 +37,15 @@ Explorer supports httpd 0.28.0 and newer, set by `minimumSupportedVersion` in - Changed in place: `files` in the commit and diff responses leaves out blobs over 512 KiB, and blobs once the response holds 8 MiB of them. Both sides of a file are left out together. Older clients already handle a missing blob. +- Added: `tooLarge` on a file's `binary` diff, for files httpd did not diff + because of their size, and `truncated` on the diff when any file was not + diffed or was left out. Both are optional in the client. +- Changed in place: text files over the diff limits come back as `binary`, and + files after the first 3,000 are left out. A truncated diff takes its stats + from `git diff --numstat`, which counts every file. Older clients show these + files as binary. +- Changed in place: `git diff --numstat`, also behind `/diff/:base/:oid/stats`, + counts files over 1 MiB as binary, with no lines. - Read by: client. ## 0.31.0