utopia_span/exporter/
pretty.rs1use 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
22pub 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
67fn 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
84fn 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 pub fn new() -> Self {
126 Self { sampler: Box::new(|_| true), max_trace_frames: 3, width: 60, streams: Streams::standard() }
127 }
128
129 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 pub fn max_trace_frames(mut self, frames: usize) -> Self {
141 self.max_trace_frames = frames;
142 self
143 }
144
145 pub fn width(mut self, width: usize) -> Self {
149 self.width = width;
150 self
151 }
152
153 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 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}