feat(ui): xray cluster ownership graph (#23)

`:xray [namespace|all]` opens a live ownership graph, replacing the old stub
and closing gap #3 from the k9s parity audit (4.7). Rather than a per-kind tree,
it's a single namespace-rooted forest of the workload topology:

  ns/<name>
  ├─ deploy → rs → pod → container
  ├─ sts / ds → pod → container
  ├─ cronjob → job → pod
  ├─ job / bare rs → pod
  └─ standalone pods (no controller)

`:xray` defaults to the current namespace; `:xray all` spans the cluster grouped
by namespace.

Rendering is a real tree, not indented text: box-drawing connectors
(├──/└──/│), ▾/▸ expand markers, severity-colored per-node status, and a
selectable cursor. Navigate j/k (+ g/G); →/← expand/collapse the node under the
cursor, Enter toggles, esc closes. Collapse state is keyed by stable node id so
it survives the per-frame rebuild.

The graph rebuilds from store state every frame so it tracks the cluster live;
opening it adds the workload kinds it draws to the active watch plan so it fills
in within a moment. Large graphs truncate with `… N more` nodes (no silent
caps). Cross-cutting relations (Service/PVC/ConfigMap/Node — non-ownership,
multi-parent edges that don't fit a tree) are intentionally left to the Enter
drill-down and describe views.

Reuses the existing owner-chain helpers (the log fan-in's
deployment/replicaset/pod key lookups).

Tests: namespace-rooted tree structure + connectors + expand marker; collapse
hides a subtree; arrow-key directed collapse/expand.

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
ErfanandClaude Opus 4.8 authored and GitHub committed 2026-06-25 23:05:21 +02:00
1 parent d563d6d542
commit fce242df7c
7 files changed
+658 -8

No files matched your search

+7 -1
View File
@@ -201,7 +201,13 @@ Root problem: full object JSON kept for every entity.
- [x] **Previous logs** — DONE. `P` in the logs pane toggles the previous (terminated) container
instance (`kubectl logs -p`) as a one-shot fetch (no follow/reconnect); status line shows
`instance:current|previous`. Plumbing (`PodLogRequest.previous`) already existed.
- **xray** relationship-tree view (replace stub).
- [x] **xray** — DONE. `:xray [ns|all]` opens a live **cluster ownership graph** — a
namespace-rooted forest (ns → deploy/rs, sts, ds, cj/job, bare rs, standalone pods → pods →
containers), not a per-kind tree. Rebuilt from store state each frame; opening it watches the
workload kinds it draws. Proper tree rendering: box-drawing connectors (`├──`/`└──`/`│`),
`▾`/`▸` expand markers, severity-colored status, selectable cursor (`j`/`k`/`g`/`G`), `Enter`
expand/collapse (state keyed by node id, survives rebuild). Truncates with `… N more` (no silent
caps). Cross-cutting relations (node, PVC, service) intentionally left to Enter-drill/describe.
- Medium: jump-to-owner (`Shift-J`), UsedBy/dependents (`U`), log timestamps, pod metric-column
sort, inline `:pod /term`/`@ctx`.
- Decide: popeye sanitizer (large, separable); pulses dashboard (likely redundant with the
+26
View File
@@ -154,12 +154,38 @@ Common command mode entries:
- `:ns` namespaces
- `:po`, `:deploy`, `:svc`, `:ing`, `:cm`, `:sec`, etc.
- `:api [filter]` list all API resources/CRDs discovered on the context
- `:xray [namespace|all]` open the namespace ownership graph (workloads → pods → containers)
- `:<resource>` browse any discovered resource/CRD (e.g. `:endpoints`, `:widgets`); `:<resource> <name>` describes one
- `:fmt yaml|json`
- `:edit [yaml|json]`
- `:sort <name|namespace|status|age> [asc|desc]` set the table sort column/direction
- `:helm [show|hide]` toggle (or set) visibility of Helm release secrets in the Secrets list
## XRay (relationship graph)
`:xray [namespace]` opens a live ownership graph of a namespace — a single forest rooted at the
namespace, grouping every workload down to its pods and containers:
```
ns/default
├─ deploy/api → rs/api-7d9 → po/… → ctr/…
├─ sts/db → po/db-0 → ctr/…
├─ ds/agent → po/…
├─ cj/backup → job/… → po/…
├─ job/migrate → po/…
└─ po/debug (standalone — no controller)
```
`:xray` defaults to the current namespace; `:xray all` covers the whole cluster (grouped by
namespace). It renders as a real tree with box-drawing connectors (`├──`/`└──`/`│`) and `▾`/`▸`
expand markers; each node carries a severity-colored status. Navigate with `j`/`k` (or up/down),
`g`/`G` for top/bottom; `→`/`←` expand/collapse the node under the cursor (`Enter` toggles), `esc`
to close.
The graph rebuilds from live cluster state each frame and opening it watches the workload kinds it
draws, so it populates within a moment and tracks the cluster as it changes. Large graphs are
truncated with `… N more` nodes (collapse subtrees to keep it manageable).
## Detail Pane Behavior
- `w`: wrap toggle
+167 -4
View File
@@ -26,6 +26,7 @@ use ratatui::{
Terminal,
backend::CrosstermBackend,
layout::{Alignment, Constraint, Direction, Layout},
style::{Color, Style},
text::{Line, Span, Text},
widgets::{Block, Borders, Cell, Padding, Paragraph, Row, Table, Wrap},
};
@@ -81,6 +82,7 @@ mod detail_pane;
mod logs;
mod overlay;
mod render_loop;
mod xray;
#[derive(Debug, Clone)]
struct ContextTabState {
@@ -177,6 +179,15 @@ enum Overlay {
hscroll: u16,
wrap: bool,
},
/// Live cluster relationship graph (`:xray`): a namespace-rooted ownership forest
/// (ns → controllers → pods → containers). Holds the scope + view state (cursor, collapsed
/// nodes), not the rows — rows are rebuilt from the store each frame so the tree tracks the
/// cluster. `namespace` is None for the whole cluster. Collapsed nodes are keyed by stable id.
Xray {
namespace: Option<String>,
selected: usize,
collapsed: HashSet<String>,
},
Contexts {
title: String,
contexts: Vec<String>,
@@ -806,7 +817,7 @@ impl App {
| Overlay::LogSources { filter, .. } => {
return filter.clone();
}
Overlay::Text { .. } => {}
Overlay::Text { .. } | Overlay::Xray { .. } => {}
}
}
let tab = self.current_tab();
@@ -834,7 +845,7 @@ impl App {
} => {
*overlay_filter = filter;
}
Overlay::Text { .. } => {}
Overlay::Text { .. } | Overlay::Xray { .. } => {}
}
return;
}
@@ -864,7 +875,7 @@ impl App {
Overlay::Contexts { .. }
| Overlay::Containers { .. }
| Overlay::LogSources { .. } => "Filter",
Overlay::Text { .. } => "Search",
Overlay::Text { .. } | Overlay::Xray { .. } => "Search",
};
}
if self.current_tab().pane == Pane::Table {
@@ -1344,6 +1355,29 @@ impl App {
if let Some(overlay) = &self.overlay {
return match overlay {
Overlay::Text { lines, .. } => Some(lines.join("\n")),
Overlay::Xray {
namespace,
collapsed,
..
} => {
let rows = self.xray_rows(namespace.as_deref(), collapsed);
Some(
rows.iter()
.map(|r| {
let status = r
.status
.as_deref()
.map(|s| format!(" {s}"))
.unwrap_or_default();
format!(
"{}{} {}/{}{status}",
r.connectors, r.marker, r.kind, r.name
)
})
.collect::<Vec<_>>()
.join("\n"),
)
}
Overlay::Contexts {
contexts,
selected,
@@ -1781,7 +1815,20 @@ impl App {
async fn ensure_active_watch(&mut self) {
let tab = self.current_tab().clone();
let targets = Self::active_watch_targets(&tab);
let mut targets = Self::active_watch_targets(&tab);
// An open xray graph spans the whole ownership forest, so watch every kind it draws,
// scoped to its namespace (None = whole cluster).
if let Some(Overlay::Xray { namespace, .. }) = &self.overlay {
for kind in XRAY_WATCH_KINDS {
let target = WatchTarget {
kind,
namespace: namespace.clone(),
};
if !targets.contains(&target) {
targets.push(target);
}
}
}
if let Err(err) = self
.resource_provider
.replace_watch_plan(&tab.context, &targets)
@@ -2228,6 +2275,17 @@ fn context_filtered_indices(contexts: &[String], filter: &str) -> Vec<usize> {
list_filtered_indices(contexts, filter)
}
/// Kinds the xray ownership forest draws — watched while an xray overlay is open so it populates.
const XRAY_WATCH_KINDS: [ResourceKind; 7] = [
ResourceKind::Deployments,
ResourceKind::ReplicaSets,
ResourceKind::StatefulSets,
ResourceKind::DaemonSets,
ResourceKind::CronJobs,
ResourceKind::Jobs,
ResourceKind::Pods,
];
fn format_millicpu(value: u64) -> String {
if value >= 1000 {
let cores = value as f64 / 1000.0;
@@ -3257,6 +3315,111 @@ mod tests {
assert!(snap.contains("helm shown"), "title hint: {snap}");
}
#[test]
fn xray_builds_owner_child_tree() {
let mut app = test_app();
app.store.apply(StateDelta::Upsert(mk_entity(
"ctx-dev",
ResourceKind::Deployments,
Some("default"),
"dep1",
"1/1 ready",
)));
let mut rs = mk_entity(
"ctx-dev",
ResourceKind::ReplicaSets,
Some("default"),
"rs1",
"-",
);
rs.extracted.owners = vec![crate::model::OwnerRef {
kind: "Deployment".to_string(),
name: "dep1".to_string(),
}];
app.store.apply(StateDelta::Upsert(rs));
let mut pod = mk_entity(
"ctx-dev",
ResourceKind::Pods,
Some("default"),
"p1",
"Running",
);
pod.extracted.owners = vec![crate::model::OwnerRef {
kind: "ReplicaSet".to_string(),
name: "rs1".to_string(),
}];
pod.extracted.containers = vec!["app".to_string()];
app.store.apply(StateDelta::Upsert(pod));
let empty = std::collections::HashSet::new();
let rows = app.xray_rows(Some("default"), &empty);
let labels: Vec<String> = rows
.iter()
.map(|r| format!("{}/{}", r.kind, r.name))
.collect();
// Namespace-rooted forest: ns → deploy → rs → pod → container.
assert!(labels.contains(&"ns/default".to_string()), "{labels:?}");
assert!(labels.contains(&"deploy/dep1".to_string()), "{labels:?}");
assert!(labels.contains(&"rs/rs1".to_string()), "{labels:?}");
assert!(labels.contains(&"po/p1".to_string()), "{labels:?}");
assert!(labels.contains(&"ctr/app".to_string()), "{labels:?}");
let ns = rows.iter().find(|r| r.name == "default").expect("ns row");
assert!(ns.connectors.is_empty(), "ns root is flush-left");
let dep = rows.iter().find(|r| r.name == "dep1").expect("deploy row");
assert!(dep.has_children && dep.marker == '▾', "deploy expandable");
assert!(
dep.connectors.contains('─'),
"deploy nested under ns: {:?}",
dep.connectors
);
// Collapsing the namespace hides its whole subtree.
let mut collapsed = std::collections::HashSet::new();
collapsed.insert(ns.id.clone());
let rows = app.xray_rows(Some("default"), &collapsed);
assert_eq!(rows.len(), 1, "only the collapsed namespace remains");
assert_eq!(rows[0].marker, '▸', "collapsed marker");
}
#[test]
fn xray_arrow_keys_collapse_and_expand() {
let mut app = test_app();
app.store.apply(StateDelta::Upsert(mk_entity(
"ctx-dev",
ResourceKind::Deployments,
Some("default"),
"dep1",
"1/1 ready",
)));
app.show_xray_overlay(Some("default".to_string()));
// Cursor starts on the ns root (selected = 0), which has the deployment as a child.
let visible = |app: &App| -> usize {
let Some(super::Overlay::Xray {
namespace,
collapsed,
..
}) = &app.overlay
else {
panic!("xray overlay");
};
app.xray_rows(namespace.as_deref(), collapsed).len()
};
let expanded = visible(&app);
assert!(expanded > 1, "ns starts expanded: {expanded}");
// Left collapses the namespace → only the ns row remains.
app.set_xray_collapsed(true);
assert_eq!(visible(&app), 1, "collapsed to ns root only");
// Right expands it again.
app.set_xray_collapsed(false);
assert_eq!(visible(&app), expanded, "re-expanded");
}
#[test]
fn enter_on_deployment_drills_into_its_pods() {
let mut app = test_app();
+11 -1
View File
@@ -389,7 +389,17 @@ impl App {
self.show_api_catalog(args.first().copied()).await;
false
}
"pulse" | "pulses" | "pu" | "xray" | "popeye" | "pop" | "plugins" | "plugin" => {
"xray" => {
// :xray [namespace|all] — default to the current namespace; `all` = whole cluster.
let namespace = match args.first() {
Some(token) if token.eq_ignore_ascii_case("all") => None,
Some(token) => Some(token.to_string()),
None => self.current_tab().namespace.clone(),
};
self.show_xray_overlay(namespace);
false
}
"pulse" | "pulses" | "pu" | "popeye" | "pop" | "plugins" | "plugin" => {
self.status_line =
format!("Command ':{cmd}' is recognized but not implemented yet");
false
+24 -2
View File
@@ -187,6 +187,10 @@ impl App {
};
}
}
if matches!(self.overlay, Some(Overlay::Xray { .. })) {
self.toggle_xray_collapse();
}
}
KeyCode::Char(' ') => {
if let Some(Overlay::LogSources {
@@ -224,10 +228,18 @@ impl App {
self.scroll_overlay_or_select(1);
}
KeyCode::Left => {
self.scroll_overlay_horizontal(-4);
if matches!(self.overlay, Some(Overlay::Xray { .. })) {
self.set_xray_collapsed(true);
} else {
self.scroll_overlay_horizontal(-4);
}
}
KeyCode::Right => {
self.scroll_overlay_horizontal(4);
if matches!(self.overlay, Some(Overlay::Xray { .. })) {
self.set_xray_collapsed(false);
} else {
self.scroll_overlay_horizontal(4);
}
}
KeyCode::PageUp => {
self.scroll_overlay_or_select(-10);
@@ -254,6 +266,13 @@ impl App {
*scroll = scroll.saturating_add(delta as u16);
}
}
Some(Overlay::Xray { selected, .. }) => {
if delta < 0 {
*selected = selected.saturating_sub(delta.unsigned_abs() as usize);
} else {
*selected = selected.saturating_add(delta as usize);
}
}
Some(Overlay::Contexts {
contexts,
selected,
@@ -340,6 +359,7 @@ impl App {
pub(super) fn overlay_home(&mut self) {
match &mut self.overlay {
Some(Overlay::Text { scroll, .. }) => *scroll = 0,
Some(Overlay::Xray { selected, .. }) => *selected = 0,
Some(Overlay::Contexts {
contexts,
selected,
@@ -374,6 +394,8 @@ impl App {
pub(super) fn overlay_end(&mut self) {
match &mut self.overlay {
Some(Overlay::Text { scroll, .. }) => *scroll = u16::MAX,
// Clamped to the row count in render.
Some(Overlay::Xray { selected, .. }) => *selected = usize::MAX,
Some(Overlay::Contexts {
contexts,
selected,
+76
View File
@@ -465,6 +465,19 @@ impl App {
.style(theme.block);
frame.render_widget(pulse_widget, chunks[1]);
// The xray tree is rebuilt from store state each frame; compute its rows before the
// mutable borrow of `self.overlay` below (building them needs `&self`).
let xray_rows = if let Some(Overlay::Xray {
namespace,
collapsed,
..
}) = &self.overlay
{
Some(self.xray_rows(namespace.as_deref(), collapsed))
} else {
None
};
if let Some(overlay) = &mut self.overlay {
match overlay {
Overlay::Text {
@@ -496,6 +509,61 @@ impl App {
}
frame.render_widget(paragraph, chunks[2]);
}
Overlay::Xray {
namespace,
selected,
..
} => {
let scope = namespace.as_deref().unwrap_or("all namespaces");
let rows = xray_rows.unwrap_or_default();
let title = format!(
"[XRAY] {scope} ({}) | j/k move · enter expand/collapse · esc close",
rows.len()
);
let block = Block::default().borders(Borders::ALL).title(title);
if rows.is_empty() {
frame.render_widget(
Paragraph::new("(loading… resources appear as their watches populate)")
.block(block)
.style(theme.block),
chunks[2],
);
} else {
*selected = (*selected).min(rows.len().saturating_sub(1));
let dim = Style::default().fg(Color::DarkGray);
let table_rows: Vec<Row<'_>> = rows
.iter()
.map(|r| {
let mut spans = vec![Span::styled(r.connectors.clone(), dim)];
spans.push(Span::raw(if r.has_children {
format!("{} ", r.marker)
} else {
" ".to_string()
}));
if r.kind.is_empty() {
spans.push(Span::styled(r.name.clone(), dim));
} else {
spans.push(Span::styled(format!("{}/", r.kind), dim));
spans.push(Span::raw(r.name.clone()));
}
if let Some(status) = &r.status {
spans.push(Span::raw(" "));
spans.push(Span::styled(
format!("{} {status}", severity_tag(r.severity)),
severity_style(&theme, r.severity),
));
}
Row::new(vec![Cell::from(Line::from(spans))])
})
.collect();
let table = Table::new(table_rows, [Constraint::Percentage(100)])
.block(block)
.row_highlight_style(theme.row_highlight);
let mut state =
ratatui::widgets::TableState::default().with_selected(Some(*selected));
frame.render_stateful_widget(table, chunks[2], &mut state);
}
}
Overlay::Contexts {
title,
contexts,
@@ -1132,6 +1200,14 @@ impl App {
"Esc close",
]
.join(" | "),
Overlay::Xray { .. } => [
"overlay:xray-graph",
"j/k move",
"←/→ or Enter collapse/expand",
"g/G top/bottom",
"Esc close",
]
.join(" | "),
};
}
+347
View File
@@ -0,0 +1,347 @@
use std::collections::HashSet;
use super::*;
/// Max top-level rows and children-per-node before truncating, so an xray over a large namespace
/// can't blow up the tree (and we always say what we dropped — no silent caps).
const XRAY_MAX_ROOTS: usize = 100;
const XRAY_MAX_CHILDREN: usize = 50;
/// A node in the relationship tree before flattening.
struct XrayNode {
id: String,
/// Short kind tag shown before the name (e.g. `deploy`, `rs`, `po`, `ctr`).
kind: &'static str,
name: String,
/// `None` for container leaves (no status of their own).
status: Option<String>,
severity: Severity,
children: Vec<XrayNode>,
}
/// A flattened, render-ready tree row: tree connectors + expand marker + node identity + status.
pub(super) struct XrayRow {
pub id: String,
pub connectors: String,
pub marker: char,
pub kind: &'static str,
pub name: String,
pub status: Option<String>,
pub severity: Severity,
pub has_children: bool,
}
impl App {
/// Open the live `:xray` relationship graph. `namespace` None = whole cluster.
pub(super) fn show_xray_overlay(&mut self, namespace: Option<String>) {
self.overlay = Some(Overlay::Xray {
namespace,
selected: 0,
collapsed: HashSet::new(),
});
self.status_line = "xray".to_string();
}
/// Flatten the live forest into render rows, honoring the collapsed set. Rebuilt each frame.
pub(super) fn xray_rows(
&self,
namespace: Option<&str>,
collapsed: &HashSet<String>,
) -> Vec<XrayRow> {
let roots = self.xray_tree(namespace);
let mut rows = Vec::new();
flatten(&roots, "", true, collapsed, &mut rows);
rows
}
/// Id of the expandable node under the xray cursor (None if the cursor is on a leaf).
/// Resolved in a scoped borrow so callers can mutate the overlay afterward.
fn xray_collapsible_id(&self) -> Option<String> {
let Some(Overlay::Xray {
namespace,
selected,
collapsed,
}) = &self.overlay
else {
return None;
};
let rows = self.xray_rows(namespace.as_deref(), collapsed);
rows.get(*selected)
.filter(|row| row.has_children)
.map(|row| row.id.clone())
}
/// Toggle expand/collapse of the node under the cursor (Enter).
pub(super) fn toggle_xray_collapse(&mut self) {
let Some(id) = self.xray_collapsible_id() else {
self.status_line = "Nothing to expand".to_string();
return;
};
if let Some(Overlay::Xray { collapsed, .. }) = &mut self.overlay {
if collapsed.remove(&id) {
self.status_line = "Expanded".to_string();
} else {
collapsed.insert(id);
self.status_line = "Collapsed".to_string();
}
}
}
/// Collapse (`collapse=true`, Left) or expand (`collapse=false`, Right) the node under the
/// cursor. No-op on leaves or when already in the requested state.
pub(super) fn set_xray_collapsed(&mut self, collapse: bool) {
let Some(id) = self.xray_collapsible_id() else {
return;
};
if let Some(Overlay::Xray { collapsed, .. }) = &mut self.overlay {
if collapse {
if collapsed.insert(id) {
self.status_line = "Collapsed".to_string();
}
} else if collapsed.remove(&id) {
self.status_line = "Expanded".to_string();
}
}
}
/// Namespace-rooted ownership forest: ns → controllers → pods → containers.
fn xray_tree(&self, namespace: Option<&str>) -> Vec<XrayNode> {
let context = self.current_tab().context.clone();
let namespaces: Vec<String> = match namespace {
Some(ns) => vec![ns.to_string()],
None => {
let mut all = self.store.namespaces(&context);
all.sort();
all
}
};
let total_ns = namespaces.len();
let mut roots: Vec<XrayNode> = namespaces
.into_iter()
.take(XRAY_MAX_ROOTS)
.map(|ns| {
let children = self.namespace_children(&context, &ns);
XrayNode {
id: format!("ns:{ns}"),
kind: "ns",
name: ns,
status: None,
severity: Severity::Ok,
children,
}
})
.collect();
if total_ns > roots.len() {
roots.push(more_node("namespaces", total_ns - roots.len()));
}
roots
}
/// Top-level controllers (and standalone replicasets/pods) for one namespace.
fn namespace_children(&self, context: &str, ns: &str) -> Vec<XrayNode> {
let ns_opt = Some(ns);
let mut nodes = Vec::new();
// Deployments → ReplicaSets → pods → containers.
for dep in self.store.list(context, ResourceKind::Deployments, ns_opt) {
let mut node = self.xray_node("deploy", &dep.key, Some(&dep.status));
node.children = self
.deployment_replica_set_keys(&dep.key)
.into_iter()
.map(|rs_key| {
let mut rs = self.xray_node("rs", &rs_key, Some(&self.entity_status(&rs_key)));
rs.children = self.pod_nodes(self.replica_set_pod_keys(&rs_key));
rs
})
.collect();
nodes.push(node);
}
// StatefulSets / DaemonSets → pods.
for (kind, owner) in [
(ResourceKind::StatefulSets, "StatefulSet"),
(ResourceKind::DaemonSets, "DaemonSet"),
] {
for ctrl in self.store.list(context, kind, ns_opt) {
let mut node = self.xray_node(kind.short_name(), &ctrl.key, Some(&ctrl.status));
node.children = self.pod_nodes(self.owned_pod_keys(&ctrl.key, owner));
nodes.push(node);
}
}
// CronJobs → Jobs → pods.
for cj in self.store.list(context, ResourceKind::CronJobs, ns_opt) {
let mut node = self.xray_node("cj", &cj.key, Some(&cj.status));
node.children = self
.store
.list(context, ResourceKind::Jobs, ns_opt)
.into_iter()
.filter(|job| job.extracted.owned_by("CronJob", &cj.key.name))
.map(|job| self.job_node(job))
.collect();
nodes.push(node);
}
// Jobs not owned by a CronJob.
for job in self.store.list(context, ResourceKind::Jobs, ns_opt) {
if !job.extracted.owners.iter().any(|o| o.kind == "CronJob") {
nodes.push(self.job_node(job));
}
}
// ReplicaSets not owned by a Deployment (bare RS).
for rs in self.store.list(context, ResourceKind::ReplicaSets, ns_opt) {
if !rs.extracted.owners.iter().any(|o| o.kind == "Deployment") {
let mut node = self.xray_node("rs", &rs.key, Some(&rs.status));
node.children = self.pod_nodes(self.replica_set_pod_keys(&rs.key));
nodes.push(node);
}
}
// Standalone pods (no controller).
let standalone: Vec<ResourceKey> = self
.store
.list(context, ResourceKind::Pods, ns_opt)
.into_iter()
.filter(|pod| pod.extracted.owners.is_empty())
.map(|pod| pod.key.clone())
.collect();
nodes.extend(self.pod_nodes(standalone));
nodes
}
fn job_node(&self, job: &crate::model::ResourceEntity) -> XrayNode {
let mut node = self.xray_node("job", &job.key, Some(&job.status));
node.children = self.pod_nodes(self.owned_pod_keys(&job.key, "Job"));
node
}
/// Pod nodes (capped) with their container leaves.
fn pod_nodes(&self, pod_keys: Vec<ResourceKey>) -> Vec<XrayNode> {
let total = pod_keys.len();
let mut nodes: Vec<XrayNode> = pod_keys
.into_iter()
.take(XRAY_MAX_CHILDREN)
.map(|pod_key| {
let mut node = self.xray_node("po", &pod_key, Some(&self.entity_status(&pod_key)));
node.children = self.container_nodes(&pod_key);
node
})
.collect();
if total > nodes.len() {
nodes.push(more_node("po", total - nodes.len()));
}
nodes
}
fn container_nodes(&self, pod_key: &ResourceKey) -> Vec<XrayNode> {
self.store
.get(pod_key)
.map(|entity| {
entity
.extracted
.containers
.iter()
.map(|name| XrayNode {
id: format!("ctr:{}:{name}", pod_key.name),
kind: "ctr",
name: name.clone(),
status: None,
severity: Severity::Ok,
children: Vec::new(),
})
.collect()
})
.unwrap_or_default()
}
fn xray_node(&self, kind: &'static str, key: &ResourceKey, status: Option<&str>) -> XrayNode {
let severity = status.map(classify_status_severity).unwrap_or(Severity::Ok);
XrayNode {
id: format!(
"{kind}:{}:{}",
key.namespace.as_deref().unwrap_or("-"),
key.name
),
kind,
name: key.name.clone(),
status: status.map(str::to_string),
severity,
children: Vec::new(),
}
}
fn entity_status(&self, key: &ResourceKey) -> String {
self.store
.get(key)
.map(|e| e.status.clone())
.unwrap_or_else(|| "-".to_string())
}
/// Pods directly owned by a `StatefulSet`/`DaemonSet`.
fn owned_pod_keys(&self, owner_key: &ResourceKey, owner_kind: &str) -> Vec<ResourceKey> {
let mut pods: Vec<ResourceKey> = self
.store
.list(
&owner_key.context,
ResourceKind::Pods,
owner_key.namespace.as_deref(),
)
.into_iter()
.filter(|pod| pod.extracted.owned_by(owner_kind, &owner_key.name))
.map(|pod| pod.key.clone())
.collect();
pods.sort_by(|a, b| a.name.cmp(&b.name));
pods
}
}
/// A synthetic `… N more` row (its own node so it slots into the tree like a sibling).
fn more_node(kind: &'static str, n: usize) -> XrayNode {
XrayNode {
id: format!("more:{kind}"),
kind: "",
name: format!("… {n} more {kind}"),
status: None,
severity: Severity::Ok,
children: Vec::new(),
}
}
/// Depth-first flatten with box-drawing connectors. Roots sit flush-left; descendants get
/// `├──`/`└──` branch glyphs and `│` continuation bars for ancestors that still have siblings.
fn flatten(
nodes: &[XrayNode],
prefix: &str,
is_root: bool,
collapsed: &HashSet<String>,
rows: &mut Vec<XrayRow>,
) {
let n = nodes.len();
for (i, node) in nodes.iter().enumerate() {
let is_last = i + 1 == n;
let (connectors, child_prefix) = if is_root {
(String::new(), String::new())
} else {
let glyph = if is_last { "└─ " } else { "├─ " };
let cont = if is_last { " " } else { "│ " };
(format!("{prefix}{glyph}"), format!("{prefix}{cont}"))
};
let has_children = !node.children.is_empty();
let is_collapsed = collapsed.contains(&node.id);
let marker = if has_children {
if is_collapsed { '▸' } else { '▾' }
} else {
' '
};
rows.push(XrayRow {
id: node.id.clone(),
connectors,
marker,
kind: node.kind,
name: node.name.clone(),
status: node.status.clone(),
severity: node.severity,
has_children,
});
if has_children && !is_collapsed {
flatten(&node.children, &child_prefix, false, collapsed, rows);
}
}
}