Skip to main content

schedr_ui/
deployments.rs

1//! The Deployments page (M4.4b, decisions 121-129): one graph of everything the UI shows. The
2//! UI on top (in standalone inside its process), linked by HTTP to each deployment's
3//! webserver; in each deployment's frame its webserver, linked by the database to its
4//! masters, and its workers, each linked by gRPC to the master it registered with. Each
5//! rectangle around nodes is a process. A node with a problem is yellow (a warning) or red
6//! (an error). Clicking a node opens its panel: its facts, its problems and its configuration,
7//! as TOML. Every configuration was masked by the node it belongs to before it left that
8//! node's process, and is masked again before it is shown.
9
10use std::collections::{BTreeMap, HashMap};
11use std::fmt::Write as _;
12use std::sync::Arc;
13use std::time::{Duration, Instant};
14
15use askama::Template;
16use axum::extract::State;
17use axum::http::{HeaderMap, StatusCode};
18use axum::response::Response;
19use schedr_api::views::{
20    DeploymentView, MasterView, MemoryTotals, NodeView, ProblemView, WorkerNodeView,
21};
22use schedr_client::{ClientError, Transport};
23
24use crate::Ui;
25use crate::page::Page;
26use crate::pages::render;
27
28/// A node's width on the graph.
29pub const NODE_WIDTH: u32 = 200;
30/// A node's height on the graph (three lines).
31pub const NODE_HEIGHT: u32 = 52;
32/// The space above a process's first node (its title).
33const PROCESS_TITLE: u32 = 24;
34/// The space above a deployment frame's first process (its name).
35const FRAME_TITLE: u32 = 30;
36/// The space between nodes, and around them in a process.
37const GAP: u32 = 10;
38/// The space between rows (and around frames): room for the lines between them.
39const ROW_GAP: u32 = 40;
40/// A process's width.
41const PROCESS_WIDTH: u32 = NODE_WIDTH + 2 * GAP;
42/// Processes side by side in a row of a frame, at most.
43const PER_ROW: usize = 3;
44/// A node's label, at most (characters; the rest is cut, the whole kept in its tooltip).
45const LABEL_CHARS: usize = 24;
46/// A node's other lines, at most.
47const LINE_CHARS: usize = 30;
48
49/// How bad a node's problems are: its colour.
50#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
51pub enum Level {
52    /// None.
53    Fine,
54    /// A warning: yellow.
55    Warning,
56    /// An error: red.
57    Error,
58}
59
60impl Level {
61    /// The worst of `problems`.
62    #[must_use]
63    pub fn of(problems: &[ProblemView]) -> Self {
64        problems.iter().fold(Self::Fine, |level, problem| {
65            level.max(if problem.error {
66                Self::Error
67            } else {
68                Self::Warning
69            })
70        })
71    }
72
73    /// Its CSS class (empty when fine).
74    #[must_use]
75    pub const fn class(self) -> &'static str {
76        match self {
77            Self::Fine => "",
78            Self::Warning => "warning",
79            Self::Error => "error",
80        }
81    }
82}
83
84/// A node on the graph.
85#[derive(Debug, Clone)]
86pub struct GraphNode {
87    /// Its anchor: its panel's ID.
88    pub anchor: String,
89    /// `ui`, `webserver`, `master` or `worker`.
90    pub kind: &'static str,
91    /// Its name on the graph (cut to fit).
92    pub label: String,
93    /// Its second line: its role or state, and its version.
94    pub sub: String,
95    /// Its third line (a worker's queues; may be empty).
96    pub extra: String,
97    /// Its whole name and lines, as its tooltip.
98    pub tooltip: String,
99    /// Its role or state as a CSS class (`leader`, `standby`, a worker's state).
100    pub state: String,
101    /// How bad its problems are.
102    pub level: Level,
103    /// Its top-left corner.
104    pub x: u32,
105    /// Its top.
106    pub y: u32,
107}
108
109impl GraphNode {
110    /// Its box's CSS classes: its state, and its problems' level, which colours it.
111    #[must_use]
112    pub fn classes(&self) -> String {
113        ["box", self.state.as_str(), self.level.class()]
114            .into_iter()
115            .filter(|class| !class.is_empty())
116            .collect::<Vec<_>>()
117            .join(" ")
118    }
119
120    /// The mark on its corner: `!` for a warning, `×` for an error.
121    #[must_use]
122    pub const fn mark(&self) -> &'static str {
123        match self.level {
124            Level::Fine => "",
125            Level::Warning => "!",
126            Level::Error => "×",
127        }
128    }
129}
130
131/// A rectangle on the graph: a process (around its nodes) or a deployment's frame.
132#[derive(Debug, Clone, PartialEq, Eq)]
133pub struct Frame {
134    /// Its title.
135    pub title: String,
136    /// Its top-left corner.
137    pub x: u32,
138    /// Its top.
139    pub y: u32,
140    /// Its width.
141    pub width: u32,
142    /// Its height.
143    pub height: u32,
144}
145
146/// A line between two nodes.
147#[derive(Debug, Clone, PartialEq, Eq)]
148pub struct Edge {
149    /// `http`, `database` or `grpc`: its CSS class.
150    pub kind: &'static str,
151    /// Drawn dashed: not connected now.
152    pub dashed: bool,
153    /// What it is, as its tooltip.
154    pub title: String,
155    /// Its SVG path.
156    pub path: String,
157}
158
159/// The graph: deployment frames, processes, the lines between nodes, the nodes, in drawing
160/// order.
161#[derive(Debug, Clone)]
162pub struct Graph {
163    /// Its width.
164    pub width: u32,
165    /// Its height.
166    pub height: u32,
167    /// Each deployment's frame.
168    pub frames: Vec<Frame>,
169    /// Each process.
170    pub processes: Vec<Frame>,
171    /// The lines (none inside a process).
172    pub edges: Vec<Edge>,
173    /// The nodes.
174    pub nodes: Vec<GraphNode>,
175}
176
177/// A node's panel, shown when its node is clicked.
178#[derive(Debug, Clone)]
179pub struct NodePanel {
180    /// Its anchor (see [`GraphNode::anchor`]).
181    pub anchor: String,
182    /// Its title: `Master …0d3a9c1f (leader) · prod`.
183    pub title: String,
184    /// What else there is to say: its host, process, version, master.
185    pub facts: Vec<(String, String)>,
186    /// Its problems now.
187    pub problems: Vec<ProblemView>,
188    /// Its configuration as TOML (masked, unset values left out); empty when it sent none.
189    pub config: String,
190    /// What to say when there is no configuration (empty: nothing).
191    pub no_config: &'static str,
192    /// The UI's connections (the UI's panel only).
193    pub connections: Vec<ConnectionRow>,
194    /// Its process on the Metrics page, as a query (`deployment=…&process=…`); empty when not
195    /// known (M5.1j: the panel loads its 24 h chart from it).
196    pub metrics: String,
197}
198
199/// The Metrics page's query for `process` of `deployment`; empty without a process.
200fn metrics_query(deployment: &str, process: &str) -> String {
201    if process.is_empty() {
202        return String::new();
203    }
204    format!(
205        "deployment={}&process={}",
206        schedr_client::path_segment(deployment),
207        schedr_client::path_segment(process)
208    )
209}
210
211/// One of the UI's connections, in its panel.
212#[derive(Debug, Clone)]
213pub struct ConnectionRow {
214    /// The deployment.
215    pub name: String,
216    /// Its webserver's node.
217    pub href: String,
218    /// Its webserver's version (empty when unreachable).
219    pub version: String,
220    /// Whether that differs from this UI's.
221    pub mismatch: bool,
222    /// How long the answer took.
223    pub latency: String,
224    /// How the UI proves itself to it.
225    pub proof: &'static str,
226    /// Who the webserver took the request as.
227    pub user: String,
228    /// Why it couldn't be reached.
229    pub error: Option<String>,
230}
231
232/// The UI's own side, as the graph shows it.
233#[derive(Debug, Clone)]
234pub struct UiSide {
235    /// Its process (empty: not known).
236    pub process_id: String,
237    /// Its host (empty: not known).
238    pub host: String,
239    /// Its version.
240    pub version: String,
241    /// Who is signed in.
242    pub user: String,
243    /// Its configuration, masked.
244    pub config: serde_json::Value,
245}
246
247/// A deployment as asked.
248#[derive(Debug, Clone)]
249pub struct Asked {
250    /// Its name.
251    pub name: String,
252    /// How the UI proves itself to its webserver.
253    pub proof: &'static str,
254    /// Its answer, or why there was none.
255    pub answer: Result<DeploymentView, String>,
256    /// How long that took.
257    pub took: Duration,
258    /// Every process's memory together over 24 h (decision 462's sparkline); none when it
259    /// couldn't be read (an older webserver).
260    pub memory: Option<MemoryTotals>,
261}
262
263/// Said in a panel of a node that sent no configuration.
264const NO_CONFIG: &str = "It sent no configuration (an older agent).";
265
266/// The UI's anchor.
267pub const UI_ANCHOR: &str = "node.ui";
268
269/// A part of an anchor: every character but `A-Z a-z 0-9 _ -` percent-encoded, so the `.`
270/// between parts never comes from a name (two nodes never share an anchor).
271fn anchor_part(text: &str) -> String {
272    let mut part = String::with_capacity(text.len());
273    for byte in text.bytes() {
274        if byte.is_ascii_alphanumeric() || matches!(byte, b'_' | b'-') {
275            part.push(char::from(byte));
276        } else {
277            let _ = write!(part, "%{byte:02X}");
278        }
279    }
280    part
281}
282
283/// A deployment's webserver's anchor.
284#[must_use]
285pub fn webserver_anchor(deployment: &str) -> String {
286    format!("node.{}.webserver", anchor_part(deployment))
287}
288
289/// A master's anchor on the Deployments page.
290#[must_use]
291pub fn master_anchor(deployment: &str, master_id: &str) -> String {
292    format!(
293        "node.{}.master.{}",
294        anchor_part(deployment),
295        anchor_part(master_id)
296    )
297}
298
299/// A worker's anchor on the Deployments page.
300#[must_use]
301pub fn worker_anchor(deployment: &str, worker_id: &str) -> String {
302    format!(
303        "node.{}.worker.{}",
304        anchor_part(deployment),
305        anchor_part(worker_id)
306    )
307}
308
309/// An ID's last 8 characters: a UUIDv7's are random, enough to tell its masters apart (its
310/// first ones are its time, the same for masters started within a minute).
311#[must_use]
312pub fn short(id: &str) -> &str {
313    id.char_indices()
314        .rev()
315        .nth(7)
316        .map_or(id, |(at, _)| &id[at..])
317}
318
319/// `text` cut to `chars` characters, `…` saying it was.
320fn cut(text: &str, chars: usize) -> String {
321    if text.chars().count() <= chars {
322        return text.to_owned();
323    }
324    let mut cut: String = text.chars().take(chars.saturating_sub(1)).collect();
325    cut.push('…');
326    cut
327}
328
329/// `value` without its unset (null) values, in objects and arrays alike.
330fn without_nulls(value: &mut serde_json::Value) {
331    match value {
332        serde_json::Value::Object(map) => {
333            map.retain(|_, v| !v.is_null());
334            map.values_mut().for_each(without_nulls);
335        }
336        serde_json::Value::Array(items) => {
337            items.retain(|v| !v.is_null());
338            items.iter_mut().for_each(without_nulls);
339        }
340        _ => {}
341    }
342}
343
344/// A configuration as shown: masked again here (each node masked its own before it left its
345/// process; one that didn't, an older or altered node, still shows no secret), its unset
346/// values left out, as TOML (as JSON, indented, should TOML not hold it).
347#[must_use]
348pub fn pretty(config: &serde_json::Value) -> String {
349    let mut config = config.clone();
350    schedr_config::masked::mask(&mut config);
351    without_nulls(&mut config);
352    if config.is_object()
353        && let Ok(toml) = toml::to_string_pretty(&config)
354    {
355        // An empty one is still one (not "it sent none").
356        return if toml.is_empty() {
357            "# nothing set".to_owned()
358        } else {
359            toml
360        };
361    }
362    serde_json::to_string_pretty(&config).unwrap_or_default()
363}
364
365/// A process being laid out: its key, host, and nodes (with their tiers).
366struct Group {
367    key: String,
368    host: String,
369    nodes: Vec<(u8, GraphNode)>,
370}
371
372impl Group {
373    fn tier(&self) -> u8 {
374        self.nodes.first().map_or(u8::MAX, |(tier, _)| *tier)
375    }
376
377    fn height(&self) -> u32 {
378        let count = u32::try_from(self.nodes.len()).unwrap_or(u32::MAX);
379        PROCESS_TITLE + count.saturating_mul(NODE_HEIGHT + GAP)
380    }
381
382    fn title(&self) -> String {
383        let host = if self.host.is_empty() {
384            "process"
385        } else {
386            &self.host
387        };
388        if self.key.contains(':') || self.key.is_empty() {
389            host.to_owned()
390        } else {
391            format!("{host} · {}", short(&self.key))
392        }
393    }
394}
395
396/// The processes being laid out, found by key.
397#[derive(Default)]
398struct Groups {
399    list: Vec<Group>,
400    by_key: HashMap<String, usize>,
401}
402
403impl Groups {
404    /// Adds `node` to its process's group (`key`), or a new one.
405    fn add(&mut self, key: String, host: &str, tier: u8, node: GraphNode) {
406        if let Some(&at) = self.by_key.get(&key) {
407            let group = &mut self.list[at];
408            if group.host.is_empty() {
409                host.clone_into(&mut group.host);
410            }
411            group.nodes.push((tier, node));
412        } else {
413            self.by_key.insert(key.clone(), self.list.len());
414            self.list.push(Group {
415                key,
416                host: host.to_owned(),
417                nodes: vec![(tier, node)],
418            });
419        }
420    }
421}
422
423fn node(anchor: String, kind: &'static str, label: &str, sub: &str) -> GraphNode {
424    GraphNode {
425        anchor,
426        kind,
427        tooltip: format!("{label}\n{sub}"),
428        label: cut(label, LABEL_CHARS),
429        sub: cut(sub, LINE_CHARS),
430        extra: String::new(),
431        state: String::new(),
432        level: Level::Fine,
433        x: 0,
434        y: 0,
435    }
436}
437
438/// Lays `groups` out from (`x`, `y`): a row for each tier (wrapping at [`PER_ROW`]), the
439/// processes' nodes stacked. Returns each process's rectangle, with its nodes, and the size.
440fn place(groups: Vec<Group>, x: u32, y: u32) -> (Vec<(Frame, Vec<GraphNode>)>, u32, u32) {
441    let mut rows: Vec<Vec<Group>> = Vec::new();
442    let mut groups = groups;
443    groups.sort_by_key(Group::tier);
444    for group in groups {
445        match rows.last_mut() {
446            Some(row) if row.len() < PER_ROW && row[0].tier() == group.tier() => row.push(group),
447            _ => rows.push(vec![group]),
448        }
449    }
450    let mut placed = Vec::new();
451    let (mut width, mut top) = (0, y);
452    for row in rows {
453        let tallest = row.iter().map(Group::height).max().unwrap_or(0);
454        let mut left = x;
455        for group in row {
456            let height = group.height();
457            let frame = Frame {
458                title: group.title(),
459                x: left,
460                y: top,
461                width: PROCESS_WIDTH,
462                height,
463            };
464            let nodes = group
465                .nodes
466                .into_iter()
467                .enumerate()
468                .map(|(i, (_, mut node))| {
469                    node.x = left + GAP;
470                    node.y = top
471                        + PROCESS_TITLE
472                        + u32::try_from(i)
473                            .unwrap_or(0)
474                            .saturating_mul(NODE_HEIGHT + GAP);
475                    node
476                })
477                .collect();
478            placed.push((frame, nodes));
479            left += PROCESS_WIDTH + GAP;
480        }
481        width = width.max(left - GAP - x);
482        top += tallest + ROW_GAP;
483    }
484    (placed, width, (top - y).saturating_sub(ROW_GAP))
485}
486
487/// A line to draw: from a node to a node (anchors), its kind, dashed, its tooltip.
488struct Link {
489    from: String,
490    to: String,
491    kind: &'static str,
492    dashed: bool,
493    title: String,
494}
495
496/// The SVG path from `from`'s bottom to `to`'s top (`to`'s left side from `from`'s right when
497/// `to` isn't below it).
498fn path(from: (u32, u32), to: (u32, u32)) -> String {
499    let (fx, fy) = (from.0 + NODE_WIDTH / 2, from.1 + NODE_HEIGHT);
500    let (tx, ty) = (to.0 + NODE_WIDTH / 2, to.1);
501    if ty > fy {
502        let bend = (ty - fy) / 2;
503        format!(
504            "M{fx} {fy} C{fx} {} {tx} {} {tx} {ty}",
505            fy + bend,
506            ty - bend
507        )
508    } else {
509        let (fx, fy) = (from.0 + NODE_WIDTH, from.1 + NODE_HEIGHT / 2);
510        let (tx, ty) = (to.0, to.1 + NODE_HEIGHT / 2);
511        format!("M{fx} {fy} L{tx} {ty}")
512    }
513}
514
515/// What the graph gathers while going through the deployments: the panels, the lines, the
516/// UI's connections and problems.
517#[derive(Default)]
518struct Gathered {
519    panels: Vec<NodePanel>,
520    links: Vec<Link>,
521    connections: Vec<ConnectionRow>,
522    ui_problems: Vec<ProblemView>,
523}
524
525impl Gathered {
526    /// A deployment whose webserver couldn't be reached (`error`): a red placeholder.
527    fn unreachable(&mut self, asked: &Asked, error: &str, groups: &mut Groups) {
528        let ws_anchor = webserver_anchor(&asked.name);
529        let latency = format!("{} ms", asked.took.as_millis());
530        self.ui_problems.push(ProblemView {
531            error: true,
532            message: format!("can't reach `{}`'s webserver: {error}", asked.name),
533        });
534        let mut placeholder = node(ws_anchor.clone(), "webserver", "webserver", "unreachable");
535        "unreachable".clone_into(&mut placeholder.state);
536        placeholder.level = Level::Error;
537        groups.add(format!("webserver:{}", asked.name), "", 1, placeholder);
538        self.panels.push(NodePanel {
539            anchor: ws_anchor.clone(),
540            title: format!("Webserver · {}", asked.name),
541            facts: vec![
542                ("The UI proves itself by".to_owned(), asked.proof.to_owned()),
543                ("Gave up after".to_owned(), latency.clone()),
544            ],
545            problems: vec![ProblemView {
546                error: true,
547                message: format!("unreachable: {error}"),
548            }],
549            config: String::new(),
550            no_config: "",
551            metrics: String::new(),
552            connections: Vec::new(),
553        });
554        self.links.push(Link {
555            from: UI_ANCHOR.to_owned(),
556            to: ws_anchor.clone(),
557            kind: "http",
558            dashed: true,
559            title: format!("HTTP: `{}` unreachable", asked.name),
560        });
561        self.connections.push(ConnectionRow {
562            name: asked.name.clone(),
563            href: format!("#{ws_anchor}"),
564            version: String::new(),
565            mismatch: false,
566            latency,
567            proof: asked.proof,
568            user: String::new(),
569            error: Some(error.to_owned()),
570        });
571    }
572
573    /// A deployment that answered (`view`); the UI's node drawn in its webserver's process when
574    /// `ui_node` is given.
575    fn answered(
576        &mut self,
577        (ui, ui_node): (&UiSide, Option<GraphNode>),
578        asked: &Asked,
579        view: &DeploymentView,
580        groups: &mut Groups,
581    ) {
582        let ws_anchor = webserver_anchor(&asked.name);
583        let latency = format!("{} ms", asked.took.as_millis());
584        let mismatch = view.webserver.schedr_version != ui.version;
585        if mismatch {
586            self.ui_problems.push(ProblemView {
587                error: false,
588                message: format!(
589                    "`{}`'s webserver is version {}; this UI is {}",
590                    asked.name, view.webserver.schedr_version, ui.version
591                ),
592            });
593        }
594        self.connections.push(ConnectionRow {
595            name: asked.name.clone(),
596            href: format!("#{ws_anchor}"),
597            version: view.webserver.schedr_version.clone(),
598            mismatch,
599            latency: latency.clone(),
600            proof: asked.proof,
601            user: view.user.clone(),
602            error: None,
603        });
604        let ws_key = process_key(&view.webserver.process_id, "webserver", &asked.name);
605        if let Some(ui_node) = ui_node {
606            groups.add(ws_key.clone(), &view.webserver.host, 0, ui_node);
607        }
608        deployment_nodes(asked, view, &ws_key, groups, self);
609        if let Some(panel) = self.panels.iter_mut().find(|p| p.anchor == ws_anchor) {
610            panel.facts.extend([
611                ("Answered in".to_owned(), latency),
612                ("The UI proves itself by".to_owned(), asked.proof.to_owned()),
613                ("It took the UI's requests as".to_owned(), view.user.clone()),
614            ]);
615        }
616        self.links.push(Link {
617            from: UI_ANCHOR.to_owned(),
618            to: ws_anchor,
619            kind: "http",
620            dashed: false,
621            title: format!("HTTP: the UI reads `{}`", asked.name),
622        });
623    }
624}
625
626/// The graph and the nodes' panels for the UI (`ui`) and the deployments as asked.
627#[must_use]
628pub fn graph(ui: &UiSide, deployments: &[Asked]) -> (Graph, Vec<NodePanel>) {
629    let mut gathered = Gathered::default();
630    // The UI's node, in its own process unless it shares one with a webserver (standalone).
631    let ui_home = deployments.iter().position(|d| {
632        !ui.process_id.is_empty()
633            && d.answer
634                .as_ref()
635                .is_ok_and(|v| v.webserver.process_id == ui.process_id)
636    });
637    let mut ui_node = Some(node(
638        UI_ANCHOR.to_owned(),
639        "ui",
640        "UI",
641        &format!("signed in as {} · {}", ui.user, ui.version),
642    ));
643    let mut deployment_groups = Vec::new();
644    for (index, asked) in deployments.iter().enumerate() {
645        let mut groups = Groups::default();
646        match &asked.answer {
647            Err(error) => gathered.unreachable(asked, error, &mut groups),
648            Ok(view) => {
649                let home = if ui_home == Some(index) {
650                    ui_node.take()
651                } else {
652                    None
653                };
654                gathered.answered((ui, home), asked, view, &mut groups);
655            }
656        }
657        deployment_groups.push((asked.name.clone(), groups.list));
658    }
659    let Gathered {
660        mut panels,
661        links,
662        connections,
663        ui_problems,
664    } = gathered;
665    let ui_level = Level::of(&ui_problems);
666    let mut ui_facts = vec![
667        ("Signed in as".to_owned(), ui.user.clone()),
668        ("Version".to_owned(), ui.version.clone()),
669    ];
670    if !ui.host.is_empty() {
671        ui_facts.push(("Host".to_owned(), ui.host.clone()));
672    }
673    if !ui.process_id.is_empty() {
674        ui_facts.push(("Process".to_owned(), ui.process_id.clone()));
675    }
676    panels.insert(
677        0,
678        NodePanel {
679            anchor: UI_ANCHOR.to_owned(),
680            title: "UI".to_owned(),
681            facts: ui_facts,
682            problems: ui_problems,
683            config: pretty(&ui.config),
684            no_config: NO_CONFIG,
685            connections,
686            metrics: String::new(),
687        },
688    );
689    let ui_group = ui_node.map(|ui_node| Group {
690        key: process_key(&ui.process_id, "ui", ""),
691        host: ui.host.clone(),
692        nodes: vec![(0, ui_node)],
693    });
694    let mut graph = lay_out(ui_group, deployment_groups, links);
695    if let Some(ui) = graph.nodes.iter_mut().find(|n| n.anchor == UI_ANCHOR) {
696        ui.level = ui_level;
697    }
698    (graph, panels)
699}
700
701/// The graph laid out: the UI's own process (`ui`, when it has one) on top, the deployments'
702/// frames side by side below it, and the lines between nodes of different processes.
703fn lay_out(ui: Option<Group>, deployments: Vec<(String, Vec<Group>)>, links: Vec<Link>) -> Graph {
704    let mut placed: Vec<(Frame, Vec<GraphNode>)> = Vec::new();
705    let mut frames = Vec::new();
706    let mut top = ROW_GAP / 2;
707    let mut width = 0;
708    if let Some(group) = ui {
709        let (mut process, w, h) = place(vec![group], ROW_GAP / 2, top);
710        placed.append(&mut process);
711        width = width.max(w);
712        top += h + ROW_GAP;
713    }
714    let mut left = ROW_GAP / 2;
715    let mut bottom = top;
716    for (name, groups) in deployments {
717        let (mut processes, w, h) = place(groups, left + GAP, top + FRAME_TITLE);
718        let frame = Frame {
719            title: name,
720            x: left,
721            y: top,
722            width: w + 2 * GAP,
723            height: FRAME_TITLE + h + GAP,
724        };
725        left += frame.width + ROW_GAP;
726        bottom = bottom.max(frame.y + frame.height);
727        frames.push(frame);
728        placed.append(&mut processes);
729    }
730    width = width.max(left.saturating_sub(ROW_GAP / 2));
731    let mut processes = Vec::new();
732    let mut nodes = Vec::new();
733    let mut at = HashMap::new();
734    for (process, process_nodes) in placed {
735        for node in &process_nodes {
736            at.insert(node.anchor.clone(), (node.x, node.y, processes.len()));
737        }
738        processes.push(process);
739        nodes.extend(process_nodes);
740    }
741    let edges = links
742        .into_iter()
743        .filter_map(|link| {
744            let (fx, fy, from_process) = *at.get(&link.from)?;
745            let (tx, ty, to_process) = *at.get(&link.to)?;
746            (from_process != to_process).then(|| Edge {
747                kind: link.kind,
748                dashed: link.dashed,
749                title: link.title,
750                path: path((fx, fy), (tx, ty)),
751            })
752        })
753        .collect();
754    Graph {
755        width: width + ROW_GAP / 2,
756        height: bottom + ROW_GAP / 2,
757        frames,
758        processes,
759        edges,
760        nodes,
761    }
762}
763
764/// A process's key: its ID, or (an older node, which doesn't send it) one of its own.
765fn process_key(process_id: &str, kind: &str, id: &str) -> String {
766    if process_id.is_empty() {
767        format!("{kind}:{id}")
768    } else {
769        process_id.to_owned()
770    }
771}
772
773/// One deployment's webserver, masters and workers: their nodes in `groups`, their panels and
774/// the lines between them.
775fn deployment_nodes(
776    asked: &Asked,
777    view: &DeploymentView,
778    ws_key: &str,
779    groups: &mut Groups,
780    gathered: &mut Gathered,
781) {
782    let Gathered { panels, links, .. } = gathered;
783    let name = &asked.name;
784    let ws_anchor = webserver_anchor(name);
785    let ws = &view.webserver;
786    groups.add(
787        ws_key.to_owned(),
788        &ws.host,
789        1,
790        node(
791            ws_anchor.clone(),
792            "webserver",
793            "webserver",
794            &ws.schedr_version,
795        ),
796    );
797    panels.push(NodePanel {
798        anchor: ws_anchor.clone(),
799        title: format!("Webserver · {name}"),
800        facts: node_facts(ws),
801        problems: Vec::new(),
802        config: pretty(&ws.config),
803        no_config: NO_CONFIG,
804        connections: Vec::new(),
805        metrics: metrics_query(name, &ws.process_id),
806    });
807    for master in &view.masters {
808        let anchor = master_anchor(name, &master.master_id);
809        let mut graph_node = node(
810            anchor.clone(),
811            "master",
812            &format!("master {}", short(&master.master_id)),
813            &format!("{} · {}", master.role, master.node.schedr_version),
814        );
815        graph_node.state.clone_from(&master.role);
816        graph_node.level = Level::of(&master.problems);
817        groups.add(
818            process_key(&master.node.process_id, "master", &master.master_id),
819            &master.node.host,
820            2,
821            graph_node,
822        );
823        panels.push(master_panel(name, master));
824        links.push(Link {
825            from: ws_anchor.clone(),
826            to: anchor,
827            kind: "database",
828            dashed: false,
829            title: format!(
830                "database: the webserver and master {} share it",
831                short(&master.master_id)
832            ),
833        });
834    }
835    for worker in &view.workers {
836        worker_node(name, view, worker, groups, (panels, links));
837    }
838}
839
840/// A worker's node in `groups`, its panel, and its line to its master.
841fn worker_node(
842    name: &str,
843    view: &DeploymentView,
844    worker: &WorkerNodeView,
845    groups: &mut Groups,
846    (panels, links): (&mut Vec<NodePanel>, &mut Vec<Link>),
847) {
848    let anchor = worker_anchor(name, &worker.worker_id);
849    let mut graph_node = node(
850        anchor.clone(),
851        "worker",
852        &format!("worker {}", worker.worker_id),
853        &format!("{} · {}", worker.state, worker.schedr_version),
854    );
855    if !worker.queues.is_empty() {
856        let queues = format!("queues: {}", worker.queues.join(", "));
857        graph_node.extra = cut(&queues, LINE_CHARS);
858        graph_node.tooltip = format!("{}\n{queues}", graph_node.tooltip);
859    }
860    graph_node.state.clone_from(&worker.state);
861    graph_node.level = Level::of(&worker.problems);
862    groups.add(
863        process_key(
864            worker.process_id.as_deref().unwrap_or_default(),
865            "worker",
866            &worker.worker_id,
867        ),
868        "",
869        3,
870        graph_node,
871    );
872    panels.push(worker_panel(name, view, worker));
873    if let Some(master) = &worker.master_id
874        && view.masters.iter().any(|m| &m.master_id == master)
875    {
876        let connected = matches!(worker.state.as_str(), "active" | "draining");
877        links.push(Link {
878            from: master_anchor(name, master),
879            to: anchor,
880            kind: "grpc",
881            dashed: !connected,
882            title: format!(
883                "gRPC: worker {} {} master {}",
884                worker.worker_id,
885                if connected {
886                    "is connected to"
887                } else {
888                    "isn't connected to"
889                },
890                short(master)
891            ),
892        });
893    }
894}
895
896/// A node's problems as shown: masked again (an older webserver didn't).
897fn masked_problems(problems: &[ProblemView]) -> Vec<ProblemView> {
898    problems
899        .iter()
900        .map(|problem| ProblemView {
901            error: problem.error,
902            message: schedr_config::masked::mask_text(&problem.message),
903        })
904        .collect()
905}
906
907fn node_facts(node: &NodeView) -> Vec<(String, String)> {
908    let mut facts = Vec::new();
909    if !node.host.is_empty() {
910        facts.push(("Host".to_owned(), node.host.clone()));
911    }
912    if !node.process_id.is_empty() {
913        facts.push(("Process".to_owned(), node.process_id.clone()));
914    }
915    facts.push(("Version".to_owned(), node.schedr_version.clone()));
916    facts
917}
918
919fn master_panel(deployment: &str, master: &MasterView) -> NodePanel {
920    let mut facts = vec![
921        ("ID".to_owned(), master.master_id.clone()),
922        ("Role".to_owned(), master.role.clone()),
923    ];
924    facts.extend(node_facts(&master.node));
925    NodePanel {
926        anchor: master_anchor(deployment, &master.master_id),
927        title: format!(
928            "Master {} ({}) · {deployment}",
929            short(&master.master_id),
930            master.role
931        ),
932        facts,
933        problems: masked_problems(&master.problems),
934        config: pretty(&master.node.config),
935        no_config: NO_CONFIG,
936        connections: Vec::new(),
937        metrics: metrics_query(deployment, &master.node.process_id),
938    }
939}
940
941fn worker_panel(deployment: &str, view: &DeploymentView, worker: &WorkerNodeView) -> NodePanel {
942    let mut facts = vec![
943        ("State".to_owned(), worker.state.clone()),
944        ("Queues".to_owned(), worker.queues.join(", ")),
945        ("Version".to_owned(), worker.schedr_version.clone()),
946    ];
947    if let Some(process) = &worker.process_id {
948        facts.push(("Process".to_owned(), process.clone()));
949    }
950    if let Some(master) = &worker.master_id {
951        let heard = view.masters.iter().any(|m| &m.master_id == master);
952        facts.push((
953            "Registered with".to_owned(),
954            if heard {
955                format!("master {}", short(master))
956            } else {
957                format!("master {} (not heard from lately)", short(master))
958            },
959        ));
960    }
961    NodePanel {
962        anchor: worker_anchor(deployment, &worker.worker_id),
963        title: format!("Worker {} · {deployment}", worker.worker_id),
964        facts,
965        problems: masked_problems(&worker.problems),
966        config: worker.config.as_ref().map(pretty).unwrap_or_default(),
967        no_config: NO_CONFIG,
968        connections: Vec::new(),
969        metrics: metrics_query(deployment, worker.process_id.as_deref().unwrap_or_default()),
970    }
971}
972
973/// The worker states in the order the Status block counts them: the ones that need a look
974/// first after `active`.
975pub const WORKER_STATES: [&str; 5] = ["active", "draining", "disconnected", "lost", "offline"];
976
977/// A problem in the Status block's list, opening its node's panel.
978#[derive(Debug, Clone, PartialEq, Eq)]
979pub struct StatusProblem {
980    /// An error; a warning otherwise.
981    pub error: bool,
982    /// The node it is on (`master 1a2b3c4d`, `worker w1`).
983    pub node: String,
984    /// What it is.
985    pub message: String,
986    /// Its node's panel.
987    pub href: String,
988}
989
990/// A deployment's line in the Status block above the graph (decision 462).
991#[derive(Debug, Clone, PartialEq, Eq)]
992pub struct StatusRow {
993    /// The deployment.
994    pub name: String,
995    /// Its webserver's panel.
996    pub href: String,
997    /// Why its webserver couldn't be reached; none when it answered.
998    pub unreachable: Option<String>,
999    /// How long the answer (or giving up) took.
1000    pub took: String,
1001    /// Its masters leading (one, unless the lease is changing hands) and standing by.
1002    pub leaders: usize,
1003    /// Its standbys.
1004    pub standbys: usize,
1005    /// Its workers by state, those there are: `active`, `draining`, `disconnected`, `lost`,
1006    /// `offline`, in that order.
1007    pub workers: Vec<(&'static str, usize)>,
1008    /// The attempts running on its active workers.
1009    pub running: u32,
1010    /// Its active workers' task slots.
1011    pub slots: u32,
1012    /// Its nodes' problems, errors first.
1013    pub problems: Vec<StatusProblem>,
1014    /// Its schedr versions, each with how many processes run it (webserver, masters and the
1015    /// workers not gone): more than one is warned.
1016    pub versions: Vec<(String, usize)>,
1017    /// Every process's memory now, tasks included (empty: not known).
1018    pub memory: String,
1019    /// A sparkline of it over 24 h (SVG; empty: none).
1020    pub sparkline: String,
1021    /// Its Metrics page.
1022    pub metrics_href: String,
1023}
1024
1025impl StatusRow {
1026    /// How many of its problems are errors.
1027    #[must_use]
1028    pub fn errors(&self) -> usize {
1029        self.problems.iter().filter(|p| p.error).count()
1030    }
1031
1032    /// How many are warnings.
1033    #[must_use]
1034    pub fn warnings(&self) -> usize {
1035        self.problems.len() - self.errors()
1036    }
1037
1038    /// No master leads: nothing is scheduled.
1039    #[must_use]
1040    pub const fn leaderless(&self) -> bool {
1041        self.unreachable.is_none() && self.leaders == 0
1042    }
1043
1044    /// Its processes run more than one version.
1045    #[must_use]
1046    pub fn mixed(&self) -> bool {
1047        self.versions.len() > 1
1048    }
1049}
1050
1051/// The Status block: a line per deployment as asked, in their order (decision 462).
1052#[must_use]
1053pub fn status(deployments: &[Asked]) -> Vec<StatusRow> {
1054    deployments.iter().map(status_row).collect()
1055}
1056
1057/// One deployment's line.
1058/// A deployment's memory now and its 24 h sparkline; none without a point.
1059fn memory_now(name: &str, totals: &MemoryTotals) -> Option<(String, String)> {
1060    let last = totals.points.last()?;
1061    #[expect(clippy::cast_precision_loss, reason = "a chart's coordinates")]
1062    let points: Vec<(i64, f64)> = totals
1063        .points
1064        .iter()
1065        .map(|p| (p.at.as_second(), p.resident as f64))
1066        .collect();
1067    #[expect(clippy::cast_precision_loss, reason = "a size shown")]
1068    let now = crate::chart::bytes(last.resident as f64);
1069    let sparkline = crate::chart::sparkline(
1070        &points,
1071        totals.from.as_second(),
1072        totals.to.as_second(),
1073        i64::from(totals.step_s),
1074        &format!("{name}'s memory over 24 h, now {now}"),
1075    );
1076    Some((now, sparkline))
1077}
1078
1079fn status_row(asked: &Asked) -> StatusRow {
1080    let name = &asked.name;
1081    let mut row = StatusRow {
1082        name: name.clone(),
1083        href: format!("#{}", webserver_anchor(name)),
1084        unreachable: None,
1085        took: format!("{} ms", asked.took.as_millis()),
1086        leaders: 0,
1087        standbys: 0,
1088        workers: Vec::new(),
1089        running: 0,
1090        slots: 0,
1091        problems: Vec::new(),
1092        versions: Vec::new(),
1093        memory: String::new(),
1094        sparkline: String::new(),
1095        metrics_href: format!("metrics?deployment={}", schedr_client::path_segment(name)),
1096    };
1097    if let Some((memory, sparkline)) = asked.memory.as_ref().and_then(|t| memory_now(name, t)) {
1098        row.memory = memory;
1099        row.sparkline = sparkline;
1100    }
1101    let view = match &asked.answer {
1102        Err(error) => {
1103            row.unreachable = Some(error.clone());
1104            return row;
1105        }
1106        Ok(view) => view,
1107    };
1108    let mut versions: BTreeMap<&str, usize> = BTreeMap::new();
1109    *versions.entry(&view.webserver.schedr_version).or_default() += 1;
1110    for master in &view.masters {
1111        if master.role == "leader" {
1112            row.leaders += 1;
1113        } else {
1114            row.standbys += 1;
1115        }
1116        *versions.entry(&master.node.schedr_version).or_default() += 1;
1117        let href = format!("#{}", master_anchor(name, &master.master_id));
1118        row.problems.extend(
1119            masked_problems(&master.problems)
1120                .into_iter()
1121                .map(|p| StatusProblem {
1122                    error: p.error,
1123                    node: format!("master {}", short(&master.master_id)),
1124                    message: p.message,
1125                    href: href.clone(),
1126                }),
1127        );
1128    }
1129    let mut states: BTreeMap<usize, usize> = BTreeMap::new();
1130    for worker in &view.workers {
1131        let at = WORKER_STATES
1132            .iter()
1133            .position(|s| *s == worker.state)
1134            .unwrap_or(WORKER_STATES.len() - 1);
1135        *states.entry(at).or_default() += 1;
1136        if worker.state == "active" {
1137            row.running += worker.running;
1138            row.slots += worker.slots;
1139        }
1140        if !matches!(worker.state.as_str(), "offline" | "lost") {
1141            *versions.entry(&worker.schedr_version).or_default() += 1;
1142        }
1143        let href = format!("#{}", worker_anchor(name, &worker.worker_id));
1144        row.problems.extend(
1145            masked_problems(&worker.problems)
1146                .into_iter()
1147                .map(|p| StatusProblem {
1148                    error: p.error,
1149                    node: format!("worker {}", worker.worker_id),
1150                    message: p.message,
1151                    href: href.clone(),
1152                }),
1153        );
1154    }
1155    row.workers = states
1156        .into_iter()
1157        .map(|(at, count)| (WORKER_STATES[at], count))
1158        .collect();
1159    // Errors first, each kind in node order.
1160    row.problems.sort_by_key(|p| !p.error);
1161    row.versions = versions
1162        .into_iter()
1163        .map(|(version, count)| (version.to_owned(), count))
1164        .collect();
1165    row
1166}
1167
1168/// Each deployment's nodes (asked at once), in deployment order, each with how long its answer
1169/// took.
1170async fn ask_all<T: Transport + Send + Sync + 'static>(
1171    ui: &Arc<Ui<T>>,
1172) -> Vec<(
1173    Result<DeploymentView, ClientError>,
1174    Duration,
1175    Option<MemoryTotals>,
1176)> {
1177    let mut asked = tokio::task::JoinSet::new();
1178    for index in 0..ui.deployments.len() {
1179        let ui = Arc::clone(ui);
1180        asked.spawn(schedr_client::for_same_user(async move {
1181            let started = Instant::now();
1182            let client = &ui.deployments[index].client;
1183            let (answer, memory) = tokio::join!(client.deployment(), client.memory_totals("24h"));
1184            (index, answer, started.elapsed(), memory.ok())
1185        }));
1186    }
1187    let mut answers = asked.join_all().await;
1188    answers.sort_by_key(|(index, _, _, _)| *index);
1189    answers
1190        .into_iter()
1191        .map(|(_, answer, took, memory)| (answer, took, memory))
1192        .collect()
1193}
1194
1195#[derive(Template)]
1196#[template(path = "deployments.html")]
1197struct DeploymentsPage {
1198    page: Page,
1199    status: Vec<StatusRow>,
1200    graph: Graph,
1201    panels: Vec<NodePanel>,
1202}
1203
1204/// `GET /deployments`: the graph of everything the UI shows, each deployment asked at once,
1205/// and each node's panel.
1206pub async fn list<T: Transport + Send + Sync + 'static>(
1207    State(ui): State<Arc<Ui<T>>>,
1208    headers: HeaderMap,
1209) -> Response {
1210    let page = Page::new(&headers, ui.docs_dir.is_some()).live("kinds=workers", "/deployments");
1211    let asked: Vec<Asked> = ui
1212        .deployments
1213        .iter()
1214        .zip(ask_all(&ui).await)
1215        .map(|(deployment, (answer, took, memory))| Asked {
1216            name: deployment.name.clone(),
1217            proof: deployment.proof,
1218            answer: answer.map_err(|e| e.to_string()),
1219            took,
1220            memory,
1221        })
1222        .collect();
1223    let side = UiSide {
1224        process_id: ui.process_id.clone(),
1225        host: ui.host.clone(),
1226        version: env!("CARGO_PKG_VERSION").to_owned(),
1227        user: schedr_client::current_user().unwrap_or_else(|| "anonymous".to_owned()),
1228        config: ui.config.clone(),
1229    };
1230    let (graph, panels) = graph(&side, &asked);
1231    render(
1232        &DeploymentsPage {
1233            page,
1234            status: status(&asked),
1235            graph,
1236            panels,
1237        },
1238        StatusCode::OK,
1239    )
1240}