use std::process::Stdio;
use std::time::Duration;
use mlua::{Lua, UserData, UserDataMethods};
use crate::TOOL_TIMEOUT;
const CHILD_TIMEOUT: Duration = TOOL_TIMEOUT;
const MAX_OUTPUT: usize = 1024 * 1024;
#[derive(Clone, Copy, Debug)]
pub struct ProcessRunner;
impl ProcessRunner {
async fn spawn_tool(lua: &Lua, command: &str, args: &[String]) -> mlua::Result<mlua::Table> {
Self::spawn_tool_within(lua, command, args, CHILD_TIMEOUT).await
}
async fn spawn_tool_within(
lua: &Lua,
command: &str,
args: &[String],
timeout: Duration,
) -> mlua::Result<mlua::Table> {
let child = tokio::process::Command::new(command)
.args(args)
.stdin(Stdio::null())
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.kill_on_drop(true)
.spawn()
.map_err(|e| mlua::Error::RuntimeError(format!("could not start `{command}`: {e}")))?;
let output = tokio::time::timeout(timeout, child.wait_with_output())
.await
.map_err(|_| mlua::Error::RuntimeError(format!("`{command}` exceeded {timeout:?}")))?
.map_err(|e| mlua::Error::RuntimeError(format!("`{command}`: {e}")))?;
let stdout = String::from_utf8(output.stdout).map_err(|_| {
mlua::Error::RuntimeError(format!("`{command}` stdout is not valid UTF-8"))
})?;
let stderr = String::from_utf8(output.stderr).map_err(|_| {
mlua::Error::RuntimeError(format!("`{command}` stderr is not valid UTF-8"))
})?;
let truncated = stdout.len() > MAX_OUTPUT || stderr.len() > MAX_OUTPUT;
let table = lua
.create_table()
.map_err(|e| mlua::Error::RuntimeError(e.to_string()))?;
table
.set("code", output.status.code().unwrap_or(-1))
.map_err(|e| mlua::Error::RuntimeError(e.to_string()))?;
table
.set("stdout", truncate(&stdout, MAX_OUTPUT))
.map_err(|e| mlua::Error::RuntimeError(e.to_string()))?;
table
.set("stderr", truncate(&stderr, MAX_OUTPUT))
.map_err(|e| mlua::Error::RuntimeError(e.to_string()))?;
table
.set("truncated", truncated)
.map_err(|e| mlua::Error::RuntimeError(e.to_string()))?;
Ok(table)
}
}
impl UserData for ProcessRunner {
fn add_methods<M: UserDataMethods<Self>>(methods: &mut M) {
methods.add_async_function(
"spawn_tool",
|lua, (command, args): (String, mlua::Table)| async move {
let mut argv = Vec::new();
for arg in args.sequence_values::<String>() {
argv.push(arg.map_err(|e| mlua::Error::RuntimeError(format!("args: {e}")))?);
}
Self::spawn_tool(&lua, &command, &argv).await
},
);
}
}
fn truncate(text: &str, max: usize) -> &str {
if text.len() <= max {
return text;
}
let mut end = max;
while end > 0 && !text.is_char_boundary(end) {
end = end.saturating_sub(1);
}
text.get(..end).unwrap_or(text)
}
#[cfg(test)]
mod tests {
#![allow(
clippy::unwrap_used,
clippy::expect_used,
clippy::indexing_slicing,
clippy::as_conversions,
clippy::arithmetic_side_effects
)]
use mlua::Lua;
use super::{ProcessRunner, truncate};
#[test]
fn truncate_cuts_on_a_utf8_boundary() {
assert_eq!(truncate("hello", 10), "hello");
assert_eq!(truncate("hello", 3), "hel");
assert_eq!(truncate("héllo", 3), "hé");
assert_eq!(truncate("héllo", 2), "h");
}
#[tokio::test]
async fn spawn_tool_runs_a_real_process_and_returns_its_stdout() {
let lua = Lua::new();
let table = ProcessRunner::spawn_tool(&lua, "echo", &["hello".to_owned()])
.await
.expect("runs");
let code: i64 = table.get("code").expect("code");
let stdout: String = table.get("stdout").expect("stdout");
assert_eq!(code, 0);
assert_eq!(stdout.trim(), "hello");
}
#[tokio::test]
async fn a_non_zero_exit_is_a_value_carrying_the_code() {
let lua = Lua::new();
let table = ProcessRunner::spawn_tool(&lua, "sh", &["-c".to_owned(), "exit 3".to_owned()])
.await
.expect("runs");
let code: i64 = table.get("code").expect("code");
assert_eq!(code, 3);
}
#[tokio::test]
async fn an_unknown_command_is_an_error() {
let lua = Lua::new();
let error = ProcessRunner::spawn_tool(&lua, "yk-definitely-not-a-real-binary-12345", &[])
.await
.expect_err("must fail");
assert!(error.to_string().contains("could not start"), "{error}");
}
#[tokio::test]
async fn stderr_is_captured() {
let lua = Lua::new();
let table =
ProcessRunner::spawn_tool(&lua, "sh", &["-c".to_owned(), "echo oops >&2".to_owned()])
.await
.expect("runs");
let stderr: String = table.get("stderr").expect("stderr");
assert!(stderr.contains("oops"), "{stderr}");
}
#[tokio::test]
async fn a_child_that_outruns_its_deadline_is_killed_and_reported() {
let lua = Lua::new();
let error = ProcessRunner::spawn_tool_within(
&lua,
"sleep",
&["30".to_owned()],
std::time::Duration::from_millis(100),
)
.await
.expect_err("must time out");
assert!(error.to_string().contains("exceeded"), "{error}");
}
#[tokio::test]
async fn output_over_the_cap_is_truncated_and_flagged() {
let lua = Lua::new();
let table = ProcessRunner::spawn_tool(
&lua,
"sh",
&["-c".to_owned(), "yes | head -c 2000000".to_owned()],
)
.await
.expect("runs");
let stdout: String = table.get("stdout").expect("stdout");
let truncated: bool = table.get("truncated").expect("truncated");
assert_eq!(stdout.len(), super::MAX_OUTPUT);
assert!(truncated);
}
#[tokio::test]
async fn a_signal_killed_child_reports_minus_one() {
let lua = Lua::new();
let table =
ProcessRunner::spawn_tool(&lua, "sh", &["-c".to_owned(), "kill -9 $$".to_owned()])
.await
.expect("runs");
let code: i64 = table.get("code").expect("code");
assert_eq!(code, -1);
}
}