use crate::runtime::{Executor, OutputLine, OutputStream, RuntimeError};
use std::collections::VecDeque;
use std::sync::Arc;
use std::time::Instant;
use tokio::io::{AsyncBufReadExt, BufReader};
use tokio::process::Child;
use tokio::sync::mpsc::UnboundedReceiver;
use tokio::task::JoinHandle;
pub const OUTPUT_BUFFER_CAP: usize = 2_000;
#[derive(Debug, Clone)]
pub struct CapturedLine {
pub stream: OutputStream,
pub text: String,
}
impl From<OutputLine> for CapturedLine {
fn from(o: OutputLine) -> Self {
Self {
stream: o.stream,
text: o.line,
}
}
}
pub struct RunState {
pub name: String,
pub started_at: Instant,
pub finished_at: Option<Instant>,
pub completion: Option<JoinHandle<Result<i32, RuntimeError>>>,
pub output_rx: UnboundedReceiver<OutputLine>,
pub buffer: VecDeque<CapturedLine>,
pub exit_code: Option<i32>,
pub error: Option<String>,
}
impl RunState {
pub fn spawn_child(label: impl Into<String>, mut child: Child) -> Self {
let (tx, output_rx) = tokio::sync::mpsc::unbounded_channel::<OutputLine>();
let stdout = child.stdout.take();
let stderr = child.stderr.take();
let tx_out = tx.clone();
if let Some(s) = stdout {
tokio::spawn(async move {
let mut lines = BufReader::new(s).lines();
while let Ok(Some(line)) = lines.next_line().await {
if tx_out
.send(OutputLine {
stream: OutputStream::Stdout,
line,
})
.is_err()
{
break;
}
}
});
}
if let Some(s) = stderr {
tokio::spawn(async move {
let mut lines = BufReader::new(s).lines();
while let Ok(Some(line)) = lines.next_line().await {
if tx
.send(OutputLine {
stream: OutputStream::Stderr,
line,
})
.is_err()
{
break;
}
}
});
}
let completion = tokio::spawn(async move {
child
.wait()
.await
.map(|s| s.code().unwrap_or(-1))
.map_err(|e| RuntimeError::Backend(crate::container::BackendError::Spawn(e)))
});
Self {
name: label.into(),
started_at: Instant::now(),
finished_at: None,
completion: Some(completion),
output_rx,
buffer: VecDeque::with_capacity(OUTPUT_BUFFER_CAP),
exit_code: None,
error: None,
}
}
pub fn spawn(executor: &Executor, name: impl Into<String>, args: Vec<String>) -> Self {
let (sink, output_rx) = crate::runtime::ChannelSink::new_pair();
let owned_name: String = name.into();
let task_name = owned_name.clone();
let exec = executor.with_sink(Arc::new(sink));
let completion = tokio::spawn(async move { exec.run_recipe(&task_name, &args).await });
Self {
name: owned_name,
started_at: Instant::now(),
finished_at: None,
completion: Some(completion),
output_rx,
buffer: VecDeque::with_capacity(OUTPUT_BUFFER_CAP),
exit_code: None,
error: None,
}
}
pub fn drain(&mut self) -> usize {
let mut drained = 0;
while let Ok(line) = self.output_rx.try_recv() {
push_capped(&mut self.buffer, line.into());
drained += 1;
}
drained
}
pub fn poll_completion(&mut self) {
if self.is_done() {
return;
}
let Some(handle) = self.completion.as_mut() else {
return;
};
if !handle.is_finished() {
return;
}
let handle = self.completion.take().expect("checked above");
use futures::FutureExt;
let result = handle
.now_or_never()
.expect("is_finished returned true above");
match result {
Ok(Ok(code)) => self.exit_code = Some(code),
Ok(Err(e)) => self.error = Some(format!("{e}")),
Err(e) => self.error = Some(format!("task panicked: {e}")),
}
self.finished_at = Some(Instant::now());
}
pub fn is_done(&self) -> bool {
self.exit_code.is_some() || self.error.is_some()
}
pub fn abort(&mut self) {
if self.is_done() {
return;
}
if let Some(handle) = self.completion.take() {
handle.abort();
}
self.error = Some("aborted".into());
self.finished_at = Some(Instant::now());
}
pub fn duration(&self) -> std::time::Duration {
match self.finished_at {
Some(t) => t.saturating_duration_since(self.started_at),
None => self.started_at.elapsed(),
}
}
pub fn status_label(&self) -> String {
if let Some(code) = self.exit_code {
if code == 0 {
format!("{} · ✓ exit 0", self.name)
} else {
format!("{} · ✗ exit {}", self.name, code)
}
} else if let Some(err) = &self.error {
format!("{} · ! {}", self.name, err)
} else {
format!(
"{} · running ({:.1}s)",
self.name,
self.started_at.elapsed().as_secs_f32()
)
}
}
}
pub(crate) fn push_capped(buf: &mut VecDeque<CapturedLine>, line: CapturedLine) {
if buf.len() == OUTPUT_BUFFER_CAP {
buf.pop_front();
}
buf.push_back(line);
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn push_capped_evicts_oldest() {
let mut buf = VecDeque::new();
for i in 0..(OUTPUT_BUFFER_CAP + 5) {
push_capped(
&mut buf,
CapturedLine {
stream: OutputStream::Stdout,
text: format!("line {i}"),
},
);
}
assert_eq!(buf.len(), OUTPUT_BUFFER_CAP);
assert_eq!(buf.front().unwrap().text, "line 5");
}
}