feat(cluster): dynamic resource discovery + list/describe (Phase 4.1a)

First slice of readonly parity for arbitrary resources/CRDs (ROADMAP 4.1).
Hybrid design: keep the curated 24 kinds; add a dynamic path for any discovered
GVK. This commit lands the provider layer + a headless verification mode.

- ResourceProvider::discover -> all API resources on a context via kube::discovery
- ResourceProvider::list_dynamic -> bounded one-shot list of any resource as
  generic rows (namespace/name/age/best-effort status) via Api<DynamicObject>
- ResourceProvider::get_dynamic -> full manifest for describe
- DiscoveredResource / DynamicRow types (cluster module)
- hidden `--discover [--discover-resource <plural|kind>]` mode prints the catalog
  and optionally lists+describes one resource (verifies the path end-to-end)
- scripts/scale/crds.sh installs a sample CRD (widgets.demo.krust.io) + CRs

Verified against the kwok lab: discovered 68 resources incl. the CRD and core
kinds outside the curated set (endpoints, endpointslices); listed and described
the Widgets. The interactive UI (:api catalog + dynamic browse overlay) lands
next in 4.1a-2.

Validation: fmt, check, test (75 passed / 4 ignored), release build all green.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
Erfan YousefiandClaude Opus 4.8 authored and Erfan committed 2026-06-24 14:49:43 +02:00
1 parent fc991709ab
commit e19cca315a
8 files changed
+417 -6

No files matched your search

