use crate::background_tasks::track_background_tasks;
use crate::completion::completion_state;
use crate::executor::ProcessHandle;
use crate::streaming::{JsonRecordEvent, JsonRecordScanner};
use serde_json::Value;
use std::io;
use std::time::{Duration, Instant};
pub const DEFAULT_RESULT_POLL: Duration = Duration::from_millis(100);
#[derive(Debug, Clone, Default)]
pub struct StdoutMessageReader {
scanner: JsonRecordScanner,
messages: Vec<Value>,
scanned: usize,
}
impl StdoutMessageReader {
pub fn new() -> Self {
Self::default()
}
pub fn read(&mut self, stdout: &str) -> &[Value] {
let end = stdout.rfind('\n').map_or(0, |index| index + 1);
if end > self.scanned {
for event in self.scanner.write(&stdout[self.scanned..end]) {
if let JsonRecordEvent::Json { value, .. } = event {
match value {
Value::Array(values) => self.messages.extend(values),
value => self.messages.push(value),
}
}
}
self.scanned = end;
}
&self.messages
}
}
pub fn has_final_result(tool: &str, messages: &[Value]) -> bool {
matches!(
completion_state(tool, messages),
Some("completed" | "failed")
)
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ResultCloseOptions {
pub close_timeout: Option<Duration>,
pub background_wait: Option<Duration>,
pub poll: Duration,
}
impl Default for ResultCloseOptions {
fn default() -> Self {
Self {
close_timeout: None,
background_wait: None,
poll: DEFAULT_RESULT_POLL,
}
}
}
pub async fn wait_for_exit_after_result(
handle: &mut ProcessHandle,
tool: &str,
options: ResultCloseOptions,
) -> io::Result<(i32, bool)> {
let Some(close_timeout) = options.close_timeout else {
return Ok((handle.wait_for_exit().await?, false));
};
let mut reader = StdoutMessageReader::new();
let mut result_at: Option<Instant> = None;
let mut idle_at: Option<Instant> = None;
while !handle.try_wait()? {
tokio::time::sleep(options.poll).await;
if handle.try_wait()? {
break;
}
let messages = reader.read(&handle.peek_stdout());
if !has_final_result(tool, messages) {
result_at = None;
idle_at = None;
continue;
}
let now = Instant::now();
let first_result = *result_at.get_or_insert(now);
let running = !track_background_tasks(messages).running.is_empty();
idle_at = if running {
None
} else {
Some(idle_at.unwrap_or(now))
};
let idle_expired = idle_at.is_some_and(|at| now - at >= close_timeout);
let background_expired = options
.background_wait
.is_some_and(|wait| now - first_result >= wait + close_timeout);
if idle_expired || background_expired {
handle.terminate().await?;
return Ok((handle.wait_for_exit().await?, true));
}
}
Ok((handle.wait_for_exit().await?, false))
}