diff --git a/explorer/CHANGELOG.md b/explorer/CHANGELOG.md index 5ba085464..3b28ce5bc 100644 --- a/explorer/CHANGELOG.md +++ b/explorer/CHANGELOG.md @@ -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 diff --git a/explorer/crates/radicle-httpd/src/api.rs b/explorer/crates/radicle-httpd/src/api.rs index 1b7d68b16..c7fce77b2 100644 --- a/explorer/crates/radicle-httpd/src/api.rs +++ b/explorer/crates/radicle-httpd/src/api.rs @@ -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>, + /// Permits for diffing commits, see [`Context::diff_permit`]. + diffs: Arc, } 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, 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 { + 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)] diff --git a/explorer/crates/radicle-httpd/src/api/error.rs b/explorer/crates/radicle-httpd/src/api/error.rs index 2eb237387..12ae45f12 100644 --- a/explorer/crates/radicle-httpd/src/api/error.rs +++ b/explorer/crates/radicle-httpd/src/api/error.rs @@ -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)); + } } diff --git a/explorer/crates/radicle-httpd/src/api/v1/repos.rs b/explorer/crates/radicle-httpd/src/api/v1/repos.rs index 83198c189..6cf97bc88 100644 --- a/explorer/crates/radicle-httpd/src/api/v1/repos.rs +++ b/explorer/crates/radicle-httpd/src/api/v1/repos.rs @@ -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) }) diff --git a/explorer/docs/api-changes.md b/explorer/docs/api-changes.md index 86e6ce1eb..b328432ec 100644 --- a/explorer/docs/api-changes.md +++ b/explorer/docs/api-changes.md @@ -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