kube_runtime/utils/watch_ext.rs
1use crate::{
2 utils::{
3 event_decode::EventDecode,
4 event_modify::EventModify,
5 predicate::{Predicate, PredicateFilter},
6 stream_backoff::StreamBackoff,
7 },
8 watcher,
9};
10use kube_client::Resource;
11
12use crate::{
13 reflector::store::Writer,
14 utils::{Backoff, Reflect},
15};
16
17use crate::watcher::DefaultBackoff;
18use futures::{Stream, TryStream};
19
20/// Extension trait for streams returned by [`watcher`](watcher()) or [`reflector`](crate::reflector::reflector)
21pub trait WatchStreamExt: Stream {
22 /// Apply the [`DefaultBackoff`] watcher [`Backoff`] policy
23 ///
24 /// This is recommended for controllers that want to play nicely with the apiserver.
25 fn default_backoff(self) -> StreamBackoff<Self, DefaultBackoff>
26 where
27 Self: TryStream + Sized,
28 {
29 StreamBackoff::new(self, DefaultBackoff::default())
30 }
31
32 /// Apply a specific [`Backoff`] policy to a [`Stream`] using [`StreamBackoff`]
33 fn backoff<B>(self, b: B) -> StreamBackoff<Self, B>
34 where
35 B: Backoff,
36 Self: TryStream + Sized,
37 {
38 StreamBackoff::new(self, b)
39 }
40
41 /// Decode a [`watcher()`] stream into a stream of applied objects
42 ///
43 /// All Added/Modified events are passed through, and critical errors bubble up.
44 fn applied_objects<K>(self) -> EventDecode<Self>
45 where
46 Self: Stream<Item = Result<watcher::Event<K>, watcher::Error>> + Sized,
47 {
48 EventDecode::new(self, false)
49 }
50
51 /// Decode a [`watcher()`] stream into a stream of touched objects
52 ///
53 /// All Added/Modified/Deleted events are passed through, and critical errors bubble up.
54 fn touched_objects<K>(self) -> EventDecode<Self>
55 where
56 Self: Stream<Item = Result<watcher::Event<K>, watcher::Error>> + Sized,
57 {
58 EventDecode::new(self, true)
59 }
60
61 /// Modify elements of a [`watcher()`] stream.
62 ///
63 /// Calls [`watcher::Event::modify()`] on every element.
64 /// Stream shorthand for `stream.map_ok(|event| { event.modify(f) })`.
65 ///
66 /// ```no_run
67 /// # use std::pin::pin;
68 /// # use futures::{Stream, StreamExt, TryStreamExt};
69 /// # use kube::{Api, Client, ResourceExt};
70 /// # use kube_runtime::{watcher, WatchStreamExt};
71 /// # use k8s_openapi::api::apps::v1::Deployment;
72 /// # async fn wrapper() -> Result<(), Box<dyn std::error::Error>> {
73 /// # let client: kube::Client = todo!();
74 /// let deploys: Api<Deployment> = Api::all(client);
75 /// let mut truncated_deploy_stream = pin!(watcher(deploys, watcher::Config::default())
76 /// .modify(|deploy| {
77 /// deploy.managed_fields_mut().clear();
78 /// deploy.status = None;
79 /// })
80 /// .applied_objects());
81 ///
82 /// while let Some(d) = truncated_deploy_stream.try_next().await? {
83 /// println!("Truncated Deployment: '{:?}'", serde_json::to_string(&d)?);
84 /// }
85 /// # Ok(())
86 /// # }
87 /// ```
88 fn modify<F, K>(self, f: F) -> EventModify<Self, F>
89 where
90 Self: Stream<Item = Result<watcher::Event<K>, watcher::Error>> + Sized,
91 F: FnMut(&mut K),
92 {
93 EventModify::new(self, f)
94 }
95
96 /// Filter a stream based on on [`predicates`](crate::predicates).
97 ///
98 /// This will filter out repeat calls where the predicate returns the same result.
99 /// Common use case for this is to avoid repeat events for status updates
100 /// by filtering on [`predicates::generation`](crate::predicates::generation).
101 ///
102 /// ## Usage
103 /// ```no_run
104 /// # use std::pin::pin;
105 /// # use futures::{Stream, StreamExt, TryStreamExt};
106 /// use kube::{Api, Client, ResourceExt};
107 /// use kube_runtime::{watcher, WatchStreamExt, predicates};
108 /// use k8s_openapi::api::apps::v1::Deployment;
109 /// # async fn wrapper() -> Result<(), Box<dyn std::error::Error>> {
110 /// # let client: kube::Client = todo!();
111 /// let deploys: Api<Deployment> = Api::default_namespaced(client);
112 /// let mut changed_deploys = pin!(watcher(deploys, watcher::Config::default())
113 /// .applied_objects()
114 /// .predicate_filter(predicates::generation));
115 ///
116 /// while let Some(d) = changed_deploys.try_next().await? {
117 /// println!("saw Deployment '{} with hitherto unseen generation", d.name_any());
118 /// }
119 /// # Ok(())
120 /// # }
121 /// ```
122 fn predicate_filter<K, P>(self, predicate: P) -> PredicateFilter<Self, K, P>
123 where
124 Self: Stream<Item = Result<K, watcher::Error>> + Sized,
125 K: Resource + 'static,
126 P: Predicate<K> + 'static,
127 {
128 PredicateFilter::new(self, predicate)
129 }
130
131 /// Reflect a [`watcher()`] stream into a [`Store`] through a [`Writer`]
132 ///
133 /// Returns the stream unmodified, but passes every [`watcher::Event`] through a [`Writer`].
134 /// This populates a [`Store`] as the stream is polled.
135 ///
136 /// ## Usage
137 /// ```no_run
138 /// # use futures::{Stream, StreamExt, TryStreamExt};
139 /// # use std::time::Duration;
140 /// # use tracing::{info, warn};
141 /// use kube::{Api, Client, ResourceExt};
142 /// use kube_runtime::{watcher, WatchStreamExt, reflector};
143 /// use k8s_openapi::api::apps::v1::Deployment;
144 /// # async fn wrapper() -> Result<(), Box<dyn std::error::Error>> {
145 /// # let client: kube::Client = todo!();
146 ///
147 /// let deploys: Api<Deployment> = Api::default_namespaced(client);
148 /// let (reader, writer) = reflector::store::<Deployment>();
149 ///
150 /// tokio::spawn(async move {
151 /// // start polling the store once the reader is ready
152 /// reader.wait_until_ready().await.unwrap();
153 /// loop {
154 /// let names = reader.state().iter().map(|d| d.name_any()).collect::<Vec<_>>();
155 /// info!("Current {} deploys: {:?}", names.len(), names);
156 /// tokio::time::sleep(Duration::from_secs(10)).await;
157 /// }
158 /// });
159 ///
160 /// // configure the watcher stream and populate the store while polling
161 /// watcher(deploys, watcher::Config::default())
162 /// .reflect(writer)
163 /// .applied_objects()
164 /// .for_each(|res| async move {
165 /// match res {
166 /// Ok(o) => info!("saw {}", o.name_any()),
167 /// Err(e) => warn!("watcher error: {}", e),
168 /// }
169 /// })
170 /// .await;
171 ///
172 /// # Ok(())
173 /// # }
174 /// ```
175 ///
176 /// [`Store`]: crate::reflector::Store
177 fn reflect<K>(self, writer: Writer<K>) -> Reflect<Self, K>
178 where
179 Self: Stream<Item = watcher::Result<watcher::Event<K>>> + Sized,
180 K: Resource + Clone + 'static,
181 K::DynamicType: Eq + std::hash::Hash + Clone,
182 {
183 Reflect::new(self, writer)
184 }
185
186 /// Reflect a shared [`watcher()`] stream into a [`Store`] through a [`Writer`]
187 ///
188 /// Returns the stream unmodified, but passes every [`watcher::Event`]
189 /// through a [`Writer`]. This populates a [`Store`] as the stream is
190 /// polled. When the [`watcher::Event`] is not an error or a
191 /// [`watcher::Event::Deleted`] then its inner object will also be
192 /// propagated to subscribers.
193 ///
194 /// Subscribers can be created by calling [`subscribe()`] on a [`Writer`].
195 /// This will return a [`ReflectHandle`] stream that should be polled
196 /// independently. When the root stream is dropped, or it ends, all [`ReflectHandle`]s
197 /// subscribed to the stream will also terminate after all events yielded by
198 /// the root stream have been observed. This means [`ReflectHandle`] streams
199 /// can still be polled after the root stream has been dropped.
200 ///
201 /// **NB**: This adapter requires an
202 /// [`unstable`](https://github.com/kube-rs/kube/blob/main/kube-runtime/Cargo.toml#L17-L21)
203 /// feature
204 ///
205 /// ## Warning
206 ///
207 /// If the root [`Stream`] is not polled, [`ReflectHandle`] streams will
208 /// never receive any events. This will cause the streams to deadlock since
209 /// the root stream will apply backpressure when downstream readers are not
210 /// consuming events.
211 ///
212 ///
213 /// [`Store`]: crate::reflector::Store
214 /// [`subscribe()`]: crate::reflector::store::Writer::subscribe()
215 /// [`Stream`]: futures::stream::Stream
216 /// [`ReflectHandle`]: crate::reflector::dispatcher::ReflectHandle
217 /// ## Usage
218 /// ```no_run
219 /// # use futures::StreamExt;
220 /// # use std::time::Duration;
221 /// # use tracing::{info, warn};
222 /// use kube::{Api, ResourceExt};
223 /// use kube_runtime::{watcher, WatchStreamExt, reflector};
224 /// use k8s_openapi::api::apps::v1::Deployment;
225 /// # async fn wrapper() -> Result<(), Box<dyn std::error::Error>> {
226 /// # let client: kube::Client = todo!();
227 ///
228 /// let deploys: Api<Deployment> = Api::default_namespaced(client);
229 /// let subscriber_buf_sz = 100;
230 /// let (reader, writer) = reflector::store_shared::<Deployment>(subscriber_buf_sz);
231 /// let subscriber = writer.subscribe().unwrap();
232 ///
233 /// tokio::spawn(async move {
234 /// // start polling the store once the reader is ready
235 /// reader.wait_until_ready().await.unwrap();
236 /// loop {
237 /// let names = reader.state().iter().map(|d| d.name_any()).collect::<Vec<_>>();
238 /// info!("Current {} deploys: {:?}", names.len(), names);
239 /// tokio::time::sleep(Duration::from_secs(10)).await;
240 /// }
241 /// });
242 ///
243 /// tokio::spawn(async move {
244 /// // subscriber can be used to receive applied_objects
245 /// subscriber.for_each(|obj| async move {
246 /// info!("saw in subscriber {}", &obj.name_any())
247 /// }).await;
248 /// });
249 ///
250 /// // configure the watcher stream and populate the store while polling
251 /// watcher(deploys, watcher::Config::default())
252 /// .reflect_shared(writer)
253 /// .applied_objects()
254 /// .for_each(|res| async move {
255 /// match res {
256 /// Ok(o) => info!("saw in root stream {}", o.name_any()),
257 /// Err(e) => warn!("watcher error in root stream: {}", e),
258 /// }
259 /// })
260 /// .await;
261 ///
262 /// # Ok(())
263 /// # }
264 /// ```
265 #[cfg(feature = "unstable-runtime-subscribe")]
266 fn reflect_shared<K>(self, writer: Writer<K>) -> impl Stream<Item = Self::Item>
267 where
268 Self: Stream<Item = watcher::Result<watcher::Event<K>>> + Sized,
269 K: Resource + Clone + 'static,
270 K::DynamicType: Eq + std::hash::Hash + Clone,
271 {
272 crate::reflector(writer, self)
273 }
274}
275
276impl<St: ?Sized> WatchStreamExt for St where St: Stream {}
277
278// Compile tests
279#[cfg(test)]
280pub(crate) mod tests {
281 use super::watcher;
282 use crate::{predicates, WatchStreamExt as _};
283 use futures::prelude::*;
284 use k8s_openapi::api::core::v1::Pod;
285 use kube_client::{Api, Resource};
286
287 fn compile_type<T>() -> T {
288 unimplemented!("not called - compile test only")
289 }
290
291 pub fn assert_stream<T, K>(x: T) -> T
292 where
293 T: Stream<Item = watcher::Result<K>> + Send,
294 K: Resource + Clone + Send + 'static,
295 {
296 x
297 }
298
299 // not #[test] because this is only a compile check verification
300 #[allow(dead_code, unused_must_use)]
301 fn test_watcher_stream_type_drift() {
302 let pred_watch = watcher(compile_type::<Api<Pod>>(), Default::default())
303 .touched_objects()
304 .predicate_filter(predicates::generation)
305 .boxed();
306 assert_stream(pred_watch);
307 }
308}