+11 -3
View File
@@ -144,9 +144,17 @@ Root problem: full object JSON kept for every entity.
---
## Phase 4 — Readonly parity vs k9s (HARD REQUIREMENT: all readonly k9s functions)
- [ ] **4.1 Dynamic resource discovery + CRDs** — biggest functional gap. Today 24 fixed
kinds (`ResourceKind::ORDERED`, model.rs:36). Add API discovery + arbitrary GVK browse so
any resource/CRD is listable/describable (readonly).
- [~] **4.1 Dynamic resource discovery + CRDs** — biggest functional gap. Hybrid design (curated 24
+ generic dynamic), `docs/design/phase-4.1-dynamic-resources.md`. Shipped incrementally:
- [x] **4.1a-1 provider layer** — `ResourceProvider::{discover,list_dynamic,get_dynamic}` via
`kube::discovery` + `Api<DynamicObject>` (cluster/mod.rs, kube_provider.rs); `DiscoveredResource`
/`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.
- [ ] **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).
Current numbers are from spec requests/limits, not usage.
- [ ] **4.3 Resource-correlated events** — selecting a pod shows its events; today Events pane
@@ -0,0 +1,95 @@
# Design: Phase 4.1 — Dynamic resources / CRDs
Status: **proposed** (awaiting sign-off). Related: ROADMAP.md Phase 4.1.
## Problem
krust supports a fixed set of 24 built-in kinds (`ResourceKind` enum, model.rs). Operators on real
clusters need to browse **any** resource — CRDs (the M3/Infor platform alone has many), plus core
kinds we don't enumerate (endpoints, leases, storageclasses, etc.). This is the biggest readonly
parity gap vs k9s. Today `:crd`, `:sc`, etc. report "recognized but not implemented".
## Constraint that shapes the design
The watch layer is **typed-generic**: `spawn_namespaced_watch::<Pod>`, `::<Deployment>`, … — 24
hard-coded dispatches (kube_provider.rs). Arbitrary kinds cannot be typed at compile time, so they
**must** be watched via `Api<DynamicObject>` + a runtime `ApiResource`. We already use exactly this
path for `get_object` (Phase 1.1) and proved `DynamicObject` watches parse fine (1.2 micro-bench:
~7.9µs/obj vs 5µs typed — acceptable).
## Approach: hybrid (curated built-ins + generic dynamic) — like k9s
Do **not** rip out `ResourceKind`. Keep the 24 curated kinds with their tailored columns/status
extraction (pod phase, deploy ready, node capacity, …). Add a **dynamic resource layer** that can
list/watch/describe **any** discovered GVK with generic columns. Known kinds render rich; everything
else renders generic (name / namespace / age / best-effort status) — exactly k9s's model.
### New core type
A resource is identified by a `ResourceRef` (runtime), superseding the enum *as the key* while the
enum remains an optional "curated profile":
```rust
struct GvkKey { group: String, version: String, kind: String } // e.g. ("apps","v1","Deployment")
```
- `ResourceKey` changes `kind: ResourceKind` → a key that carries the GVK (plus a cheap interned id).
This is the invasive part (ResourceKey is in every delta/index/cache). Mitigation below.
- A `ResourceCatalog` (per context, from discovery) maps GVK ↔ `ApiResource` (plural, namespaced,
short names) and flags whether a curated profile exists.
### Migration that limits blast radius
`ResourceKey`/`StateStore`/projection are generic over "kind identity". To avoid editing ~290 sites
at once, introduce an interned `KindId` (u32) that both the enum and dynamic GVKs resolve to:
- `KindId` is the hash-keyed identity used in `ResourceKey`, indexes, watch keys (cheap Copy, no
String churn in the hot path — important after we just made keys lean).
- A registry resolves `KindId → ResourceDescriptor { gvk, api_resource, curated: Option<ResourceKind>, namespaced, columns }`.
- Built-in kinds register deterministic `KindId`s at startup; discovered kinds register on demand.
This keeps the store/projection/key hot paths Copy-cheap and confines GVK strings to the registry.
## Incremental sub-phases (each shippable)
- **4.1a — discovery + dynamic list/describe (read-only, command-driven).** Add `kube::discovery`
per context; a `:api`/`:<crd-plural>` command lists any discovered resource via `Api<DynamicObject>`
(one-shot list, not yet watched) with generic columns; describe already works via `get_object`.
Lowest risk, immediately closes "can I even see my CRDs". No change to the enum/key yet — dynamic
results held in a parallel path.
- **4.1b — dynamic watches.** Replace the one-shot list with a `DynamicObject` watcher reusing
`run_watch_loop` (generalized) + the relist generation logic; introduce `KindId` and fold the 24
typed watches into the dynamic path (keeping curated extraction by GVK match). This is the
ResourceKey refactor.
- **4.1c — navigation/UX.** Discovered kinds in the kind cycle / a resource picker (`:res`), short
names from discovery, namespaced/cluster scoping from discovery.
We ship 4.1a first and reassess before the deeper 4.1b key refactor.
## Touch list (4.1b, the deep one)
`model.rs` (KindId, ResourceKey), `cluster/kube_provider.rs` (discovery, dynamic watch, drop 24
typed dispatches), `cluster/extract.rs` (extract by curated GVK match), `state/store.rs` (KindId
indexes), `view/projector.rs`, `ui/*` (kind nav, commands, columns). Curated column/status code
keyed by GVK instead of enum variant.
## Risks
1. **ResourceKey churn** — it's in every delta/index. Mitigated by interned Copy `KindId` (no perf
regression vs today's enum, which is also Copy).
2. **Discovery cost/RBAC** — discovery is one call per context, cached; handle 403 gracefully
(show only what's discoverable).
3. **Watch load** — arbitrary kinds still go through `replace_watch_plan` (lazy, scoped) — no change
to the activation model; a CRD is only watched when viewed.
4. **Generic columns** — best-effort status for unknown kinds; acceptable and matches k9s.
5. **CRD scale** — clusters with hundreds of CRDs: discovery list is fine; we only watch what's open.
## Validation
- 4.1a: against the lab, `:` a core kind not in the 24 (e.g. endpoints) and a CRD → lists + describes.
- 4.1b: bench shows no regression on the 24 built-ins (KindId Copy vs enum Copy); relist still works.
- Tests: discovery parsing, KindId registry, generic column projection, curated-vs-generic dispatch.
## Open questions for sign-off
1. OK with the **hybrid** model (keep curated 24 + generic for the rest), not a full dynamic rewrite?
2. OK to **ship 4.1a first** (discovery + dynamic list/describe, command-driven) and reassess before
the deeper `KindId`/ResourceKey refactor in 4.1b?
3. `KindId` interning approach for the key (vs carrying GVK strings in ResourceKey) — agree it's worth
it to protect the hot path?
+52
View File
@@ -0,0 +1,52 @@
#!/usr/bin/env bash
# Install a sample CRD + a few custom resources on the kwok cluster, so the dynamic
# resource discovery path (Phase 4.1) has a real CRD to find and browse.
source "$(dirname "${BASH_SOURCE[0]}")/lib.sh"
require kubectl
kc apply -f - <<'EOF'
apiVersion: apiextensions.k8s.io/v1
kind: CustomResourceDefinition
metadata:
name: widgets.demo.krust.io
spec:
group: demo.krust.io
scope: Namespaced
names:
plural: widgets
singular: widget
kind: Widget
shortNames: [wdg]
versions:
- name: v1
served: true
storage: true
schema:
openAPIV3Schema:
type: object
properties:
spec:
type: object
properties:
size: { type: string }
status:
type: object
properties:
phase: { type: string }
EOF
echo "waiting for CRD to register ..."
kc wait --for=condition=Established crd/widgets.demo.krust.io --timeout=30s || true
for i in 0 1 2; do
kc apply -f - <<EOF
apiVersion: demo.krust.io/v1
kind: Widget
metadata: { name: widget-${i}, namespace: ns-00 }
spec: { size: "large" }
EOF
done
echo "created CRD widgets.demo.krust.io + 3 Widgets in ns-00"
echo "verify: krust --kubeconfig $KRUST_SCALE_KUBECONFIG --discover --discover-resource widgets"
+8
View File
@@ -40,4 +40,12 @@ pub struct Cli {
/// Bench: seconds to let watchers settle / initial-sync before measuring.
#[arg(long, hide = true, default_value_t = 20)]
pub bench_settle_secs: u64,
/// Print the discovered API resources for the initial context, then exit (Phase 4.1 check).
#[arg(long, hide = true, default_value_t = false)]
pub discover: bool,
/// With --discover: also list (and describe the first object of) this resource (plural or kind).
#[arg(long, hide = true)]
pub discover_resource: Option<String>,
}
+84 -3
View File
@@ -26,9 +26,10 @@ use k8s_openapi::{
};
use kube::{
Api, Client, Config, Resource, ResourceExt,
api::{DeleteParams, LogParams, PostParams},
api::{DeleteParams, ListParams, LogParams, PostParams},
config::{KubeConfigOptions, Kubeconfig},
core::{ApiResource, DynamicObject, GroupVersionKind},
discovery::{Discovery, Scope},
};
use kube_runtime::watcher::{self, Event};
use serde::Serialize;
@@ -38,10 +39,13 @@ use tracing::{error, warn};
use crate::model::{ResourceEntity, ResourceKey, ResourceKind, StateDelta};
use super::{
ActionError, ActionExecutor, ActionResult, PodLogEvent, PodLogRequest, PodLogStream,
ResourceProvider, WatchTarget, extract::extracted_for,
ActionError, ActionExecutor, ActionResult, DiscoveredResource, DynamicRow, PodLogEvent,
PodLogRequest, PodLogStream, ResourceProvider, WatchTarget, extract::extracted_for,
};
/// Bounded one-shot dynamic list size (Phase 4.1 read-only browse).
const DYNAMIC_LIST_LIMIT: u32 = 500;
#[derive(Debug, Clone)]
pub struct KubeProviderOptions {
pub kubeconfig: Option<PathBuf>,
@@ -336,6 +340,83 @@ impl ResourceProvider for KubeResourceProvider {
Ok(serde_json::to_value(obj)?)
}
async fn discover(&self, context: &str) -> anyhow::Result<Vec<DiscoveredResource>> {
let client = self.client_for_context(context).await?;
let discovery = Discovery::new(client).run().await?;
let mut out = Vec::new();
for group in discovery.groups() {
for (api_resource, caps) in group.recommended_resources() {
out.push(DiscoveredResource {
api_resource,
namespaced: matches!(caps.scope, Scope::Namespaced),
});
}
}
out.sort_by(|a, b| a.full_name().cmp(&b.full_name()));
out.dedup_by(|a, b| a.full_name() == b.full_name());
Ok(out)
}
async fn list_dynamic(
&self,
context: &str,
resource: &DiscoveredResource,
namespace: Option<&str>,
) -> anyhow::Result<Vec<DynamicRow>> {
let client = self.client_for_context(context).await?;
let ar = &resource.api_resource;
let api: Api<DynamicObject> = match (resource.namespaced, namespace) {
(true, Some(ns)) => Api::namespaced_with(client, ns, ar),
_ => Api::all_with(client, ar),
};
let list = api
.list(&ListParams::default().limit(DYNAMIC_LIST_LIMIT))
.await?;
let rows = list
.into_iter()
.map(|obj| DynamicRow {
namespace: obj.namespace(),
age: obj
.creation_timestamp()
.map(|ts| DateTime::<Utc>::from(std::time::SystemTime::from(ts.0))),
status: dynamic_status(&obj),
name: obj.name_any(),
})
.collect();
Ok(rows)
}
async fn get_dynamic(
&self,
context: &str,
resource: &DiscoveredResource,
namespace: Option<&str>,
name: &str,
) -> anyhow::Result<serde_json::Value> {
let client = self.client_for_context(context).await?;
let ar = &resource.api_resource;
let api: Api<DynamicObject> = match (resource.namespaced, namespace) {
(true, Some(ns)) => Api::namespaced_with(client, ns, ar),
(true, None) => Api::namespaced_with(client, "default", ar),
(false, _) => Api::all_with(client, ar),
};
Ok(serde_json::to_value(api.get(name).await?)?)
}
}
/// Best-effort status string for a dynamic object (no curated extractor for unknown kinds).
fn dynamic_status(obj: &DynamicObject) -> String {
obj.data
.pointer("/status/phase")
.and_then(serde_json::Value::as_str)
.or_else(|| {
obj.data
.pointer("/status/conditions/0/type")
.and_then(serde_json::Value::as_str)
})
.unwrap_or("-")
.to_string()
}
fn select_warm_contexts(
+63
View File
@@ -2,12 +2,54 @@ mod extract;
mod kube_provider;
use async_trait::async_trait;
use chrono::{DateTime, Utc};
use kube::core::ApiResource;
use tokio::{sync::mpsc, task::JoinHandle};
use crate::model::{ResourceKey, ResourceKind};
pub use kube_provider::{KubeProviderOptions, KubeResourceProvider};
/// An API resource discovered on a cluster (built-in or CRD), beyond krust's curated kinds.
/// Phase 4.1: enables read-only browse/describe of arbitrary GVKs via the dynamic path.
#[derive(Debug, Clone)]
pub struct DiscoveredResource {
pub api_resource: ApiResource,
pub namespaced: bool,
}
impl DiscoveredResource {
pub fn group(&self) -> &str {
&self.api_resource.group
}
pub fn version(&self) -> &str {
&self.api_resource.version
}
pub fn kind(&self) -> &str {
&self.api_resource.kind
}
pub fn plural(&self) -> &str {
&self.api_resource.plural
}
/// `kind.group` (or just `kind` for core), lowercased — a stable display/match handle.
pub fn full_name(&self) -> String {
if self.api_resource.group.is_empty() {
self.api_resource.plural.clone()
} else {
format!("{}.{}", self.api_resource.plural, self.api_resource.group)
}
}
}
/// A generic row from a one-shot dynamic list (no curated columns).
#[derive(Debug, Clone)]
pub struct DynamicRow {
pub namespace: Option<String>,
pub name: String,
pub age: Option<DateTime<Utc>>,
pub status: String,
}
#[derive(Debug, Clone)]
pub struct ActionResult {
pub message: String,
@@ -74,6 +116,27 @@ pub trait ResourceProvider: Send + Sync {
/// Fetch the full object for a single resource on demand (for detail/describe/decode/edit).
/// Not retained per row — see the lean entity model (docs/design/phase-1.1-lean-entity-model.md).
async fn get_object(&self, key: &ResourceKey) -> anyhow::Result<serde_json::Value>;
/// Discover all API resources available on a context (built-ins + CRDs). One cached call per
/// context. Phase 4.1 (dynamic resources).
async fn discover(&self, context: &str) -> anyhow::Result<Vec<DiscoveredResource>>;
/// One-shot list of a discovered resource's objects (bounded), with generic columns.
async fn list_dynamic(
&self,
context: &str,
resource: &DiscoveredResource,
namespace: Option<&str>,
) -> anyhow::Result<Vec<DynamicRow>>;
/// Fetch a single dynamic object's full manifest for describe.
async fn get_dynamic(
&self,
context: &str,
resource: &DiscoveredResource,
namespace: Option<&str>,
name: &str,
) -> anyhow::Result<serde_json::Value>;
}
#[async_trait]
+78
View File
@@ -65,6 +65,16 @@ pub async fn run() -> anyhow::Result<()> {
let action_executor: Arc<dyn ActionExecutor> = provider.clone();
let resource_provider: Arc<dyn ResourceProvider> = provider;
if cli.discover {
return run_discover(
resource_provider.as_ref(),
&initial_context,
cli.discover_resource.as_deref(),
initial_namespace.as_deref(),
)
.await;
}
if cli.bench {
return ui::run_bench(
contexts,
@@ -97,6 +107,74 @@ pub async fn run() -> anyhow::Result<()> {
.await
}
/// Headless Phase 4.1 check: print discovered API resources for a context, and optionally list +
/// describe one resource. Verifies the dynamic discovery/list/get path against a real cluster.
async fn run_discover(
provider: &dyn ResourceProvider,
context: &str,
resource: Option<&str>,
namespace: Option<&str>,
) -> anyhow::Result<()> {
let catalog = provider.discover(context).await?;
println!(
"Discovered {} API resources on context '{context}':",
catalog.len()
);
for r in &catalog {
println!(
" {:<44} {:<22} {}",
r.full_name(),
r.kind(),
if r.namespaced {
"namespaced"
} else {
"cluster"
}
);
}
if let Some(token) = resource {
let Some(res) = 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)
}) else {
println!("\nresource '{token}' not found in discovery");
return Ok(());
};
println!(
"\nListing {} (namespace={namespace:?}) ...",
res.full_name()
);
let rows = provider.list_dynamic(context, res, namespace).await?;
println!(" {} object(s) returned (bounded):", rows.len());
for row in rows.iter().take(20) {
println!(
" {}/{} status={}",
row.namespace.as_deref().unwrap_or("-"),
row.name,
row.status
);
}
if let Some(first) = rows.first() {
let obj = provider
.get_dynamic(context, res, first.namespace.as_deref(), &first.name)
.await?;
let yaml = serde_yaml::to_string(&obj).unwrap_or_default();
let preview: Vec<&str> = yaml.lines().take(15).collect();
println!(
"\ndescribe {} (first 15 lines):\n{}",
first.name,
preview.join("\n")
);
}
}
Ok(())
}
fn init_tracing() {
if std::env::var_os("RUST_LOG").is_none() {
return;
+26
View File
@@ -2253,6 +2253,32 @@ mod tests {
async fn get_object(&self, _key: &ResourceKey) -> anyhow::Result<serde_json::Value> {
Ok(serde_json::json!({}))
}
async fn discover(
&self,
_context: &str,
) -> anyhow::Result<Vec<crate::cluster::DiscoveredResource>> {
Ok(Vec::new())
}
async fn list_dynamic(
&self,
_context: &str,
_resource: &crate::cluster::DiscoveredResource,
_namespace: Option<&str>,
) -> anyhow::Result<Vec<crate::cluster::DynamicRow>> {
Ok(Vec::new())
}
async fn get_dynamic(
&self,
_context: &str,
_resource: &crate::cluster::DiscoveredResource,
_namespace: Option<&str>,
_name: &str,
) -> anyhow::Result<serde_json::Value> {
Ok(serde_json::json!({}))
}
}
struct NoopExecutor;