Skip to main content

ertangle_adapter/
stderr.rs

1//! 子處理程序 stderr 的收集:固定大小的環狀緩衝,只留最後幾行。
2//!
3//! stderr 必須持續讀取,否則 agent 大量輸出時 pipe 塞滿會把 agent 卡死。
4//! 處理程序以非 0 結束時,把這幾行當成 `Output` 送出,讓使用者看得到原因。
5
6use crate::ansi::AnsiStripper;
7use crate::AgentEvent;
8use std::collections::VecDeque;
9use std::io::Read;
10use std::process::ChildStderr;
11use std::sync::mpsc::{self, Receiver, Sender};
12use std::sync::{Arc, Mutex};
13use std::time::Duration;
14use tr::tr;
15
16/// 最多保留的行數。
17const MAX_LINES: usize = 20;
18/// 單行最多保留的位元組數 (超過的部分丟掉)。
19const MAX_LINE_BYTES: usize = 500;
20
21#[derive(Default)]
22struct Inner {
23    lines: VecDeque<String>,
24    cur: Vec<u8>,
25}
26
27impl Inner {
28    fn push_text(&mut self, text: &str) {
29        for ch in text.chars() {
30            if ch == '\n' {
31                self.end_line();
32            } else if self.cur.len() < MAX_LINE_BYTES {
33                let mut buf = [0u8; 4];
34                self.cur
35                    .extend_from_slice(ch.encode_utf8(&mut buf).as_bytes());
36            }
37        }
38    }
39
40    fn end_line(&mut self) {
41        let line = String::from_utf8_lossy(&self.cur).trim_end().to_string();
42        self.cur.clear();
43        if line.is_empty() {
44            return;
45        }
46        if self.lines.len() == MAX_LINES {
47            self.lines.pop_front();
48        }
49        self.lines.push_back(line);
50    }
51}
52
53/// stderr 的尾巴。
54pub struct StderrTail {
55    inner: Arc<Mutex<Inner>>,
56    done: Mutex<Receiver<()>>,
57}
58
59impl StderrTail {
60    /// 啟動讀取執行緒,持續把 stderr 排乾。
61    pub fn spawn(mut stderr: ChildStderr) -> Arc<StderrTail> {
62        let inner = Arc::new(Mutex::new(Inner::default()));
63        let (done_tx, done_rx) = mpsc::channel();
64        let shared = inner.clone();
65        std::thread::spawn(move || {
66            let mut strip = AnsiStripper::new();
67            let mut buf = [0u8; 8192];
68            // 非 UTF-8 邊界被切開的位元組交給 lossy 處理即可;這裡只求不卡 pipe。
69            while let Ok(n) = stderr.read(&mut buf) {
70                if n == 0 {
71                    break;
72                }
73                let text = strip.feed(buf.get(..n).unwrap_or_default());
74                shared
75                    .lock()
76                    .unwrap_or_else(|e| e.into_inner())
77                    .push_text(&text);
78            }
79            shared.lock().unwrap_or_else(|e| e.into_inner()).end_line();
80            // 讀取執行緒結束通知,接收端逾時放棄時忽略
81            let _ = done_tx.send(());
82        });
83        Arc::new(StderrTail {
84            inner,
85            done: Mutex::new(done_rx),
86        })
87    }
88
89    /// 目前保留的行 (最舊在前)。
90    pub fn lines(&self) -> Vec<String> {
91        self.inner
92            .lock()
93            .unwrap_or_else(|e| e.into_inner())
94            .lines
95            .iter()
96            .cloned()
97            .collect()
98    }
99
100    /// 處理程序結束後呼叫:短暫等讀取執行緒收尾;非 0 結束且有內容時送出 `Output`。
101    pub fn report_exit(&self, code: Option<i32>, tx: &Sender<AgentEvent>) {
102        // 等待背景 stderr 讀取結束,逾時或無訊息皆繼續回報
103        let _ = self
104            .done
105            .lock()
106            .unwrap_or_else(|e| e.into_inner())
107            .recv_timeout(Duration::from_millis(500));
108        if !matches!(code, Some(c) if c != 0) {
109            return;
110        }
111        let lines = self.lines();
112        if lines.is_empty() {
113            return;
114        }
115        // 接收端若已關閉則忽略輸出事件
116        let _ = tx.send(AgentEvent::Output(tr!(
117            "⚠ 處理程序以結束碼 {code} 結束,stderr 最後 {count} 行:\n{lines}\n",
118            code = code.unwrap_or(-1),
119            count = lines.len(),
120            lines = lines.join("\n")
121        )));
122    }
123}
124
125#[cfg(test)]
126mod tests {
127    use super::*;
128
129    #[test]
130    fn keeps_only_last_lines_and_truncates_long_ones() {
131        let mut i = Inner::default();
132        for n in 0..50 {
133            i.push_text(&format!("line {n}\n"));
134        }
135        i.push_text(&"x".repeat(5000));
136        i.end_line();
137        assert_eq!(i.lines.len(), MAX_LINES);
138        assert_eq!(i.lines.front().unwrap(), "line 31");
139        assert_eq!(i.lines.back().unwrap().len(), MAX_LINE_BYTES);
140    }
141}