use crate::utils::{Backoff, ResetTimerBackoff};
use backon::BackoffBuilder;
use educe::Educe;
use futures::{Stream, StreamExt, stream::BoxStream};
use kube_client::{
Api, Error as ClientErr,
api::{ListParams, Resource, ResourceExt, VersionMatch, WatchEvent, WatchParams},
core::{ObjectList, Selector, metadata::PartialObjectMeta},
error::Status,
};
use serde::de::DeserializeOwned;
#[cfg(test)]
#[path = "stub_watcher.rs"]
mod stub_watcher;
use std::{
clone::Clone,
collections::VecDeque,
fmt::{Debug, Display},
future::{self, Future},
time::Duration,
};
use thiserror::Error;
use tracing::{debug, error, warn};
#[derive(Debug, Error)]
pub enum Error {
#[error("failed to perform initial object list: {0}")]
InitialListFailed(#[source] kube_client::Error),
#[error("failed to start watching object: {0}")]
WatchStartFailed(#[source] kube_client::Error),
#[error("error returned by apiserver during watch: {0}")]
WatchError(#[source] Box<Status>),
#[error("watch stream failed: {0}")]
WatchFailed(#[source] kube_client::Error),
#[error("no metadata.resourceVersion in watch result (does resource support watch?)")]
NoResourceVersion,
}
pub type Result<T, E = Error> = std::result::Result<T, E>;
#[derive(Debug, Clone)]
pub enum Event<K> {
Apply(K),
Delete(K),
Init,
InitApply(K),
InitDone,
}
impl<K> Display for Event<K>
where
K: ResourceExt,
{
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let desc = match self {
Event::Init => "Init".into(),
Event::InitApply(obj) => format!("InitApply({})", obj.name_any()),
Event::InitDone => "InitDone".into(),
Event::Apply(obj) => format!("Apply({})", obj.name_any()),
Event::Delete(obj) => format!("Delete({})", obj.name_any()),
};
write!(f, "{desc}")
}
}
impl<K> Event<K> {
#[must_use]
pub fn modify(mut self, mut f: impl FnMut(&mut K)) -> Self {
match &mut self {
Self::Apply(obj) | Self::Delete(obj) | Self::InitApply(obj) => (f)(obj),
Self::Init | Self::InitDone => {} }
self
}
}
#[derive(Educe, Default)]
#[educe(Debug)]
enum State<K> {
#[default]
Empty,
InitPage {
continue_token: Option<String>,
objects: VecDeque<K>,
last_bookmark: Option<String>,
},
InitialWatch {
#[educe(Debug(ignore))]
stream: BoxStream<'static, kube_client::Result<WatchEvent<K>>>,
},
InitListed { resource_version: String },
Watching {
resource_version: String,
#[educe(Debug(ignore))]
stream: BoxStream<'static, kube_client::Result<WatchEvent<K>>>,
},
}
trait ApiMode: Send + Sync {
type Value: Clone + Send + 'static;
fn list(
&self,
lp: &ListParams,
) -> impl Future<Output = kube_client::Result<ObjectList<Self::Value>>> + Send;
fn watch(
&self,
wp: &WatchParams,
version: &str,
) -> impl Future<
Output = kube_client::Result<BoxStream<'static, kube_client::Result<WatchEvent<Self::Value>>>>,
> + Send;
}
struct FullObject<K> {
api: Api<K>,
}
#[derive(Clone, Default, Debug, PartialEq)]
pub enum ListSemantic {
#[default]
MostRecent,
Any,
}
#[derive(Clone, Default, Debug, PartialEq)]
pub enum InitialListStrategy {
#[default]
ListWatch,
StreamingList,
}
#[derive(Clone, Debug, PartialEq)]
pub struct Config {
pub label_selector: Option<String>,
pub field_selector: Option<String>,
pub timeout: Option<u32>,
pub list_semantic: ListSemantic,
pub initial_list_strategy: InitialListStrategy,
pub page_size: Option<u32>,
pub bookmarks: bool,
}
impl Default for Config {
fn default() -> Self {
Self {
bookmarks: true,
label_selector: None,
field_selector: None,
timeout: None,
list_semantic: ListSemantic::default(),
page_size: Some(500),
initial_list_strategy: InitialListStrategy::ListWatch,
}
}
}
impl Config {
#[must_use]
pub fn timeout(mut self, timeout_secs: u32) -> Self {
self.timeout = Some(timeout_secs);
self
}
#[must_use]
pub fn fields(mut self, field_selector: &str) -> Self {
self.field_selector = Some(field_selector.to_string());
self
}
#[must_use]
pub fn labels(mut self, label_selector: &str) -> Self {
self.label_selector = Some(label_selector.to_string());
self
}
#[must_use]
pub fn labels_from(mut self, selector: &Selector) -> Self {
self.label_selector = Some(selector.to_string());
self
}
#[must_use]
pub fn list_semantic(mut self, semantic: ListSemantic) -> Self {
self.list_semantic = semantic;
self
}
#[must_use]
pub fn any_semantic(self) -> Self {
self.list_semantic(ListSemantic::Any)
}
#[must_use]
pub fn disable_bookmarks(mut self) -> Self {
self.bookmarks = false;
self
}
#[must_use]
pub fn page_size(mut self, page_size: u32) -> Self {
self.page_size = Some(page_size);
self
}
#[must_use]
pub fn streaming_lists(mut self) -> Self {
self.initial_list_strategy = InitialListStrategy::StreamingList;
self
}
fn to_list_params(&self) -> ListParams {
let (resource_version, version_match) = match self.list_semantic {
ListSemantic::Any => (Some("0".into()), Some(VersionMatch::NotOlderThan)),
ListSemantic::MostRecent => (None, None),
};
ListParams {
label_selector: self.label_selector.clone(),
field_selector: self.field_selector.clone(),
version_match,
resource_version,
limit: self.page_size,
continue_token: None,
..Default::default()
}
}
fn to_watch_params(&self, phase: WatchPhase) -> WatchParams {
WatchParams {
label_selector: self.label_selector.clone(),
field_selector: self.field_selector.clone(),
timeout: self.timeout,
bookmarks: self.bookmarks,
send_initial_events: phase == WatchPhase::Initial
&& self.initial_list_strategy == InitialListStrategy::StreamingList,
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum WatchPhase {
Initial,
Resumed,
}
impl<K> ApiMode for FullObject<K>
where
K: Clone + Debug + DeserializeOwned + Send + 'static,
{
type Value = K;
async fn list(&self, lp: &ListParams) -> kube_client::Result<ObjectList<Self::Value>> {
self.api.list(lp).await
}
async fn watch(
&self,
wp: &WatchParams,
version: &str,
) -> kube_client::Result<BoxStream<'static, kube_client::Result<WatchEvent<Self::Value>>>> {
self.api.watch(wp, version).await.map(StreamExt::boxed)
}
}
struct MetaOnly<K> {
api: Api<K>,
}
impl<K> ApiMode for MetaOnly<K>
where
K: Clone + Debug + DeserializeOwned + Send + 'static,
{
type Value = PartialObjectMeta<K>;
async fn list(&self, lp: &ListParams) -> kube_client::Result<ObjectList<Self::Value>> {
self.api.list_metadata(lp).await
}
async fn watch(
&self,
wp: &WatchParams,
version: &str,
) -> kube_client::Result<BoxStream<'static, kube_client::Result<WatchEvent<Self::Value>>>> {
self.api.watch_metadata(wp, version).await.map(StreamExt::boxed)
}
}
const WATCH_IDLE_TIMEOUT_MARGIN: Duration = Duration::from_secs(5);
async fn next_with_idle_timeout<S, T>(stream: &mut S, timeout: Option<u32>) -> Option<T>
where
S: Stream<Item = T> + Unpin,
{
if timeout == Some(0) {
return stream.next().await;
}
let idle_timeout = Duration::from_secs(u64::from(timeout.unwrap_or(290))) + WATCH_IDLE_TIMEOUT_MARGIN;
match tokio::time::timeout(idle_timeout, stream.next()).await {
Ok(item) => item,
Err(_elapsed) => {
debug!(
timeout_secs = idle_timeout.as_secs(),
"watch stream idle timeout, reconnecting"
);
None
}
}
}
#[allow(clippy::too_many_lines)] async fn step_trampolined<A>(
api: &A,
wc: &Config,
state: State<A::Value>,
) -> (Option<Result<Event<A::Value>>>, State<A::Value>)
where
A: ApiMode,
A::Value: Resource + 'static,
{
match state {
State::Empty => match wc.initial_list_strategy {
InitialListStrategy::ListWatch => (Some(Ok(Event::Init)), State::InitPage {
continue_token: None,
objects: VecDeque::default(),
last_bookmark: None,
}),
InitialListStrategy::StreamingList => {
match api.watch(&wc.to_watch_params(WatchPhase::Initial), "0").await {
Ok(stream) => (Some(Ok(Event::Init)), State::InitialWatch { stream }),
Err(err) => {
if std::matches!(err, ClientErr::Api(ref status) if status.is_forbidden()) {
warn!("watch initlist error with 403: {err:?}");
} else {
debug!("watch initlist error: {err:?}");
}
(Some(Err(Error::WatchStartFailed(err))), State::default())
}
}
}
},
State::InitPage {
continue_token,
mut objects,
last_bookmark,
} => {
if let Some(next) = objects.pop_front() {
return (Some(Ok(Event::InitApply(next))), State::InitPage {
continue_token,
objects,
last_bookmark,
});
}
if continue_token.is_none()
&& let Some(resource_version) = last_bookmark
{
return (Some(Ok(Event::InitDone)), State::InitListed { resource_version });
}
let mut lp = wc.to_list_params();
lp.continue_token = continue_token;
match api.list(&lp).await {
Ok(list) => {
let last_bookmark = list.metadata.resource_version.filter(|s| !s.is_empty());
let continue_token = list.metadata.continue_.filter(|s| !s.is_empty());
if last_bookmark.is_none() && continue_token.is_none() {
return (Some(Err(Error::NoResourceVersion)), State::Empty);
}
(None, State::InitPage {
continue_token,
objects: list.items.into_iter().collect(),
last_bookmark,
})
}
Err(err) => {
if std::matches!(err, ClientErr::Api(ref status) if status.is_forbidden()) {
warn!("watch list error with 403: {err:?}");
} else {
debug!("watch list error: {err:?}");
}
(Some(Err(Error::InitialListFailed(err))), State::Empty)
}
}
}
State::InitialWatch { mut stream } => {
match next_with_idle_timeout(&mut stream, wc.timeout).await {
Some(Ok(WatchEvent::Added(obj) | WatchEvent::Modified(obj))) => {
(Some(Ok(Event::InitApply(obj))), State::InitialWatch { stream })
}
Some(Ok(WatchEvent::Deleted(_obj))) => {
error!("got deleted event during initial watch. this is a bug");
(None, State::InitialWatch { stream })
}
Some(Ok(WatchEvent::Bookmark(bm))) => {
let marks_initial_end = bm.metadata.annotations.contains_key("k8s.io/initial-events-end");
if marks_initial_end {
(Some(Ok(Event::InitDone)), State::Watching {
resource_version: bm.metadata.resource_version,
stream,
})
} else {
(None, State::InitialWatch { stream })
}
}
Some(Ok(WatchEvent::Error(err))) => {
let new_state = if err.code == 410 {
State::default()
} else {
State::InitialWatch { stream }
};
if err.code == 403 {
warn!("watcher watchevent error 403: {err:?}");
} else {
debug!("error watchevent error: {err:?}");
}
(Some(Err(Error::WatchError(err.boxed()))), new_state)
}
Some(Err(err)) => {
if std::matches!(err, ClientErr::Api(ref status) if status.is_forbidden()) {
warn!("watcher error 403: {err:?}");
} else {
debug!("watcher error: {err:?}");
}
(Some(Err(Error::WatchFailed(err))), State::InitialWatch { stream })
}
None => (None, State::default()),
}
}
State::InitListed { resource_version } => {
match api
.watch(&wc.to_watch_params(WatchPhase::Resumed), &resource_version)
.await
{
Ok(stream) => (None, State::Watching {
resource_version,
stream,
}),
Err(err) => {
if std::matches!(err, ClientErr::Api(ref status) if status.is_forbidden()) {
warn!("watch initlist error with 403: {err:?}");
} else {
debug!("watch initlist error: {err:?}");
}
(Some(Err(Error::WatchStartFailed(err))), State::InitListed {
resource_version,
})
}
}
}
State::Watching {
resource_version,
mut stream,
} => match next_with_idle_timeout(&mut stream, wc.timeout).await {
Some(Ok(WatchEvent::Added(obj) | WatchEvent::Modified(obj))) => {
let resource_version = obj.resource_version().unwrap_or_default();
if resource_version.is_empty() {
(Some(Err(Error::NoResourceVersion)), State::default())
} else {
(Some(Ok(Event::Apply(obj))), State::Watching {
resource_version,
stream,
})
}
}
Some(Ok(WatchEvent::Deleted(obj))) => {
let resource_version = obj.resource_version().unwrap_or_default();
if resource_version.is_empty() {
(Some(Err(Error::NoResourceVersion)), State::default())
} else {
(Some(Ok(Event::Delete(obj))), State::Watching {
resource_version,
stream,
})
}
}
Some(Ok(WatchEvent::Bookmark(bm))) => (None, State::Watching {
resource_version: bm.metadata.resource_version,
stream,
}),
Some(Ok(WatchEvent::Error(err))) => {
let new_state = if err.code == 410 {
State::default()
} else {
State::Watching {
resource_version,
stream,
}
};
if err.code == 403 {
warn!("watcher watchevent error 403: {err:?}");
} else {
debug!("error watchevent error: {err:?}");
}
(Some(Err(Error::WatchError(err.boxed()))), new_state)
}
Some(Err(err)) => {
if std::matches!(err, ClientErr::Api(ref status) if status.is_forbidden()) {
warn!("watcher error 403: {err:?}");
} else {
debug!("watcher error: {err:?}");
}
(Some(Err(Error::WatchFailed(err))), State::Watching {
resource_version,
stream,
})
}
None => (None, State::InitListed { resource_version }),
},
}
}
async fn step<A>(
api: &A,
config: &Config,
mut state: State<A::Value>,
) -> (Result<Event<A::Value>>, State<A::Value>)
where
A: ApiMode,
A::Value: Resource + 'static,
{
loop {
match step_trampolined(api, config, state).await {
(Some(result), new_state) => return (result, new_state),
(None, new_state) => state = new_state,
}
}
}
#[doc(alias = "informer")]
pub fn watcher<K: Resource + Clone + DeserializeOwned + Debug + Send + 'static>(
api: Api<K>,
watcher_config: Config,
) -> impl Stream<Item = Result<Event<K>>> + Send {
watcher_inner(FullObject { api }, watcher_config)
}
fn watcher_inner<A>(api: A, watcher_config: Config) -> impl Stream<Item = Result<Event<A::Value>>> + Send
where
A: ApiMode,
A::Value: Resource,
{
futures::stream::unfold(
(api, watcher_config, State::default()),
|(api, watcher_config, state)| async {
let (event, state) = step(&api, &watcher_config, state).await;
Some((event, (api, watcher_config, state)))
},
)
}
#[deprecated(
since = "3.1.0",
note = "Use `watcher(Api::<PartialObjectMeta<K>>::all(client), config)` instead. \
`Api<PartialObjectMeta<K>>` now automatically uses metadata-only requests."
)]
pub fn metadata_watcher<K: Resource + Clone + DeserializeOwned + Debug + Send + 'static>(
api: Api<K>,
watcher_config: Config,
) -> impl Stream<Item = Result<Event<PartialObjectMeta<K>>>> + Send {
watcher_inner(MetaOnly { api }, watcher_config)
}
pub fn watch_object<K: Resource + Clone + DeserializeOwned + Debug + Send + 'static>(
api: Api<K>,
name: &str,
) -> impl Stream<Item = Result<Option<K>>> + Send + use<K> {
let fields = format!("metadata.name={name}");
watcher(api, Config::default().fields(&fields))
.scan(false, |obj_seen, event| {
if matches!(event, Ok(Event::Init)) {
*obj_seen = false;
} else if matches!(event, Ok(Event::InitApply(_))) {
*obj_seen = true;
}
future::ready(Some((*obj_seen, event)))
})
.filter_map(|(obj_seen, event)| async move {
match event {
Ok(Event::Apply(obj) | Event::InitApply(obj)) => Some(Ok(Some(obj))),
Ok(Event::Delete(_)) => Some(Ok(None)),
Ok(Event::InitDone) if !obj_seen => Some(Ok(None)),
Ok(Event::Init | Event::InitDone) => None,
Err(err) => Some(Err(err)),
}
})
}
pub struct ExponentialBackoff {
inner: backon::ExponentialBackoff,
builder: backon::ExponentialBuilder,
}
impl ExponentialBackoff {
fn new(min_delay: Duration, max_delay: Duration, factor: f32, enable_jitter: bool) -> Self {
let builder = backon::ExponentialBuilder::default()
.with_min_delay(min_delay)
.with_max_delay(max_delay)
.with_factor(factor)
.without_max_times();
let builder = if enable_jitter {
builder.with_jitter()
} else {
builder
};
Self {
inner: builder.build(),
builder,
}
}
}
impl Backoff for ExponentialBackoff {
fn reset(&mut self) {
self.inner = self.builder.build();
}
}
impl Iterator for ExponentialBackoff {
type Item = Duration;
fn next(&mut self) -> Option<Self::Item> {
self.inner.next()
}
}
impl From<backon::ExponentialBuilder> for ExponentialBackoff {
fn from(builder: backon::ExponentialBuilder) -> Self {
Self {
inner: builder.build(),
builder,
}
}
}
pub struct DefaultBackoff(Strategy);
type Strategy = ResetTimerBackoff<ExponentialBackoff>;
impl Default for DefaultBackoff {
fn default() -> Self {
Self(ResetTimerBackoff::new(
ExponentialBackoff::new(Duration::from_millis(800), Duration::from_secs(30), 2.0, true),
Duration::from_secs(120),
))
}
}
impl Iterator for DefaultBackoff {
type Item = Duration;
fn next(&mut self) -> Option<Self::Item> {
self.0.next()
}
}
impl Backoff for DefaultBackoff {
fn reset(&mut self) {
self.0.reset();
}
}
#[cfg(test)]
mod tests {
use std::{collections::BTreeMap, time::Duration};
use futures::StreamExt;
use k8s_openapi::{api::core::v1::ConfigMap, apimachinery::pkg::apis::meta::v1::ObjectMeta};
use kube_client::{
api::{TypeMeta, WatchEvent, WatchParams},
core::{
Status,
watch::{Bookmark, BookmarkMeta},
},
};
use crate::watcher::{
ApiMode, Config, ExponentialBackoff, State, WatchPhase, next_with_idle_timeout, step,
stub_watcher::{
Recording, Sequence, SequenceStep, TestMode, error_indicates_graceful_watch_seq_exhaustion,
},
watcher_inner,
};
use super::stub_watcher::ResultPage;
fn config_map(name: &str, resource_version: &str) -> ConfigMap {
ConfigMap {
metadata: ObjectMeta {
name: Some(name.to_string()),
resource_version: Some(resource_version.to_string()),
..ObjectMeta::default()
},
..ConfigMap::default()
}
}
#[tokio::test(start_paused = true)]
async fn test_mode_watch_waits_before_returning_next_event() {
let api = TestMode::new(vec![], vec![Sequence::new(vec![
SequenceStep::Wait(Duration::from_millis(50)),
SequenceStep::List(vec![Ok(WatchEvent::Added(config_map("a", "1")))].into()),
])]);
let mut stream = api.watch(&WatchParams::default(), "0").await.unwrap();
assert!(futures::poll!(stream.next()).is_pending());
tokio::time::advance(Duration::from_millis(49)).await;
assert!(futures::poll!(stream.next()).is_pending());
tokio::time::advance(Duration::from_millis(1)).await;
assert!(matches!(
stream.next().await,
Some(Ok(WatchEvent::Added(config_map))) if config_map.metadata.name.as_deref() == Some("a")
));
}
#[allow(clippy::too_many_lines)]
#[tokio::test]
async fn streaming_list_resync() {
const LAST_VALID_RESOURCE_VERSION: &str = "5";
let mut recoverable_err = Box::new(Status::default());
recoverable_err.code = 502;
recoverable_err.message = "some err".to_string();
recoverable_err.reason = "Something went wrong".to_string();
let api = TestMode::new(vec![], vec![
Sequence::new(vec![
SequenceStep::List(
vec![
Ok(WatchEvent::Added(config_map("a", "2"))),
Ok(WatchEvent::Added(config_map("b", "3"))),
Ok(WatchEvent::Added(config_map("c", "4"))),
Ok(WatchEvent::Bookmark(Bookmark {
types: TypeMeta::resource::<ConfigMap>(),
metadata: BookmarkMeta {
resource_version: "4".to_string(),
annotations: BTreeMap::from_iter(vec![(
"k8s.io/initial-events-end".into(),
"true".into(),
)]),
},
})),
]
.into(),
),
SequenceStep::List(
vec![
Ok(WatchEvent::Modified(config_map("a", LAST_VALID_RESOURCE_VERSION))),
Ok(WatchEvent::Error(recoverable_err)),
]
.into(),
),
SequenceStep::List(
vec![Ok(WatchEvent::Modified(config_map(
"a",
LAST_VALID_RESOURCE_VERSION,
)))]
.into(),
),
]),
Sequence::new(vec![SequenceStep::List(
vec![
Ok(WatchEvent::Added(config_map("a", "5"))),
Ok(WatchEvent::Bookmark(Bookmark {
types: TypeMeta::resource::<ConfigMap>(),
metadata: BookmarkMeta {
resource_version: "5".to_string(),
annotations: BTreeMap::from_iter(vec![(
"k8s.io/initial-events-end".into(),
"true".into(),
)]),
},
})),
]
.into(),
)]),
]);
let config = Config::default()
.timeout(1)
.streaming_lists()
.labels("app=test")
.fields("metadata.name!=ignored");
let mut stream = std::pin::pin!(watcher_inner(api.clone(), config));
for expected in [
"Init",
"InitApply(a)",
"InitApply(b)",
"InitApply(c)",
"InitDone",
"Apply(a)",
"error returned by apiserver during watch: some err: Something went wrong",
"Apply(a)",
"Apply(a)",
] {
let event = stream.next().await.expect("watcher stream should not end");
let repr = match event {
Ok(event) => event.to_string(),
Err(err) => err.to_string(),
};
assert_eq!(repr, expected);
}
let event = tokio::time::timeout(Duration::from_millis(100), stream.next())
.await
.expect("watcher should return when the TestMode sequence is exhausted")
.expect("watcher stream should not end");
dbg!(&event);
assert!(event.is_err_and(|err| error_indicates_graceful_watch_seq_exhaustion(&err)),);
let records = api.get_recordings();
match &records[..] {
[
Recording::Watch(initial_params, initial_version),
Recording::Watch(resumed_params, resumed_version),
Recording::Watch(exhausted_params, exhausted_version),
] => {
assert_eq!(initial_version, "0");
assert_eq!(initial_params.label_selector.as_deref(), Some("app=test"));
assert_eq!(
initial_params.field_selector.as_deref(),
Some("metadata.name!=ignored")
);
assert!(initial_params.send_initial_events);
for (watch_params, watch_version) in [
(resumed_params, resumed_version),
(exhausted_params, exhausted_version),
] {
assert_eq!(watch_version, LAST_VALID_RESOURCE_VERSION);
assert_eq!(watch_params.label_selector.as_deref(), Some("app=test"));
assert_eq!(
watch_params.field_selector.as_deref(),
Some("metadata.name!=ignored")
);
assert!(!watch_params.send_initial_events);
}
}
_ => panic!("unexpected API call sequence {records:?}"),
}
}
#[tokio::test]
async fn streaming_list_init() {
let api = TestMode::new(vec![], vec![Sequence::new(vec![
SequenceStep::List(
vec![
Ok(WatchEvent::Added(config_map("a", "2"))),
Ok(WatchEvent::Added(config_map("b", "3"))),
Ok(WatchEvent::Added(config_map("c", "4"))),
Ok(WatchEvent::Bookmark(Bookmark {
types: TypeMeta::resource::<ConfigMap>(),
metadata: BookmarkMeta {
resource_version: "145".to_string(),
annotations: BTreeMap::from_iter(vec![(
"k8s.io/initial-events-end".into(),
"true".into(),
)]),
},
})),
]
.into(),
),
SequenceStep::List(
vec![
Ok(WatchEvent::Modified(config_map("a", "5"))),
Ok(WatchEvent::Deleted(config_map("b", "7"))),
Ok(WatchEvent::Modified(config_map("c", "9"))),
]
.into(),
),
])]);
let config = Config::default()
.timeout(1)
.streaming_lists()
.labels("app=test")
.fields("metadata.name!=ignored");
let mut state = State::default();
for expected in [
"Init",
"InitApply(a)",
"InitApply(b)",
"InitApply(c)",
"InitDone",
"Apply(a)",
"Delete(b)",
"Apply(c)",
] {
let (event, next) = step(&api, &config, state).await;
state = next;
assert_eq!(event.unwrap().to_string(), expected);
}
let (event, _) = tokio::time::timeout(Duration::from_millis(100), step(&api, &config, state))
.await
.expect("step should return when the TestMode sequence is exhausted");
assert!(event.is_err_and(|err| error_indicates_graceful_watch_seq_exhaustion(&err)));
let records = api.get_recordings();
match &records[..] {
[
Recording::Watch(initial_params, initial_version),
Recording::Watch(resumed_params, resumed_version),
] => {
assert_eq!(initial_version, "0");
assert_eq!(initial_params.label_selector.as_deref(), Some("app=test"));
assert_eq!(
initial_params.field_selector.as_deref(),
Some("metadata.name!=ignored")
);
assert!(initial_params.send_initial_events);
assert_eq!(resumed_version, "9");
assert_eq!(resumed_params.label_selector.as_deref(), Some("app=test"));
assert_eq!(
resumed_params.field_selector.as_deref(),
Some("metadata.name!=ignored")
);
assert!(!resumed_params.send_initial_events);
}
_ => panic!("unexpected API call sequence {records:?}"),
}
}
#[tokio::test]
async fn streaming_list_initial_stream_eof_before_bookmark_drops_partial_objects() {
let api = TestMode::new(vec![], vec![
Sequence::new(vec![SequenceStep::List(
vec![
Ok(WatchEvent::Added(config_map("a", "1"))),
Ok(WatchEvent::Added(config_map("b", "2"))),
]
.into(),
)]),
Sequence::new(vec![SequenceStep::List(
vec![
Ok(WatchEvent::Added(config_map("a", "1"))),
Ok(WatchEvent::Bookmark(Bookmark {
types: TypeMeta::resource::<ConfigMap>(),
metadata: BookmarkMeta {
resource_version: "1".to_string(),
annotations: BTreeMap::from_iter(vec![(
"k8s.io/initial-events-end".into(),
"true".into(),
)]),
},
})),
]
.into(),
)]),
]);
let config = Config::default().streaming_lists();
let (reader, mut writer) = crate::reflector::store::<ConfigMap>();
let mut state = State::default();
for expected in [
"Init",
"InitApply(a)",
"InitApply(b)",
"Init",
"InitApply(a)",
"InitDone",
] {
let (event, next) = step(&api, &config, state).await;
state = next;
let event = event.unwrap();
assert_eq!(event.to_string(), expected);
writer.apply_watcher_event(&event);
}
let mut names: Vec<_> = reader
.state()
.iter()
.filter_map(|cm| cm.metadata.name.clone())
.collect();
names.sort();
assert_eq!(names, ["a".to_string()]);
let records = api.get_recordings();
match &records[..] {
[
Recording::Watch(first, first_version),
Recording::Watch(second, second_version),
] => {
assert_eq!(first_version, "0");
assert!(first.send_initial_events);
assert_eq!(second_version, "0");
assert!(second.send_initial_events);
}
_ => panic!("unexpected API call sequence {records:?}"),
}
}
#[tokio::test]
async fn streaming_list_initial_watch_410_before_bookmark_drops_partial_objects() {
let mut gone = Box::new(Status::default());
gone.code = 410;
gone.message = "expired".to_string();
gone.reason = "Expired".to_string();
let api = TestMode::new(vec![], vec![
Sequence::new(vec![SequenceStep::List(
vec![
Ok(WatchEvent::Added(config_map("a", "1"))),
Ok(WatchEvent::Added(config_map("b", "2"))),
Ok(WatchEvent::Error(gone)),
]
.into(),
)]),
Sequence::new(vec![SequenceStep::List(
vec![
Ok(WatchEvent::Added(config_map("a", "1"))),
Ok(WatchEvent::Bookmark(Bookmark {
types: TypeMeta::resource::<ConfigMap>(),
metadata: BookmarkMeta {
resource_version: "1".to_string(),
annotations: BTreeMap::from_iter(vec![(
"k8s.io/initial-events-end".into(),
"true".into(),
)]),
},
})),
]
.into(),
)]),
]);
let config = Config::default().streaming_lists();
let (reader, mut writer) = crate::reflector::store::<ConfigMap>();
let mut state = State::default();
for expected in [
"Init",
"InitApply(a)",
"InitApply(b)",
"error returned by apiserver during watch: expired: Expired",
"Init",
"InitApply(a)",
"InitDone",
] {
let (event, next) = step(&api, &config, state).await;
state = next;
let repr = match &event {
Ok(event) => event.to_string(),
Err(err) => err.to_string(),
};
assert_eq!(repr, expected);
if let Ok(event) = &event {
writer.apply_watcher_event(event);
}
}
let mut names: Vec<_> = reader
.state()
.iter()
.filter_map(|cm| cm.metadata.name.clone())
.collect();
names.sort();
assert_eq!(names, ["a".to_string()]);
let records = api.get_recordings();
match &records[..] {
[
Recording::Watch(first, first_version),
Recording::Watch(second, second_version),
] => {
assert_eq!(first_version, "0");
assert!(first.send_initial_events);
assert_eq!(second_version, "0");
assert!(second.send_initial_events);
}
_ => panic!("unexpected API call sequence {records:?}"),
}
}
#[tokio::test]
async fn listwatch_paginates_initial_list_before_starting_watch() {
let api = TestMode::new(
vec![
Ok(ResultPage::empty()
.items(vec![config_map("a", "1")])
.continue_token("first".into())
.into()),
Ok(ResultPage::empty()
.items(vec![config_map("b", "2")])
.resource_version("2".into())
.continue_token("second".into())
.into()),
Ok(ResultPage::empty()
.items(vec![config_map("c", "3")])
.resource_version("3".into())
.into()),
],
vec![Sequence::new(vec![SequenceStep::List(
vec![Ok(WatchEvent::Added(config_map("d", "4")))].into(),
)])],
);
let config = Config::default()
.page_size(1)
.labels("app=test")
.fields("metadata.name!=ignored");
let mut state = State::default();
let (event, next) = step(&api, &config, state).await;
state = next;
assert_eq!(event.unwrap().to_string(), "Init");
let (event, next) = step(&api, &config, state).await;
state = next;
assert_eq!(event.unwrap().to_string(), "InitApply(a)");
let (event, next) = step(&api, &config, state).await;
state = next;
assert_eq!(event.unwrap().to_string(), "InitApply(b)");
let (event, next) = step(&api, &config, state).await;
state = next;
assert_eq!(event.unwrap().to_string(), "InitApply(c)");
let (event, next) = step(&api, &config, state).await;
state = next;
assert_eq!(event.unwrap().to_string(), "InitDone");
let (event, _) = step(&api, &config, state).await;
assert_eq!(event.unwrap().to_string(), "Apply(d)");
let records = api.get_recordings();
match &records[..] {
[
Recording::List(first),
Recording::List(second),
Recording::List(third),
Recording::Watch(watch_params, watch_version),
] => {
assert_eq!(first.continue_token.as_deref(), None);
assert_eq!(second.continue_token.as_deref(), Some("first"));
assert_eq!(third.continue_token.as_deref(), Some("second"));
assert_eq!(first.limit, Some(1));
assert_eq!(first.label_selector.as_deref(), Some("app=test"));
assert_eq!(first.field_selector.as_deref(), Some("metadata.name!=ignored"));
assert_eq!(watch_version, "3");
assert_eq!(watch_params.label_selector.as_deref(), Some("app=test"));
assert_eq!(
watch_params.field_selector.as_deref(),
Some("metadata.name!=ignored")
);
assert!(!watch_params.send_initial_events);
}
_ => panic!("unexpected API call sequence"),
}
}
#[test]
fn to_watch_params_initial_phase_with_streaming_list_sets_send_initial_events() {
let config = Config::default().streaming_lists();
let params = config.to_watch_params(WatchPhase::Initial);
assert!(params.send_initial_events);
}
#[test]
fn to_watch_params_resumed_phase_with_streaming_list_does_not_set_send_initial_events() {
let config = Config::default().streaming_lists();
let params = config.to_watch_params(WatchPhase::Resumed);
assert!(!params.send_initial_events);
}
#[test]
fn to_watch_params_listwatch_mode_does_not_set_send_initial_events() {
let config = Config::default(); let params_initial = config.to_watch_params(WatchPhase::Initial);
let params_resumed = config.to_watch_params(WatchPhase::Resumed);
assert!(!params_initial.send_initial_events);
assert!(!params_resumed.send_initial_events);
}
fn approx_eq(a: Duration, b: Duration) -> bool {
a.abs_diff(b) < Duration::from_micros(100)
}
#[test]
fn exponential_backoff_without_jitter() {
let mut backoff =
ExponentialBackoff::new(Duration::from_millis(100), Duration::from_secs(1), 2.0, false);
assert!(approx_eq(backoff.next().unwrap(), Duration::from_millis(100)));
assert!(approx_eq(backoff.next().unwrap(), Duration::from_millis(200)));
assert!(approx_eq(backoff.next().unwrap(), Duration::from_millis(400)));
}
#[test]
fn exponential_backoff_with_jitter_applies_randomness() {
let mut backoff =
ExponentialBackoff::new(Duration::from_millis(100), Duration::from_secs(1), 2.0, true);
let delays: Vec<_> = (0..5).filter_map(|_| backoff.next()).collect();
for d in &delays {
assert!(*d > Duration::ZERO);
}
let exact_values = [
Duration::from_millis(100),
Duration::from_millis(200),
Duration::from_millis(400),
Duration::from_millis(800),
Duration::from_secs(1),
];
let all_exact = delays
.iter()
.zip(exact_values.iter())
.all(|(d, e)| approx_eq(*d, *e));
assert!(
!all_exact,
"With jitter enabled, delays should not all match exact exponential values"
);
}
#[tokio::test(start_paused = true)]
async fn idle_timeout_returns_item_when_stream_has_data() {
let mut stream = futures::stream::iter(vec![1, 2, 3]);
let result = next_with_idle_timeout(&mut stream, Some(290)).await;
assert_eq!(result, Some(1));
}
#[tokio::test(start_paused = true)]
async fn zero_timeout_does_not_trigger_idle_timeout() {
let mut stream = futures::stream::once(async {
tokio::time::sleep(Duration::from_secs(6)).await;
42
})
.boxed();
let result = next_with_idle_timeout(&mut stream, Some(0)).await;
assert_eq!(result, Some(42));
}
#[tokio::test(start_paused = true)]
async fn idle_timeout_returns_none_on_dead_connection() {
let mut stream = futures::stream::pending::<i32>();
let result = next_with_idle_timeout(&mut stream, Some(290)).await;
assert_eq!(result, None);
}
#[tokio::test(start_paused = true)]
async fn idle_timeout_returns_none_when_stream_ends() {
let mut stream = futures::stream::empty::<i32>();
let result = next_with_idle_timeout(&mut stream, Some(290)).await;
assert_eq!(result, None);
}
}