use crate::attachment::{AttachmentResolution, CommandSpec};
use anyhow::{Context, Result, bail};
use std::{
io::Read,
process::{Command, Stdio},
sync::mpsc,
thread,
time::{Duration, Instant},
};
#[derive(Clone, Copy, Debug)]
pub struct ResolverLimits {
pub timeout: Duration,
pub output_bytes: usize,
}
impl Default for ResolverLimits {
fn default() -> Self {
Self {
timeout: Duration::from_secs(10),
output_bytes: 1024 * 1024,
}
}
}
pub fn resolve(spec: &CommandSpec, limits: ResolverLimits) -> Result<AttachmentResolution> {
spec.validate()?;
if limits.timeout.is_zero() || limits.output_bytes == 0 {
bail!("resolver limits must be nonzero");
}
let mut command = Command::new(&spec.program);
command
.args(&spec.args)
.stdin(Stdio::null())
.stdout(Stdio::piped())
.stderr(Stdio::null());
if let Some(cwd) = &spec.cwd {
command.current_dir(cwd);
}
let mut child = command.spawn().context("could not start resolver")?;
let stdout = child.stdout.take().context("resolver stdout unavailable")?;
let (send, receive) = mpsc::channel();
thread::spawn(move || {
let mut bytes = Vec::new();
let result = stdout
.take(limits.output_bytes.saturating_add(1) as u64)
.read_to_end(&mut bytes)
.map(|_| bytes);
let _ = send.send(result);
});
let deadline = Instant::now() + limits.timeout;
let status = loop {
if let Some(status) = child.try_wait()? {
break status;
}
if Instant::now() >= deadline {
let _ = child.kill();
let _ = child.wait();
bail!("resolver timed out");
}
thread::sleep(Duration::from_millis(10));
};
let bytes = receive
.recv_timeout(deadline.saturating_duration_since(Instant::now()))
.context("resolver output did not close before timeout")??;
if bytes.len() > limits.output_bytes {
bail!("resolver output exceeds limit");
}
if !status.success() {
bail!("resolver exited unsuccessfully");
}
serde_json::from_slice(&bytes).context("invalid attachment resolution")
}