//! Bounded, backpressured output from a pinned Git process. use axum::body::{Body, Bytes}; use futures_util::{StreamExt, stream}; use std::{io, process::Stdio, time::Duration}; #[cfg(test)] use tokio::sync::Semaphore; use tokio::{ io::{AsyncReadExt, AsyncWriteExt}, process::Command, sync::{mpsc, oneshot}, }; pub struct Output { child: tokio::process::Child, stdout: tokio::process::ChildStdout, } impl Output { pub fn start(mut command: Command) -> io::Result { let mut child = command.kill_on_drop(true).stdout(Stdio::piped()).spawn()?; let stdout = child.stdout.take().ok_or_else(|| io::Error::other("missing Git stdout"))?; Ok(Self { child, stdout }) } pub async fn prefix(&mut self, len: usize) -> io::Result { let mut bytes = vec![0; len]; tokio::time::timeout(gitv_core::GIT_TIMEOUT, self.stdout.read_exact(&mut bytes)).await??; Ok(bytes.into()) } pub fn body(mut self, prefix: Bytes, input: Option, permit: impl Send + 'static, timeout: Duration) -> Body { let (tx, rx) = mpsc::channel::(2); let (finished, status) = oneshot::channel(); let (body_guard, dropped) = oneshot::channel::<()>(); tokio::spawn(async move { let _permit = permit; let deadline = tokio::time::Instant::now() + timeout; let mut stdin = self.child.stdin.take(); let write = async move { if let Some(input) = input { stdin.as_mut().ok_or_else(|| io::Error::other("missing Git stdin"))?.write_all(&input).await?; } drop(stdin); Ok::<_, io::Error>(()) }; let read = async { let mut buf = vec![0; 65536]; loop { let count = self.stdout.read(&mut buf).await?; if count == 0 { break; } tx.send(Bytes::copy_from_slice(&buf[..count])).await.map_err(|_| io::ErrorKind::BrokenPipe)?; } if !self.child.wait().await?.success() { return Err(io::Error::other("Git transfer failed")); } Ok(()) }; let outcome = tokio::select! { _ = tx.closed() => return, result = tokio::time::timeout_at(deadline, async { tokio::try_join!(write, read).map(|_| ()) }) => result.unwrap_or_else(|_| Err(io::ErrorKind::TimedOut.into())), }; drop(self); drop(tx); let _ = finished.send(outcome); // Hold the slot through buffered delivery, but never beyond the transfer deadline. let _ = tokio::time::timeout_at(deadline, dropped).await; }); // The worker's terminal status has its own channel (a oneshot), so a full // byte queue cannot turn a failed transfer into successful EOF. let chunks = stream::unfold(rx, |mut rx| async { Some((rx.recv().await?, rx)) }).map(Ok); let end = stream::once(async move { let _guard = body_guard; status.await.map_err(io::Error::other)??; Ok::<_, io::Error>(Bytes::new()) }); Body::from_stream(stream::iter((!prefix.is_empty()).then_some(Ok(prefix))).chain(chunks).chain(end)) } } #[cfg(test)] mod tests { use super::*; #[tokio::test] async fn dropping_a_transfer_body_releases_its_slot() { static SLOT: Semaphore = Semaphore::const_new(1); let mut command = Command::new("head"); command.args(["-c", "1048576", "/dev/zero"]); let output = Output::start(command).unwrap(); let body = output.body(Bytes::new(), None, SLOT.try_acquire().unwrap(), Duration::from_secs(300)); drop(body); let permit = tokio::time::timeout(Duration::from_secs(3), SLOT.acquire()).await.unwrap().unwrap(); drop(permit); } #[tokio::test] async fn stalled_body_times_out_and_reports_the_error_after_buffered_bytes() { static SLOT: Semaphore = Semaphore::const_new(1); let mut command = Command::new("head"); command.args(["-c", "1048576", "/dev/zero"]); let output = Output::start(command).unwrap(); let body = output.body(Bytes::new(), None, SLOT.try_acquire().unwrap(), Duration::from_millis(50)); assert!(SLOT.try_acquire().is_err()); let permit = tokio::time::timeout(Duration::from_secs(3), SLOT.acquire()).await.unwrap().unwrap(); assert!(axum::body::to_bytes(body, 1 << 20).await.is_err()); drop(permit); } }