1use crate::error::{Error, Result};
10use serde::{Deserialize, Serialize};
11use serde_json::Value;
12
13pub const MAX_ROWS: usize = 5_000;
15pub const MAX_POINTS: usize = 20_000;
16pub const MAX_TILES: usize = 12;
18pub const MAX_DEPTH: usize = 3;
19
20#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
21#[serde(rename_all = "snake_case")]
22pub enum Dir {
23 #[default]
24 Right,
25 Below,
26}
27
28#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
29pub struct Axis {
30 #[serde(default)]
31 pub name: String,
32 #[serde(default)]
34 pub time: bool,
35 pub values: Vec<Option<f64>>,
36}
37
38#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
39pub struct Line {
40 pub name: String,
41 pub values: Vec<Option<f64>>,
42}
43
44#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
45#[serde(tag = "kind", rename_all = "snake_case")]
46pub enum ResultView {
47 Table {
48 #[serde(default)]
49 title: String,
50 columns: Vec<String>,
51 #[serde(default)]
52 rows: Vec<Vec<Value>>,
53 },
54 Chart {
55 #[serde(default)]
56 title: String,
57 x: Axis,
58 #[serde(default)]
59 series: Vec<Line>,
60 },
61 Text {
62 #[serde(default)]
63 title: String,
64 text: String,
65 },
66 Tiles {
67 #[serde(default)]
68 title: String,
69 #[serde(default)]
70 dir: Dir,
71 tiles: Vec<ResultView>,
72 },
73}
74
75pub fn num(v: f64) -> String {
78 if v.is_finite() && v.fract() == 0.0 && v.abs() < 1e15 {
79 format!("{v:.0}")
80 } else if v.abs() >= 1000.0 {
81 format!("{v:.2}")
82 } else {
83 let s = format!("{v:.8}");
84 s.trim_end_matches('0').trim_end_matches('.').to_string()
85 }
86}
87
88pub fn fmt_ts(ms: i64) -> String {
90 use chrono::TimeZone;
91 match chrono::Utc.timestamp_millis_opt(ms) {
92 chrono::LocalResult::Single(d) => d.format("%Y-%m-%d %H:%M:%S").to_string(),
93 _ => ms.to_string(),
94 }
95}
96
97fn cell(v: &Value) -> String {
98 match v {
99 Value::Null => String::new(),
100 Value::String(s) => s.clone(),
101 Value::Number(n) => n.as_f64().map(num).unwrap_or_else(|| n.to_string()),
102 o => o.to_string(),
103 }
104}
105
106impl ResultView {
107 pub fn from_plugin(v: Value) -> Result<(ResultView, Vec<String>)> {
110 let mut view: ResultView = serde_json::from_value(v).map_err(|e| Error::invalid("result", format!("not a view: {e}")))?;
111 let mut notes = vec![];
112 let mut tiles = 0;
113 view.check(0, &mut tiles, &mut notes)?;
114 Ok((view, notes))
115 }
116
117 fn check(&mut self, depth: usize, tiles: &mut usize, notes: &mut Vec<String>) -> Result<()> {
118 let bad = |m: String| Err(Error::invalid("result", m));
119 match self {
120 ResultView::Table { title, columns, rows } => {
121 *tiles += 1;
122 if columns.is_empty() {
123 return bad(format!("table {title:?} has no columns"));
124 }
125 if let Some(i) = rows.iter().position(|r| r.len() != columns.len()) {
126 return bad(format!("table {title:?}: row {} has {} values for {} columns", i + 1, rows[i].len(), columns.len()));
127 }
128 if rows.len() > MAX_ROWS {
129 notes.push(format!("table {title:?}: showing the first {MAX_ROWS} of {} rows", rows.len()));
130 rows.truncate(MAX_ROWS);
131 }
132 }
133 ResultView::Chart { title, x, series } => {
134 *tiles += 1;
135 if let Some(s) = series.iter().find(|s| s.values.len() != x.values.len()) {
136 return bad(format!("chart {title:?}: line {} has {} points for {} x values", s.name, s.values.len(), x.values.len()));
137 }
138 if x.values.len() > MAX_POINTS {
139 let cut = x.values.len() - MAX_POINTS;
140 notes.push(format!("chart {title:?}: showing the last {MAX_POINTS} of {} points", x.values.len()));
141 x.values.drain(..cut);
142 for s in series.iter_mut() {
143 s.values.drain(..cut);
144 }
145 }
146 }
147 ResultView::Text { .. } => *tiles += 1,
148 ResultView::Tiles { title, tiles: ts, .. } => {
149 if depth >= MAX_DEPTH {
150 return bad(format!("tiles {title:?} nest deeper than {MAX_DEPTH}"));
151 }
152 if ts.is_empty() {
153 return bad(format!("tiles {title:?} is empty"));
154 }
155 for t in ts.iter_mut() {
156 t.check(depth + 1, tiles, notes)?;
157 }
158 }
159 }
160 if *tiles > MAX_TILES {
161 return bad(format!("more than {MAX_TILES} tiles"));
162 }
163 Ok(())
164 }
165
166 pub fn title(&self) -> &str {
167 match self {
168 ResultView::Table { title, .. } | ResultView::Chart { title, .. } | ResultView::Text { title, .. } | ResultView::Tiles { title, .. } => {
169 title
170 }
171 }
172 }
173
174 pub fn leaves(&self) -> Vec<&ResultView> {
176 match self {
177 ResultView::Tiles { tiles, .. } => tiles.iter().flat_map(|t| t.leaves()).collect(),
178 v => vec![v],
179 }
180 }
181
182 pub fn summary(&self) -> String {
184 match self {
185 ResultView::Table { columns, rows, .. } => format!("table ({} columns, {} rows)", columns.len(), rows.len()),
186 ResultView::Chart { x, series, .. } => format!("chart ({} lines, {} points)", series.len(), x.values.len()),
187 ResultView::Text { text, .. } => format!("text ({} lines)", text.lines().count()),
188 ResultView::Tiles { tiles, .. } => format!("{} tiles: {}", tiles.len(), tiles.iter().map(|t| t.summary()).collect::<Vec<_>>().join(", ")),
189 }
190 }
191
192 pub fn as_table(&self) -> (Vec<String>, Vec<Vec<String>>) {
194 match self {
195 ResultView::Table { columns, rows, .. } => (columns.clone(), rows.iter().map(|r| r.iter().map(cell).collect()).collect()),
196 ResultView::Chart { x, series, .. } => {
197 let mut head = vec![if x.name.is_empty() { "x".to_string() } else { x.name.clone() }];
198 head.extend(series.iter().map(|s| s.name.clone()));
199 let f = |v: Option<f64>| v.map(num).unwrap_or_default();
200 let rows = (0..x.values.len())
201 .map(|i| {
202 let mut r = vec![match (x.time, x.values[i]) {
203 (true, Some(t)) => fmt_ts(t as i64),
204 (_, v) => f(v),
205 }];
206 r.extend(series.iter().map(|s| f(s.values[i])));
207 r
208 })
209 .collect();
210 (head, rows)
211 }
212 ResultView::Text { text, .. } => (vec!["text".into()], text.lines().map(|l| vec![l.to_string()]).collect()),
213 ResultView::Tiles { .. } => (vec![], vec![]),
214 }
215 }
216
217 pub fn as_chart(&self) -> Option<(Axis, Vec<Line>)> {
220 match self {
221 ResultView::Chart { x, series, .. } => Some((x.clone(), series.clone())),
222 ResultView::Table { columns, rows, .. } => {
223 let num = |c: usize| rows.iter().map(|r| r[c].as_f64()).collect::<Vec<_>>();
224 let is_num = |c: usize| rows.iter().any(|r| r[c].is_number()) && rows.iter().all(|r| r[c].is_number() || r[c].is_null());
225 let (x, from) = if !columns.is_empty() && is_num(0) {
226 let time = matches!(columns[0].as_str(), "timestamp" | "time" | "date" | "_created_at" | "_updated_at");
227 (Axis { name: columns[0].clone(), time, values: num(0) }, 1)
228 } else {
229 (Axis { name: "row".into(), time: false, values: (0..rows.len()).map(|i| Some(i as f64)).collect() }, 0)
230 };
231 let lines: Vec<Line> =
232 (from..columns.len()).filter(|c| is_num(*c)).map(|c| Line { name: columns[c].clone(), values: num(c) }).collect();
233 (!lines.is_empty()).then_some((x, lines))
234 }
235 _ => None,
236 }
237 }
238
239 pub fn text_lines(&self, rows: usize) -> Vec<String> {
242 let mut out = vec![];
243 self.lines_into(&mut out, rows, 0);
244 out
245 }
246
247 fn lines_into(&self, out: &mut Vec<String>, max: usize, depth: usize) {
248 let pad = " ".repeat(depth);
249 if !self.title().is_empty() {
250 out.push(format!("{pad}== {} ==", self.title()));
251 }
252 match self {
253 ResultView::Tiles { tiles, .. } => {
254 for t in tiles {
255 t.lines_into(out, max, depth + 1);
256 }
257 }
258 ResultView::Text { text, .. } => out.extend(text.lines().map(|l| format!("{pad}{l}"))),
259 ResultView::Chart { x, series, .. } => {
260 out.push(format!("{pad}{} points over {}", x.values.len(), if x.name.is_empty() { "x" } else { &x.name }));
261 for s in series {
262 let vals: Vec<f64> = s.values.iter().flatten().copied().filter(|v| v.is_finite()).collect();
263 let (lo, hi) = vals.iter().fold((f64::INFINITY, f64::NEG_INFINITY), |(a, b), v| (a.min(*v), b.max(*v)));
264 let last = vals.last().map(|v| num(*v)).unwrap_or_else(|| "-".into());
265 let range = if vals.is_empty() { "no values".to_string() } else { format!("{} … {}", num(lo), num(hi)) };
266 out.push(format!("{pad}{:<12} {} {range} last {last}", s.name, sparkline(&s.values, 40)));
267 }
268 }
269 ResultView::Table { .. } => {
270 let (head, rows) = self.as_table();
271 let shown = &rows[..rows.len().min(max)];
272 let mut w: Vec<usize> = head.iter().map(|h| h.chars().count()).collect();
273 for r in shown {
274 for (i, c) in r.iter().enumerate() {
275 w[i] = w[i].max(c.chars().count()).min(40);
276 }
277 }
278 let line = |r: &[String]| {
279 let cells: Vec<String> =
280 r.iter().enumerate().map(|(i, c)| format!("{:<w$}", c.chars().take(40).collect::<String>(), w = w[i])).collect();
281 format!("{pad}{}", cells.join(" ").trim_end())
282 };
283 out.push(line(&head));
284 out.extend(shown.iter().map(|r| line(r)));
285 if rows.len() > shown.len() {
286 out.push(format!("{pad}… {} more rows", rows.len() - shown.len()));
287 }
288 }
289 }
290 }
291}
292
293pub fn sparkline(values: &[Option<f64>], width: usize) -> String {
295 const BARS: [char; 8] = ['▁', '▂', '▃', '▄', '▅', '▆', '▇', '█'];
296 if values.is_empty() || width == 0 {
297 return String::new();
298 }
299 let n = values.len().min(width);
300 let pts: Vec<Option<f64>> = (0..n).map(|i| values[((i + 1) * values.len() / n).saturating_sub(1)].filter(|v| v.is_finite())).collect();
301 let (lo, hi) = pts.iter().flatten().fold((f64::INFINITY, f64::NEG_INFINITY), |(a, b), v| (a.min(*v), b.max(*v)));
302 pts.iter()
303 .map(|p| match p {
304 None => ' ',
305 Some(v) if hi > lo => BARS[(((v - lo) / (hi - lo)) * 7.0).round() as usize],
306 Some(_) => BARS[3],
307 })
308 .collect()
309}
310
311#[cfg(test)]
312mod tests {
313 use super::*;
314 use serde_json::json;
315
316 #[test]
317 fn views_parse_check_and_switch() {
318 let (v, notes) = ResultView::from_plugin(json!({
319 "kind": "tiles", "title": "t", "dir": "below", "tiles": [
320 {"kind": "table", "columns": ["timestamp", "close", "side"], "rows": [[0, 1.5, "buy"], [60000, 2.5, "sell"]]},
321 {"kind": "chart", "x": {"name": "row", "values": [0, 1]}, "series": [{"name": "a", "values": [1, null]}]},
322 {"kind": "text", "text": "hello"}
323 ]
324 }))
325 .unwrap();
326 assert!(notes.is_empty());
327 assert_eq!(v.leaves().len(), 3);
328 let (x, lines) = v.leaves()[0].as_chart().unwrap();
329 assert_eq!((x.time, lines.len(), lines[0].name.as_str()), (true, 1, "close"), "text columns are not drawn");
330 let (head, rows) = v.leaves()[1].as_table();
331 assert_eq!((head, rows[1][1].as_str()), (vec!["row".to_string(), "a".to_string()], ""));
332 let txt = v.text_lines(10).join("\n");
333 assert!(txt.contains("== t ==") && txt.contains("sell") && txt.contains("hello"), "{txt}");
334 assert!(ResultView::from_plugin(json!({"kind": "table", "columns": ["a"], "rows": [[1, 2]]})).is_err());
335 assert!(ResultView::from_plugin(json!({"kind": "chart", "x": {"values": [1]}, "series": [{"name": "a", "values": []}]})).is_err());
336 assert!(ResultView::from_plugin(json!({"kind": "pie"})).is_err());
337 let rows: Vec<Value> = (0..MAX_ROWS + 3).map(|i| json!([i])).collect();
338 let (v, notes) = ResultView::from_plugin(json!({"kind": "table", "columns": ["n"], "rows": rows})).unwrap();
339 assert_eq!((notes.len(), v.as_table().1.len()), (1, MAX_ROWS));
340 assert_eq!(sparkline(&[Some(0.0), Some(1.0)], 10), "▁█");
341 }
342}