feat(ui): browse and describe any resource/CRD via commands (Phase 4.1a-2)
Wires the dynamic discovery layer into the UI (read-only): - `:api [filter]` lists the discovered API resource catalog for the context (name/kind/scope), optionally filtered. - `:<resource>` for any discovered resource/CRD not in the curated 24 lists its objects with generic columns (namespace/name/age/best-effort status). - `:<resource> <name>` describes a single dynamic object (YAML). Resolution matches plural, kind, or kind.group; the `:<unknown>` command fallback now routes to this path instead of "not implemented". Discovery is cached per context. Reuses the existing Overlay::Text (no new interactive overlay) to keep the change low-risk; a selectable dynamic-list overlay is deferred to 4.1c. Verified: unit test dynamic_browse_catalog_list_and_describe (catalog + list + describe + unknown), and --discover against the lab still resolves 68 resources incl. the sample CRD. Validation: fmt, check, test (76 passed / 4 ignored), release build all green. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
1 parent
6a97730c92
commit
eb471a957a
4 files changed
+264
-16
No files matched your search
+5
-2
@@ -151,8 +151,11 @@ Root problem: full object JSON kept for every entity.
|
||||
/`DynamicRow` types; hidden `--discover[ --discover-resource X]` headless check; `scripts/scale/crds.sh`
|
||||
adds a sample CRD. Verified against lab: 68 resources incl. CRD `widgets.demo.krust.io`, listed +
|
||||
described 3 Widgets. 75 tests pass.
|
||||
- [ ] **4.1a-2 UI** — `:api` discovery catalog overlay + interactive dynamic-browse overlay
|
||||
(generic columns) + describe-on-select, wiring the `:<unknown/CRD>` command fallback to the dynamic path.
|
||||
- [x] **4.1a-2 UI** — `:api [filter]` shows the discovery catalog; `:<resource>` lists any
|
||||
discovered resource/CRD's objects (generic columns) and `:<resource> <name>` describes one — all
|
||||
via the proven `Overlay::Text` (command-driven, no new interactive overlay). Per-context
|
||||
discovery cached. Unit test `dynamic_browse_catalog_list_and_describe`. 76 tests pass.
|
||||
(Interactive selectable dynamic-list overlay deferred to 4.1c polish.)
|
||||
- [ ] **4.1b dynamic watches + KindId/ResourceKey refactor** (fold 24 typed watches into the dynamic path).
|
||||
- [ ] **4.1c navigation/UX** (discovered kinds in kind-cycle / resource picker, short names from discovery).
|
||||
- [ ] **4.2 Metrics integration** — `metrics.k8s.io` for real pod/node CPU+mem (top-style).
|
||||
|
||||
+86
-6
@@ -61,8 +61,8 @@ use super::search::{
|
||||
|
||||
use crate::{
|
||||
cluster::{
|
||||
ActionError, ActionExecutor, PodLogEvent, PodLogRequest, PodLogStream, ResourceProvider,
|
||||
WatchTarget,
|
||||
ActionError, ActionExecutor, DiscoveredResource, PodLogEvent, PodLogRequest, PodLogStream,
|
||||
ResourceProvider, WatchTarget,
|
||||
},
|
||||
keymap::{Action, Keymap},
|
||||
model::{
|
||||
@@ -364,6 +364,8 @@ struct App {
|
||||
pending_detail_g: bool,
|
||||
needs_terminal_reset: bool,
|
||||
detail_cache: Option<DetailObject>,
|
||||
/// Per-context API discovery catalog (Phase 4.1), cached after first `:api`/dynamic browse.
|
||||
discovery_cache: HashMap<String, Vec<DiscoveredResource>>,
|
||||
}
|
||||
|
||||
/// On-demand full object for the active detail/describe/decode/edit view. Single-slot: holds the
|
||||
@@ -911,6 +913,7 @@ impl App {
|
||||
pending_detail_g: false,
|
||||
needs_terminal_reset: false,
|
||||
detail_cache: None,
|
||||
discovery_cache: HashMap::new(),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2034,6 +2037,23 @@ fn percent(numerator: u64, denominator: u64) -> String {
|
||||
format!("{pct:.0}%")
|
||||
}
|
||||
|
||||
/// Compact age (e.g. "3d", "5h", "12m") for dynamic-resource rows.
|
||||
fn short_age(when: Option<chrono::DateTime<chrono::Utc>>) -> String {
|
||||
let Some(when) = when else {
|
||||
return "-".to_string();
|
||||
};
|
||||
let delta = chrono::Utc::now().signed_duration_since(when);
|
||||
if delta.num_days() > 0 {
|
||||
format!("{}d", delta.num_days())
|
||||
} else if delta.num_hours() > 0 {
|
||||
format!("{}h", delta.num_hours())
|
||||
} else if delta.num_minutes() > 0 {
|
||||
format!("{}m", delta.num_minutes())
|
||||
} else {
|
||||
format!("{}s", delta.num_seconds().max(0))
|
||||
}
|
||||
}
|
||||
|
||||
fn log_target_name(target: &LogTarget) -> String {
|
||||
if let Some(container) = &target.container {
|
||||
format!("{}/{}/{}", target.namespace, target.pod, container)
|
||||
@@ -2258,7 +2278,16 @@ mod tests {
|
||||
&self,
|
||||
_context: &str,
|
||||
) -> anyhow::Result<Vec<crate::cluster::DiscoveredResource>> {
|
||||
Ok(Vec::new())
|
||||
let mut ar = kube::core::ApiResource::from_gvk(&kube::core::GroupVersionKind::gvk(
|
||||
"demo.krust.io",
|
||||
"v1",
|
||||
"Widget",
|
||||
));
|
||||
ar.plural = "widgets".to_string();
|
||||
Ok(vec![crate::cluster::DiscoveredResource {
|
||||
api_resource: ar,
|
||||
namespaced: true,
|
||||
}])
|
||||
}
|
||||
|
||||
async fn list_dynamic(
|
||||
@@ -2267,7 +2296,20 @@ mod tests {
|
||||
_resource: &crate::cluster::DiscoveredResource,
|
||||
_namespace: Option<&str>,
|
||||
) -> anyhow::Result<Vec<crate::cluster::DynamicRow>> {
|
||||
Ok(Vec::new())
|
||||
Ok(vec![
|
||||
crate::cluster::DynamicRow {
|
||||
namespace: Some("ns-00".to_string()),
|
||||
name: "widget-0".to_string(),
|
||||
age: None,
|
||||
status: "-".to_string(),
|
||||
},
|
||||
crate::cluster::DynamicRow {
|
||||
namespace: Some("ns-00".to_string()),
|
||||
name: "widget-1".to_string(),
|
||||
age: None,
|
||||
status: "-".to_string(),
|
||||
},
|
||||
])
|
||||
}
|
||||
|
||||
async fn get_dynamic(
|
||||
@@ -2275,9 +2317,13 @@ mod tests {
|
||||
_context: &str,
|
||||
_resource: &crate::cluster::DiscoveredResource,
|
||||
_namespace: Option<&str>,
|
||||
_name: &str,
|
||||
name: &str,
|
||||
) -> anyhow::Result<serde_json::Value> {
|
||||
Ok(serde_json::json!({}))
|
||||
Ok(serde_json::json!({
|
||||
"apiVersion": "demo.krust.io/v1",
|
||||
"kind": "Widget",
|
||||
"metadata": { "name": name, "namespace": "ns-00" }
|
||||
}))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2419,6 +2465,8 @@ mod tests {
|
||||
"resources",
|
||||
"res",
|
||||
"aliases",
|
||||
"api",
|
||||
"apis",
|
||||
"clear",
|
||||
"clear-filter",
|
||||
"c",
|
||||
@@ -2788,6 +2836,38 @@ mod tests {
|
||||
assert!(snap.contains("[XX]"));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn dynamic_browse_catalog_list_and_describe() {
|
||||
let mut app = test_app();
|
||||
|
||||
// :api catalog lists the discovered CRD.
|
||||
app.show_api_catalog(None).await;
|
||||
let catalog = app.current_view_text().expect("catalog overlay");
|
||||
assert!(
|
||||
catalog.contains("widgets.demo.krust.io"),
|
||||
"catalog: {catalog}"
|
||||
);
|
||||
|
||||
// :widgets lists objects.
|
||||
assert!(app.browse_dynamic("widgets", None).await);
|
||||
let list = app.current_view_text().expect("list overlay");
|
||||
assert!(
|
||||
list.contains("widget-0") && list.contains("widget-1"),
|
||||
"list: {list}"
|
||||
);
|
||||
|
||||
// :Widget (by kind) resolves too.
|
||||
assert!(app.browse_dynamic("Widget", None).await);
|
||||
|
||||
// :widgets widget-0 describes one object.
|
||||
assert!(app.browse_dynamic("widgets", Some("widget-0")).await);
|
||||
let described = app.current_view_text().expect("describe overlay");
|
||||
assert!(described.contains("kind: Widget"), "describe: {described}");
|
||||
|
||||
// Unknown token does not resolve.
|
||||
assert!(!app.browse_dynamic("definitely-not-a-resource", None).await);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn snapshot_describe_pane_has_viewer_state_line() {
|
||||
let mut app = test_app();
|
||||
|
||||
+171
-8
@@ -137,7 +137,7 @@ impl App {
|
||||
match cmd.as_str() {
|
||||
"q" | "quit" | "exit" => true,
|
||||
"help" | "?" => {
|
||||
self.status_line = "Commands: :ctx [name] | :ns [name|all] | :kind <kind> | :fmt [yaml|json] | :c | :sources | :pause | :resume | :edit [yaml|json] | :tail | :copy | :dump <path> | :resources | :clear | :quit | :all".to_string();
|
||||
self.status_line = "Commands: :ctx [name] | :ns [name|all] | :kind <kind> | :api [filter] | :<resource> [name] | :fmt [yaml|json] | :c | :sources | :pause | :resume | :edit [yaml|json] | :tail | :copy | :dump <path> | :resources | :clear | :quit | :all".to_string();
|
||||
false
|
||||
}
|
||||
"contexts" | "ctxs" => {
|
||||
@@ -283,6 +283,10 @@ impl App {
|
||||
self.dump_current_view(args);
|
||||
false
|
||||
}
|
||||
"api" | "apis" => {
|
||||
self.show_api_catalog(args.first().copied()).await;
|
||||
false
|
||||
}
|
||||
"pulse" | "pulses" | "pu" | "xray" | "popeye" | "pop" | "plugins" | "plugin" => {
|
||||
self.status_line =
|
||||
format!("Command ':{cmd}' is recognized but not implemented yet");
|
||||
@@ -293,19 +297,178 @@ impl App {
|
||||
self.execute_resource_command(kind, args);
|
||||
false
|
||||
}
|
||||
ResourceAlias::Unsupported(resource) => {
|
||||
self.status_line =
|
||||
format!("Resource '{resource}' is recognized but not implemented yet");
|
||||
false
|
||||
}
|
||||
ResourceAlias::Unknown => {
|
||||
self.status_line = format!("Unknown command: :{raw}");
|
||||
// Not a curated kind — try the dynamic path (any discovered resource/CRD).
|
||||
// `:<resource>` lists objects; `:<resource> <name>` describes one.
|
||||
other => {
|
||||
let name = args.first().copied();
|
||||
if self.browse_dynamic(&cmd, name).await {
|
||||
return false;
|
||||
}
|
||||
self.status_line = match other {
|
||||
ResourceAlias::Unsupported(resource) => format!(
|
||||
"'{resource}' not found on this context (try the full plural, e.g. :customresourcedefinitions)"
|
||||
),
|
||||
_ => format!("Unknown command or resource: :{raw}"),
|
||||
};
|
||||
false
|
||||
}
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
/// Discovered API resources for a context, cached after the first lookup (Phase 4.1).
|
||||
pub(super) async fn discovery_for(&mut self, context: &str) -> Vec<DiscoveredResource> {
|
||||
if let Some(cached) = self.discovery_cache.get(context) {
|
||||
return cached.clone();
|
||||
}
|
||||
let provider = self.resource_provider.clone();
|
||||
match provider.discover(context).await {
|
||||
Ok(list) => {
|
||||
self.discovery_cache
|
||||
.insert(context.to_string(), list.clone());
|
||||
list
|
||||
}
|
||||
Err(err) => {
|
||||
self.status_line = format!("API discovery failed: {err}");
|
||||
Vec::new()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// `:api [filter]` — show the discovered API resource catalog in a scrollable overlay.
|
||||
pub(super) async fn show_api_catalog(&mut self, filter: Option<&str>) {
|
||||
let context = self.current_tab().context.clone();
|
||||
let catalog = self.discovery_for(&context).await;
|
||||
if catalog.is_empty() {
|
||||
return;
|
||||
}
|
||||
let needle = filter.map(|f| f.to_ascii_lowercase());
|
||||
let mut lines = vec![
|
||||
format!("API resources on {context} ({} total)", catalog.len()),
|
||||
String::new(),
|
||||
format!("{:<46} {:<26} SCOPE", "NAME", "KIND"),
|
||||
];
|
||||
let mut shown = 0usize;
|
||||
for r in &catalog {
|
||||
if let Some(n) = &needle
|
||||
&& !r.full_name().to_ascii_lowercase().contains(n.as_str())
|
||||
&& !r.kind().to_ascii_lowercase().contains(n.as_str())
|
||||
{
|
||||
continue;
|
||||
}
|
||||
shown += 1;
|
||||
lines.push(format!(
|
||||
"{:<46} {:<26} {}",
|
||||
r.full_name(),
|
||||
r.kind(),
|
||||
if r.namespaced {
|
||||
"namespaced"
|
||||
} else {
|
||||
"cluster"
|
||||
}
|
||||
));
|
||||
}
|
||||
lines.push(String::new());
|
||||
lines.push("Browse: :<plural|kind> Describe: :<plural|kind> <name>".to_string());
|
||||
self.overlay = Some(Overlay::Text {
|
||||
title: "API Resources".to_string(),
|
||||
lines,
|
||||
scroll: 0,
|
||||
hscroll: 0,
|
||||
wrap: false,
|
||||
});
|
||||
self.status_line = format!("API resources: {shown} shown / {} total", catalog.len());
|
||||
}
|
||||
|
||||
/// Resolve `token` against discovery and either list its objects or, with `name`, describe one.
|
||||
/// Returns false if the token doesn't match any discovered resource.
|
||||
pub(super) async fn browse_dynamic(&mut self, token: &str, name: Option<&str>) -> bool {
|
||||
let context = self.current_tab().context.clone();
|
||||
let tab_namespace = self.current_tab().namespace.clone();
|
||||
let catalog = self.discovery_for(&context).await;
|
||||
let Some(resource) = catalog
|
||||
.iter()
|
||||
.find(|r| {
|
||||
r.plural().eq_ignore_ascii_case(token)
|
||||
|| r.kind().eq_ignore_ascii_case(token)
|
||||
|| r.full_name().eq_ignore_ascii_case(token)
|
||||
})
|
||||
.cloned()
|
||||
else {
|
||||
return false;
|
||||
};
|
||||
|
||||
let namespace = if resource.namespaced {
|
||||
tab_namespace
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let provider = self.resource_provider.clone();
|
||||
|
||||
if let Some(name) = name {
|
||||
match provider
|
||||
.get_dynamic(&context, &resource, namespace.as_deref(), name)
|
||||
.await
|
||||
{
|
||||
Ok(obj) => {
|
||||
let yaml = to_pretty_yaml(&obj);
|
||||
self.overlay = Some(Overlay::Text {
|
||||
title: format!("{} {}", resource.kind(), name),
|
||||
lines: yaml.lines().map(str::to_string).collect(),
|
||||
scroll: 0,
|
||||
hscroll: 0,
|
||||
wrap: false,
|
||||
});
|
||||
self.status_line = format!("Describe {} {name}", resource.kind());
|
||||
}
|
||||
Err(err) => {
|
||||
self.status_line = format!("get {} {name} failed: {err}", resource.kind())
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
match provider
|
||||
.list_dynamic(&context, &resource, namespace.as_deref())
|
||||
.await
|
||||
{
|
||||
Ok(rows) => {
|
||||
let capped = if rows.len() >= 500 { ", capped" } else { "" };
|
||||
let mut lines = vec![
|
||||
format!(
|
||||
"{} ({} shown{capped}) ns={}",
|
||||
resource.full_name(),
|
||||
rows.len(),
|
||||
namespace.as_deref().unwrap_or("all")
|
||||
),
|
||||
String::new(),
|
||||
format!("{:<24} {:<50} {:<8} STATUS", "NAMESPACE", "NAME", "AGE"),
|
||||
];
|
||||
for row in &rows {
|
||||
lines.push(format!(
|
||||
"{:<24} {:<50} {:<8} {}",
|
||||
row.namespace.as_deref().unwrap_or("-"),
|
||||
row.name,
|
||||
short_age(row.age),
|
||||
row.status
|
||||
));
|
||||
}
|
||||
lines.push(String::new());
|
||||
lines.push(format!("Describe: :{token} <name>"));
|
||||
self.overlay = Some(Overlay::Text {
|
||||
title: format!("{} objects", resource.kind()),
|
||||
lines,
|
||||
scroll: 0,
|
||||
hscroll: 0,
|
||||
wrap: false,
|
||||
});
|
||||
self.status_line = format!("{} {} object(s)", rows.len(), resource.kind());
|
||||
}
|
||||
Err(err) => self.status_line = format!("list {} failed: {err}", resource.full_name()),
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
pub(super) fn autocomplete_command_input(&mut self) {
|
||||
let Some(input) = self.command_input.as_ref() else {
|
||||
return;
|
||||
|
||||
@@ -20,6 +20,8 @@ pub(crate) fn command_names() -> &'static [&'static str] {
|
||||
"resources",
|
||||
"res",
|
||||
"aliases",
|
||||
"api",
|
||||
"apis",
|
||||
"clear",
|
||||
"clear-filter",
|
||||
"fmt",
|
||||
|
||||
Reference in new issue
Block a user