From 5455c8a1ecf6c5a884426af499c21f2b8ef77dec Mon Sep 17 00:00:00 2001 From: Beardthelion Date: Mon, 30 Nov 2026 05:30:26 +0000 Subject: [PATCH] perf: batch git issue listing reads --- crates/twigpine-node/src/git/issues.rs | 162 +++++++++++++++++-------- 1 file changed, 111 insertions(+), 51 deletions(-) diff --git a/crates/twigpine-node/src/git/issues.rs b/crates/twigpine-node/src/git/issues.rs index e8beb2322..63d4da106 100644 --- a/crates/twigpine-node/src/git/issues.rs +++ b/crates/twigpine-node/src/git/issues.rs @@ -6,8 +6,9 @@ //! This makes them content-addressed and travel with the repo. use anyhow::{Context, Result}; +use std::io::Write; use std::path::Path; -use std::process::Command; +use std::process::{Command, Stdio}; /// Write a JSON blob for an issue and set the ref. pub fn create_issue(repo_path: &Path, issue_id: &str, json: &str) -> Result<()> { @@ -21,7 +22,6 @@ pub fn create_issue(repo_path: &Path, issue_id: &str, json: &str) -> Result<()> .spawn() .context("failed to spawn git hash-object")?; - use std::io::Write; let mut child = hash_output; // Write the blob to stdin, but always reap the child afterward even if the // write fails, so a stdin-write error can't drop the Child unwaited and leak @@ -115,16 +115,21 @@ fn ref_name_resolves_bounded( Ok(ref_listed(&out, ref_name)) } -/// The " blob " header parse and body slice of `cat-file --batch` -/// output, shared by the unbounded and bounded readers. The caller handles the -/// " missing" line first; anything else here is one object's answer. -fn catfile_batch_body(ref_name: &str, stdout: &[u8]) -> Result> { - // Header: " \n" then exactly bytes plus a newline. +/// Consume one `cat-file --batch` record, leaving the next record in `stdout`. +fn read_batch_record(ref_name: &str, stdout: &mut &[u8]) -> Result> { let header_end = stdout .iter() - .position(|b| *b == b'\n') + .position(|&b| b == b'\n') .context("unexpected git cat-file --batch output")?; - let header = String::from_utf8_lossy(&stdout[..header_end]); + let header = &stdout[..header_end]; + let rest = &stdout[header_end + 1..]; + if header.strip_suffix(b" missing") == Some(ref_name.as_bytes()) { + *stdout = rest; + return Ok(None); + } + + // Header: " \n" then exactly bytes plus a newline. + let header = String::from_utf8_lossy(header); let mut parts = header.split(' '); parts.next(); let obj_type = parts.next().unwrap_or(""); @@ -135,12 +140,13 @@ fn catfile_batch_body(ref_name: &str, stdout: &[u8]) -> Result> { .next() .and_then(|s| s.parse().ok()) .context("unexpected git cat-file --batch header")?; - let body = &stdout[header_end + 1..]; - anyhow::ensure!( - body.len() >= size, - "truncated git cat-file --batch body for {ref_name}" - ); - Ok(Some(String::from_utf8_lossy(&body[..size]).to_string())) + let (body, rest) = rest + .split_at_checked(size) + .with_context(|| format!("truncated git cat-file --batch body for {ref_name}"))?; + *stdout = rest + .strip_prefix(b"\n") + .with_context(|| format!("missing git cat-file --batch separator for {ref_name}"))?; + Ok(Some(String::from_utf8_lossy(body).into_owned())) } /// Read the blob behind an issue ref. @@ -169,7 +175,6 @@ fn read_issue_blob(repo_path: &Path, ref_name: &str) -> Result> { .spawn() .context("failed to spawn git cat-file --batch")?; - use std::io::Write; // Reap the child even when the write fails so a stdin error cannot drop an // unwaited Child and leak a zombie (#53). let write_result = match child.stdin.take() { @@ -193,15 +198,11 @@ fn read_issue_blob(repo_path: &Path, ref_name: &str) -> Result> { // " missing\n" covers an absent ref and an unreadable object; only a // ref that still resolves is the error case. - let missing = format!("{ref_name} missing\n"); - if output.stdout.as_slice() == missing.as_bytes() { - return match ref_name_resolves(repo_path, ref_name)? { - true => anyhow::bail!("issue ref resolves but its object is unreadable: {ref_name}"), - false => Ok(None), - }; + let content = read_batch_record(ref_name, &mut output.stdout.as_slice())?; + if content.is_none() && ref_name_resolves(repo_path, ref_name)? { + anyhow::bail!("issue ref resolves but its object is unreadable: {ref_name}"); } - - catfile_batch_body(ref_name, &output.stdout) + Ok(content) } /// Deadline-bounded variant of [`read_issue_blob`]: the same missing-vs-error @@ -229,15 +230,11 @@ fn read_issue_blob_bounded( // Same disambiguation as the unbounded reader: "missing" covers an absent // ref and an unreadable object; only a ref that still resolves is an error. - let missing = format!("{ref_name} missing\n"); - if stdout.as_slice() == missing.as_bytes() { - return match ref_name_resolves_bounded(git_bin, repo_path, ref_name, deadline)? { - true => anyhow::bail!("issue ref resolves but its object is unreadable: {ref_name}"), - false => Ok(None), - }; + let content = read_batch_record(ref_name, &mut stdout.as_slice())?; + if content.is_none() && ref_name_resolves_bounded(git_bin, repo_path, ref_name, deadline)? { + anyhow::bail!("issue ref resolves but its object is unreadable: {ref_name}"); } - - catfile_batch_body(ref_name, &stdout) + Ok(content) } /// Deadline-bounded variant of [`create_issue`] for compensation paths: the @@ -313,22 +310,75 @@ pub fn list_issues(repo_path: &Path) -> Result> { } let refs_str = String::from_utf8_lossy(&list_output.stdout); - let mut issues = Vec::new(); + let refs: Vec<_> = refs_str + .lines() + .map(str::trim) + .filter(|name| !name.is_empty()) + .collect(); + if refs.is_empty() { + return Ok(Vec::new()); + } - for ref_name in refs_str.lines() { - let ref_name = ref_name.trim(); - if ref_name.is_empty() { - continue; + let mut input = Vec::with_capacity(list_output.stdout.len()); + for ref_name in &refs { + if !issue_ref_name_is_safe(ref_name) { + anyhow::bail!("refusing issue ref outside the issues namespace: {ref_name}"); } + input.extend_from_slice(ref_name.as_bytes()); + input.push(b'\n'); + } + + // allow-unbounded-git: listing retains the existing unbounded read path. + let mut child = Command::new("git") + .args(["cat-file", "--batch"]) + .current_dir(repo_path) + .stdin(Stdio::piped()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .spawn() + .context("failed to spawn git cat-file --batch")?; + + let stdin = child.stdin.take(); + let output = std::thread::scope(|scope| { + // Drain output while writing requests so neither side blocks on a full pipe. + let writer = std::thread::Builder::new().spawn_scoped(scope, move || { + stdin + .context("git cat-file --batch stdin unavailable")? + .write_all(&input) + .context("failed to write ref names to git cat-file stdin") + }); + let output = child + .wait_with_output() + .context("git cat-file --batch failed")?; + writer + .context("failed to spawn git cat-file stdin writer")? + .join() + .map_err(|_| anyhow::anyhow!("git cat-file stdin writer panicked"))??; + Ok::<_, anyhow::Error>(output) + })?; + if !output.status.success() { + let stderr = String::from_utf8_lossy(&output.stderr); + anyhow::bail!("git cat-file --batch failed: {}", stderr.trim()); + } + let mut stdout = output.stdout.as_slice(); + let mut issues = Vec::with_capacity(refs.len()); + for ref_name in refs { // Read the blob content. A ref that vanished between for-each-ref and // here is skipped; a ref that resolves but fails to read propagates so // a degraded object store errors the listing instead of under-reporting. - match read_issue_blob(repo_path, ref_name)? { + match read_batch_record(ref_name, &mut stdout)? { Some(content) => issues.push(content), - None => continue, + None if ref_name_resolves(repo_path, ref_name)? => { + anyhow::bail!("issue ref resolves but its object is unreadable: {ref_name}"); + } + None => {} } } + anyhow::ensure!( + stdout.is_empty(), + "unexpected extra git cat-file --batch output" + ); Ok(issues) } @@ -970,18 +1020,28 @@ mod tests { fn test_list_issues_returns_all() { let dir = TempDir::new().unwrap(); init_repo(&dir); - create_issue( - dir.path(), - "aaa00000-0000-0000-0000-000000000000", - r#"{"status":"open"}"#, - ) - .unwrap(); - create_issue( - dir.path(), - "bbb00000-0000-0000-0000-000000000000", - r#"{"status":"open"}"#, - ) - .unwrap(); + let first = format!( + "{{\n \"status\": \"open\",\n \"body\": \"{}\"\n}}\n", + "x".repeat(128 * 1024) + ); + let second = "not valid JSON\n"; + create_issue(dir.path(), "bbb00000-0000-0000-0000-000000000000", second).unwrap(); + create_issue(dir.path(), "aaa00000-0000-0000-0000-000000000000", &first).unwrap(); assert_eq!(list_issues(dir.path()).unwrap().len(), 2); + assert_eq!(list_issues(dir.path()).unwrap(), [first.as_str(), second]); + } + + #[test] + fn test_read_batch_record_skips_missing_before_next_issue() { + let mut stdout = &b"refs/gitlawb/issues/missing missing\n0000 blob 5\na\nb\xff\n\n"[..]; + assert_eq!( + read_batch_record("refs/gitlawb/issues/missing", &mut stdout).unwrap(), + None + ); + assert_eq!( + read_batch_record("refs/gitlawb/issues/present", &mut stdout).unwrap(), + Some("a\nb\u{fffd}\n".to_owned()) + ); + assert!(stdout.is_empty()); } }