httpd: Cap inlined blob size in commit and diff

The commit and diff endpoints inlined every changed blob in `files`, so
a commit with large files grew the response, and httpd's memory, with
it. Blobs are now inlined only up to 512 KiB each and 8 MiB per
response, with sizes read from object headers so skipped blobs are never
loaded. Both sides of a file are inlined or neither, and the explorer
shows skipped files without syntax highlighting.

Co-authored-by: Rūdolfs Ošiņš <rudolfs@osins.org>
This commit is contained in:
Yorgos Saslis
2026-12-01 16:30:56 +01:00
committed by Rūdolfs Ošiņš
co-authored by Rūdolfs Ošiņš
parent 96bdcb03a6
commit 693ce8661d
3 changed files with 248 additions and 79 deletions
+5
View File
@@ -22,6 +22,11 @@
now ends in a transfer error instead of a complete-looking 200
- **Exit code for a pathless Unix socket**: `--listen unix:` now exits 1 instead
of 0
- **Bounded inlined blobs**: The commit and diff endpoints inline a changed
file's content in `files` only if each blob is at most 512 KiB and the
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
## radicle-httpd + radicle-search 0.31.0
+236 -79
View File
@@ -27,7 +27,6 @@ use crate::api::search::SearchQueryString;
use crate::api::Context;
use crate::api::PeelToCommit;
use crate::axum_extra::{cached_response, immutable_response, Path, Query};
const MAX_BODY_LIMIT: usize = 4_194_304;
pub fn router(ctx: Context) -> Router {
@@ -508,8 +507,8 @@ async fn commit_handler(
) -> impl IntoResponse {
let rid = ctx.resolve_repo(&rid)?;
let response = api::blocking(move || {
let (repo, _) = ctx.repo(rid)?;
let repo = Repository::open(repo.path())?;
let (storage, _) = ctx.repo(rid)?;
let repo = Repository::open(storage.path())?;
let commit = repo.commit(sha)?;
let diff = repo.diff_commit(commit.id)?;
@@ -520,44 +519,12 @@ async fn commit_handler(
.map(|b| b.refname().to_string())
.collect();
let mut files: HashMap<Oid, BlobRef<'_>> = HashMap::new();
diff.files().for_each(|file_diff| match file_diff {
diff::FileDiff::Added(added) => {
if let Ok(blob) = repo.blob_ref(added.new.oid) {
files.insert(blob.id(), blob);
}
}
diff::FileDiff::Deleted(deleted) => {
if let Ok(old_blob) = repo.blob_ref(deleted.old.oid) {
files.insert(old_blob.id(), old_blob);
}
}
diff::FileDiff::Modified(modified) => {
if let (Ok(old_blob), Ok(new_blob)) = (
repo.blob_ref(modified.old.oid),
repo.blob_ref(modified.new.oid),
) {
files.insert(old_blob.id(), old_blob);
files.insert(new_blob.id(), new_blob);
}
}
diff::FileDiff::Moved(moved) => {
if let (Ok(old_blob), Ok(new_blob)) =
(repo.blob_ref(moved.old.oid), repo.blob_ref(moved.new.oid))
{
files.insert(old_blob.id(), old_blob);
files.insert(new_blob.id(), new_blob);
}
}
diff::FileDiff::Copied(copied) => {
if let (Ok(old_blob), Ok(new_blob)) =
(repo.blob_ref(copied.old.oid), repo.blob_ref(copied.new.oid))
{
files.insert(old_blob.id(), old_blob);
files.insert(new_blob.id(), new_blob);
}
}
});
let files = inline_blobs(
&repo,
&storage.backend,
changed_blob_groups(&diff),
InlineBlobLimits::DEFAULT,
)?;
Ok::<_, Error>(json!({
"commit": api::json::commit::Commit::new(&commit).as_json(),
@@ -583,44 +550,12 @@ async fn diff_handler(
let base = repo.commit(base)?;
let commit = repo.commit(oid)?;
let diff = repo.diff(base.id, commit.id)?;
let mut files: HashMap<Oid, BlobRef<'_>> = HashMap::new();
diff.files().for_each(|file_diff| match file_diff {
diff::FileDiff::Added(added) => {
if let Ok(new_blob) = repo.blob_ref(added.new.oid) {
files.insert(new_blob.id(), new_blob);
}
}
diff::FileDiff::Deleted(deleted) => {
if let Ok(old_blob) = repo.blob_ref(deleted.old.oid) {
files.insert(old_blob.id(), old_blob);
}
}
diff::FileDiff::Modified(modified) => {
if let (Ok(new_blob), Ok(old_blob)) = (
repo.blob_ref(modified.old.oid),
repo.blob_ref(modified.new.oid),
) {
files.insert(new_blob.id(), new_blob);
files.insert(old_blob.id(), old_blob);
}
}
diff::FileDiff::Moved(moved) => {
if let (Ok(new_blob), Ok(old_blob)) =
(repo.blob_ref(moved.new.oid), repo.blob_ref(moved.old.oid))
{
files.insert(new_blob.id(), new_blob);
files.insert(old_blob.id(), old_blob);
}
}
diff::FileDiff::Copied(copied) => {
if let (Ok(new_blob), Ok(old_blob)) =
(repo.blob_ref(copied.new.oid), repo.blob_ref(copied.old.oid))
{
files.insert(new_blob.id(), new_blob);
files.insert(old_blob.id(), old_blob);
}
}
});
let files = inline_blobs(
&repo,
&storage.backend,
changed_blob_groups(&diff),
InlineBlobLimits::DEFAULT,
)?;
// Hide `base` from the walk rather than stopping at the first commit
// that equals it. A merge commit reaches `base` through one of its
@@ -645,6 +580,113 @@ async fn diff_handler(
Ok::<_, Error>(immutable_response(response))
}
fn changed_blob_groups(diff: &diff::Diff) -> Vec<Vec<Oid>> {
diff.files()
.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],
diff::FileDiff::Moved(moved) => vec![moved.old.oid, moved.new.oid],
diff::FileDiff::Copied(copied) => vec![copied.old.oid, copied.new.oid],
})
.collect()
}
/// Limits on the blob content inlined in the `files` map of the commit and
/// diff responses.
#[derive(Debug, Clone, Copy)]
struct InlineBlobLimits {
/// The largest blob that is inlined, in bytes.
per_file: usize,
/// The total size of the blobs inlined in one response, in bytes.
per_response: usize,
}
impl InlineBlobLimits {
const DEFAULT: Self = Self {
per_file: 512 * 1024,
per_response: 8 * 1024 * 1024,
};
}
/// Merge blob groups that share a blob, so that they are inlined together
/// or not at all.
///
/// The `files` map is keyed by blob, so a blob shared between two files is
/// inlined for both. Deciding on each file separately could inline the old
/// side of a file without its new side.
fn merge_blob_groups(groups: impl IntoIterator<Item = Vec<Oid>>) -> Vec<Vec<Oid>> {
let mut merged: Vec<Vec<Oid>> = Vec::new();
let mut index: HashMap<Oid, usize> = HashMap::new();
for group in groups {
let mut targets: Vec<usize> = group
.iter()
.filter_map(|oid| index.get(oid).copied())
.collect();
targets.sort_unstable();
targets.dedup();
let target = match targets.first() {
Some(target) => *target,
None => {
merged.push(Vec::new());
merged.len() - 1
}
};
for other in targets.into_iter().skip(1) {
let oids = std::mem::take(&mut merged[other]);
for oid in &oids {
index.insert(*oid, target);
}
merged[target].extend(oids);
}
for oid in group {
if index.insert(oid, target).is_none() {
merged[target].push(oid);
}
}
}
merged.retain(|group| !group.is_empty());
merged
}
/// Load the blobs of `groups` for the `files` map, as long as every blob of
/// a group fits `limits.per_file` and the group fits what is left of
/// `limits.per_response`. Sizes are read from the object headers, so blobs
/// that are not inlined are never loaded.
fn inline_blobs<'r>(
repo: &'r Repository,
backend: &radicle::git::raw::Repository,
groups: impl IntoIterator<Item = Vec<Oid>>,
limits: InlineBlobLimits,
) -> Result<HashMap<Oid, BlobRef<'r>>, Error> {
let mut files = HashMap::new();
let odb = backend.odb()?;
let mut budget = limits.per_response;
for group in merge_blob_groups(groups) {
let Ok(sizes) = group
.iter()
.map(|oid| odb.read_header((*oid).into()).map(|(size, _)| size))
.collect::<Result<Vec<_>, _>>()
else {
continue;
};
let total: usize = sizes.iter().sum();
if sizes.iter().any(|size| *size > limits.per_file) || total > budget {
continue;
}
let Ok(blobs) = group
.iter()
.map(|oid| repo.blob_ref(*oid))
.collect::<Result<Vec<_>, _>>()
else {
continue;
};
budget -= total;
files.extend(group.into_iter().zip(blobs));
}
Ok(files)
}
/// Get diff stats between two commits.
/// `GET /repos/:rid/diff/:base/:oid/stats`
async fn diff_stats_handler(
@@ -2941,4 +2983,119 @@ mod routes {
assert_eq!(repos.as_array().unwrap().len(), 1);
assert_eq!(repos[0]["rid"], json!(RID));
}
mod inline_blobs {
use radicle_surf::{Oid, Repository};
use super::super::{inline_blobs, InlineBlobLimits};
struct Fixture {
_dir: tempfile::TempDir,
backend: radicle::git::raw::Repository,
repo: Repository,
}
impl Fixture {
fn new() -> Self {
let dir = tempfile::tempdir().unwrap();
let backend = radicle::git::raw::Repository::init_bare(dir.path()).unwrap();
let repo = Repository::open(dir.path()).unwrap();
Self {
_dir: dir,
backend,
repo,
}
}
fn blob(&self, size: usize) -> Oid {
self.backend
.blob("x".repeat(size).as_bytes())
.unwrap()
.into()
}
}
fn limits(per_file: usize, per_response: usize) -> InlineBlobLimits {
InlineBlobLimits {
per_file,
per_response,
}
}
#[test]
fn skips_blobs_over_the_per_file_limit() {
let f = Fixture::new();
let (small, large) = (f.blob(10), f.blob(11));
let files = inline_blobs(
&f.repo,
&f.backend,
vec![vec![small], vec![large]],
limits(10, 100),
)
.unwrap();
assert!(files.contains_key(&small));
assert!(!files.contains_key(&large));
}
#[test]
fn skips_groups_over_the_remaining_budget() {
let f = Fixture::new();
let (a, b, c) = (f.blob(6), f.blob(5), f.blob(4));
let files = inline_blobs(
&f.repo,
&f.backend,
vec![vec![a], vec![b], vec![c]],
limits(10, 10),
)
.unwrap();
assert!(files.contains_key(&a));
assert!(!files.contains_key(&b));
assert!(files.contains_key(&c));
}
#[test]
fn inlines_both_sides_of_a_file_or_neither() {
let f = Fixture::new();
let (old, new) = (f.blob(5), f.blob(20));
let files =
inline_blobs(&f.repo, &f.backend, vec![vec![old, new]], limits(10, 100)).unwrap();
assert!(files.is_empty());
let files =
inline_blobs(&f.repo, &f.backend, vec![vec![old, new]], limits(20, 24)).unwrap();
assert!(files.is_empty());
let files =
inline_blobs(&f.repo, &f.backend, vec![vec![old, new]], limits(20, 25)).unwrap();
assert_eq!(files.len(), 2);
}
#[test]
fn counts_a_blob_shared_by_two_files_once() {
let f = Fixture::new();
let shared = f.blob(6);
let other = f.blob(4);
let files = inline_blobs(
&f.repo,
&f.backend,
vec![vec![shared], vec![shared, other]],
limits(10, 10),
)
.unwrap();
assert_eq!(files.len(), 2);
}
#[test]
fn inlines_files_sharing_a_blob_together_or_not_at_all() {
let f = Fixture::new();
let (shared, large) = (f.blob(5), f.blob(20));
for groups in [
vec![vec![shared], vec![shared, large]],
vec![vec![shared, large], vec![shared]],
] {
let files = inline_blobs(&f.repo, &f.backend, groups, limits(10, 100)).unwrap();
assert!(files.is_empty());
}
}
}
}
+7
View File
@@ -32,6 +32,13 @@ Explorer supports httpd 0.28.0 and newer, set by `minimumSupportedVersion` in
## Unreleased
### Bounded diffs
- 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.
- Read by: client.
## 0.31.0
### API at `/api`