Skip to main content

utopia_span/exporter/
pretty.rs

1//! Spans as colourful, human-readable text.
2
3use std::io::Write;
4
5use php_std::format::{RoundingMode, round};
6use php_std::types::KeyRef;
7use php_std::value::Number;
8use php_std::{Array, ArrayKey};
9
10use super::{Exporter, Sampler, Streams, kept};
11use crate::{Span, Value};
12
13const RESET: &str = "\x1b[0m";
14const BOLD: &str = "\x1b[1m";
15const DIM: &str = "\x1b[2m";
16const RED: &str = "\x1b[31m";
17const GREEN: &str = "\x1b[32m";
18const YELLOW: &str = "\x1b[33m";
19const CYAN: &str = "\x1b[36m";
20const WHITE: &str = "\x1b[37m";
21
22/// Writes each span as a coloured block for local development: a header
23/// (action, duration, short trace id), the attributes other than `span.*`
24/// aligned in a column with `level` first, the error with at most
25/// `max_trace_frames` stack frames, and a separator line `width` wide. Spans
26/// with an error go to standard error, the others to standard output.
27///
28/// PHP: `Utopia\Span\Exporter\Pretty`.
29///
30/// ```
31/// use utopia_span::{Pretty, Span};
32///
33/// let span = Span::new("db.query");
34/// span.set("span.duration", 0.0123).set("rows", 3);
35/// let text = String::from_utf8(Pretty::new().width(10).render(&span)).unwrap();
36/// assert!(text.contains("12.3ms"));
37/// assert!(text.contains("rows"));
38/// ```
39///
40/// ```php
41/// use Utopia\Span\Exporter\Pretty;
42/// use Utopia\Span\Span;
43///
44/// $span = new Span('db.query');
45/// $span->set('span.duration', 0.0123)->set('rows', 3);
46/// (new Pretty(width: 10))->export($span); // db.query · 12.3ms · … then "rows 3"
47/// ```
48pub struct Pretty {
49    sampler: Sampler,
50    max_trace_frames: usize,
51    width: usize,
52    streams: Streams,
53}
54
55impl Default for Pretty {
56    fn default() -> Self {
57        Self::new()
58    }
59}
60
61impl std::fmt::Debug for Pretty {
62    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
63        f.debug_struct("Pretty").field("max_trace_frames", &self.max_trace_frames).field("width", &self.width).finish()
64    }
65}
66
67/// `(string) $key` of an array key.
68fn key_bytes(key: KeyRef<'_>) -> Vec<u8> {
69    match key {
70        KeyRef::Int(i) => i.to_string().into_bytes(),
71        KeyRef::Str(s) => s.to_vec(),
72    }
73}
74
75fn format_value(value: &php_std::Value) -> Vec<u8> {
76    match value {
77        php_std::Value::Null => b"null".to_vec(),
78        php_std::Value::Bool(true) => b"true".to_vec(),
79        php_std::Value::Bool(false) => b"false".to_vec(),
80        other => escape(&other.to_php_string().map(|s| s.as_bytes().to_vec()).unwrap_or_default()),
81    }
82}
83
84/// Replaces C0 controls and DEL with `\xNN`, so a value cannot forge extra
85/// log lines or inject terminal control sequences.
86///
87/// PHP: `Pretty::escape()`.
88fn escape(value: &[u8]) -> Vec<u8> {
89    let mut escaped = Vec::with_capacity(value.len());
90    for &byte in value {
91        if byte < 0x20 || byte == 0x7F {
92            escaped.extend_from_slice(format!("\\x{byte:02x}").as_bytes());
93        } else {
94            escaped.push(byte);
95        }
96    }
97    escaped
98}
99
100fn format_duration(seconds: f64) -> String {
101    let round = |x: f64, places: i64| round(Number::Float(x), places, RoundingMode::HalfAwayFromZero);
102    if seconds >= 1.0 {
103        format!("{}s", php_std::number::to_string(round(seconds, 2)))
104    } else {
105        format!("{}ms", php_std::number::to_string(round(seconds * 1000.0, 1)))
106    }
107}
108
109fn duration_color(seconds: f64) -> &'static str {
110    if seconds >= 1.0 {
111        RED
112    } else if seconds >= 0.1 {
113        YELLOW
114    } else {
115        GREEN
116    }
117}
118
119impl Pretty {
120    /// An exporter of every span, with at most 3 stack frames per error and a
121    /// 60 columns wide separator, writing to the process's standard output
122    /// and error.
123    ///
124    /// PHP: `new Pretty()`.
125    pub fn new() -> Self {
126        Self { sampler: Box::new(|_| true), max_trace_frames: 3, width: 60, streams: Streams::standard() }
127    }
128
129    /// Exports only the spans `sampler` accepts.
130    ///
131    /// PHP: the `$sampler` argument.
132    pub fn sampler(mut self, sampler: impl Fn(&Span) -> bool + Send + Sync + 'static) -> Self {
133        self.sampler = Box::new(sampler);
134        self
135    }
136
137    /// Prints at most `frames` stack frames of an error.
138    ///
139    /// PHP: the `$maxTraceFrames` argument.
140    pub fn max_trace_frames(mut self, frames: usize) -> Self {
141        self.max_trace_frames = frames;
142        self
143    }
144
145    /// The width of the separator line, in columns.
146    ///
147    /// PHP: the `$width` argument.
148    pub fn width(mut self, width: usize) -> Self {
149        self.width = width;
150        self
151    }
152
153    /// Writes spans to `out`, and spans with an error to `err`.
154    ///
155    /// PHP: the `$stdout` and `$stderr` arguments.
156    pub fn writers(mut self, out: Box<dyn Write + Send>, err: Box<dyn Write + Send>) -> Self {
157        self.streams = Streams::new(out, err);
158        self
159    }
160
161    /// The text this exporter writes for `span`.
162    pub fn render(&self, span: &Span) -> Vec<u8> {
163        let error = span.error();
164        let mut lines: Vec<Vec<u8>> = vec![self.header(span, error.is_some()), Vec::new()];
165
166        let mut attributes = Array::<php_std::Never>::default();
167        span.with_attributes(|attrs| {
168            for (key, value) in attrs {
169                if !key.starts_with("span.") {
170                    attributes.set(ArrayKey::from(&**key), value.to_php());
171                }
172            }
173        });
174        let level = ArrayKey::from("level");
175        if let Some(value) = attributes.remove(&level) {
176            let mut first = Array::default();
177            first.set(level, value);
178            for (key, value) in attributes {
179                first.set(key, value);
180            }
181            attributes = first;
182        }
183        let pad = attributes.keys().map(|k| escape(&key_bytes(k)).len()).max().unwrap_or(0);
184        for (key, value) in attributes.iter() {
185            let mut line = format!("  {CYAN}").into_bytes();
186            let key = escape(&key_bytes(key));
187            line.extend_from_slice(&key);
188            line.resize(line.len() + pad.saturating_sub(key.len()), b' ');
189            line.extend_from_slice(format!("{RESET} {WHITE}").as_bytes());
190            line.extend_from_slice(&format_value(value));
191            line.extend_from_slice(RESET.as_bytes());
192            lines.push(line);
193        }
194
195        if let Some(error) = &error {
196            if !attributes.is_empty() {
197                lines.push(Vec::new());
198            }
199            let mut line = format!("{RED}{BOLD}  ").into_bytes();
200            line.extend_from_slice(&escape(error.class().as_bytes()));
201            line.extend_from_slice(format!("{RESET}{RED}: ").as_bytes());
202            line.extend_from_slice(&escape(error.message_bytes()));
203            line.extend_from_slice(format!("{RESET}\n{DIM}    at ").as_bytes());
204            line.extend_from_slice(&escape(error.file().as_bytes()));
205            line.extend_from_slice(format!(":{}{RESET}", error.line()).as_bytes());
206            lines.push(line);
207            let frames = error.frames();
208            for frame in &frames[..kept(frames.len(), self.max_trace_frames)] {
209                let file = escape(frame.file.as_deref().unwrap_or("unknown").as_bytes());
210                let line = frame.line.map_or_else(|| "?".to_owned(), |l| l.to_string());
211                let mut out = format!("{DIM}    at ").into_bytes();
212                out.extend_from_slice(&file);
213                out.extend_from_slice(format!(":{line}{RESET}").as_bytes());
214                lines.push(out);
215            }
216            if frames.len() > self.max_trace_frames {
217                lines.push(format!("{DIM}    ... {} more{RESET}", frames.len() - self.max_trace_frames).into_bytes());
218            }
219        }
220
221        lines.push(Vec::new());
222        lines.push(format!("{DIM}{}{RESET}", "─".repeat(self.width)).into_bytes());
223        let mut out = lines.join(&b"\n"[..]);
224        out.push(b'\n');
225        out
226    }
227
228    fn header(&self, span: &Span, error: bool) -> Vec<u8> {
229        let color = if error { RED } else { GREEN };
230        let mut action = format!("{BOLD}{color}").into_bytes();
231        action.extend_from_slice(&escape(span.action().as_bytes()));
232        action.extend_from_slice(RESET.as_bytes());
233        let mut parts = vec![action];
234        if let Value::Float(duration) = span.get("span.duration") {
235            parts.push(format!("{}{}{RESET}", duration_color(duration), format_duration(duration)).into_bytes());
236        }
237        if let Value::Str(trace) = span.get("span.trace_id") {
238            let mut part = DIM.as_bytes().to_vec();
239            part.extend_from_slice(&trace.as_bytes()[..trace.len().min(8)]);
240            part.extend_from_slice(RESET.as_bytes());
241            parts.push(part);
242        }
243        parts.join(format!("{DIM} · {RESET}").as_bytes())
244    }
245}
246
247impl Exporter for Pretty {
248    fn sample(&self, span: &Span) -> bool {
249        (self.sampler)(span)
250    }
251
252    fn export(&self, span: &Span) {
253        self.streams.write(span.error().is_some(), &self.render(span));
254    }
255}