httpd: Limit concurrent diffs

The limits on commit and diff responses bound each request, but not
how many run at once. Each request runs on its own blocking thread and
keeps running after its client disconnects, so a client sending many
requests for large diffs in parallel can still exhaust httpd's memory.

At most 4 commit, diff and diff stats requests now compute diffs at the
same time. Others wait for up to 10 seconds, which takes no memory
beyond the request, and then fail with 503 and `Retry-After`. Waiting
instead of failing at once keeps pages that request many commits at
once, such as repo listings in deployed explorers, working.
This commit is contained in:
Rūdolfs Ošiņš
2026-12-01 16:30:56 +01:00
parent 9dd13264e0
commit 3d353ca8ad
5 changed files with 63 additions and 0 deletions
+3
View File
@@ -36,6 +36,9 @@
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
- **Concurrent diff limit**: At most 4 commit, diff and diff stats requests
compute diffs at the same time. Others wait up to 10 seconds, then get a 503
with `Retry-After`
## radicle-httpd + radicle-search 0.31.0
+33
View File
@@ -1,5 +1,6 @@
use std::collections::{BTreeMap, HashMap};
use std::sync::Arc;
use std::time::Duration;
use axum::Router;
use serde_json::{json, Value};
@@ -80,9 +81,17 @@ pub struct Context {
/// [`RepoId`]. Used to resolve alias path segments to a repo and to
/// advertise a repo's short name in its info.
repo_aliases: Arc<HashMap<String, RepoId>>,
/// Permits for diffing commits, see [`Context::diff_permit`].
diffs: Arc<tokio::sync::Semaphore>,
}
impl Context {
/// The number of commit diffs computed at the same time. Each one stays
/// within about 150 MiB under the diff limits in `api::v1::repos`, so
/// this bounds httpd's memory under many concurrent requests for large
/// diffs.
const CONCURRENT_DIFFS: usize = 4;
pub fn new(
profile: Arc<Profile>,
web_config: WebConfig,
@@ -123,9 +132,33 @@ impl Context {
web_config,
search,
repo_aliases: Arc::new(options.aliases.clone()),
diffs: Arc::new(tokio::sync::Semaphore::new(Self::CONCURRENT_DIFFS)),
})
}
/// How long a request waits for a permit to diff commits before it
/// fails. Waiting requests take no memory beyond the request itself.
const DIFF_PERMIT_TIMEOUT: Duration = Duration::from_secs(10);
/// Wait for a permit to diff commits, or fail with [`error::Error::Busy`]
/// after [`Context::DIFF_PERMIT_TIMEOUT`]. The permit is held until it
/// is dropped, so a request whose client disconnects keeps it while its
/// blocking task runs.
#[allow(clippy::result_large_err)]
pub(crate) async fn diff_permit(
&self,
) -> Result<tokio::sync::OwnedSemaphorePermit, error::Error> {
match tokio::time::timeout(
Self::DIFF_PERMIT_TIMEOUT,
self.diffs.clone().acquire_owned(),
)
.await
{
Ok(Ok(permit)) => Ok(permit),
Ok(Err(_)) | Err(_) => Err(error::Error::Busy),
}
}
/// Resolve a repo path segment (RID or alias) to a [`RepoId`], mapping an
/// unknown segment to [`Error::NotFound`].
#[allow(clippy::result_large_err)]
@@ -14,6 +14,10 @@ pub enum Error {
#[error("entity not found")]
NotFound,
/// Too many requests of a kind are in progress.
#[error("too many requests in progress, retry later")]
Busy,
/// A blocking task failed to complete.
#[error(transparent)]
Task(#[from] tokio::task::JoinError),
@@ -114,8 +118,10 @@ impl IntoResponse for Error {
Error::Surf(e) => surf_not_found_message(e),
_ => None,
};
let busy = matches!(self, Error::Busy);
let (status, msg) = match self {
Error::NotFound => (StatusCode::NOT_FOUND, None),
Error::Busy => (StatusCode::SERVICE_UNAVAILABLE, Some(message)),
Error::CobStore(e @ radicle::cob::store::Error::NotFound(_, _)) => {
(StatusCode::NOT_FOUND, Some(e.to_string()))
}
@@ -154,6 +160,9 @@ impl IntoResponse for Error {
"code": status.as_u16()
}));
if busy {
return (status, [(axum::http::header::RETRY_AFTER, "1")], body).into_response();
}
(status, body).into_response()
}
}
@@ -167,4 +176,13 @@ mod tests {
let response = Error::NotFound.into_response();
assert_eq!(response.status(), StatusCode::NOT_FOUND);
}
#[test]
fn busy_maps_to_503_with_retry_after() {
let response = Error::Busy.into_response();
assert_eq!(response.status(), StatusCode::SERVICE_UNAVAILABLE);
assert!(response
.headers()
.contains_key(axum::http::header::RETRY_AFTER));
}
}
@@ -506,7 +506,9 @@ async fn commit_handler(
Path((rid, sha)): Path<(String, Oid)>,
) -> impl IntoResponse {
let rid = ctx.resolve_repo(&rid)?;
let permit = ctx.diff_permit().await?;
let response = api::blocking(move || {
let _permit = permit;
let (storage, _) = ctx.repo(rid)?;
let repo = Repository::open(storage.path())?;
let commit = repo.commit(sha)?;
@@ -555,7 +557,9 @@ async fn diff_handler(
Path((rid, base, oid)): Path<(String, Oid, Oid)>,
) -> impl IntoResponse {
let rid = ctx.resolve_repo(&rid)?;
let permit = ctx.diff_permit().await?;
let response = api::blocking(move || {
let _permit = permit;
let (storage, _) = ctx.repo(rid)?;
let repo = Repository::open(storage.path())?;
let base = repo.commit(base)?;
@@ -971,7 +975,9 @@ async fn diff_stats_handler(
Path((rid, base, oid)): Path<(String, Oid, Oid)>,
) -> impl IntoResponse {
let rid = ctx.resolve_repo(&rid)?;
let permit = ctx.diff_permit().await?;
let stats = api::blocking(move || {
let _permit = permit;
let (repo, _) = ctx.repo(rid)?;
diff_stats(&repo, base, oid)
})
+3
View File
@@ -46,6 +46,9 @@ Explorer supports httpd 0.28.0 and newer, set by `minimumSupportedVersion` in
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.
- Changed in place: the commit, diff and diff stats endpoints return 503 with
`Retry-After` when no diff slot frees up within 10 seconds. Older clients show
it as a failed request.
- Read by: client.
## 0.31.0