capy-cli 0.9.0

The command-line interface for the Capy web framework.
Documentation
//! Convert child output into safe styled lines. Only SGR styling reaches the UI.
use super::events::{OutputStream, ProcessId};
use ratatui::{
    style::{Color, Modifier, Style},
    text::{Line, Span},
};
use vte::{Params, Perform};

pub const MAX_LINE_BYTES: usize = 16 * 1024;
pub const LOG_PREFIX: &str = "CAPY_LOG_V1 ";

#[derive(Clone, Debug)]
pub struct LogLine {
    pub source: ProcessId,
    pub time: String,
    pub stream: OutputStream,
    pub text: String,
    pub styled: Line<'static>,
}

#[derive(Default)]
pub struct Decoder {
    parser: vte::Parser,
    sink: Styled,
}

impl Decoder {
    pub fn line(&mut self, source: ProcessId, stream: OutputStream, raw: &str) -> LogLine {
        self.parser.advance(&mut self.sink, raw.as_bytes());
        self.sink.flush();
        let spans = std::mem::take(&mut self.sink.spans);
        let text = spans.iter().map(|span| span.content.as_ref()).collect();
        LogLine {
            source,
            stream,
            time: chrono::Local::now().format("%H:%M:%S").to_string(),
            text,
            styled: Line::from(spans),
        }
    }
}

#[derive(Default)]
struct Styled {
    spans: Vec<Span<'static>>,
    pending: String,
    style: Style,
}

impl Styled {
    fn flush(&mut self) {
        if !self.pending.is_empty() {
            self.spans
                .push(Span::styled(std::mem::take(&mut self.pending), self.style));
        }
    }
}

impl Perform for Styled {
    fn print(&mut self, c: char) {
        if !c.is_control() {
            self.pending.push(c);
        }
    }

    fn execute(&mut self, byte: u8) {
        if byte == b'\t' {
            self.pending.push_str("    ");
        }
    }

    fn csi_dispatch(&mut self, params: &Params, intermediates: &[u8], ignore: bool, action: char) {
        if action != 'm' || ignore || !intermediates.is_empty() {
            return;
        }
        self.flush();
        let values: Vec<u16> = params
            .iter()
            .flat_map(|param| param.iter().copied())
            .collect();
        let mut i = 0;
        while i < values.len() {
            match values[i] {
                0 => self.style = Style::default(),
                1 => self.style = self.style.add_modifier(Modifier::BOLD),
                2 => self.style = self.style.add_modifier(Modifier::DIM),
                3 => self.style = self.style.add_modifier(Modifier::ITALIC),
                4 => self.style = self.style.add_modifier(Modifier::UNDERLINED),
                7 => self.style = self.style.add_modifier(Modifier::REVERSED),
                9 => self.style = self.style.add_modifier(Modifier::CROSSED_OUT),
                22 => self.style = self.style.remove_modifier(Modifier::BOLD | Modifier::DIM),
                23 => self.style = self.style.remove_modifier(Modifier::ITALIC),
                24 => self.style = self.style.remove_modifier(Modifier::UNDERLINED),
                27 => self.style = self.style.remove_modifier(Modifier::REVERSED),
                29 => self.style = self.style.remove_modifier(Modifier::CROSSED_OUT),
                n @ (30..=37 | 90..=97) => {
                    self.style.fg = Some(Color::Indexed(if n >= 90 {
                        (n - 90 + 8) as u8
                    } else {
                        (n - 30) as u8
                    }))
                }
                n @ (40..=47 | 100..=107) => {
                    self.style.bg = Some(Color::Indexed(if n >= 100 {
                        (n - 100 + 8) as u8
                    } else {
                        (n - 40) as u8
                    }))
                }
                39 => self.style.fg = Some(Color::Reset),
                49 => self.style.bg = Some(Color::Reset),
                n @ (38 | 48) => {
                    let mut color = None;
                    if values.get(i + 1) == Some(&5) {
                        if let Some(&v) = values.get(i + 2) {
                            color = Some(Color::Indexed(v.min(255) as u8));
                            i += 2;
                        }
                    } else if values.get(i + 1) == Some(&2) && i + 4 < values.len() {
                        color = Some(Color::Rgb(
                            values[i + 2].min(255) as u8,
                            values[i + 3].min(255) as u8,
                            values[i + 4].min(255) as u8,
                        ));
                        i += 4;
                    }
                    if let Some(color) = color {
                        if n == 38 {
                            self.style.fg = Some(color);
                        } else {
                            self.style.bg = Some(color);
                        }
                    }
                }
                _ => {}
            }
            i += 1;
        }
    }
}

