From a533b7a3e8d31ac2a94a84a7fd013643e8d5ba7e Mon Sep 17 00:00:00 2001 From: Beardthelion Date: Mon, 30 Nov 2026 05:27:13 +0000 Subject: [PATCH 1/2] perf(node): bound blob and tree git reads off the async runtime --- crates/twigpine-node/src/api/repos.rs | 253 ++++++++++++++++++++++---- crates/twigpine-node/src/git/store.rs | 72 +++++--- 2 files changed, 269 insertions(+), 56 deletions(-) diff --git a/crates/twigpine-node/src/api/repos.rs b/crates/twigpine-node/src/api/repos.rs index 453c5f8b2..9c02f45a5 100644 --- a/crates/twigpine-node/src/api/repos.rs +++ b/crates/twigpine-node/src/api/repos.rs @@ -932,6 +932,8 @@ pub async fn get_blob( State(state): State, Path((owner, name, file_path)): Path<(String, String, String)>, auth: Option>, + crate::rate_limit::PeerAddr(peer): crate::rate_limit::PeerAddr, + headers: axum::http::HeaderMap, ) -> Result { use axum::http::header; use axum::response::IntoResponse; @@ -953,25 +955,31 @@ pub async fn get_blob( let (record, _rules) = crate::api::authorize_repo_read(&state, &owner, &name, caller, &gate_path).await?; - let disk_path = state - .repo_store - .acquire(&record.owner_did, &record.name) - .await - .map_err(|e| AppError::Git(e.to_string()))?; - let head_ref = store::resolve_head(&disk_path, &record.default_branch); - let content = store::read_file(&disk_path, &head_ref, file_path).map_err(|e| { - let msg = e.to_string(); - // `git show ref:path` on a path absent from the tree is a 404, - // not a server error - if msg.contains("does not exist in") - || msg.contains("invalid object name") - || msg.contains("exists on disk, but not in") - { - AppError::NotFound(format!("file not found: {file_path}")) - } else { - AppError::Git(msg) - } - })?; + let default_branch = record.default_branch.clone(); + let repo = record.name.clone(); + let blob_path = file_path.to_string(); + let content = run_repo_git_read( + &state, + &headers, + peer, + &record, + "blob", + move |git_bin, path, deadline| { + let fail = |e: anyhow::Error| git_read_app_error(&e, &repo); + // A path absent from the tree, or a head with no commit yet, is a 404. + let not_found = || AppError::NotFound(format!("file not found: {blob_path}")); + let Some(head) = + store::resolve_head_id_bounded(git_bin, path, &default_branch, deadline) + .map_err(fail)? + else { + return Err(not_found()); + }; + store::read_file_bounded(git_bin, path, &head, &blob_path, deadline) + .map_err(fail)? + .ok_or_else(not_found) + }, + ) + .await?; // Guess content type let mime = match file_path.rsplit('.').next() { @@ -993,18 +1001,14 @@ pub async fn get_tree_root( State(state): State, Path((owner, name)): Path<(String, String)>, auth: Option>, + crate::rate_limit::PeerAddr(peer): crate::rate_limit::PeerAddr, + headers: axum::http::HeaderMap, ) -> Result> { let caller = auth.as_ref().map(|e| e.0 .0.as_str()); let (record, _rules) = crate::api::authorize_repo_read(&state, &owner, &name, caller, "/").await?; - let disk_path = state - .repo_store - .acquire(&record.owner_did, &record.name) - .await - .map_err(|e| AppError::Git(e.to_string()))?; - let head_ref = store::resolve_head(&disk_path, &record.default_branch); - let entries = store::ls_tree(&disk_path, &head_ref, "").unwrap_or_default(); + let entries = read_head_tree(&state, &headers, peer, &record, String::new()).await?; Ok(Json(serde_json::json!({ "entries": entries, "path": "" }))) } @@ -1014,6 +1018,8 @@ pub async fn get_tree( State(state): State, Path((owner, name, tree_path)): Path<(String, String, String)>, auth: Option>, + crate::rate_limit::PeerAddr(peer): crate::rate_limit::PeerAddr, + headers: axum::http::HeaderMap, ) -> Result> { let caller = auth.as_ref().map(|e| e.0 .0.as_str()); // Gate on the REQUESTED subtree, not the repo root (N3) — otherwise a caller @@ -1036,19 +1042,53 @@ pub async fn get_tree( let (record, _rules) = crate::api::authorize_repo_read(&state, &owner, &name, caller, &gate_path).await?; - let disk_path = state - .repo_store - .acquire(&record.owner_did, &record.name) - .await - .map_err(|e| AppError::Git(e.to_string()))?; - let head_ref = store::resolve_head(&disk_path, &record.default_branch); - let entries = store::ls_tree(&disk_path, &head_ref, &tree_path).unwrap_or_default(); + let entries = read_head_tree(&state, &headers, peer, &record, tree_path.clone()).await?; Ok(Json( serde_json::json!({ "entries": entries, "path": tree_path }), )) } +/// The tree listing at `tree_path` in the served head, read under +/// [`run_repo_git_read`]. A git read past the deadline is a 504. Any other +/// failure (no commit yet, a path git cannot list, an unreadable repo) is an +/// empty listing, as it was before the reads were bounded. +async fn read_head_tree( + state: &AppState, + headers: &axum::http::HeaderMap, + peer: Option, + record: &RepoRecord, + tree_path: String, +) -> Result> { + let default_branch = record.default_branch.clone(); + let repo = record.name.clone(); + run_repo_git_read( + state, + headers, + peer, + record, + "tree", + move |git_bin, path, deadline| { + let listing = store::resolve_head_id_bounded(git_bin, path, &default_branch, deadline) + .and_then(|head| match head { + Some(head) => store::ls_tree_bounded(git_bin, path, &head, &tree_path, deadline), + None => Ok(Vec::new()), + }); + match listing { + Ok(entries) => Ok(entries), + Err(e) if e.is::() => { + Err(git_read_app_error(&e, &repo)) + } + Err(e) => { + tracing::warn!(repo = %repo, err = %format!("{e:#}"), "tree read failed; listing empty"); + Ok(Vec::new()) + } + } + }, + ) + .await +} + // ── Git smart HTTP endpoints ────────────────────────────────────────────── fn smart_http_repo_name(repo: &str) -> Result<&str> { @@ -21303,6 +21343,18 @@ mod commits_tags_tests { "/api/v1/repos/{owner}/{repo}/tags", axum::routing::get(super::list_tags), ) + .route( + "/api/v1/repos/{owner}/{repo}/blob/{*path}", + axum::routing::get(super::get_blob), + ) + .route( + "/api/v1/repos/{owner}/{repo}/tree", + axum::routing::get(super::get_tree_root), + ) + .route( + "/api/v1/repos/{owner}/{repo}/tree/{*path}", + axum::routing::get(super::get_tree), + ) .with_state(state.clone()); if let Some(d) = did { r = r.layer(axum::Extension(AuthenticatedDid(d.to_string()))); @@ -22339,4 +22391,139 @@ mod commits_tags_tests { tokens.extend(ids); assert_denied_like_missing(&fx, "tags", &[String::new()], &tokens).await; } + + /// `src/lib.rs` and `README.md` committed on main. + fn blob_tree_fixture(dir: &Path) { + std::fs::create_dir_all(dir.join("src")).unwrap(); + std::fs::write(dir.join("src/lib.rs"), b"pub fn answer() -> u32 { 42 }\n").unwrap(); + std::fs::write(dir.join("README.md"), b"# fixture\n").unwrap(); + git_at(dir, &["add", "."], T0); + git_at(dir, &["commit", "-q", "-m", "files"], T0); + } + + async fn get(fx: &Fx, repo: &str, route: &str) -> (StatusCode, HeaderMap, String) { + let uri = format!("/api/v1/repos/{OWNER_SHORT}/{repo}/{route}"); + call(&fx.state, None, Some(PEER), &uri).await + } + + fn entry_paths(body: &str) -> Vec { + let v: serde_json::Value = serde_json::from_str(body).unwrap(); + v["entries"] + .as_array() + .unwrap_or_else(|| panic!("no entries array in {body}")) + .iter() + .map(|e| e["name"].as_str().unwrap().to_string()) + .collect() + } + + #[sqlx::test] + async fn blob_and_tree_serve_the_head_commit(pool: sqlx::PgPool) { + let fx = Fx::new(pool).await; + let dir = fx.repo("files", true).await; + blob_tree_fixture(&dir); + + let (status, headers, body) = get(&fx, "files", "blob/src/lib.rs").await; + assert_eq!(status, StatusCode::OK, "{body}"); + assert_eq!(body, "pub fn answer() -> u32 { 42 }\n"); + assert_eq!(headers["content-type"], "text/plain; charset=utf-8"); + + let (status, _, body) = get(&fx, "files", "tree").await; + assert_eq!(status, StatusCode::OK, "{body}"); + assert_eq!(entry_paths(&body), ["README.md", "src"]); + + let (status, _, body) = get(&fx, "files", "tree/src").await; + assert_eq!(status, StatusCode::OK, "{body}"); + assert_eq!(entry_paths(&body), ["lib.rs"]); + } + + #[sqlx::test] + async fn blob_of_a_missing_path_or_an_unborn_head_is_404(pool: sqlx::PgPool) { + let fx = Fx::new(pool).await; + let dir = fx.repo("files", true).await; + blob_tree_fixture(&dir); + let (status, _, body) = get(&fx, "files", "blob/src/nope.rs").await; + assert_eq!(status, StatusCode::NOT_FOUND, "{body}"); + assert!(body.contains("file not found: src/nope.rs"), "{body}"); + + fx.repo("unborn", true).await; + let (status, _, body) = get(&fx, "unborn", "blob/README.md").await; + assert_eq!(status, StatusCode::NOT_FOUND, "{body}"); + assert!(body.contains("file not found: README.md"), "{body}"); + } + + #[sqlx::test] + async fn tree_of_a_missing_path_or_an_unborn_head_is_empty(pool: sqlx::PgPool) { + let fx = Fx::new(pool).await; + let dir = fx.repo("files", true).await; + blob_tree_fixture(&dir); + let (status, _, body) = get(&fx, "files", "tree/nope").await; + assert_eq!(status, StatusCode::OK, "{body}"); + assert!(entry_paths(&body).is_empty(), "{body}"); + + fx.repo("unborn", true).await; + let (status, _, body) = get(&fx, "unborn", "tree").await; + assert_eq!(status, StatusCode::OK, "{body}"); + assert!(entry_paths(&body).is_empty(), "{body}"); + } + + #[sqlx::test] + async fn blob_and_tree_on_unreadable_repos_read_exactly_like_a_missing_one(pool: sqlx::PgPool) { + let fx = Fx::new(pool).await; + let token = "private-fixture-token-7731"; + let mut tokens = vec![token.to_string()]; + tokens.extend(seed_unreadable(&fx, token).await); + assert_denied_like_missing(&fx, "tree", &[String::new()], &tokens).await; + assert_denied_like_missing(&fx, "blob/README.md", &[String::new()], &tokens).await; + } + + #[sqlx::test] + async fn blob_and_tree_shed_503_when_the_read_pool_is_exhausted(pool: sqlx::PgPool) { + let mut fx = Fx::new(pool).await; + let dir = fx.repo("files", true).await; + blob_tree_fixture(&dir); + fx.state.git_read_semaphore = Arc::new(tokio::sync::Semaphore::new(0)); + for route in ["blob/README.md", "tree", "tree/src"] { + let (status, headers, body) = get(&fx, "files", route).await; + assert_eq!(status, StatusCode::SERVICE_UNAVAILABLE, "{route}: {body}"); + assert!(headers.get("retry-after").is_some(), "{route}"); + } + } + + /// A wedged `git show` or `git ls-tree` is reaped at the read deadline and + /// answers 504, while the runtime keeps serving: a timer on the same + /// current-thread runtime still fires on time during the stall. + #[cfg(unix)] + #[sqlx::test] + async fn blob_and_tree_past_the_deadline_are_504_without_stalling_the_runtime( + pool: sqlx::PgPool, + ) { + let mut fx = Fx::new(pool).await; + let dir = fx.repo("slow", true).await; + blob_tree_fixture(&dir); + let shim = tempfile::TempDir::new().unwrap(); + fx.state.git_bin = fake_git( + shim.path(), + "#!/bin/sh\ncase \" $*\" in *\" show \"*|*\" ls-tree \"*) sleep 30;; esac\nexec git \"$@\"\n", + ); + fx.set_deadline_secs(1); + for route in ["blob/README.md", "tree", "tree/src"] { + let started = std::time::Instant::now(); + let ticker = tokio::spawn(async { + let t = std::time::Instant::now(); + tokio::time::sleep(std::time::Duration::from_millis(100)).await; + t.elapsed() + }); + let (status, _, body) = get(&fx, "slow", route).await; + assert_eq!(status, StatusCode::GATEWAY_TIMEOUT, "{route}: {body}"); + assert!( + started.elapsed() < std::time::Duration::from_secs(20), + "{route}" + ); + let ticked = ticker.await.unwrap(); + assert!( + ticked < std::time::Duration::from_millis(900), + "{route}: a 100ms timer took {ticked:?}, so the git read held the runtime" + ); + } + } } diff --git a/crates/twigpine-node/src/git/store.rs b/crates/twigpine-node/src/git/store.rs index 62a6df58a..2016670f6 100644 --- a/crates/twigpine-node/src/git/store.rs +++ b/crates/twigpine-node/src/git/store.rs @@ -1756,26 +1756,36 @@ pub fn list_tags_bounded( Ok((tags, truncated)) } -/// List files in a tree at the given ref and path. -pub fn ls_tree(repo_path: &Path, refname: &str, tree_path: &str) -> Result> { +/// List the tree at `commit_id:tree_path` (the root when `tree_path` is empty), +/// the git child bounded by `deadline`. A path git cannot list (absent, or not a +/// tree) is an empty listing; a deadline or spawn failure is an error. +pub fn ls_tree_bounded( + git_bin: &str, + repo_path: &Path, + commit_id: &str, + tree_path: &str, + deadline: std::time::Instant, +) -> Result> { let tree_spec = if tree_path.is_empty() { - refname.to_string() + commit_id.to_string() } else { - format!("{refname}:{tree_path}") + format!("{commit_id}:{tree_path}") }; // Use -l to include blob sizes; standard output: " \t" - let output = Command::new("git") - .args(["ls-tree", "-l", &tree_spec]) - .current_dir(repo_path) - .output() - .context("failed to run git ls-tree")?; + let (status, out, _) = crate::git::visibility_pack::run_bounded_git_raw( + git_bin, + &["ls-tree", "-l", &tree_spec], + repo_path, + b"", + deadline, + )?; - if !output.status.success() { + if !status.success() { return Ok(vec![]); } - let stdout = String::from_utf8_lossy(&output.stdout); + let stdout = String::from_utf8_lossy(&out); let entries = stdout .lines() .filter_map(|line| { @@ -1799,21 +1809,37 @@ pub fn ls_tree(repo_path: &Path, refname: &str, tree_path: &str) -> Result Result> { - let spec = format!("{refname}:{file_path}"); - let output = Command::new("git") - .args(["show", &spec]) - .current_dir(repo_path) - .output() - .context("failed to run git show")?; +/// Read `commit_id:file_path` with `git show`, the git child bounded by +/// `deadline`. `None` means the path is not in that commit's tree; any other +/// git failure is an error. +pub fn read_file_bounded( + git_bin: &str, + repo_path: &Path, + commit_id: &str, + file_path: &str, + deadline: std::time::Instant, +) -> Result>> { + let spec = format!("{commit_id}:{file_path}"); + let (status, out, err) = crate::git::visibility_pack::run_bounded_git_raw( + git_bin, + &["show", &spec], + repo_path, + b"", + deadline, + )?; - if !output.status.success() { - let stderr = String::from_utf8_lossy(&output.stderr); - bail!("git show failed: {stderr}"); + if !status.success() { + let stderr = String::from_utf8_lossy(&err); + if stderr.contains("does not exist in") + || stderr.contains("invalid object name") + || stderr.contains("exists on disk, but not in") + { + return Ok(None); + } + bail!("git show failed: {}", stderr.trim()); } - Ok(output.stdout) + Ok(Some(out)) } #[derive(Debug, Clone, serde::Serialize)] From 72938ef84caf5d5cc6ddd0b33f898def51ced050 Mon Sep 17 00:00:00 2001 From: Beardthelion Date: Mon, 30 Nov 2026 06:47:32 +0000 Subject: [PATCH 2/2] fix(node): bound the post-read repo re-check by the read deadline The re-check after the git work had no timeout, so a stalled database could hold a blob, tree, commit or tag read past git_service_timeout_secs. It now runs under the read deadline, with a 2s grace so a read that spent the whole budget can still be verified. On expiry it returns the same fixed error as the pre-work re-check. --- crates/twigpine-node/src/api/repos.rs | 80 +++++++++++++++++++++++++-- 1 file changed, 75 insertions(+), 5 deletions(-) diff --git a/crates/twigpine-node/src/api/repos.rs b/crates/twigpine-node/src/api/repos.rs index 9c02f45a5..16f3bf801 100644 --- a/crates/twigpine-node/src/api/repos.rs +++ b/crates/twigpine-node/src/api/repos.rs @@ -640,6 +640,8 @@ const BAD_BEFORE_MESSAGE: &str = const GIT_READ_FAILED_MESSAGE: &str = "git read failed"; /// Cap on the git-read deadline so the `Instant` addition cannot overflow. const MAX_GIT_READ_DEADLINE: std::time::Duration = std::time::Duration::from_secs(365 * 24 * 3600); +/// How long the post-read repo row re-check may run past the read deadline. +const POST_READ_RECHECK_GRACE: std::time::Duration = std::time::Duration::from_secs(2); /// Query of `GET /api/v1/repos/:owner/:repo/commits`. Unknown keys are ignored on /// purpose: `gl repo commits` sends `branch`, which the server has never honored. @@ -778,19 +780,31 @@ where // (a `before` cursor missing from the replacement's history is a 400 about // the replacement): a missing or replaced row answers like the missing-repo // case the gate produces, exactly as the pre-work check does. The permits - // went with the blocking work, so this query holds no read slot. - match state.db.get_repo(&record.owner_did, &record.name).await { - Ok(Some(current)) if current.id == record.id => {} - Ok(_) => { + // went with the blocking work, so this query holds no read slot. It is + // bounded by the read deadline, with a short grace so a read that spent + // the whole budget can still be verified instead of failing here. + let recheck_deadline = deadline.max(std::time::Instant::now() + POST_READ_RECHECK_GRACE); + match tokio::time::timeout_at( + tokio::time::Instant::from_std(recheck_deadline), + state.db.get_repo(&record.owner_did, &record.name), + ) + .await + { + Ok(Ok(Some(current))) if current.id == record.id => {} + Ok(Ok(_)) => { return Err(AppError::RepoNotFound(format!( "{}/{}", record.owner_did, record.name ))); } - Err(e) => { + Ok(Err(e)) => { tracing::error!(repo = %record.name, err = %format!("{e:#}"), "repo row post-read re-check failed"); return Err(AppError::Git(GIT_READ_FAILED_MESSAGE.into())); } + Err(_elapsed) => { + tracing::warn!(repo = %record.name, "repo row post-read re-check timed out"); + return Err(AppError::Git(GIT_READ_FAILED_MESSAGE.into())); + } } result } @@ -22526,4 +22540,60 @@ mod commits_tags_tests { ); } } + + #[cfg(unix)] + #[sqlx::test] + async fn a_stalled_post_read_recheck_is_bounded_by_the_deadline(pool: sqlx::PgPool) { + use std::time::Duration; + let mut fx = Fx::new(pool.clone()).await; + let dir = fx.repo("stall", true).await; + blob_tree_fixture(&dir); + let shim = tempfile::TempDir::new().unwrap(); + let marker = shim.path().join("show-started"); + fx.state.git_bin = fake_git( + shim.path(), + &format!( + "#!/bin/sh\ncase \" $*\" in *\" show \"*) touch '{}'; sleep 1;; esac\nexec git \"$@\"\n", + marker.display() + ), + ); + fx.set_deadline_secs(2); + + let state = fx.state.clone(); + let uri = format!("/api/v1/repos/{OWNER_SHORT}/stall/blob/README.md"); + let started = std::time::Instant::now(); + let req = tokio::spawn(async move { call(&state, None, Some(PEER), &uri).await }); + for _ in 0..500 { + if marker.exists() { + break; + } + tokio::time::sleep(Duration::from_millis(10)).await; + } + assert!(marker.exists(), "the git read must have started"); + + // The pre-work re-check is done once git runs. Hold the repos table so + // the post-read re-check stalls the way a locked or slow database would. + let mut lock = pool.begin().await.unwrap(); + sqlx::query("LOCK TABLE repos IN ACCESS EXCLUSIVE MODE") + .execute(&mut *lock) + .await + .unwrap(); + let (status, _, body) = tokio::time::timeout(Duration::from_secs(15), req) + .await + .expect("the post-read re-check must not wait on the stalled database") + .unwrap(); + let elapsed = started.elapsed(); + lock.rollback().await.unwrap(); + + assert_eq!(status, StatusCode::INTERNAL_SERVER_ERROR, "{body}"); + assert!( + !body.contains("pub fn answer"), + "unverified content leaked: {body}" + ); + assert!( + elapsed + < Duration::from_secs(2) + super::POST_READ_RECHECK_GRACE + Duration::from_secs(2), + "the re-check ran {elapsed:?}, past the deadline plus grace" + ); + } }