Skip to main content

services/
services.rs

1//! A services dashboard: groups on the left, a table of services with a column per
2//! environment, details for the one under the cursor, a filter, dialogs and toasts.
3//!
4//!   cargo run --example services
5//!
6//! ↑↓ or j/k move, ←→ or h/l move between panels and scroll the table sideways, tab
7//! switches panel, 1-4 pick a group, / filters, d shows only drifted services, x restarts,
8//! r refreshes, e picks the environment the details show, s signs in (leaving the dashboard
9//! while a login command runs), ? for help, q to quit.
10//!
11//! To draw one frame as a web page instead of running, for a screenshot:
12//!
13//!   cargo run --example services -- --html 120x30 > services.html
14
15use std::sync::mpsc;
16use std::thread;
17use std::time::{Duration, Instant};
18
19use tinsel::anim::shimmer;
20use tinsel::app::{
21    self, App, Event, Flow, Footer, Frame, Grid, GridState, Key, Keymap, List, Modal, Panel, Size::*, Tabs, TextInput,
22    Toasts, Waker,
23};
24use tinsel::{ColorMode, Line, Spinner, Table, Theme, Tone, format, paint, palette};
25
26#[derive(Clone)]
27struct Service {
28    name: &'static str,
29    group: &'static str,
30    staging: String,
31    production: String,
32    health: Health,
33    replicas: u32,
34    updated_mins: u64,
35}
36
37#[derive(Clone, Copy, PartialEq)]
38enum Health {
39    Healthy,
40    Slow,
41    Down,
42}
43
44impl Service {
45    fn drifted(&self) -> bool {
46        self.staging != self.production
47    }
48
49    /// A coloured mark and a word for how it's doing.
50    fn health(&self) -> (String, &'static str) {
51        match self.health {
52            Health::Healthy => (paint(palette::SAGE, "●"), "healthy"),
53            Health::Slow => (paint(palette::AMBER, "▲"), "slow"),
54            Health::Down => (paint(palette::RED, "✕"), "down"),
55        }
56    }
57}
58
59const GROUPS: [&str; 4] = ["all", "core", "data", "edge"];
60const ENVS: [&str; 2] = ["staging", "production"];
61
62/// What the pretend backend says, after a pretend wait.
63fn fetch(round: u32) -> Vec<Service> {
64    thread::sleep(Duration::from_millis(1200));
65    let services = [
66        ("api", "core"),
67        ("auth", "core"),
68        ("billing", "core"),
69        ("worker", "core"),
70        ("scheduler", "core"),
71        ("db", "data"),
72        ("cache", "data"),
73        ("search", "data"),
74        ("queue", "data"),
75        ("web", "edge"),
76        ("gateway", "edge"),
77        ("cdn-purger", "edge"),
78    ];
79    services
80        .iter()
81        .enumerate()
82        .map(|(i, &(name, group))| {
83            let n = i as u32 + round;
84            let minor = 4 + n % 5;
85            Service {
86                name,
87                group,
88                staging: format!("v2.{minor}.{}", n % 3),
89                production: format!("v2.{}.{}", if i % 4 == 1 { minor - 1 } else { minor }, n % 3),
90                health: match n % 7 {
91                    3 => Health::Slow,
92                    5 if round > 0 => Health::Down,
93                    _ => Health::Healthy,
94                },
95                replicas: 1 + n % 6,
96                updated_mins: (n as u64 * 37) % 600,
97            }
98        })
99        .collect()
100}
101
102#[derive(Clone, Copy, PartialEq)]
103enum Pane {
104    Groups,
105    Table,
106    Filter,
107}
108
109enum Dialog {
110    Help,
111    Environment(usize),
112    Restart(&'static str),
113}
114
115struct Dashboard {
116    services: Vec<Service>,
117    group: usize,
118    pane: Pane,
119    cursor: GridState,
120    filter: TextInput,
121    drifted_only: bool,
122    env: usize,
123    dialog: Option<(Dialog, f64)>,
124    toasts: Toasts,
125    loading: bool,
126    refreshed: Option<Instant>,
127    results: mpsc::Receiver<Vec<Service>>,
128    send: mpsc::Sender<Vec<Service>>,
129    waker: Waker,
130    round: u32,
131}
132
133impl Dashboard {
134    fn new() -> Self {
135        let (send, results) = mpsc::channel();
136        let mut d = Dashboard {
137            services: Vec::new(),
138            group: 0,
139            pane: Pane::Table,
140            cursor: GridState::new(),
141            filter: TextInput::new().prompt("/").placeholder("filter services by name"),
142            drifted_only: false,
143            env: 1,
144            dialog: None,
145            toasts: Toasts::new(),
146            loading: false,
147            refreshed: None,
148            results,
149            send,
150            waker: Waker::new(),
151            round: 0,
152        };
153        d.refresh();
154        d
155    }
156
157    /// A dashboard with the data already in, without the wait: for screenshots.
158    fn loaded(services: Vec<Service>) -> Self {
159        let (send, results) = mpsc::channel();
160        Dashboard {
161            services,
162            group: 0,
163            pane: Pane::Table,
164            cursor: GridState::new(),
165            filter: TextInput::new().prompt("/").placeholder("filter services by name"),
166            drifted_only: false,
167            env: 1,
168            dialog: None,
169            toasts: Toasts::new(),
170            loading: false,
171            refreshed: Instant::now().checked_sub(Duration::from_secs(40)),
172            results,
173            send,
174            waker: Waker::new(),
175            round: 1,
176        }
177    }
178
179    /// Load in the background; the dashboard is woken the moment it's done.
180    fn refresh(&mut self) {
181        if self.loading {
182            return;
183        }
184        self.loading = true;
185        let (send, waker, round) = (self.send.clone(), self.waker.clone(), self.round);
186        thread::spawn(move || {
187            let _ = send.send(fetch(round));
188            waker.wake();
189        });
190        self.round += 1;
191    }
192
193    /// The services in the table, in its order: by group, then by name.
194    fn shown(&self) -> Vec<&Service> {
195        let filter = self.filter.value().to_lowercase();
196        let mut shown: Vec<&Service> = self
197            .services
198            .iter()
199            .filter(|s| self.group == 0 || s.group == GROUPS[self.group])
200            .filter(|s| s.name.contains(&filter))
201            .filter(|s| !self.drifted_only || s.drifted())
202            .collect();
203        shown.sort_by_key(|s| (s.group, s.name));
204        shown
205    }
206
207    fn chosen(&self) -> Option<&Service> {
208        let shown = self.shown();
209        shown.get(self.cursor.row().min(shown.len().saturating_sub(1))).copied()
210    }
211
212    fn focus(&mut self, pane: Pane) {
213        self.pane = pane;
214        self.filter.focus(pane == Pane::Filter);
215    }
216
217    fn open(&mut self, dialog: Dialog) {
218        self.dialog = Some((dialog, app::time()));
219    }
220
221    fn sign_in(&mut self) {
222        let ran = app::suspend(|| {
223            println!("\n  signing in to {}\n", ENVS[self.env]);
224            login()
225        });
226        match ran {
227            Ok(Ok(status)) if status.success() => {
228                self.toasts
229                    .push(app::time(), Tone::Success, format!("signed in to {}", ENVS[self.env]));
230                self.refresh();
231            }
232            Ok(Ok(status)) => self
233                .toasts
234                .push(app::time(), Tone::Error, format!("sign-in failed ({status})")),
235            Ok(Err(e)) => self
236                .toasts
237                .push(app::time(), Tone::Error, format!("couldn't run the login command: {e}")),
238            Err(e) => self.toasts.push(app::time(), Tone::Error, e.to_string()),
239        }
240    }
241
242    // MARK: drawing
243
244    fn header(&self, frame: &mut Frame, area: app::Rect) {
245        let t = frame.ambient_time();
246        frame.animate_at(10);
247        let title = Line::new().push(palette::ROSE, "✦ ").append(shimmer("services", t));
248        frame.render(area, title);
249        let tabs = self.environments();
250        // each tab is its title, a mark and a space either side, with a space between tabs
251        let w = ENVS.iter().map(|e| e.len() + 4).sum::<usize>() + ENVS.len() - 1;
252        frame.render(
253            app::Rect::new(area.x + area.width.saturating_sub(w), area.y, w, 1),
254            tabs,
255        );
256    }
257
258    /// The environments as tabs, the one the details show chosen. Production is red, so it's
259    /// never picked by mistake, and each has a mark: ○ while loading, ✖ when a service is down.
260    fn environments(&self) -> Tabs {
261        let down = self.services.iter().any(|s| s.health == Health::Down);
262        let mut tabs = Tabs::new(ENVS).selected(self.env).color(1, palette::RED);
263        for i in 0..ENVS.len() {
264            tabs = if self.services.is_empty() {
265                tabs.badge(i, palette::MUTED, "○")
266            } else if down && i == 1 {
267                tabs.badge(i, palette::RED, "✖")
268            } else {
269                tabs.badge(i, palette::SAGE, "✔")
270            };
271        }
272        tabs
273    }
274
275    fn groups(&self, frame: &mut Frame, area: app::Rect) {
276        let names: Vec<String> = GROUPS
277            .iter()
278            .enumerate()
279            .map(|(i, g)| {
280                let n = self.services.iter().filter(|s| i == 0 || s.group == *g).count();
281                let count = paint(palette::MUTED, &format!("{n:>3}"));
282                format!("{}  {:<8}{count}", paint(palette::MUTED, &(i + 1).to_string()), g)
283            })
284            .collect();
285        frame.render(
286            area,
287            Panel::new("groups")
288                .body(List::new(names).selected(self.group))
289                .focused(self.pane == Pane::Groups),
290        );
291    }
292
293    fn table(&self, frame: &mut Frame, area: app::Rect) {
294        let shown = self.shown();
295        let mut grid = Grid::new(["service", "staging", "production", "health", "replicas", "updated", ""])
296            .state(&self.cursor)
297            .focused(self.pane == Pane::Table)
298            .striped()
299            .blank_cells()
300            .fill(6)
301            .sorted(0)
302            .empty(if self.services.is_empty() {
303                "nothing here yet"
304            } else {
305                "no services match"
306            })
307            .loading(self.loading && self.services.is_empty());
308        for (i, s) in shown.iter().enumerate() {
309            // in the "all" view, services sit under their group's name
310            if self.group == 0 && (i == 0 || shown[i - 1].group != s.group) {
311                grid = grid.heading(paint(palette::PETAL, s.group));
312            }
313            let production = if s.drifted() {
314                paint(palette::AMBER, &s.production)
315            } else {
316                s.production.clone()
317            };
318            let (mark, word) = s.health();
319            let health = format!("{mark} {word}");
320            let drift = if s.drifted() {
321                paint(palette::AMBER, "drifted")
322            } else {
323                String::new()
324            };
325            grid = grid.row([
326                s.name.to_string(),
327                s.staging.clone(),
328                production,
329                health,
330                s.replicas.to_string(),
331                format!("{}m ago", s.updated_mins),
332                drift,
333            ]);
334        }
335        let count = if shown.len() == self.services.len() {
336            shown.len().to_string()
337        } else {
338            format!("{}/{}", shown.len(), self.services.len())
339        };
340        let position = if shown.is_empty() {
341            String::new()
342        } else {
343            format!("{} of {}", self.cursor.row().min(shown.len() - 1) + 1, shown.len())
344        };
345
346        let status = match self.refreshed {
347            Some(at) if !self.loading => format!("{} · refreshed {}", ENVS[self.env], format::ago(at.elapsed())),
348            _ => ENVS[self.env].to_string(),
349        };
350        let filtering = self.pane == Pane::Filter || !self.filter.value().is_empty();
351        let panel = Panel::new(GROUPS[self.group])
352            .count(count)
353            .status(status)
354            .footer(position)
355            .focused(self.pane != Pane::Groups);
356        let inner = panel.inner(area);
357        frame.render(area, panel);
358        let rows = if filtering {
359            let [input, _, rest] = inner.rows([Fixed(1), Fixed(1), Fill(1)]);
360            frame.render(input, &self.filter);
361            rest
362        } else {
363            inner
364        };
365        frame.render(rows, grid);
366    }
367
368    fn details(&self, frame: &mut Frame, area: app::Rect) {
369        let Some(s) = self.chosen() else {
370            frame.render(area, Panel::new("details"));
371            return;
372        };
373        let version = if self.env == 0 { &s.staging } else { &s.production };
374        let mut table = Table::new(["", ""])
375            .row(["version", version.as_str()])
376            .row(["replicas", &s.replicas.to_string()])
377            .row(["updated", &format!("{} minutes ago", s.updated_mins)]);
378        if s.drifted() {
379            table = table.row([
380                "drift".to_string(),
381                paint(palette::AMBER, &format!("staging has {}", s.staging)),
382            ]);
383        }
384        let lines = table.lines();
385        // drop the empty header and its rule: just the pairs
386        let pairs: tinsel::Block = lines.lines().iter().skip(2).cloned().collect();
387        let (mark, _) = s.health();
388        let title = format!(
389            "{mark} {}",
390            paint(palette::TEXT, &format!("{} in {}", s.name, ENVS[self.env]))
391        );
392        frame.render(area, Panel::new(title).body(pairs));
393    }
394
395    fn footer(&self, frame: &mut Frame, area: app::Rect) {
396        let status = if self.loading {
397            frame.animate_at(30);
398            format!("{} refreshing", Spinner::Sparkle.frame(frame.ambient_time()))
399        } else {
400            String::new()
401        };
402        // the keys that matter most first: a narrow footer keeps those
403        let footer = Footer::new()
404            .keys(&[("↑↓", "move"), ("/", "filter"), ("?", "help")])
405            .keys(&[("x", "restart"), ("r", "refresh"), ("e", "env")])
406            .keys(&[("tab", "panel"), ("d", "drifted"), ("s", "sign in"), ("q", "quit")])
407            .status(status);
408        frame.render(area, footer);
409    }
410
411    fn dialog(&self, frame: &mut Frame) {
412        let Some((dialog, opened)) = &self.dialog else { return };
413        let modal = match dialog {
414            Dialog::Help => {
415                let help = Table::new(["key", "does"])
416                    .row(["↑ ↓  j k", "move"])
417                    .row(["← → h l", "panels, scroll sideways"])
418                    .row(["tab", "next panel"])
419                    .row(["1-4", "pick a group"])
420                    .row(["/", "filter by name"])
421                    .row(["d", "only drifted services"])
422                    .row(["x", "restart the service"])
423                    .row(["r", "refresh"])
424                    .row(["e", "pick the environment"])
425                    .row(["s", "sign in"])
426                    .row(["q", "quit"]);
427                Modal::new(Panel::new("keys").body(help).padding(2, 1).focused(true))
428            }
429            Dialog::Environment(at) => Modal::new(
430                Panel::new("environment")
431                    .body(List::new(ENVS).selected(*at))
432                    .footer("enter")
433                    .padding(2, 1)
434                    .focused(true),
435            ),
436            Dialog::Restart(name) => {
437                let body = tinsel::Block::from(vec![
438                    format!(
439                        "Restart {} in {}?",
440                        paint(palette::PETAL, name),
441                        paint(palette::PETAL, ENVS[self.env])
442                    ),
443                    String::new(),
444                    app::hints(&[("y", "restart"), ("n", "not now")]).to_string(),
445                ]);
446                Modal::new(Panel::new("restart").body(body).padding(2, 1).focused(true))
447            }
448        };
449        frame.render(frame.area(), modal.opened(*opened));
450    }
451
452    // MARK: keys
453
454    fn dialog_key(&mut self, key: Key) {
455        let Some((dialog, _)) = &mut self.dialog else { return };
456        match (dialog, key) {
457            (Dialog::Environment(at), Key::Up | Key::Down | Key::Char('j' | 'k')) => {
458                app::navigate(at, ENVS.len(), &Event::Key(key), Keymap::Vim);
459            }
460            (Dialog::Environment(at), Key::Enter) => {
461                self.env = *at;
462                self.dialog = None;
463            }
464            (Dialog::Restart(name), Key::Char('y') | Key::Enter) => {
465                let msg = format!("restarting {name} in {}", ENVS[self.env]);
466                self.dialog = None;
467                self.toasts.push(app::time(), Tone::Success, msg);
468            }
469            (Dialog::Help, _) | (_, Key::Esc | Key::Char('n' | 'q')) => self.dialog = None,
470            _ => {}
471        }
472    }
473}
474
475impl App for Dashboard {
476    fn view(&self, frame: &mut Frame) {
477        let [header, body, footer] = frame.area().shrink(1, 0).rows([Fixed(2), Fill(1), Fixed(1)]);
478        self.header(frame, header.shrink(1, 0).row(0));
479        let [side, main] = body.columns_gap(1, [Fixed(22), Fill(1)]);
480        let [table, details] = main.rows([Fill(1), Fixed(7)]);
481        self.groups(frame, side);
482        self.table(frame, table);
483        self.details(frame, details);
484        self.footer(frame, footer.shrink(1, 0));
485        frame.render(body.shrink(3, 2), &self.toasts);
486        self.dialog(frame);
487    }
488
489    fn event(&mut self, event: &Event) -> Flow {
490        if *event == Event::Wake {
491            if let Some(services) = self.results.try_iter().last() {
492                let first = self.services.is_empty();
493                self.services = services;
494                self.loading = false;
495                self.refreshed = Some(Instant::now());
496                let down = self.services.iter().filter(|s| s.health == Health::Down).count();
497                if down > 0 {
498                    self.toasts.push(
499                        app::time(),
500                        Tone::Warn,
501                        format!("{} down", format::plural(down as u64, "service")),
502                    );
503                } else if !first {
504                    self.toasts.push(app::time(), Tone::Info, "all services up to date");
505                }
506            }
507            return Flow::Continue;
508        }
509        let Event::Key(key) = *event else {
510            return Flow::Continue;
511        };
512        if self.dialog.is_some() {
513            self.dialog_key(key);
514            return Flow::Continue;
515        }
516        if self.pane == Pane::Filter {
517            if !self.filter.handle(event) {
518                match key {
519                    Key::Esc => {
520                        self.filter.clear();
521                        self.focus(Pane::Table);
522                    }
523                    Key::Enter | Key::Tab | Key::Down => self.focus(Pane::Table),
524                    _ => {}
525                }
526            }
527            self.cursor.select(0);
528            return Flow::Continue;
529        }
530        let rows = self.shown().len();
531        match key {
532            Key::Char('q') => return Flow::Quit,
533            Key::Esc if !self.filter.value().is_empty() => self.filter.clear(),
534            Key::Esc => return Flow::Quit,
535            Key::Char('?') => self.open(Dialog::Help),
536            Key::Char('/') => self.focus(Pane::Filter),
537            Key::Char('e') => self.open(Dialog::Environment(self.env)),
538            Key::Char('r') => self.refresh(),
539            Key::Char('s') => self.sign_in(),
540            Key::Char('d') => {
541                self.drifted_only = !self.drifted_only;
542                self.cursor.select(0);
543            }
544            Key::Char(c @ '1'..='4') => {
545                self.group = c as usize - '1' as usize;
546                self.cursor.select(0);
547            }
548            Key::Tab | Key::BackTab => self.focus(if self.pane == Pane::Table {
549                Pane::Groups
550            } else {
551                Pane::Table
552            }),
553            Key::Char('x') => {
554                if let Some(s) = self.chosen() {
555                    let name = s.name;
556                    self.open(Dialog::Restart(name));
557                }
558            }
559            _ if self.pane == Pane::Groups => match key {
560                Key::Right | Key::Char('l') | Key::Enter => self.focus(Pane::Table),
561                _ => {
562                    if app::navigate(&mut self.group, GROUPS.len(), event, Keymap::Vim) {
563                        self.cursor.select(0);
564                    }
565                }
566            },
567            Key::Left | Key::Char('h') => {
568                if !self.cursor.scroll_left() {
569                    self.focus(Pane::Groups);
570                }
571            }
572            Key::Right | Key::Char('l') => {
573                self.cursor.scroll_right();
574            }
575            _ => {
576                self.cursor.handle(rows, event);
577            }
578        }
579        Flow::Continue
580    }
581
582    fn title(&self) -> Option<String> {
583        Some(format!("services · {} · {}", GROUPS[self.group], ENVS[self.env]))
584    }
585}
586
587/// A stand-in for a real login command, which would open a browser or ask for a code.
588fn login() -> std::io::Result<std::process::ExitStatus> {
589    let script = "printf '  open https://example.com/device and enter code WXYZ-1234\\n\\n  press enter once you have… '; read _";
590    if cfg!(windows) {
591        std::process::Command::new("cmd").args(["/C", "pause"]).status()
592    } else {
593        std::process::Command::new("sh").args(["-c", script]).status()
594    }
595}
596
597fn main() -> std::io::Result<()> {
598    let args: Vec<String> = std::env::args().collect();
599    if let [_, flag, size] = args.as_slice() {
600        if flag == "--html" {
601            let (w, h) = size.split_once('x').expect("a size like 120x30");
602            print!(
603                "{}",
604                screenshot(w.parse().expect("a width"), h.parse().expect("a height"))
605            );
606            return Ok(());
607        }
608    }
609    app::run(Dashboard::new())?;
610    Ok(())
611}
612
613/// One frame as a web page, in colour on a dark background, with the services loaded and
614/// one chosen: for the README.
615fn screenshot(width: usize, height: usize) -> String {
616    tinsel::set_color_mode(ColorMode::TrueColor);
617    tinsel::set_theme(Theme::Dark);
618    let mut dash = Dashboard::loaded(fetch(1));
619    dash.cursor.select(5);
620    let mut frame = Frame::new(width, height).at(2.0);
621    dash.view(&mut frame);
622    frame.html()
623}