feat: 5s configurable metrics refresh + per-context auth resilience (#27)

Two robustness fixes from real-cluster use.

Metrics refresh: was hardcoded to 15s. Now `runtime.metrics_interval_secs`
(default 5s — k9s polls every 2s; ours is bounded by metrics-server's ~15s
sample resolution, so 5s is live without hammering the API on large fleets).
Threaded through run()/App::new.

Per-context auth resilience: a context that can't authenticate (expired SSO /
exec-auth failure) no longer aborts the whole app at startup. Provider client
warmup is best-effort (logs a warning, doesn't propagate), and replace_watch_plan
records a per-context StateDelta::Error — surfaced as [XX] with the auth
message — instead of failing the call. Other clusters stay fully usable, and the
broken context recovers on a later watch tick once credentials refresh.

Tests: bad-context watch plan records an error delta and returns Ok.

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-26 02:24:09 +02:00
1 parent 21d7a87332
commit 6e108c8cd6
6 files changed
+88 -11

No files matched your search

+8
View File
@@ -225,6 +225,14 @@ Root problem: full object JSON kept for every entity.
- [~] **5.2 Reconnect-storm & mixed-RBAC soak** — partial: the 5.1 soak exercised periodic watcher
relists (every ~20s) under load with flat fds + RSS (no reconnect/fd leak). Still TODO: explicit
forced-reconnect storm and a mixed-RBAC (some 403) context.
**Per-context auth resilience** (DONE): a context that can't authenticate (expired SSO / exec-auth
failure) no longer aborts startup — provider client warmup is best-effort, and `replace_watch_plan`
records a per-context `StateDelta::Error` (shown as `[XX]` with the message) instead of failing the
call. Other contexts stay usable; the broken one recovers on a later watch tick once creds refresh.
Test: bad-context watch plan records an error delta and returns Ok.
- [x] **5.8 Configurable metrics refresh interval** — `runtime.metrics_interval_secs` (default **5s**,
down from a hardcoded 15s; k9s polls every 2s). Lower = more live, bounded by metrics-server's
~15s sample resolution; raise on large fleets to cut API load.
- [~] **5.0 UX consistency (labels/keybindings/help)** — ongoing pass to keep each view's help,
labels, and key hints accurate. Done so far: per-pane help corrected (table no longer claims
detail-only `ctrl+d/u` paging or `gg`; added namespace/sort/reverse/events/help/close hints);
+9
View File
@@ -250,6 +250,9 @@ fps_limit = 60
delta_channel_capacity = 2048
warm_contexts = 1
warm_context_ttl_secs = 20
# How often to re-fetch live metrics. metrics-server usually produces a new sample only every
# ~15s, so values much below that mostly re-fetch identical numbers; raise on large fleets.
metrics_interval_secs = 5
[ui]
theme = "default"
@@ -281,6 +284,12 @@ Auth mismatch vs shell:
- run from shell session where `kubectl` is already working
- ensure exec auth dependencies are available in PATH
One context failing auth (e.g. expired SSO token):
- does **not** abort startup or other contexts — krust starts with the working clusters
- the failed context shows a watch error (`[XX]`) with the auth message; switch tabs to a healthy one
- it recovers on its own once credentials refresh (krust retries the client on the next watch tick),
or refresh manually in your shell (e.g. `aws sso login`)
## Related Docs
- [Architecture](architecture.md)
+52 -7
View File
@@ -135,14 +135,20 @@ impl KubeResourceProvider {
delta_tx: std::sync::Arc::new(tokio::sync::Mutex::new(None)),
};
// Optional eager auth/client warmup.
// Optional eager auth/client warmup. Best-effort: a context that fails to authenticate
// (e.g. an expired SSO token) must not abort startup — the other clusters stay usable and
// the broken one surfaces its error when its watches run. Warmup just primes the cache.
if options.all_contexts {
let contexts = provider.contexts.clone();
for context in contexts {
provider.client_for_context(&context).await?;
if let Err(err) = provider.client_for_context(&context).await {
warn!(context = %context, error = %err, "context auth/client warmup failed");
}
}
} else if let Some(context) = provider.default_context.clone() {
provider.client_for_context(&context).await?;
} else if let Some(context) = provider.default_context.clone()
&& let Err(err) = provider.client_for_context(&context).await
{
warn!(context = %context, error = %err, "default context auth/client warmup failed");
}
Ok(provider)
@@ -219,7 +225,21 @@ impl ResourceProvider for KubeResourceProvider {
.as_ref()
.cloned()
.context("resource provider is not started")?;
let client = self.client_for_context(context).await?;
// A context whose client can't be built (e.g. expired SSO / exec-auth failure) records a
// per-context error for the UI instead of failing the call — other contexts keep working,
// and a later retry recovers once credentials are refreshed.
let client = match self.client_for_context(context).await {
Ok(client) => client,
Err(err) => {
let _ = tx
.send(StateDelta::Error {
context: context.to_string(),
message: format!("auth/connect failed: {err}"),
})
.await;
return Ok(());
}
};
let now = Instant::now();
let warm_contexts = {
@@ -1510,8 +1530,8 @@ mod tests {
extract_status, is_forbidden_watcher_error, next_watch_backoff, select_warm_contexts,
};
use crate::{
cluster::ActionExecutor,
model::{ResourceKey, ResourceKind},
cluster::{ActionExecutor, ResourceProvider, WatchTarget},
model::{ResourceKey, ResourceKind, StateDelta},
};
use kube::config::Kubeconfig;
use std::{
@@ -1519,6 +1539,7 @@ mod tests {
time::{Duration, Instant},
};
use tokio::sync::Mutex;
use tokio::sync::mpsc;
// Representative non-trivial pod (labels, annotations, 2 containers w/ env+resources, status).
fn representative_pod_json() -> serde_json::Value {
@@ -1894,6 +1915,30 @@ mod tests {
}
}
#[tokio::test]
async fn watch_plan_records_error_for_unauthorized_context_without_failing() {
// The readonly provider's "ctx" has no entry in its (empty) kubeconfig, so building a
// client fails — standing in for an expired-auth/unreachable context.
let provider = readonly_provider();
let (tx, mut rx) = mpsc::channel(8);
provider.start(tx).await.expect("start");
let targets = [WatchTarget {
kind: ResourceKind::Pods,
namespace: None,
}];
let result = provider.replace_watch_plan("ctx", &targets).await;
assert!(result.is_ok(), "a bad context must not fail the call");
match rx.try_recv() {
Ok(StateDelta::Error { context, message }) => {
assert_eq!(context, "ctx");
assert!(message.contains("auth/connect failed"), "{message}");
}
other => panic!("expected a per-context Error delta, got {other:?}"),
}
}
#[tokio::test]
async fn delete_resource_is_blocked_in_readonly_mode() {
let provider = readonly_provider();
+5
View File
@@ -32,6 +32,10 @@ pub struct RuntimeConfig {
pub delta_channel_capacity: usize,
pub warm_contexts: usize,
pub warm_context_ttl_secs: u64,
/// How often to re-fetch live metrics (metrics.k8s.io). metrics-server typically only produces
/// a new sample every ~15s, so polling much faster mostly re-fetches identical numbers; lower
/// for a more live feel at the cost of API load on large fleets.
pub metrics_interval_secs: u64,
}
impl Default for RuntimeConfig {
@@ -41,6 +45,7 @@ impl Default for RuntimeConfig {
delta_channel_capacity: 2048,
warm_contexts: 1,
warm_context_ttl_secs: 20,
metrics_interval_secs: 5,
}
}
}
+1
View File
@@ -114,6 +114,7 @@ pub async fn run() -> anyhow::Result<()> {
cli.readonly,
app_config.runtime.fps_limit,
app_config.ui.show_help,
app_config.runtime.metrics_interval_secs,
)
.await
}
+13 -4
View File
@@ -228,6 +228,7 @@ pub async fn run(
readonly: bool,
fps_limit: u16,
show_help: bool,
metrics_interval_secs: u64,
) -> anyhow::Result<()> {
enable_raw_mode().context("failed to enable raw mode")?;
let mut stdout = io::stdout();
@@ -249,6 +250,7 @@ pub async fn run(
keymap,
readonly,
show_help,
metrics_interval_secs,
);
app.ensure_active_watch().await;
@@ -354,6 +356,7 @@ pub async fn run_bench(
keymap,
readonly,
false,
5,
);
app.run_bench(
delta_rx,
@@ -414,6 +417,8 @@ struct App {
metrics_fetched: Option<(String, Option<String>, Instant)>,
/// Bumped whenever `pod_metrics` is replaced, so metric-sorted views recompute on refresh.
metrics_gen: u64,
/// How often live metrics are re-fetched (config `runtime.metrics_interval_secs`).
metrics_interval: Duration,
}
/// Cluster-wide actual usage summed from node metrics (Phase 4.2).
@@ -965,6 +970,7 @@ impl App {
keymap: Keymap,
readonly: bool,
show_help: bool,
metrics_interval_secs: u64,
) -> Self {
let tabs: Vec<ContextTabState> = contexts
.iter()
@@ -1040,6 +1046,7 @@ impl App {
metrics: None,
pod_metrics: HashMap::new(),
metrics_gen: 0,
metrics_interval: Duration::from_secs(metrics_interval_secs.max(1)),
metrics_fetched: None,
}
}
@@ -2003,15 +2010,16 @@ impl App {
out.join("\n")
}
/// Refresh live usage (metrics.k8s.io) for the active context+namespace, at most every 15s:
/// cluster totals (node metrics) for the pulse and per-pod usage for the table columns. On any
/// error/absence (no metrics-server) the caches clear and the UI degrades — never blocks.
/// Refresh live usage (metrics.k8s.io) for the active context+namespace, at most once per
/// `metrics_interval` (config `runtime.metrics_interval_secs`, default 5s): cluster totals (node
/// metrics) for the pulse and per-pod usage for the table columns. On any error/absence (no
/// metrics-server) the caches clear and the UI degrades — never blocks.
async fn maybe_refresh_metrics(&mut self) {
let context = self.current_tab().context.clone();
let namespace = self.current_tab().namespace.clone();
let stale = match &self.metrics_fetched {
Some((ctx, ns, at)) => {
ctx != &context || ns != &namespace || at.elapsed() > Duration::from_secs(15)
ctx != &context || ns != &namespace || at.elapsed() > self.metrics_interval
}
None => true,
};
@@ -2894,6 +2902,7 @@ mod tests {
Keymap::default(),
false,
true,
5,
)
}