From 4a63e81169c6616566ba63b82cd2a0055a223544 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Natalie=20Klestrup=20R=C3=B6ijezon?= Date: Fri, 25 Oct 2024 11:20:51 +0200 Subject: [PATCH] Change event watcher example to retry the connection (#1616) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * Change event watcher example to retry the connection Fixes #1615 Signed-off-by: Natalie Klestrup Röijezon * Factor out printing to ensure consistency Signed-off-by: Natalie Klestrup Röijezon * Report an error if an invalid --for= argument is supplied, instead of ignoring it Signed-off-by: Natalie Klestrup Röijezon --------- Signed-off-by: Natalie Klestrup Röijezon --- examples/event_watcher.rs | 27 +++++++++++++++++---------- 1 file changed, 17 insertions(+), 10 deletions(-) diff --git a/examples/event_watcher.rs b/examples/event_watcher.rs index e6df87c2e..dd33229f0 100644 --- a/examples/event_watcher.rs +++ b/examples/event_watcher.rs @@ -1,6 +1,6 @@ use std::pin::pin; -use futures::TryStreamExt; +use futures::StreamExt; use k8s_openapi::{ api::{core::v1::ObjectReference, events::v1::Event}, apimachinery::pkg::apis::meta::v1::Time, @@ -36,21 +36,28 @@ async fn main() -> anyhow::Result<()> { if let Some(forval) = app.r#for { if let Some((kind, name)) = forval.split_once('/') { conf = conf.fields(&format!("regarding.kind={kind},regarding.name={name}")); + } else { + return Err(anyhow::Error::msg("Usage: --for=/")); } } let event_stream = watcher(events, conf).default_backoff().applied_objects(); let mut event_stream = pin!(event_stream); - #[allow(clippy::print_literal)] // for consistency - { - println!("{0:<6} {1:<15} {2:<55} {3}", "AGE", "REASON", "OBJECT", "MESSAGE"); + fn print_event(age: &str, reason: &str, obj: &str, note: &str) { + println!("{age:<6} {reason:<15} {obj:<55} {note}"); } - while let Some(ev) = event_stream.try_next().await? { - let age = ev.creation_timestamp().map(format_creation).unwrap_or_default(); - let reason = ev.reason.unwrap_or_default(); - let obj = ev.regarding.and_then(format_objref).unwrap_or_default(); - let note = ev.note.unwrap_or_default(); - println!("{0:<6} {1:<15} {2:<55} {3}", age, reason, obj, note); + print_event("AGE", "REASON", "OBJECT", "MESSAGE"); + while let Some(ev) = event_stream.next().await { + match ev { + Ok(ev) => { + let age = ev.creation_timestamp().map(format_creation).unwrap_or_default(); + let reason = ev.reason.unwrap_or_default(); + let obj = ev.regarding.and_then(format_objref).unwrap_or_default(); + let note = ev.note.unwrap_or_default(); + print_event(&age, &reason, &obj, ¬e); + } + Err(err) => eprintln!("{:?}", anyhow::Error::new(err)), + } } Ok(()) }