use crate::container::{Backend, BackendError, ServiceStatus};
use crate::runtime::{OutputLine, OutputStream};
use crate::tui::runner::{CapturedLine, OUTPUT_BUFFER_CAP, push_capped};
use std::collections::VecDeque;
use std::sync::Arc;
use tokio::io::{AsyncBufReadExt, BufReader};
use tokio::process::Child;
use tokio::sync::mpsc::UnboundedReceiver;
use tokio::task::JoinHandle;
pub struct ServicePane {
pub name: String,
pub buffer: VecDeque<CapturedLine>,
rx: Option<UnboundedReceiver<OutputLine>>,
tail_child: Option<Child>,
stdout_task: Option<JoinHandle<()>>,
stderr_task: Option<JoinHandle<()>>,
pub status: Option<ServiceStatus>,
pub tail_error: Option<String>,
}
impl ServicePane {
pub fn new(name: String) -> Self {
Self {
name,
buffer: VecDeque::with_capacity(OUTPUT_BUFFER_CAP),
rx: None,
tail_child: None,
stdout_task: None,
stderr_task: None,
status: None,
tail_error: None,
}
}
pub fn is_tailing(&self) -> bool {
self.tail_child.is_some()
}
pub async fn ensure_tailing(&mut self, backend: &Arc<dyn Backend>) {
if self.tail_child.is_some() {
return;
}
match backend.tail_logs(&self.name).await {
Ok(child) => self.attach(child),
Err(e) => {
self.tail_error = Some(format_error(&e));
}
}
}
fn attach(&mut self, mut child: Child) {
let stdout = child.stdout.take();
let stderr = child.stderr.take();
let (tx, rx) = tokio::sync::mpsc::unbounded_channel::<OutputLine>();
let tx_out = tx.clone();
let stdout_task = stdout.map(|s| {
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;
}
}
})
});
let stderr_task = stderr.map(|s| {
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;
}
}
})
});
self.tail_child = Some(child);
self.rx = Some(rx);
self.stdout_task = stdout_task;
self.stderr_task = stderr_task;
self.tail_error = None;
}
pub fn drain(&mut self) -> usize {
let Some(rx) = self.rx.as_mut() else {
return 0;
};
let mut drained = 0;
while let Ok(line) = rx.try_recv() {
push_capped(&mut self.buffer, CapturedLine::from(line));
drained += 1;
}
drained
}
pub fn poll_tail(&mut self) {
self.drain();
let Some(child) = self.tail_child.as_mut() else {
return;
};
let exited = match child.try_wait() {
Ok(Some(status)) => status,
_ => return,
};
self.drain();
self.tail_child = None;
if !exited.success() {
let combined: String = self
.buffer
.iter()
.map(|line| line.text.as_str())
.collect::<Vec<&str>>()
.join(" ");
self.tail_error = Some(if combined.is_empty() {
let code = exited
.code()
.map(|c| c.to_string())
.unwrap_or_else(|| "?".into());
format!("tail exited {code}")
} else {
combined
});
self.buffer.clear();
}
}
}
fn format_error(e: &BackendError) -> String {
match e {
BackendError::Reported(msg) => msg.clone(),
BackendError::BinaryNotFound(name) => format!("backend binary not found: {name}"),
other => format!("{other}"),
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn new_pane_starts_empty() {
let pane = ServicePane::new("app".into());
assert_eq!(pane.name, "app");
assert!(!pane.is_tailing());
assert!(pane.buffer.is_empty());
assert!(pane.tail_error.is_none());
}
#[test]
fn drain_with_no_rx_returns_zero() {
let mut pane = ServicePane::new("app".into());
assert_eq!(pane.drain(), 0);
}
}