micromegas/servers/mcp/
render.rs1use arrow::array::RecordBatch;
2use arrow::datatypes::SchemaRef;
3use arrow::util::display::{ArrayFormatter, FormatOptions};
4use futures::{Stream, StreamExt};
5
6#[derive(Debug, Clone, Copy)]
8pub struct RenderLimits {
9 pub max_rows: usize,
10 pub max_bytes: usize,
11}
12
13#[derive(Debug)]
14pub struct Rendered {
15 pub text: String,
16 pub rows: usize,
17 pub truncated: bool,
18}
19
20fn escape_cell(value: &str) -> String {
21 value
22 .replace('|', "\\|")
23 .replace("\r\n", "\\n")
24 .replace(['\n', '\r'], "\\n")
25}
26
27fn header(schema: &SchemaRef) -> String {
28 let names: Vec<String> = schema
29 .fields()
30 .iter()
31 .map(|f| escape_cell(f.name()))
32 .collect();
33 let rule = vec!["---"; names.len()].join(" | ");
34 format!("| {} |\n| {rule} |\n", names.join(" | "))
35}
36
37fn truncation_footer(rows: usize) -> String {
38 format!("\ntruncated at {rows} rows, add filters or aggregate\n")
39}
40
41fn cut_at_char_boundary(text: &str, max: usize) -> &str {
42 let mut end = max.min(text.len());
43 while !text.is_char_boundary(end) {
44 end -= 1;
45 }
46 &text[..end]
47}
48
49pub async fn render_stream<S, E>(mut stream: S, limits: RenderLimits) -> Result<Rendered, E>
52where
53 S: Stream<Item = Result<RecordBatch, E>> + Unpin,
54{
55 let options = FormatOptions::default().with_null("NULL");
56 let mut text = String::new();
57 let mut rows = 0usize;
58 let mut truncated = false;
59 let mut header_written = false;
60 let body_cap = limits
63 .max_bytes
64 .saturating_sub(truncation_footer(limits.max_rows).len());
65
66 'batches: while let Some(batch) = stream.next().await {
67 let batch = batch?;
68 if !header_written {
69 let header = header(&batch.schema());
70 header_written = true;
71 if header.len() > body_cap {
72 text.push_str(cut_at_char_boundary(&header, body_cap));
73 truncated = true;
74 break 'batches;
75 }
76 text.push_str(&header);
77 }
78 if batch.num_rows() == 0 {
79 continue;
80 }
81 let formatters: Vec<_> = batch
82 .columns()
83 .iter()
84 .map(|c| ArrayFormatter::try_new(c.as_ref(), &options))
85 .collect();
86 for row in 0..batch.num_rows() {
87 if rows >= limits.max_rows {
88 truncated = true;
89 break 'batches;
90 }
91 let cells: Vec<String> = formatters
92 .iter()
93 .map(|f| match f {
94 Ok(f) => escape_cell(&f.value(row).to_string()),
95 Err(e) => format!("<{e}>"),
96 })
97 .collect();
98 let mut line = format!("| {} |\n", cells.join(" | "));
99 if text.len() + line.len() > body_cap {
100 if rows == 0 {
101 let room = body_cap.saturating_sub(text.len() + "…\n".len());
104 line = format!("{}…\n", cut_at_char_boundary(&line, room));
105 text.push_str(&line);
106 rows += 1;
107 }
108 truncated = true;
109 break 'batches;
110 }
111 text.push_str(&line);
112 rows += 1;
113 }
114 }
115
116 if !header_written || rows == 0 && !truncated {
117 return Ok(Rendered {
118 text: "no data".to_string(),
119 rows: 0,
120 truncated: false,
121 });
122 }
123 if truncated {
124 text.push_str(&truncation_footer(rows));
125 text.truncate(cut_at_char_boundary(&text, limits.max_bytes).len());
127 }
128 Ok(Rendered {
129 text,
130 rows,
131 truncated,
132 })
133}
134
135pub fn truncate_text(text: &str, max_bytes: usize) -> String {
137 if text.len() <= max_bytes {
138 return text.to_string();
139 }
140 format!(
141 "{}\n... truncated at {max_bytes} bytes",
142 cut_at_char_boundary(text, max_bytes)
143 )
144}