Skip to main content

kube_runtime/
watcher.rs

1//! Watches a Kubernetes Resource for changes, with error recovery
2//!
3//! See [`watcher`] for the primary entry point.
4
5use crate::utils::{Backoff, ResetTimerBackoff};
6
7use backon::BackoffBuilder;
8use educe::Educe;
9use futures::{Stream, StreamExt, stream::BoxStream};
10use kube_client::{
11    Api, Error as ClientErr,
12    api::{ListParams, Resource, ResourceExt, VersionMatch, WatchEvent, WatchParams},
13    core::{ObjectList, Selector, metadata::PartialObjectMeta},
14    error::Status,
15};
16use serde::de::DeserializeOwned;
17#[cfg(test)]
18#[path = "stub_watcher.rs"]
19mod stub_watcher;
20
21use std::{
22    clone::Clone,
23    collections::VecDeque,
24    fmt::{Debug, Display},
25    future::{self, Future},
26    time::Duration,
27};
28use thiserror::Error;
29use tracing::{debug, error, warn};
30
31/// Errors that a watcher can emit
32///
33/// These are all considered retryable from a watcher's point of view,
34/// even though they may require patching of rbac/netpols in the background to fix.
35///
36/// To avoid constantly looping errors, make sure backoff is applied.
37#[derive(Debug, Error)]
38pub enum Error {
39    /// Received a raw error while performing an api.list
40    #[error("failed to perform initial object list: {0}")]
41    InitialListFailed(#[source] kube_client::Error),
42
43    /// Received a raw error while starting an api.watch
44    #[error("failed to start watching object: {0}")]
45    WatchStartFailed(#[source] kube_client::Error),
46
47    /// Received a `WatchEvent::Error` from the apiserver
48    #[error("error returned by apiserver during watch: {0}")]
49    WatchError(#[source] Box<Status>),
50
51    /// Received a raw error while watching
52    #[error("watch stream failed: {0}")]
53    WatchFailed(#[source] kube_client::Error),
54
55    /// Missing resource version field from api server
56    #[error("no metadata.resourceVersion in watch result (does resource support watch?)")]
57    NoResourceVersion,
58}
59
60/// Type alias for Result with a `watcher::Error` as default.
61pub type Result<T, E = Error> = std::result::Result<T, E>;
62
63#[derive(Debug, Clone)]
64/// Watch events returned from the [`watcher`]
65pub enum Event<K> {
66    /// An object was added or modified
67    Apply(K),
68    /// An object was deleted
69    ///
70    /// The object need not have `metadata.deletionTimestamp` set or a changed
71    /// `metadata.generation`. After decoding with
72    /// [`touched_objects`](crate::WatchStreamExt::touched_objects), predicates based on
73    /// unchanged fields can suppress it. See [predicate deletion handling](crate::predicates).
74    ///
75    /// NOTE: This should not be used for managing persistent state elsewhere, since
76    /// events may be lost if the watcher is unavailable. Use
77    /// [finalizers](crate::finalizer::finalizer) instead.
78    Delete(K),
79    /// The watch stream was restarted.
80    ///
81    /// A series of `InitApply` events are expected to follow until all matching objects
82    /// have been listed. This event can be used to prepare a buffer for `InitApply` events.
83    Init,
84    /// Received an object during `Init`.
85    ///
86    /// Objects returned here are either from the initial stream using the `StreamingList` strategy,
87    /// or from pages using the `ListWatch` strategy.
88    ///
89    /// These events can be passed up if having a complete set of objects is not a concern.
90    /// If you need to wait for a complete set, please buffer these events until an `InitDone`.
91    InitApply(K),
92    /// The initialisation is complete.
93    ///
94    /// This can be used as a signal to replace buffered store contents atomically.
95    /// No more `InitApply` events will happen until the next `Init` event.
96    ///
97    /// Any objects that were previously [`Applied`](Event::Apply) but are not listed in any of
98    /// the `InitApply` events should be assumed to have been [`Deleted`](Event::Delete).
99    InitDone,
100}
101
102impl<K> Display for Event<K>
103where
104    K: ResourceExt,
105{
106    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
107        let desc = match self {
108            Event::Init => "Init".into(),
109            Event::InitApply(obj) => format!("InitApply({})", obj.name_any()),
110            Event::InitDone => "InitDone".into(),
111            Event::Apply(obj) => format!("Apply({})", obj.name_any()),
112            Event::Delete(obj) => format!("Delete({})", obj.name_any()),
113        };
114        write!(f, "{desc}")
115    }
116}
117
118impl<K> Event<K> {
119    /// Map each object in an event through a mutator fn
120    ///
121    /// This allows for memory optimizations in watch streams.
122    /// If you are chaining a watch stream into a reflector as an in memory state store,
123    /// you can control the space used by each object by dropping fields.
124    ///
125    /// ```no_run
126    /// use k8s_openapi::api::core::v1::Pod;
127    /// use kube::ResourceExt;
128    /// # use kube::runtime::watcher::Event;
129    /// # let event: Event<Pod> = todo!();
130    /// event.modify(|pod| {
131    ///     pod.managed_fields_mut().clear();
132    ///     pod.annotations_mut().clear();
133    ///     pod.status = None;
134    /// });
135    /// ```
136    #[must_use]
137    pub fn modify(mut self, mut f: impl FnMut(&mut K)) -> Self {
138        match &mut self {
139            Self::Apply(obj) | Self::Delete(obj) | Self::InitApply(obj) => (f)(obj),
140            Self::Init | Self::InitDone => {} // markers, nothing to modify
141        }
142        self
143    }
144}
145
146#[derive(Educe, Default)]
147#[educe(Debug)]
148/// The internal finite state machine driving the [`watcher`]
149enum State<K> {
150    /// The Watcher is empty, and the next [`poll`](Stream::poll_next) will start the initial LIST to get all existing objects
151    #[default]
152    Empty,
153    /// The Watcher is in the process of paginating through the initial LIST
154    InitPage {
155        continue_token: Option<String>,
156        objects: VecDeque<K>,
157        last_bookmark: Option<String>,
158    },
159    /// Kubernetes 1.27 Streaming Lists
160    /// The initial watch is in progress
161    InitialWatch {
162        #[educe(Debug(ignore))]
163        stream: BoxStream<'static, kube_client::Result<WatchEvent<K>>>,
164    },
165    /// The initial LIST was successful, so we should move on to starting the actual watch.
166    InitListed { resource_version: String },
167    /// The watch is in progress, from this point we just return events from the server.
168    ///
169    /// If the connection is disrupted then we propagate the error but try to restart the watch stream by
170    /// returning to the `InitListed` state.
171    /// If we fall out of the K8s watch window then we propagate the error and fall back doing a re-list
172    /// with `Empty`.
173    Watching {
174        resource_version: String,
175        #[educe(Debug(ignore))]
176        stream: BoxStream<'static, kube_client::Result<WatchEvent<K>>>,
177    },
178}
179
180/// Used to control whether the watcher receives the full object, or only the
181/// metadata
182trait ApiMode: Send + Sync {
183    type Value: Clone + Send + 'static;
184
185    fn list(
186        &self,
187        lp: &ListParams,
188    ) -> impl Future<Output = kube_client::Result<ObjectList<Self::Value>>> + Send;
189    fn watch(
190        &self,
191        wp: &WatchParams,
192        version: &str,
193    ) -> impl Future<
194        Output = kube_client::Result<BoxStream<'static, kube_client::Result<WatchEvent<Self::Value>>>>,
195    > + Send;
196}
197
198/// A wrapper around the `Api` of a `Resource` type that when used by the
199/// watcher will return the entire (full) object
200struct FullObject<K> {
201    api: Api<K>,
202}
203
204/// Configurable list semantics for `watcher` relists
205#[derive(Clone, Default, Debug, PartialEq)]
206pub enum ListSemantic {
207    /// List calls perform a full quorum read for most recent results
208    ///
209    /// Prefer this if you have strong consistency requirements. Note that this
210    /// is more taxing for the apiserver and can be less scalable for the cluster.
211    ///
212    /// If you are observing large resource sets (such as congested `Controller` cases),
213    /// you typically have a delay between the list call completing, and all the events
214    /// getting processed. In such cases, it is probably worth picking `Any` over `MostRecent`,
215    /// as your events are not guaranteed to be up-to-date by the time you get to them anyway.
216    #[default]
217    MostRecent,
218
219    /// List calls returns cached results from apiserver
220    ///
221    /// This is faster and much less taxing on the apiserver, but can result
222    /// in much older results than has previously observed for `Restarted` events,
223    /// particularly in HA configurations, due to partitions or stale caches.
224    ///
225    /// This option makes the most sense for controller usage where events have
226    /// some delay between being seen by the runtime, and it being sent to the reconciler.
227    Any,
228}
229
230/// Configurable watcher listwatch semantics
231
232#[derive(Clone, Default, Debug, PartialEq)]
233pub enum InitialListStrategy {
234    /// List first, then watch from given resource version
235    ///
236    /// This is the old and default way of watching. The watcher will do a paginated list call first before watching.
237    /// When using this mode, you can configure the `page_size` on the watcher.
238    #[default]
239    ListWatch,
240    /// Kubernetes 1.27 Streaming Lists
241    ///
242    /// See [upstream documentation on streaming lists](https://kubernetes.io/docs/reference/using-api/api-concepts/#streaming-lists),
243    /// and the [KEP](https://github.com/kubernetes/enhancements/tree/master/keps/sig-api-machinery/3157-watch-list#design-details).
244    StreamingList,
245}
246
247/// Accumulates all options that can be used on the watcher invocation.
248#[derive(Clone, Debug, PartialEq)]
249pub struct Config {
250    /// A selector to restrict the list of returned objects by their labels.
251    ///
252    /// Defaults to everything if `None`.
253    pub label_selector: Option<String>,
254
255    /// A selector to restrict the list of returned objects by their fields.
256    ///
257    /// Defaults to everything if `None`.
258    pub field_selector: Option<String>,
259
260    /// Timeout for the watch call.
261    ///
262    /// This limits the duration of the call, regardless of any activity or inactivity.
263    /// If unset, we will use 290s.
264    /// The watcher's dead-connection detection window is this value plus 5s,
265    /// so larger values delay noticing a silently dropped connection.
266    pub timeout: Option<u32>,
267
268    /// Semantics for list calls.
269    ///
270    /// Configures re-list for performance vs. consistency.
271    ///
272    /// NB: This option only has an effect for [`InitialListStrategy::ListWatch`].
273    pub list_semantic: ListSemantic,
274
275    /// Control how the watcher fetches the initial list of objects.
276    ///
277    /// - `ListWatch`: The watcher will fetch the initial list of objects using a list call.
278    /// - `StreamingList`: The watcher will fetch the initial list of objects using a watch call.
279    ///
280    /// `StreamingList` is more efficient than `ListWatch`, but it requires the server to support
281    /// streaming list bookmarks (opt-in feature gate in Kubernetes 1.27).
282    ///
283    /// See [upstream documentation on streaming lists](https://kubernetes.io/docs/reference/using-api/api-concepts/#streaming-lists),
284    /// and the [KEP](https://github.com/kubernetes/enhancements/tree/master/keps/sig-api-machinery/3157-watch-list#design-details).
285    pub initial_list_strategy: InitialListStrategy,
286
287    /// Maximum number of objects retrieved per list operation resyncs.
288    ///
289    /// This can reduce the memory consumption during resyncs, at the cost of requiring more
290    /// API roundtrips to complete.
291    ///
292    /// Defaults to 500. Note that `None` represents unbounded.
293    ///
294    /// NB: This option only has an effect for [`InitialListStrategy::ListWatch`].
295    pub page_size: Option<u32>,
296
297    /// Enables watch events with type "BOOKMARK".
298    ///
299    /// Requests watch bookmarks from the apiserver when enabled for improved watch precision and reduced list calls.
300    /// This is default enabled and should generally not be turned off.
301    pub bookmarks: bool,
302}
303
304impl Default for Config {
305    fn default() -> Self {
306        Self {
307            bookmarks: true,
308            label_selector: None,
309            field_selector: None,
310            timeout: None,
311            list_semantic: ListSemantic::default(),
312            // same default page size limit as client-go
313            // https://github.com/kubernetes/client-go/blob/aed71fa5cf054e1c196d67b2e21f66fd967b8ab1/tools/pager/pager.go#L31
314            page_size: Some(500),
315            initial_list_strategy: InitialListStrategy::ListWatch,
316        }
317    }
318}
319
320/// Builder interface to Config
321///
322/// Usage:
323/// ```
324/// use kube::runtime::watcher::Config;
325/// let wc = Config::default()
326///     .timeout(60)
327///     .labels("kubernetes.io/lifecycle=spot");
328/// ```
329impl Config {
330    /// Configure the timeout for watch calls
331    ///
332    /// This limits the duration of the call, regardless of any activity or inactivity.
333    /// Defaults to 290s
334    #[must_use]
335    pub fn timeout(mut self, timeout_secs: u32) -> Self {
336        self.timeout = Some(timeout_secs);
337        self
338    }
339
340    /// Configure the selector to restrict the list of returned objects by their fields.
341    ///
342    /// Defaults to everything.
343    /// Supports `=`, `==`, `!=`, and can be comma separated: `key1=value1,key2=value2`.
344    /// The server only supports a limited number of field queries per type.
345    #[must_use]
346    pub fn fields(mut self, field_selector: &str) -> Self {
347        self.field_selector = Some(field_selector.to_string());
348        self
349    }
350
351    /// Configure the selector to restrict the list of returned objects by their labels.
352    ///
353    /// Defaults to everything.
354    /// Supports `=`, `==`, `!=`, and can be comma separated: `key1=value1,key2=value2`.
355    #[must_use]
356    pub fn labels(mut self, label_selector: &str) -> Self {
357        self.label_selector = Some(label_selector.to_string());
358        self
359    }
360
361    /// Configure typed label selectors
362    ///
363    /// Configure typed selectors from [`Selector`](kube_client::core::Selector) and [`Expression`](kube_client::core::Expression) lists.
364    ///
365    /// ```
366    /// use kube_runtime::watcher::Config;
367    /// use kube_client::core::{Expression, Selector, ParseExpressionError};
368    /// use k8s_openapi::apimachinery::pkg::apis::meta::v1::LabelSelector;
369    /// let selector: Selector = Expression::In("env".into(), ["development".into(), "sandbox".into()].into()).into();
370    /// let cfg = Config::default().labels_from(&selector);
371    /// let cfg = Config::default().labels_from(&Expression::Exists("foo".into()).into());
372    /// let selector: Selector = LabelSelector::default().try_into()?;
373    /// let cfg = Config::default().labels_from(&selector);
374    /// # Ok::<(), ParseExpressionError>(())
375    ///```
376    #[must_use]
377    pub fn labels_from(mut self, selector: &Selector) -> Self {
378        self.label_selector = Some(selector.to_string());
379        self
380    }
381
382    /// Sets list semantic to configure re-list performance and consistency
383    ///
384    /// NB: This option only has an effect for [`InitialListStrategy::ListWatch`].
385    #[must_use]
386    pub fn list_semantic(mut self, semantic: ListSemantic) -> Self {
387        self.list_semantic = semantic;
388        self
389    }
390
391    /// Sets list semantic to `Any` to improve list performance
392    ///
393    /// NB: This option only has an effect for [`InitialListStrategy::ListWatch`].
394    #[must_use]
395    pub fn any_semantic(self) -> Self {
396        self.list_semantic(ListSemantic::Any)
397    }
398
399    /// Disables watch bookmarks to simplify watch handling
400    ///
401    /// This is not recommended to use with production watchers as it can cause desyncs.
402    /// See [#219](https://github.com/kube-rs/kube/issues/219) for details.
403    #[must_use]
404    pub fn disable_bookmarks(mut self) -> Self {
405        self.bookmarks = false;
406        self
407    }
408
409    /// Limits the number of objects retrieved in each list operation during resync.
410    ///
411    /// This can reduce the memory consumption during resyncs, at the cost of requiring more
412    /// API roundtrips to complete.
413    ///
414    /// NB: This option only has an effect for [`InitialListStrategy::ListWatch`].
415    #[must_use]
416    pub fn page_size(mut self, page_size: u32) -> Self {
417        self.page_size = Some(page_size);
418        self
419    }
420
421    /// Kubernetes 1.27 Streaming Lists
422    /// Sets list semantic to `Stream` to make use of watch bookmarks
423    #[must_use]
424    pub fn streaming_lists(mut self) -> Self {
425        self.initial_list_strategy = InitialListStrategy::StreamingList;
426        self
427    }
428
429    /// Converts generic `watcher::Config` structure to the instance of `ListParams` used for list requests.
430    fn to_list_params(&self) -> ListParams {
431        let (resource_version, version_match) = match self.list_semantic {
432            ListSemantic::Any => (Some("0".into()), Some(VersionMatch::NotOlderThan)),
433            ListSemantic::MostRecent => (None, None),
434        };
435        ListParams {
436            label_selector: self.label_selector.clone(),
437            field_selector: self.field_selector.clone(),
438            version_match,
439            resource_version,
440            // The watcher handles pagination internally.
441            limit: self.page_size,
442            continue_token: None,
443            ..Default::default()
444        }
445    }
446
447    /// Converts generic `watcher::Config` structure to the instance of `WatchParams` used for watch requests.
448    fn to_watch_params(&self, phase: WatchPhase) -> WatchParams {
449        WatchParams {
450            label_selector: self.label_selector.clone(),
451            field_selector: self.field_selector.clone(),
452            timeout: self.timeout,
453            bookmarks: self.bookmarks,
454            send_initial_events: phase == WatchPhase::Initial
455                && self.initial_list_strategy == InitialListStrategy::StreamingList,
456        }
457    }
458}
459
460/// Distinguishes between initial watch and resumed watch for streaming lists.
461///
462/// This is used to determine whether to set `sendInitialEvents=true` in watch requests.
463/// Only initial watches should request initial events; reconnections should not.
464#[derive(Clone, Copy, Debug, PartialEq, Eq)]
465enum WatchPhase {
466    /// Initial watch from `State::Empty` - requests initial events for streaming lists
467    Initial,
468    /// Resumed watch from `State::InitListed` - does not request initial events
469    Resumed,
470}
471
472impl<K> ApiMode for FullObject<K>
473where
474    K: Clone + Debug + DeserializeOwned + Send + 'static,
475{
476    type Value = K;
477
478    async fn list(&self, lp: &ListParams) -> kube_client::Result<ObjectList<Self::Value>> {
479        self.api.list(lp).await
480    }
481
482    async fn watch(
483        &self,
484        wp: &WatchParams,
485        version: &str,
486    ) -> kube_client::Result<BoxStream<'static, kube_client::Result<WatchEvent<Self::Value>>>> {
487        self.api.watch(wp, version).await.map(StreamExt::boxed)
488    }
489}
490
491/// A wrapper around the `Api` of a `Resource` type that when used by the
492/// watcher will return only the metadata associated with an object
493struct MetaOnly<K> {
494    api: Api<K>,
495}
496
497impl<K> ApiMode for MetaOnly<K>
498where
499    K: Clone + Debug + DeserializeOwned + Send + 'static,
500{
501    type Value = PartialObjectMeta<K>;
502
503    async fn list(&self, lp: &ListParams) -> kube_client::Result<ObjectList<Self::Value>> {
504        self.api.list_metadata(lp).await
505    }
506
507    async fn watch(
508        &self,
509        wp: &WatchParams,
510        version: &str,
511    ) -> kube_client::Result<BoxStream<'static, kube_client::Result<WatchEvent<Self::Value>>>> {
512        self.api.watch_metadata(wp, version).await.map(StreamExt::boxed)
513    }
514}
515
516/// Client-side idle timeout margin added on top of the server-side watch timeout.
517///
518/// The server closes the watch stream after the configured timeout (default 290s).
519/// We add a small margin so the client detects dead connections where the
520/// server's close never arrives (e.g. network failure).
521const WATCH_IDLE_TIMEOUT_MARGIN: Duration = Duration::from_secs(5);
522
523/// Poll the next item from a watch stream with an idle timeout.
524///
525/// Returns `None` when the stream ends **or** when no item arrives within
526/// `timeout + WATCH_IDLE_TIMEOUT_MARGIN`, causing the watcher to
527/// treat the connection as dead and reconnect. An explicit zero timeout
528/// disables this client-side idle timeout.
529async fn next_with_idle_timeout<S, T>(stream: &mut S, timeout: Option<u32>) -> Option<T>
530where
531    S: Stream<Item = T> + Unpin,
532{
533    with_idle_timeout(stream.next(), timeout).await.flatten()
534}
535
536/// Await `fut` with the same idle timeout, returning `None` on expiry.
537///
538/// Also wraps the watch call, which can stall before a stream exists,
539/// e.g. on an error response whose body never completes.
540async fn with_idle_timeout<F: Future>(fut: F, timeout: Option<u32>) -> Option<F::Output> {
541    if timeout == Some(0) {
542        return Some(fut.await);
543    }
544
545    let idle_timeout = Duration::from_secs(u64::from(timeout.unwrap_or(290))) + WATCH_IDLE_TIMEOUT_MARGIN;
546    match tokio::time::timeout(idle_timeout, fut).await {
547        Ok(output) => Some(output),
548        Err(_elapsed) => {
549            debug!(
550                timeout_secs = idle_timeout.as_secs(),
551                "watch idle timeout, reconnecting"
552            );
553            None
554        }
555    }
556}
557
558/// Progresses the watcher a single step, returning (event, state)
559///
560/// This function should be trampolined: if event == `None`
561/// then the function should be called again until it returns a Some.
562#[allow(clippy::too_many_lines)] // for now
563async fn step_trampolined<A>(
564    api: &A,
565    wc: &Config,
566    state: State<A::Value>,
567) -> (Option<Result<Event<A::Value>>>, State<A::Value>)
568where
569    A: ApiMode,
570    A::Value: Resource + 'static,
571{
572    match state {
573        State::Empty => match wc.initial_list_strategy {
574            InitialListStrategy::ListWatch => (Some(Ok(Event::Init)), State::InitPage {
575                continue_token: None,
576                objects: VecDeque::default(),
577                last_bookmark: None,
578            }),
579            InitialListStrategy::StreamingList => {
580                match with_idle_timeout(
581                    api.watch(&wc.to_watch_params(WatchPhase::Initial), "0"),
582                    wc.timeout,
583                )
584                .await
585                {
586                    Some(Ok(stream)) => (Some(Ok(Event::Init)), State::InitialWatch { stream }),
587                    Some(Err(err)) => {
588                        if std::matches!(err, ClientErr::Api(ref status) if status.is_forbidden()) {
589                            warn!("watch initlist error with 403: {err:?}");
590                        } else {
591                            debug!("watch initlist error: {err:?}");
592                        }
593                        (Some(Err(Error::WatchStartFailed(err))), State::default())
594                    }
595                    None => (None, State::default()),
596                }
597            }
598        },
599        State::InitPage {
600            continue_token,
601            mut objects,
602            last_bookmark,
603        } => {
604            if let Some(next) = objects.pop_front() {
605                return (Some(Ok(Event::InitApply(next))), State::InitPage {
606                    continue_token,
607                    objects,
608                    last_bookmark,
609                });
610            }
611            // check if we need to perform more pages
612            if continue_token.is_none()
613                && let Some(resource_version) = last_bookmark
614            {
615                // we have drained the last page - move on to next stage
616                return (Some(Ok(Event::InitDone)), State::InitListed { resource_version });
617            }
618            let mut lp = wc.to_list_params();
619            lp.continue_token = continue_token;
620            match api.list(&lp).await {
621                Ok(list) => {
622                    let last_bookmark = list.metadata.resource_version.filter(|s| !s.is_empty());
623                    let continue_token = list.metadata.continue_.filter(|s| !s.is_empty());
624                    if last_bookmark.is_none() && continue_token.is_none() {
625                        return (Some(Err(Error::NoResourceVersion)), State::Empty);
626                    }
627                    // Buffer page here, causing us to return to this enum branch (State::InitPage)
628                    // until the objects buffer has drained
629                    (None, State::InitPage {
630                        continue_token,
631                        objects: list.items.into_iter().collect(),
632                        last_bookmark,
633                    })
634                }
635                Err(err) => {
636                    if std::matches!(err, ClientErr::Api(ref status) if status.is_forbidden()) {
637                        warn!("watch list error with 403: {err:?}");
638                    } else {
639                        debug!("watch list error: {err:?}");
640                    }
641                    (Some(Err(Error::InitialListFailed(err))), State::Empty)
642                }
643            }
644        }
645        State::InitialWatch { mut stream } => {
646            match next_with_idle_timeout(&mut stream, wc.timeout).await {
647                Some(Ok(WatchEvent::Added(obj) | WatchEvent::Modified(obj))) => {
648                    (Some(Ok(Event::InitApply(obj))), State::InitialWatch { stream })
649                }
650                Some(Ok(WatchEvent::Deleted(_obj))) => {
651                    // Kubernetes claims these events are impossible
652                    // https://kubernetes.io/docs/reference/using-api/api-concepts/#streaming-lists
653                    error!("got deleted event during initial watch. this is a bug");
654                    (None, State::InitialWatch { stream })
655                }
656                Some(Ok(WatchEvent::Bookmark(bm))) => {
657                    let marks_initial_end = bm.metadata.annotations.contains_key("k8s.io/initial-events-end");
658                    if marks_initial_end {
659                        (Some(Ok(Event::InitDone)), State::Watching {
660                            resource_version: bm.metadata.resource_version,
661                            stream,
662                        })
663                    } else {
664                        (None, State::InitialWatch { stream })
665                    }
666                }
667                Some(Ok(WatchEvent::Error(err))) => {
668                    // HTTP GONE, means we have desynced and need to start over and re-list :(
669                    let new_state = if err.code == 410 {
670                        State::default()
671                    } else {
672                        State::InitialWatch { stream }
673                    };
674                    if err.code == 403 {
675                        warn!("watcher watchevent error 403: {err:?}");
676                    } else {
677                        debug!("error watchevent error: {err:?}");
678                    }
679                    (Some(Err(Error::WatchError(err.boxed()))), new_state)
680                }
681                Some(Err(err)) => {
682                    if std::matches!(err, ClientErr::Api(ref status) if status.is_forbidden()) {
683                        warn!("watcher error 403: {err:?}");
684                    } else {
685                        debug!("watcher error: {err:?}");
686                    }
687                    (Some(Err(Error::WatchFailed(err))), State::InitialWatch { stream })
688                }
689                None => (None, State::default()),
690            }
691        }
692        State::InitListed { resource_version } => {
693            match with_idle_timeout(
694                api.watch(&wc.to_watch_params(WatchPhase::Resumed), &resource_version),
695                wc.timeout,
696            )
697            .await
698            {
699                Some(Ok(stream)) => (None, State::Watching {
700                    resource_version,
701                    stream,
702                }),
703                Some(Err(err)) => {
704                    if std::matches!(err, ClientErr::Api(ref status) if status.is_forbidden()) {
705                        warn!("watch initlist error with 403: {err:?}");
706                    } else {
707                        debug!("watch initlist error: {err:?}");
708                    }
709                    (Some(Err(Error::WatchStartFailed(err))), State::InitListed {
710                        resource_version,
711                    })
712                }
713                None => (None, State::InitListed { resource_version }),
714            }
715        }
716        State::Watching {
717            resource_version,
718            mut stream,
719        } => match next_with_idle_timeout(&mut stream, wc.timeout).await {
720            Some(Ok(WatchEvent::Added(obj) | WatchEvent::Modified(obj))) => {
721                let resource_version = obj.resource_version().unwrap_or_default();
722                if resource_version.is_empty() {
723                    (Some(Err(Error::NoResourceVersion)), State::default())
724                } else {
725                    (Some(Ok(Event::Apply(obj))), State::Watching {
726                        resource_version,
727                        stream,
728                    })
729                }
730            }
731            Some(Ok(WatchEvent::Deleted(obj))) => {
732                let resource_version = obj.resource_version().unwrap_or_default();
733                if resource_version.is_empty() {
734                    (Some(Err(Error::NoResourceVersion)), State::default())
735                } else {
736                    (Some(Ok(Event::Delete(obj))), State::Watching {
737                        resource_version,
738                        stream,
739                    })
740                }
741            }
742            Some(Ok(WatchEvent::Bookmark(bm))) => (None, State::Watching {
743                resource_version: bm.metadata.resource_version,
744                stream,
745            }),
746            Some(Ok(WatchEvent::Error(err))) => {
747                // HTTP GONE, means we have desynced and need to start over and re-list :(
748                let new_state = if err.code == 410 {
749                    State::default()
750                } else {
751                    State::Watching {
752                        resource_version,
753                        stream,
754                    }
755                };
756                if err.code == 403 {
757                    warn!("watcher watchevent error 403: {err:?}");
758                } else {
759                    debug!("error watchevent error: {err:?}");
760                }
761                (Some(Err(Error::WatchError(err.boxed()))), new_state)
762            }
763            Some(Err(err)) => {
764                if std::matches!(err, ClientErr::Api(ref status) if status.is_forbidden()) {
765                    warn!("watcher error 403: {err:?}");
766                } else {
767                    debug!("watcher error: {err:?}");
768                }
769                (Some(Err(Error::WatchFailed(err))), State::Watching {
770                    resource_version,
771                    stream,
772                })
773            }
774            None => (None, State::InitListed { resource_version }),
775        },
776    }
777}
778
779/// Trampoline helper for `step_trampolined`
780async fn step<A>(
781    api: &A,
782    config: &Config,
783    mut state: State<A::Value>,
784) -> (Result<Event<A::Value>>, State<A::Value>)
785where
786    A: ApiMode,
787    A::Value: Resource + 'static,
788{
789    loop {
790        match step_trampolined(api, config, state).await {
791            (Some(result), new_state) => return (result, new_state),
792            (None, new_state) => state = new_state,
793        }
794    }
795}
796
797/// Watches a Kubernetes Resource for changes continuously
798///
799/// Compared to [`Api::watch`], this automatically tries to recover the stream upon errors.
800///
801/// Errors from the underlying watch are propagated, after which the stream will go into recovery mode on the next poll.
802/// You can apply your own backoff by not polling the stream for a duration after errors.
803/// Keep in mind that some [`TryStream`](futures::TryStream) combinators (such as
804/// [`try_for_each`](futures::TryStreamExt::try_for_each) and [`try_concat`](futures::TryStreamExt::try_concat))
805/// will terminate eagerly as soon as they receive an [`Err`].
806///
807/// The events are intended to provide a safe input interface for a state store like a [`reflector`].
808/// Direct users may want to use [`WatchStreamExt`] for higher-level constructs.
809///
810/// ```
811/// use kube::{
812///   api::{Api, ResourceExt}, Client,
813///   runtime::{watcher, WatchStreamExt}
814/// };
815/// use k8s_openapi::api::core::v1::Pod;
816/// use futures::TryStreamExt;
817///
818/// # async fn wrapper() -> Result<(), watcher::Error> {
819/// #   let client: Client = todo!();
820/// let pods: Api<Pod> = Api::namespaced(client, "apps");
821///
822/// watcher(pods, watcher::Config::default()).applied_objects()
823///     .try_for_each(|p| async move {
824///         println!("Applied: {}", p.name_any());
825///        Ok(())
826///     })
827///     .await?;
828/// # Ok(())
829/// # }
830/// ```
831/// [`WatchStreamExt`]: super::WatchStreamExt
832/// [`reflector`]: super::reflector::reflector
833/// [`Api::watch`]: kube_client::Api::watch
834///
835/// # Recovery
836///
837/// The stream will attempt to be recovered on the next poll after an [`Err`] is returned.
838/// This will normally happen immediately, but you can use [`StreamBackoff`](crate::utils::StreamBackoff)
839/// to introduce an artificial delay. [`DefaultBackoff::default`] returns a suitable default set of parameters.
840///
841/// If the watch connection is interrupted, then `watcher` will attempt to restart the watch using the last
842/// [resource version](https://kubernetes.io/docs/reference/using-api/api-concepts/#efficient-detection-of-changes)
843/// that we have seen on the stream. If this is successful then the stream is simply resumed from where it left off.
844/// If this fails because the resource version is no longer valid then we start over with a new stream, starting with
845/// an [`Event::Init`]. The internals mechanics of recovery should be considered an implementation detail.
846#[doc(alias = "informer")]
847pub fn watcher<K: Resource + Clone + DeserializeOwned + Debug + Send + 'static>(
848    api: Api<K>,
849    watcher_config: Config,
850) -> impl Stream<Item = Result<Event<K>>> + Send {
851    watcher_inner(FullObject { api }, watcher_config)
852}
853
854/// [`ApiMode`] compatibility helper. Introduced later so that the core logic of [`watcher`] can be tested without
855/// having to modify its pre-existing signature.
856fn watcher_inner<A>(api: A, watcher_config: Config) -> impl Stream<Item = Result<Event<A::Value>>> + Send
857where
858    A: ApiMode,
859    A::Value: Resource,
860{
861    futures::stream::unfold(
862        (api, watcher_config, State::default()),
863        |(api, watcher_config, state)| async {
864            let (event, state) = step(&api, &watcher_config, state).await;
865            Some((event, (api, watcher_config, state)))
866        },
867    )
868}
869
870/// Watches a Kubernetes Resource for changes continuously and receives only the
871/// metadata
872///
873/// Compared to [`Api::watch_metadata`], this automatically tries to recover the stream upon errors.
874///
875/// Errors from the underlying watch are propagated, after which the stream will go into recovery mode on the next poll.
876/// You can apply your own backoff by not polling the stream for a duration after errors.
877/// Keep in mind that some [`TryStream`](futures::TryStream) combinators (such as
878/// [`try_for_each`](futures::TryStreamExt::try_for_each) and [`try_concat`](futures::TryStreamExt::try_concat))
879/// will terminate eagerly as soon as they receive an [`Err`].
880///
881/// The events are intended to provide a safe input interface for a state store like a [`reflector`].
882/// Direct users may want to use [`WatchStreamExt`] for higher-level constructs.
883///
884/// ```
885/// use kube::{
886///   api::{Api, ResourceExt}, Client,
887///   runtime::{watcher, metadata_watcher, WatchStreamExt}
888/// };
889/// use k8s_openapi::api::core::v1::Pod;
890/// use futures::TryStreamExt;
891///
892/// # async fn wrapper() -> Result<(), watcher::Error> {
893/// #   let client: Client = todo!();
894/// let pods: Api<Pod> = Api::namespaced(client, "apps");
895///
896/// metadata_watcher(pods, watcher::Config::default()).applied_objects()
897///         .try_for_each(|p| async move {
898///          println!("Applied: {}", p.name_any());
899///             Ok(())
900///         })
901///         .await?;
902/// #   Ok(())
903/// # }
904/// ```
905/// [`WatchStreamExt`]: super::WatchStreamExt
906/// [`reflector`]: super::reflector::reflector
907/// [`Api::watch`]: kube_client::Api::watch
908///
909/// # Recovery
910///
911/// The stream will attempt to be recovered on the next poll after an [`Err`] is returned.
912/// This will normally happen immediately, but you can use [`StreamBackoff`](crate::utils::StreamBackoff)
913/// to introduce an artificial delay. [`DefaultBackoff::default`] returns a suitable default set of parameters.
914///
915/// If the watch connection is interrupted, then `watcher` will attempt to restart the watch using the last
916/// [resource version](https://kubernetes.io/docs/reference/using-api/api-concepts/#efficient-detection-of-changes)
917/// that we have seen on the stream. If this is successful then the stream is simply resumed from where it left off.
918/// If this fails because the resource version is no longer valid then we start over with a new stream, starting with
919/// an [`Event::Init`]. The internals mechanics of recovery should be considered an implementation detail.
920#[deprecated(
921    since = "3.1.0",
922    note = "Use `watcher(Api::<PartialObjectMeta<K>>::all(client), config)` instead. \
923            `Api<PartialObjectMeta<K>>` now automatically uses metadata-only requests."
924)]
925pub fn metadata_watcher<K: Resource + Clone + DeserializeOwned + Debug + Send + 'static>(
926    api: Api<K>,
927    watcher_config: Config,
928) -> impl Stream<Item = Result<Event<PartialObjectMeta<K>>>> + Send {
929    watcher_inner(MetaOnly { api }, watcher_config)
930}
931
932/// Watch a single named object for updates
933///
934/// Emits `None` if the object is deleted (or not found), and `Some` if an object is updated (or created/found).
935///
936/// Often invoked indirectly via [`await_condition`](crate::wait::await_condition()).
937///
938/// ## Scope Warning
939///
940/// When using this with an `Api::all` on namespaced resources there is a chance of duplicated names.
941/// To avoid getting confusing / wrong answers for this, use `Api::namespaced` bound to a specific namespace
942/// when watching for transitions to namespaced objects.
943pub fn watch_object<K: Resource + Clone + DeserializeOwned + Debug + Send + 'static>(
944    api: Api<K>,
945    name: &str,
946) -> impl Stream<Item = Result<Option<K>>> + Send + use<K> {
947    // filtering by object name in given scope, so there's at most one matching object
948    // footgun: Api::all may generate events from namespaced objects with the same name in different namespaces
949    let fields = format!("metadata.name={name}");
950    watcher(api, Config::default().fields(&fields))
951        // The `obj_seen` state is used to track whether the object exists in each Init / InitApply / InitDone
952        // sequence of events. If the object wasn't seen in any particular sequence it is treated as deleted and
953        // `None` is emitted when the InitDone event is received.
954        //
955        // The first check ensures `None` is emitted if the object was already gone (or not found), subsequent
956        // checks ensure `None` is emitted even if for some reason the Delete event wasn't received, which
957        // could happen given K8S events aren't guaranteed delivery.
958        .scan(false, |obj_seen, event| {
959            if matches!(event, Ok(Event::Init)) {
960                *obj_seen = false;
961            } else if matches!(event, Ok(Event::InitApply(_))) {
962                *obj_seen = true;
963            }
964            future::ready(Some((*obj_seen, event)))
965        })
966        .filter_map(|(obj_seen, event)| async move {
967            match event {
968                // Pass up `Some` for Found / Updated
969                Ok(Event::Apply(obj) | Event::InitApply(obj)) => Some(Ok(Some(obj))),
970                // Pass up `None` for Deleted
971                Ok(Event::Delete(_)) => Some(Ok(None)),
972                // Pass up `None` if the object wasn't seen in the initial list
973                Ok(Event::InitDone) if !obj_seen => Some(Ok(None)),
974                // Ignore marker events
975                Ok(Event::Init | Event::InitDone) => None,
976                // Bubble up errors
977                Err(err) => Some(Err(err)),
978            }
979        })
980}
981
982/// A struct with a manually configured exponential backoff
983pub struct ExponentialBackoff {
984    inner: backon::ExponentialBackoff,
985    builder: backon::ExponentialBuilder,
986}
987
988impl ExponentialBackoff {
989    fn new(min_delay: Duration, max_delay: Duration, factor: f32, enable_jitter: bool) -> Self {
990        let builder = backon::ExponentialBuilder::default()
991            .with_min_delay(min_delay)
992            .with_max_delay(max_delay)
993            .with_factor(factor)
994            .without_max_times();
995
996        let builder = if enable_jitter {
997            builder.with_jitter()
998        } else {
999            builder
1000        };
1001
1002        Self {
1003            inner: builder.build(),
1004            builder,
1005        }
1006    }
1007}
1008
1009impl Backoff for ExponentialBackoff {
1010    fn reset(&mut self) {
1011        self.inner = self.builder.build();
1012    }
1013}
1014
1015impl Iterator for ExponentialBackoff {
1016    type Item = Duration;
1017
1018    fn next(&mut self) -> Option<Self::Item> {
1019        self.inner.next()
1020    }
1021}
1022
1023impl From<backon::ExponentialBuilder> for ExponentialBackoff {
1024    fn from(builder: backon::ExponentialBuilder) -> Self {
1025        Self {
1026            inner: builder.build(),
1027            builder,
1028        }
1029    }
1030}
1031
1032/// Default watcher backoff inspired by Kubernetes' client-go.
1033///
1034/// The parameters currently optimize for being kind to struggling apiservers.
1035/// The exact parameters are taken from
1036/// [client-go's reflector source](https://github.com/kubernetes/client-go/blob/980663e185ab6fc79163b1c2565034f6d58368db/tools/cache/reflector.go#L177-L181)
1037/// and should not be considered stable.
1038///
1039/// This struct implements [`Backoff`] and is the default strategy used
1040/// when calling `WatchStreamExt::default_backoff`. If you need to create
1041/// this manually then [`DefaultBackoff::default`] can be used.
1042pub struct DefaultBackoff(Strategy);
1043type Strategy = ResetTimerBackoff<ExponentialBackoff>;
1044
1045impl Default for DefaultBackoff {
1046    fn default() -> Self {
1047        Self(ResetTimerBackoff::new(
1048            ExponentialBackoff::new(Duration::from_millis(800), Duration::from_secs(30), 2.0, true),
1049            Duration::from_secs(120),
1050        ))
1051    }
1052}
1053
1054impl Iterator for DefaultBackoff {
1055    type Item = Duration;
1056
1057    fn next(&mut self) -> Option<Self::Item> {
1058        self.0.next()
1059    }
1060}
1061
1062impl Backoff for DefaultBackoff {
1063    fn reset(&mut self) {
1064        self.0.reset();
1065    }
1066}
1067
1068#[cfg(test)]
1069mod tests {
1070    use std::{collections::BTreeMap, time::Duration};
1071
1072    use futures::{StreamExt, TryStreamExt, stream::BoxStream};
1073    use http::{Request, Response, StatusCode, header::CONTENT_LENGTH};
1074    use http_body_util::{BodyExt, StreamBody};
1075    use k8s_openapi::{api::core::v1::ConfigMap, apimachinery::pkg::apis::meta::v1::ObjectMeta};
1076    use kube_client::{
1077        Api, Client,
1078        api::{ListParams, TypeMeta, WatchEvent, WatchParams},
1079        client::Body,
1080        core::{
1081            ObjectList, Status,
1082            watch::{Bookmark, BookmarkMeta},
1083        },
1084    };
1085
1086    use crate::{
1087        WatchStreamExt,
1088        watcher::{
1089            ApiMode, Config, Error, ExponentialBackoff, State, WatchPhase, next_with_idle_timeout, step,
1090            step_trampolined,
1091            stub_watcher::{
1092                Recording, Sequence, SequenceStep, TestMode, error_indicates_graceful_watch_seq_exhaustion,
1093            },
1094            watcher, watcher_inner,
1095        },
1096    };
1097
1098    use super::stub_watcher::ResultPage;
1099
1100    fn config_map(name: &str, resource_version: &str) -> ConfigMap {
1101        ConfigMap {
1102            metadata: ObjectMeta {
1103                name: Some(name.to_string()),
1104                resource_version: Some(resource_version.to_string()),
1105                ..ObjectMeta::default()
1106            },
1107            ..ConfigMap::default()
1108        }
1109    }
1110
1111    #[tokio::test(start_paused = true)]
1112    async fn test_mode_watch_waits_before_returning_next_event() {
1113        let api = TestMode::new(vec![], vec![Sequence::new(vec![
1114            SequenceStep::Wait(Duration::from_millis(50)),
1115            SequenceStep::List(vec![Ok(WatchEvent::Added(config_map("a", "1")))].into()),
1116        ])]);
1117        let mut stream = api.watch(&WatchParams::default(), "0").await.unwrap();
1118
1119        assert!(futures::poll!(stream.next()).is_pending());
1120        tokio::time::advance(Duration::from_millis(49)).await;
1121        assert!(futures::poll!(stream.next()).is_pending());
1122        tokio::time::advance(Duration::from_millis(1)).await;
1123
1124        assert!(matches!(
1125            stream.next().await,
1126            Some(Ok(WatchEvent::Added(config_map))) if config_map.metadata.name.as_deref() == Some("a")
1127        ));
1128    }
1129
1130    #[allow(clippy::too_many_lines)]
1131    #[tokio::test]
1132    async fn streaming_list_resync() {
1133        const LAST_VALID_RESOURCE_VERSION: &str = "5";
1134        let mut recoverable_err = Box::new(Status::default());
1135        recoverable_err.code = 502;
1136        recoverable_err.message = "some err".to_string();
1137        recoverable_err.reason = "Something went wrong".to_string();
1138        let api = TestMode::new(vec![], vec![
1139            Sequence::new(vec![
1140                SequenceStep::List(
1141                    vec![
1142                        Ok(WatchEvent::Added(config_map("a", "2"))),
1143                        Ok(WatchEvent::Added(config_map("b", "3"))),
1144                        Ok(WatchEvent::Added(config_map("c", "4"))),
1145                        // Details here: https://kubernetes.io/docs/reference/using-api/api-concepts/#streaming-lists
1146                        // Should only be sent when requested via allowWatchBookmarks=true
1147                        // Since TestMode does not contain any real logic and  is not dynamically
1148                        // progammable, this is up to the test
1149                        // author to return or not for now.
1150                        Ok(WatchEvent::Bookmark(Bookmark {
1151                            types: TypeMeta::resource::<ConfigMap>(),
1152                            metadata: BookmarkMeta {
1153                                resource_version: "4".to_string(),
1154                                annotations: BTreeMap::from_iter(vec![(
1155                                    "k8s.io/initial-events-end".into(),
1156                                    "true".into(),
1157                                )]),
1158                            },
1159                        })),
1160                    ]
1161                    .into(),
1162                ),
1163                SequenceStep::List(
1164                    vec![
1165                        Ok(WatchEvent::Modified(config_map("a", LAST_VALID_RESOURCE_VERSION))),
1166                        Ok(WatchEvent::Error(recoverable_err)),
1167                    ]
1168                    .into(),
1169                ),
1170                // After an error we expect the watcher to request its last(latest) known
1171                // resource version to be queried again.
1172                SequenceStep::List(
1173                    vec![Ok(WatchEvent::Modified(config_map(
1174                        "a",
1175                        LAST_VALID_RESOURCE_VERSION,
1176                    )))]
1177                    .into(),
1178                ),
1179            ]),
1180            // After an error we expect the watcher to request its last(latest) known
1181            // resource version to be queried again.
1182            Sequence::new(vec![SequenceStep::List(
1183                vec![
1184                    Ok(WatchEvent::Added(config_map("a", "5"))),
1185                    Ok(WatchEvent::Bookmark(Bookmark {
1186                        types: TypeMeta::resource::<ConfigMap>(),
1187                        metadata: BookmarkMeta {
1188                            resource_version: "5".to_string(),
1189                            annotations: BTreeMap::from_iter(vec![(
1190                                "k8s.io/initial-events-end".into(),
1191                                "true".into(),
1192                            )]),
1193                        },
1194                    })),
1195                ]
1196                .into(),
1197            )]),
1198        ]);
1199
1200        let config = Config::default()
1201            .timeout(1)
1202            .streaming_lists()
1203            .labels("app=test")
1204            .fields("metadata.name!=ignored");
1205        // NOTE(juf): The stream which is returned here is not the same stream that an individual `watch` result produces.
1206        // That stream is wrapped and hidden behind the inner state [`kube_runtime::watcher::State`] of the watcher implementation.
1207        let mut stream = std::pin::pin!(watcher_inner(api.clone(), config));
1208
1209        for expected in [
1210            "Init",
1211            "InitApply(a)",
1212            "InitApply(b)",
1213            "InitApply(c)",
1214            "InitDone",
1215            "Apply(a)",
1216            "error returned by apiserver during watch: some err: Something went wrong",
1217            "Apply(a)",
1218            "Apply(a)",
1219        ] {
1220            let event = stream.next().await.expect("watcher stream should not end");
1221            let repr = match event {
1222                Ok(event) => event.to_string(),
1223                Err(err) => err.to_string(),
1224            };
1225            assert_eq!(repr, expected);
1226        }
1227
1228        let event = tokio::time::timeout(Duration::from_millis(100), stream.next())
1229            .await
1230            .expect("watcher should return when the TestMode sequence is exhausted")
1231            .expect("watcher stream should not end");
1232        // See function docs for more context, we expect this error, when we want to check whether
1233        // the whole watch sequence has been consumed and as breaker to avoid consuming an infinite
1234        // async stream that returns None.
1235        dbg!(&event);
1236        assert!(event.is_err_and(|err| error_indicates_graceful_watch_seq_exhaustion(&err)),);
1237
1238        let records = api.get_recordings();
1239        match &records[..] {
1240            [
1241                Recording::Watch(initial_params, initial_version),
1242                Recording::Watch(resumed_params, resumed_version),
1243                Recording::Watch(exhausted_params, exhausted_version),
1244            ] => {
1245                assert_eq!(initial_version, "0");
1246                assert_eq!(initial_params.label_selector.as_deref(), Some("app=test"));
1247                assert_eq!(
1248                    initial_params.field_selector.as_deref(),
1249                    Some("metadata.name!=ignored")
1250                );
1251                assert!(initial_params.send_initial_events);
1252
1253                for (watch_params, watch_version) in [
1254                    (resumed_params, resumed_version),
1255                    (exhausted_params, exhausted_version),
1256                ] {
1257                    assert_eq!(watch_version, LAST_VALID_RESOURCE_VERSION);
1258                    assert_eq!(watch_params.label_selector.as_deref(), Some("app=test"));
1259                    assert_eq!(
1260                        watch_params.field_selector.as_deref(),
1261                        Some("metadata.name!=ignored")
1262                    );
1263                    assert!(!watch_params.send_initial_events);
1264                }
1265            }
1266            _ => panic!("unexpected API call sequence {records:?}"),
1267        }
1268    }
1269
1270    #[tokio::test]
1271    async fn streaming_list_init() {
1272        let api = TestMode::new(vec![], vec![Sequence::new(vec![
1273            SequenceStep::List(
1274                vec![
1275                    Ok(WatchEvent::Added(config_map("a", "2"))),
1276                    Ok(WatchEvent::Added(config_map("b", "3"))),
1277                    Ok(WatchEvent::Added(config_map("c", "4"))),
1278                    // Details here: https://kubernetes.io/docs/reference/using-api/api-concepts/#streaming-lists
1279                    // Should only be sent when requested via allowWatchBookmarks=true
1280                    // Since TestMode does not contain any real logic and  is not dynamically
1281                    // progammable, this is up to the test
1282                    // author to return or not for now.
1283                    Ok(WatchEvent::Bookmark(Bookmark {
1284                        types: TypeMeta::resource::<ConfigMap>(),
1285                        metadata: BookmarkMeta {
1286                            resource_version: "145".to_string(),
1287                            annotations: BTreeMap::from_iter(vec![(
1288                                "k8s.io/initial-events-end".into(),
1289                                "true".into(),
1290                            )]),
1291                        },
1292                    })),
1293                ]
1294                .into(),
1295            ),
1296            SequenceStep::List(
1297                vec![
1298                    Ok(WatchEvent::Modified(config_map("a", "5"))),
1299                    Ok(WatchEvent::Deleted(config_map("b", "7"))),
1300                    Ok(WatchEvent::Modified(config_map("c", "9"))),
1301                ]
1302                .into(),
1303            ),
1304        ])]);
1305
1306        let config = Config::default()
1307            .timeout(1)
1308            .streaming_lists()
1309            .labels("app=test")
1310            .fields("metadata.name!=ignored");
1311        let mut state = State::default();
1312        for expected in [
1313            "Init",
1314            "InitApply(a)",
1315            "InitApply(b)",
1316            "InitApply(c)",
1317            "InitDone",
1318            "Apply(a)",
1319            "Delete(b)",
1320            "Apply(c)",
1321        ] {
1322            let (event, next) = step(&api, &config, state).await;
1323            state = next;
1324            assert_eq!(event.unwrap().to_string(), expected);
1325        }
1326
1327        let (event, _) = tokio::time::timeout(Duration::from_millis(100), step(&api, &config, state))
1328            .await
1329            .expect("step should return when the TestMode sequence is exhausted");
1330        // See function docs for more context, we expect this error, when we want to check whether
1331        // the whole watch sequence has been consumed and as breaker to avoid consuming an infinite
1332        // async stream that returns None.
1333        assert!(event.is_err_and(|err| error_indicates_graceful_watch_seq_exhaustion(&err)));
1334
1335        let records = api.get_recordings();
1336        match &records[..] {
1337            [
1338                Recording::Watch(initial_params, initial_version),
1339                Recording::Watch(resumed_params, resumed_version),
1340            ] => {
1341                assert_eq!(initial_version, "0");
1342                assert_eq!(initial_params.label_selector.as_deref(), Some("app=test"));
1343                assert_eq!(
1344                    initial_params.field_selector.as_deref(),
1345                    Some("metadata.name!=ignored")
1346                );
1347                assert!(initial_params.send_initial_events);
1348
1349                assert_eq!(resumed_version, "9");
1350                assert_eq!(resumed_params.label_selector.as_deref(), Some("app=test"));
1351                assert_eq!(
1352                    resumed_params.field_selector.as_deref(),
1353                    Some("metadata.name!=ignored")
1354                );
1355                assert!(!resumed_params.send_initial_events);
1356            }
1357            _ => panic!("unexpected API call sequence {records:?}"),
1358        }
1359    }
1360
1361    #[tokio::test]
1362    async fn streaming_list_initial_stream_eof_before_bookmark_drops_partial_objects() {
1363        let api = TestMode::new(vec![], vec![
1364            Sequence::new(vec![SequenceStep::List(
1365                vec![
1366                    Ok(WatchEvent::Added(config_map("a", "1"))),
1367                    Ok(WatchEvent::Added(config_map("b", "2"))),
1368                ]
1369                .into(),
1370            )]),
1371            Sequence::new(vec![SequenceStep::List(
1372                vec![
1373                    Ok(WatchEvent::Added(config_map("a", "1"))),
1374                    Ok(WatchEvent::Bookmark(Bookmark {
1375                        types: TypeMeta::resource::<ConfigMap>(),
1376                        metadata: BookmarkMeta {
1377                            resource_version: "1".to_string(),
1378                            annotations: BTreeMap::from_iter(vec![(
1379                                "k8s.io/initial-events-end".into(),
1380                                "true".into(),
1381                            )]),
1382                        },
1383                    })),
1384                ]
1385                .into(),
1386            )]),
1387        ]);
1388
1389        let config = Config::default().streaming_lists();
1390        let (reader, mut writer) = crate::reflector::store::<ConfigMap>();
1391        let mut state = State::default();
1392        for expected in [
1393            "Init",
1394            "InitApply(a)",
1395            "InitApply(b)",
1396            "Init",
1397            "InitApply(a)",
1398            "InitDone",
1399        ] {
1400            let (event, next) = step(&api, &config, state).await;
1401            state = next;
1402            let event = event.unwrap();
1403            assert_eq!(event.to_string(), expected);
1404            writer.apply_watcher_event(&event);
1405        }
1406
1407        let mut names: Vec<_> = reader
1408            .state()
1409            .iter()
1410            .filter_map(|cm| cm.metadata.name.clone())
1411            .collect();
1412        names.sort();
1413        assert_eq!(names, ["a".to_string()]);
1414
1415        let records = api.get_recordings();
1416        match &records[..] {
1417            [
1418                Recording::Watch(first, first_version),
1419                Recording::Watch(second, second_version),
1420            ] => {
1421                assert_eq!(first_version, "0");
1422                assert!(first.send_initial_events);
1423                assert_eq!(second_version, "0");
1424                assert!(second.send_initial_events);
1425            }
1426            _ => panic!("unexpected API call sequence {records:?}"),
1427        }
1428    }
1429
1430    #[tokio::test]
1431    async fn streaming_list_initial_watch_410_before_bookmark_drops_partial_objects() {
1432        let mut gone = Box::new(Status::default());
1433        gone.code = 410;
1434        gone.message = "expired".to_string();
1435        gone.reason = "Expired".to_string();
1436        let api = TestMode::new(vec![], vec![
1437            Sequence::new(vec![SequenceStep::List(
1438                vec![
1439                    Ok(WatchEvent::Added(config_map("a", "1"))),
1440                    Ok(WatchEvent::Added(config_map("b", "2"))),
1441                    Ok(WatchEvent::Error(gone)),
1442                ]
1443                .into(),
1444            )]),
1445            Sequence::new(vec![SequenceStep::List(
1446                vec![
1447                    Ok(WatchEvent::Added(config_map("a", "1"))),
1448                    Ok(WatchEvent::Bookmark(Bookmark {
1449                        types: TypeMeta::resource::<ConfigMap>(),
1450                        metadata: BookmarkMeta {
1451                            resource_version: "1".to_string(),
1452                            annotations: BTreeMap::from_iter(vec![(
1453                                "k8s.io/initial-events-end".into(),
1454                                "true".into(),
1455                            )]),
1456                        },
1457                    })),
1458                ]
1459                .into(),
1460            )]),
1461        ]);
1462
1463        let config = Config::default().streaming_lists();
1464        let (reader, mut writer) = crate::reflector::store::<ConfigMap>();
1465        let mut state = State::default();
1466        for expected in [
1467            "Init",
1468            "InitApply(a)",
1469            "InitApply(b)",
1470            "error returned by apiserver during watch: expired: Expired",
1471            "Init",
1472            "InitApply(a)",
1473            "InitDone",
1474        ] {
1475            let (event, next) = step(&api, &config, state).await;
1476            state = next;
1477            let repr = match &event {
1478                Ok(event) => event.to_string(),
1479                Err(err) => err.to_string(),
1480            };
1481            assert_eq!(repr, expected);
1482            if let Ok(event) = &event {
1483                writer.apply_watcher_event(event);
1484            }
1485        }
1486
1487        let mut names: Vec<_> = reader
1488            .state()
1489            .iter()
1490            .filter_map(|cm| cm.metadata.name.clone())
1491            .collect();
1492        names.sort();
1493        assert_eq!(names, ["a".to_string()]);
1494
1495        let records = api.get_recordings();
1496        match &records[..] {
1497            [
1498                Recording::Watch(first, first_version),
1499                Recording::Watch(second, second_version),
1500            ] => {
1501                assert_eq!(first_version, "0");
1502                assert!(first.send_initial_events);
1503                assert_eq!(second_version, "0");
1504                assert!(second.send_initial_events);
1505            }
1506            _ => panic!("unexpected API call sequence {records:?}"),
1507        }
1508    }
1509
1510    #[tokio::test]
1511    async fn listwatch_paginates_initial_list_before_starting_watch() {
1512        let api = TestMode::new(
1513            vec![
1514                Ok(ResultPage::empty()
1515                    .items(vec![config_map("a", "1")])
1516                    .continue_token("first".into())
1517                    .into()),
1518                Ok(ResultPage::empty()
1519                    .items(vec![config_map("b", "2")])
1520                    .resource_version("2".into())
1521                    .continue_token("second".into())
1522                    .into()),
1523                Ok(ResultPage::empty()
1524                    .items(vec![config_map("c", "3")])
1525                    .resource_version("3".into())
1526                    .into()),
1527            ],
1528            vec![Sequence::new(vec![SequenceStep::List(
1529                vec![Ok(WatchEvent::Added(config_map("d", "4")))].into(),
1530            )])],
1531        );
1532
1533        let config = Config::default()
1534            .page_size(1)
1535            .labels("app=test")
1536            .fields("metadata.name!=ignored");
1537        let mut state = State::default();
1538
1539        let (event, next) = step(&api, &config, state).await;
1540        state = next;
1541        assert_eq!(event.unwrap().to_string(), "Init");
1542
1543        let (event, next) = step(&api, &config, state).await;
1544        state = next;
1545        assert_eq!(event.unwrap().to_string(), "InitApply(a)");
1546
1547        let (event, next) = step(&api, &config, state).await;
1548        state = next;
1549        assert_eq!(event.unwrap().to_string(), "InitApply(b)");
1550
1551        let (event, next) = step(&api, &config, state).await;
1552        state = next;
1553        assert_eq!(event.unwrap().to_string(), "InitApply(c)");
1554
1555        let (event, next) = step(&api, &config, state).await;
1556        state = next;
1557        assert_eq!(event.unwrap().to_string(), "InitDone");
1558
1559        let (event, _) = step(&api, &config, state).await;
1560        assert_eq!(event.unwrap().to_string(), "Apply(d)");
1561
1562        let records = api.get_recordings();
1563        match &records[..] {
1564            [
1565                Recording::List(first),
1566                Recording::List(second),
1567                Recording::List(third),
1568                Recording::Watch(watch_params, watch_version),
1569            ] => {
1570                assert_eq!(first.continue_token.as_deref(), None);
1571                assert_eq!(second.continue_token.as_deref(), Some("first"));
1572                assert_eq!(third.continue_token.as_deref(), Some("second"));
1573
1574                assert_eq!(first.limit, Some(1));
1575                assert_eq!(first.label_selector.as_deref(), Some("app=test"));
1576                assert_eq!(first.field_selector.as_deref(), Some("metadata.name!=ignored"));
1577
1578                assert_eq!(watch_version, "3");
1579                assert_eq!(watch_params.label_selector.as_deref(), Some("app=test"));
1580                assert_eq!(
1581                    watch_params.field_selector.as_deref(),
1582                    Some("metadata.name!=ignored")
1583                );
1584                assert!(!watch_params.send_initial_events);
1585            }
1586            _ => panic!("unexpected API call sequence"),
1587        }
1588    }
1589
1590    #[test]
1591    fn to_watch_params_initial_phase_with_streaming_list_sets_send_initial_events() {
1592        let config = Config::default().streaming_lists();
1593        let params = config.to_watch_params(WatchPhase::Initial);
1594        assert!(params.send_initial_events);
1595    }
1596
1597    #[test]
1598    fn to_watch_params_resumed_phase_with_streaming_list_does_not_set_send_initial_events() {
1599        let config = Config::default().streaming_lists();
1600        let params = config.to_watch_params(WatchPhase::Resumed);
1601        assert!(!params.send_initial_events);
1602    }
1603
1604    #[test]
1605    fn to_watch_params_listwatch_mode_does_not_set_send_initial_events() {
1606        let config = Config::default(); // ListWatch mode
1607        let params_initial = config.to_watch_params(WatchPhase::Initial);
1608        let params_resumed = config.to_watch_params(WatchPhase::Resumed);
1609        assert!(!params_initial.send_initial_events);
1610        assert!(!params_resumed.send_initial_events);
1611    }
1612
1613    fn approx_eq(a: Duration, b: Duration) -> bool {
1614        a.abs_diff(b) < Duration::from_micros(100)
1615    }
1616
1617    #[test]
1618    fn exponential_backoff_without_jitter() {
1619        let mut backoff =
1620            ExponentialBackoff::new(Duration::from_millis(100), Duration::from_secs(1), 2.0, false);
1621
1622        assert!(approx_eq(backoff.next().unwrap(), Duration::from_millis(100)));
1623        assert!(approx_eq(backoff.next().unwrap(), Duration::from_millis(200)));
1624        assert!(approx_eq(backoff.next().unwrap(), Duration::from_millis(400)));
1625    }
1626
1627    #[test]
1628    fn exponential_backoff_with_jitter_applies_randomness() {
1629        let mut backoff =
1630            ExponentialBackoff::new(Duration::from_millis(100), Duration::from_secs(1), 2.0, true);
1631
1632        let delays: Vec<_> = (0..5).filter_map(|_| backoff.next()).collect();
1633
1634        // All delays should be positive
1635        for d in &delays {
1636            assert!(*d > Duration::ZERO);
1637        }
1638
1639        // With jitter, at least one delay should differ from exact values
1640        let exact_values = [
1641            Duration::from_millis(100),
1642            Duration::from_millis(200),
1643            Duration::from_millis(400),
1644            Duration::from_millis(800),
1645            Duration::from_secs(1),
1646        ];
1647
1648        let all_exact = delays
1649            .iter()
1650            .zip(exact_values.iter())
1651            .all(|(d, e)| approx_eq(*d, *e));
1652
1653        assert!(
1654            !all_exact,
1655            "With jitter enabled, delays should not all match exact exponential values"
1656        );
1657    }
1658
1659    #[tokio::test(start_paused = true)]
1660    async fn idle_timeout_returns_item_when_stream_has_data() {
1661        let mut stream = futures::stream::iter(vec![1, 2, 3]);
1662        let result = next_with_idle_timeout(&mut stream, Some(290)).await;
1663        assert_eq!(result, Some(1));
1664    }
1665
1666    #[tokio::test(start_paused = true)]
1667    async fn zero_timeout_does_not_trigger_idle_timeout() {
1668        let mut stream = futures::stream::once(async {
1669            tokio::time::sleep(Duration::from_secs(6)).await;
1670            42
1671        })
1672        .boxed();
1673
1674        let result = next_with_idle_timeout(&mut stream, Some(0)).await;
1675        assert_eq!(result, Some(42));
1676    }
1677
1678    #[tokio::test(start_paused = true)]
1679    async fn idle_timeout_returns_none_on_dead_connection() {
1680        let mut stream = futures::stream::pending::<i32>();
1681        // NB tokio auto-advances virtual time when the runtime is idle so next_with_idle_timeout resolves immediately
1682        let result = next_with_idle_timeout(&mut stream, Some(290)).await;
1683        assert_eq!(result, None);
1684    }
1685
1686    #[tokio::test(start_paused = true)]
1687    async fn idle_timeout_returns_none_when_stream_ends() {
1688        let mut stream = futures::stream::empty::<i32>();
1689        let result = next_with_idle_timeout(&mut stream, Some(290)).await;
1690        assert_eq!(result, None);
1691    }
1692
1693    /// Never answers, like an error response whose body stalls
1694    struct StalledWatchCall;
1695
1696    impl ApiMode for StalledWatchCall {
1697        type Value = ConfigMap;
1698
1699        async fn list(&self, _lp: &ListParams) -> kube_client::Result<ObjectList<ConfigMap>> {
1700            futures::future::pending().await
1701        }
1702
1703        async fn watch(
1704            &self,
1705            _wp: &WatchParams,
1706            _version: &str,
1707        ) -> kube_client::Result<BoxStream<'static, kube_client::Result<WatchEvent<ConfigMap>>>> {
1708            futures::future::pending().await
1709        }
1710    }
1711
1712    #[tokio::test(start_paused = true)]
1713    async fn idle_timeout_retries_stalled_watch_call() {
1714        // timeout(1) plus the 5s margin, so an unbounded watch call trips the outer 7s limit
1715        let config = Config::default().timeout(1);
1716        let limit = Duration::from_secs(7);
1717        let state = State::InitListed {
1718            resource_version: "1".into(),
1719        };
1720        let start = tokio::time::Instant::now();
1721        let (event, state) = tokio::time::timeout(limit, step_trampolined(&StalledWatchCall, &config, state))
1722            .await
1723            .expect("stalled resumed watch call should hit the idle timeout");
1724        assert_eq!(start.elapsed(), Duration::from_secs(6));
1725        assert!(event.is_none());
1726        assert!(matches!(state, State::InitListed { resource_version } if resource_version == "1"));
1727
1728        let config = config.streaming_lists();
1729        let start = tokio::time::Instant::now();
1730        let (event, state) =
1731            tokio::time::timeout(limit, step_trampolined(&StalledWatchCall, &config, State::Empty))
1732                .await
1733                .expect("stalled initial watch call should hit the idle timeout");
1734        assert_eq!(start.elapsed(), Duration::from_secs(6));
1735        assert!(event.is_none());
1736        assert!(matches!(state, State::Empty));
1737    }
1738
1739    /// Serves an empty LIST, then a watch rejected with HTTP 500 whose pretty-printed `Status`
1740    /// body is held back by `error_body_delay` (forever when `None`), then watches with one event.
1741    fn stalled_error_client(error_body_delay: Option<Duration>) -> Client {
1742        let mut watches = 0;
1743        let service = tower::service_fn(move |request: Request<Body>| {
1744            let (status, body) = if request.uri().query().unwrap_or_default().contains("watch=true") {
1745                watches += 1;
1746                if watches == 1 {
1747                    let rejection = serde_json::json!({
1748                        "kind": "Status",
1749                        "apiVersion": "v1",
1750                        "status": "Failure",
1751                        "message": "watch rejected",
1752                        "reason": "InternalError",
1753                        "code": 500,
1754                    });
1755                    (
1756                        StatusCode::INTERNAL_SERVER_ERROR,
1757                        serde_json::to_vec_pretty(&rejection).unwrap(),
1758                    )
1759                } else {
1760                    let event = WatchEvent::Added(config_map("a", "11"));
1761                    (StatusCode::OK, serde_json::to_vec(&event).unwrap())
1762                }
1763            } else {
1764                let list = serde_json::json!({
1765                    "kind": "ConfigMapList",
1766                    "apiVersion": "v1",
1767                    "metadata": { "resourceVersion": "10" },
1768                    "items": [],
1769                });
1770                (StatusCode::OK, serde_json::to_vec(&list).unwrap())
1771            };
1772            let stall = status.is_server_error();
1773            let length = body.len();
1774            let frames = Body::from(body).into_stream().then(move |frame| async move {
1775                if stall {
1776                    match error_body_delay {
1777                        Some(delay) => tokio::time::sleep(delay).await,
1778                        None => futures::future::pending().await,
1779                    }
1780                }
1781                frame
1782            });
1783            std::future::ready(Ok::<_, std::convert::Infallible>(
1784                Response::builder()
1785                    .status(status)
1786                    .header(CONTENT_LENGTH, length)
1787                    .body(StreamBody::new(frames))
1788                    .unwrap(),
1789            ))
1790        });
1791        Client::new(service, "default")
1792    }
1793
1794    #[tokio::test(start_paused = true)]
1795    async fn watcher_recovers_from_stalled_error_body() {
1796        let api = Api::<ConfigMap>::default_namespaced(stalled_error_client(None));
1797        let start = tokio::time::Instant::now();
1798        // try_collect stops at the first Err, like the try_for_each pipelines in the docs
1799        let applied = watcher(api, Config::default().timeout(1))
1800            .applied_objects()
1801            .default_backoff()
1802            .take(1)
1803            .try_collect::<Vec<_>>();
1804        let applied = tokio::time::timeout(Duration::from_secs(7), applied)
1805            .await
1806            .expect("stalled error body should hit the 6s idle timeout")
1807            .expect("watcher should reconnect without surfacing an error");
1808        assert_eq!(applied[0].metadata.name.as_deref(), Some("a"));
1809        assert_eq!(start.elapsed(), Duration::from_secs(6));
1810    }
1811
1812    #[tokio::test(start_paused = true)]
1813    async fn watcher_keeps_slow_error_body_as_api_error() {
1814        // completes inside the 6s idle timeout, and with the idle timeout disabled
1815        for (timeout, delay) in [(1, 1), (0, 7)] {
1816            let delay = Duration::from_secs(delay);
1817            let api = Api::<ConfigMap>::default_namespaced(stalled_error_client(Some(delay)));
1818            let start = tokio::time::Instant::now();
1819            let collected = watcher(api, Config::default().timeout(timeout))
1820                .applied_objects()
1821                .take(1)
1822                .try_collect::<Vec<_>>();
1823            let err = tokio::time::timeout(delay + Duration::from_secs(1), collected)
1824                .await
1825                .expect("error body should arrive after its delay")
1826                .unwrap_err();
1827            assert!(
1828                matches!(&err, Error::WatchStartFailed(kube_client::Error::Api(status))
1829                    if status.code == 500 && status.message == "watch rejected"),
1830                "got {err:?}"
1831            );
1832            assert_eq!(start.elapsed(), delay);
1833        }
1834    }
1835}