/// Only the opt-in, versioned framework protocol is classified as a tracing event.
/// A custom subscriber's output remains visible in server instead of being guessed.
pub fn tracing_line(raw: &str) -> Option<(bool, String)> {
    let value: serde_json::Value = serde_json::from_str(raw.strip_prefix(LOG_PREFIX)?).ok()?;
    let target = value["target"].as_str()?;
    let server = matches!(
        target,
        "capy::diagnostics" | "capy::app" | "capy_framework::diagnostics" | "capy_framework::app"
    );
    let fields = &value["fields"];
    let http = target.ends_with("::diagnostics") && server;
    let summary = if http {
        fields["method"]
            .as_str()
            .zip(fields["route"].as_str())
            .zip(fields["status"].as_u64())
            .zip(fields["latency_ms"].as_f64())
            .map(|(((method, route), status), latency)| {
                format!("{method:<6} {route}  {status}  {latency:.2}ms")
            })
    } else {
        None
    };
    let compact = summary.is_some();
    let mut text = summary.unwrap_or_else(|| {
        format!(
            "{} {:5} {}",
            value["timestamp"].as_str().unwrap_or(""),
            value["level"].as_str().unwrap_or(""),
            fields["message"].as_str().unwrap_or("")
        )
    });
    value["level"].as_str()?;
    if let Some(fields) = fields.as_object() {
        for (key, val) in fields {
            if key == "message"
                || (compact && matches!(key.as_str(), "method" | "route" | "status" | "latency_ms"))
            {
                continue;
            }
            text.push_str(&format!("  {key}={val}"));
        }
    }
    if !server {
        if let Some(spans) = value["spans"].as_array().filter(|spans| !spans.is_empty()) {
            text.push_str(&format!(
                "  spans={}",
                serde_json::Value::Array(spans.clone())
            ));
        } else if value["span"].is_object() {
            text.push_str(&format!("  span={}", value["span"]));
        }
    }
    Some((server, text))
}

pub fn inline(line: &LogLine, name: &str) -> String {
    format!("[{name}] {}\n", line.text)
}

#[cfg(test)]
mod tests {
    use super::*;
    #[test]
    fn ansi_styles_survive_but_terminal_controls_do_not() {
        let mut decoder = Decoder::default();
        let line = decoder.line(
            0,
            OutputStream::Stdout,
            "\x1b[31;1mred\x1b[0m\x1b[2J\x1b]0;evil\x07\tplain\x07",
        );
        assert_eq!(line.text, "red    plain");
        assert_eq!(line.styled.spans[0].style.fg, Some(Color::Indexed(1)));
        assert!(line.styled.spans[0]
            .style
            .add_modifier
            .contains(Modifier::BOLD));
        assert_eq!(inline(&line, "server"), "[server] red    plain\n");
    }
    #[test]
    fn incomplete_controls_cannot_escape_into_next_line() {
        let mut decoder = Decoder::default();
        assert_eq!(
            decoder
                .line(0, OutputStream::Stderr, "hello\x1b]52;clipboard")
                .text,
            "hello"
        );
        assert_eq!(
            decoder.line(0, OutputStream::Stderr, "secret\x07safe").text,
            "safe"
        );
    }
    #[test]
    fn control_payloads_remain_bounded_across_lines() {
        let mut decoder = Decoder::default();
        decoder.line(0, OutputStream::Stdout, "\x1b]52;");
        for _ in 0..100 {
            assert!(decoder
                .line(0, OutputStream::Stdout, &"x".repeat(MAX_LINE_BYTES))
                .text
                .is_empty());
        }
        assert_eq!(
            decoder.line(0, OutputStream::Stdout, "\x07safe").text,
            "safe"
        );
    }

    #[test]
    fn http_summary_keeps_route_status_and_latency_visible_first() {
        let raw = format!(
            "{LOG_PREFIX}{}",
            serde_json::json!({"level":"INFO", "target":"capy_framework::diagnostics", "fields":{"method":"GET", "route":"/api/health", "status":200, "latency_ms":0.12345, "request_id":"abc", "message":"request completed"}})
        );
        assert_eq!(
            tracing_line(&raw),
            Some((
                true,
                "GET    /api/health  200  0.12ms  request_id=\"abc\"".into()
            ))
        );
    }
    #[test]
    fn application_span_fields_are_preserved() {
        let raw = format!(
            "{LOG_PREFIX}{}",
            serde_json::json!({"level":"WARN", "target":"application", "fields":{"message":"slow"}, "span":{"name":"payment", "user_id":42}})
        );
        assert!(tracing_line(&raw).unwrap().1.contains("\"user_id\":42"));
    }

    #[test]
    fn tracing_classification_is_explicit() {
        let json = r#"{"timestamp":"now","target":"application","level":"INFO","fields":{"message":"created","id":1}}"#;
        assert!(tracing_line(json).is_none());
        assert_eq!(
            tracing_line(&format!("{LOG_PREFIX}{json}")),
            Some((false, "now INFO  created  id=1".into()))
        );
        assert!(
            tracing_line(&format!(
                "{LOG_PREFIX}{}",
                json.replace("application", "capy::diagnostics")
            ))
            .unwrap()
            .0
        );
    }
}