Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 8 additions & 1 deletion crates/twigpine-node/src/api/issues.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2766,7 +2766,7 @@ mod corrupt_store_tests {
let owner = "did:key:zISSUELISTBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB";
let dir = TempDir::new().unwrap();
let mut state = state_with_repos_dir(&pool, dir.path()).await;
std::sync::Arc::make_mut(&mut state.config).git_service_timeout_secs = 1;
std::sync::Arc::make_mut(&mut state.config).git_service_timeout_secs = 5;
state
.db
.create_repo(&seed_repo(owner, "slow"))
Expand Down Expand Up @@ -2797,6 +2797,13 @@ mod corrupt_store_tests {
.trim()
.parse()
.unwrap();
tokio::time::timeout(std::time::Duration::from_secs(5), async {
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
while unsafe { libc::kill(pid, 0) } == 0 {
tokio::time::sleep(std::time::Duration::from_millis(10)).await;
}
})
.await
.expect("git child must be reaped after the response");
assert_eq!(
unsafe { libc::kill(pid, 0) },
-1,
Expand Down
170 changes: 161 additions & 9 deletions crates/twigpine-node/src/api/repos.rs
Original file line number Diff line number Diff line change
Expand Up @@ -678,8 +678,9 @@ fn git_read_app_error(err: &anyhow::Error, repo: &str) -> AppError {
/// uses: the per-caller read permit, then the shared read permit (a refusal of
/// either is a 503), then the repo acquire bounded by `git_acquire_timeout_secs`.
/// `work` runs on a blocking thread with one deadline of `git_service_timeout_secs`
/// and owns both permits, so they are released only after its last git child is
/// reaped, even when the client disconnects first.
/// that also bounds the wait for the blocking task. The task owns both permits,
/// so they are released only after its last git child is reaped, even when the
/// handler times out or the client disconnects first.
pub(super) async fn run_repo_git_read<T, F>(
state: &AppState,
headers: &axum::http::HeaderMap,
Expand Down Expand Up @@ -762,15 +763,23 @@ where

let git_bin = state.git_bin.clone();
let repo = record.name.clone();
let result = tokio::task::spawn_blocking(move || {
let task = tokio::task::spawn_blocking(move || {
let _held = (permit, caller_permit);
if std::time::Instant::now() >= deadline {
return Err(git_read_app_error(
&smart_http::GitServiceTimeout.into(),
&repo,
));
}
work(&git_bin, &disk_path, deadline)
})
.await
.map_err(|e| {
tracing::error!(repo = %repo, err = %e, "git read task failed");
AppError::Git(GIT_READ_FAILED_MESSAGE.into())
})?;
});
let result = tokio::time::timeout_at(tokio::time::Instant::from_std(deadline), task)
.await
.map_err(|_| git_read_app_error(&smart_http::GitServiceTimeout.into(), &record.name))?
.map_err(|e| {
tracing::error!(repo = %record.name, err = %e, "git read task failed");
AppError::Git(GIT_READ_FAILED_MESSAGE.into())
})?;

// The pre-work re-check cannot cover a replacement that lands while the
// git children run: disk identity is owner+name only, so results computed
Expand Down Expand Up @@ -22309,6 +22318,149 @@ mod commits_tags_tests {
}
}

#[sqlx::test]
async fn git_read_deadline_bounds_blocking_queue_wait(pool: sqlx::PgPool) {
use axum::response::IntoResponse;
use std::process::Command;
use std::time::{Duration, Instant};

let mut fx = Fx::new(pool).await;
fx.repo("queued", true).await;
single_slot_pools(&mut fx);
fx.set_deadline_secs(1);
let record = fx
.state
.db
.get_repo(OWNER, "queued")
.await
.unwrap()
.unwrap();
let (git_started_tx, mut git_started_rx) = tokio::sync::oneshot::channel();

tokio::task::spawn_blocking(move || {
tokio::runtime::Builder::new_current_thread()
.enable_all()
.max_blocking_threads(1)
.build()
.unwrap()
.block_on(async {
let (started_tx, started_rx) = tokio::sync::oneshot::channel();
let (release_tx, release_rx) = std::sync::mpsc::channel();
let blocker = tokio::task::spawn_blocking(move || {
started_tx.send(()).unwrap();
let _ = release_rx.recv_timeout(Duration::from_secs(10));
});
started_rx.await.unwrap();

let start = Instant::now();
let read = super::run_repo_git_read(
&fx.state,
&HeaderMap::new(),
Some(PEER.parse().unwrap()),
&record,
"commits",
move |git, dir, _deadline| {
let mut child = Command::new(git)
.arg("--version")
.current_dir(dir)
.stdout(std::process::Stdio::null())
.spawn()
.unwrap();
git_started_tx.send(()).unwrap();
assert!(child.wait().unwrap().success());
Ok(())
},
)
.await;
let elapsed = start.elapsed();
let status = read.unwrap_err().into_response().status();
eprintln!("queued git read returned {status} after {elapsed:?}");
assert_eq!(status, StatusCode::GATEWAY_TIMEOUT);
assert!(elapsed >= Duration::from_secs(1), "{elapsed:?}");
assert!(elapsed < Duration::from_secs(3), "{elapsed:?}");

release_tx.send(()).unwrap();
blocker.await.unwrap();
tokio::time::timeout(Duration::from_secs(3), &mut git_started_rx)
.await
.expect("the blocking queue drains")
.expect_err("expired queued work must not spawn Git");
});
})
.await
.unwrap();
}

#[sqlx::test]
async fn git_read_deadline_keeps_both_permits_until_git_is_reaped(pool: sqlx::PgPool) {
use axum::response::IntoResponse;
use std::process::{Command, Stdio};
use std::time::Duration;

let mut fx = Fx::new(pool).await;
fx.repo("running", true).await;
single_slot_pools(&mut fx);
fx.set_deadline_secs(1);
let record = fx
.state
.db
.get_repo(OWNER, "running")
.await
.unwrap()
.unwrap();
let (started_tx, started_rx) = tokio::sync::oneshot::channel();
let (release_tx, release_rx) = std::sync::mpsc::channel();
let (reaped_tx, reaped_rx) = tokio::sync::oneshot::channel();
let state = fx.state.clone();
let read = tokio::spawn(async move {
super::run_repo_git_read(
&state,
&HeaderMap::new(),
Some(PEER.parse().unwrap()),
&record,
"commits",
move |git, dir, _deadline| {
let mut child = Command::new(git)
.args(["hash-object", "--stdin"])
.current_dir(dir)
.stdin(Stdio::piped())
.stdout(Stdio::null())
.spawn()
.unwrap();
let _ = started_tx.send(());
let _ = release_rx.recv_timeout(Duration::from_secs(10));
assert!(child.wait().unwrap().success());
let _ = reaped_tx.send(());
Ok(())
},
)
.await
});

started_rx.await.expect("Git started before the deadline");
let status = tokio::time::timeout(Duration::from_secs(3), read)
.await
.expect("the read times out before Git is reaped")
.unwrap()
.unwrap_err()
.into_response()
.status();
assert_eq!(status, StatusCode::GATEWAY_TIMEOUT);
assert_eq!(fx.state.git_read_semaphore.available_permits(), 0);
assert!(caller_slot_is_taken(&fx));

release_tx.send(()).unwrap();
tokio::time::timeout(Duration::from_secs(3), async {
reaped_rx.await.unwrap();
while fx.state.git_read_semaphore.available_permits() == 0 || caller_slot_is_taken(&fx)
{
tokio::time::sleep(Duration::from_millis(1)).await;
}
})
.await
.expect("both permits return after Git is reaped");
}

/// The permits belong to the blocking work, not the handler future: a client that
/// disconnects while git is running must not free the slots until git has exited.
#[cfg(unix)]
Expand Down
Loading