use std::future::Future;
use std::path::Path;
use std::pin::Pin;
use std::sync::Arc;
use std::time::Duration;
use async_channel::Sender;
#[derive(Debug, thiserror::Error)]
pub enum ExportError {
#[error("cannot start git in the subagent's sandbox: {0}")]
Launch(String),
#[error("cannot talk to git in the subagent's sandbox: {0}")]
Io(#[from] std::io::Error),
#[error("git in the subagent's sandbox {}: {stderr}", exit_description(*.code))]
Failed {
code: Option<i32>,
stderr: String,
},
#[error("git in the subagent's sandbox printed more than the {limit} bytes an import may take")]
OverBudget {
limit: u64,
},
#[error("git in the subagent's sandbox did not finish within {} seconds and was killed", .0.as_secs())]
TimedOut(Duration),
#[error("nothing was reading the output of git in the subagent's sandbox")]
OutputClosed,
}
fn exit_description(code: Option<i32>) -> String {
code.map_or_else(
|| "was killed by a signal".to_string(),
|code| format!("exited with {code}"),
)
}
#[derive(Debug, Clone)]
pub struct SandboxedExit {
pub code: Option<i32>,
pub stderr: String,
}
impl SandboxedExit {
pub const fn success(&self) -> bool {
matches!(self.code, Some(0))
}
pub fn into_failure(self) -> ExportError {
ExportError::Failed {
code: self.code,
stderr: self.stderr,
}
}
}
pub struct SandboxedRun<'a> {
pub repository: &'a Path,
pub args: &'a [&'a str],
pub stdin: Vec<u8>,
pub stdout: Sender<Vec<u8>>,
}
#[derive(Debug, Clone, Copy)]
pub struct Bounds {
pub bytes: Option<u64>,
pub time: Duration,
}
pub async fn within<T>(limit: Duration, future: impl Future<Output = T>) -> Option<T> {
futures_lite::future::or(async { Some(future.await) }, async {
async_io::Timer::after(limit).await;
None
})
.await
}
pub trait SandboxedGitImpl: Send + Sync {
fn run<'a>(
&'a self,
run: SandboxedRun<'a>,
) -> Pin<Box<dyn Future<Output = Result<SandboxedExit, ExportError>> + Send + 'a>>;
}
#[derive(Clone)]
pub struct SubagentGit {
backend: Arc<dyn SandboxedGitImpl>,
}
impl std::fmt::Debug for SubagentGit {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("SubagentGit").finish_non_exhaustive()
}
}
pub struct Collected {
pub exit: SandboxedExit,
pub stdout: Vec<u8>,
}
pub const PIPE_DEPTH: usize = 8;
impl SubagentGit {
pub fn new(backend: Arc<dyn SandboxedGitImpl>) -> Self {
Self { backend }
}
pub async fn run(&self, run: SandboxedRun<'_>) -> Result<SandboxedExit, ExportError> {
self.backend.run(run).await
}
pub async fn collect(
&self,
repository: &Path,
args: &[&str],
bounds: Bounds,
) -> Result<Collected, ExportError> {
let (tx, rx) = async_channel::bounded(PIPE_DEPTH);
let run = self.run(SandboxedRun {
repository,
args,
stdin: Vec::new(),
stdout: tx,
});
let gather = async {
let mut stdout = Vec::new();
while let Ok(chunk) = rx.recv().await {
if let Some(limit) = bounds.bytes
&& u64::try_from(stdout.len() + chunk.len()).map_or(true, |len| len > limit)
{
return Err(ExportError::OverBudget { limit });
}
stdout.extend_from_slice(&chunk);
}
Ok(stdout)
};
let (exit, stdout) = within(bounds.time, futures::future::join(run, gather))
.await
.ok_or(ExportError::TimedOut(bounds.time))?;
match (exit, stdout) {
(_, Err(error)) | (Err(error), _) => Err(error),
(Ok(exit), Ok(stdout)) => Ok(Collected { exit, stdout }),
}
}
pub async fn succeed(
&self,
repository: &Path,
args: &[&str],
bounds: Bounds,
) -> Result<Vec<u8>, ExportError> {
let Collected { exit, stdout } = self.collect(repository, args, bounds).await?;
if exit.success() {
Ok(stdout)
} else {
Err(exit.into_failure())
}
}
}