kube_runtime/utils/predicate.rs
1use crate::watcher::Error;
2use core::{
3 pin::Pin,
4 task::{Context, Poll, ready},
5};
6use futures::Stream;
7use kube_client::{Resource, api::ObjectMeta};
8use pin_project::pin_project;
9use std::{
10 collections::{
11 HashMap,
12 hash_map::{DefaultHasher, Entry},
13 },
14 hash::{Hash, Hasher},
15 marker::PhantomData,
16 time::Duration,
17};
18use tokio::time::Instant;
19
20fn hash<T: Hash + ?Sized>(t: &T) -> u64 {
21 let mut hasher = DefaultHasher::new();
22 t.hash(&mut hasher);
23 hasher.finish()
24}
25
26/// Private cache key that includes UID in equality for predicate filtering
27#[derive(Debug, Clone, PartialEq, Eq, Hash)]
28struct PredicateCacheKey {
29 name: String,
30 namespace: Option<String>,
31 uid: Option<String>,
32}
33
34impl From<&ObjectMeta> for PredicateCacheKey {
35 fn from(meta: &ObjectMeta) -> Self {
36 Self {
37 name: meta.name.clone().unwrap_or_default(),
38 namespace: meta.namespace.clone(),
39 uid: meta.uid.clone(),
40 }
41 }
42}
43
44/// A predicate is a hasher of Kubernetes objects stream filtering
45pub trait Predicate<K> {
46 /// A predicate only needs to implement optional hashing when keys exist
47 fn hash_property(&self, obj: &K) -> Option<u64>;
48
49 /// Returns a `Predicate` that falls back to an alternate property if the first does not exist
50 ///
51 /// The alternate predicate is only used when the first returns `None`, not when its
52 /// hash is unchanged. In particular, `generation.fallback(resource_version)` can still
53 /// suppress deletions for objects with an unchanged generation.
54 ///
55 /// Generation support generally depends on the resource type: Deployments and custom
56 /// resources normally populate it, while `ConfigMaps` and Secrets normally do not.
57 /// Thus, `generation.fallback(resource_version)` is useful as a shared policy across
58 /// resource types, but the fallback is redundant for a type known to always provide
59 /// generation. Generation is not normally a field that appears and disappears over
60 /// an object's lifetime, though support can vary by API implementation and version.
61 ///
62 /// Persisted objects returned by ordinary API-server list/watch requests have a
63 /// resource version, so reversing the order to `resource_version.fallback(generation)`
64 /// generally makes the generation fallback redundant. Locally constructed objects
65 /// and non-persisted API responses need not have a resource version.
66 ///
67 /// # Usage
68 ///
69 /// ```
70 /// # use k8s_openapi::api::core::v1::Pod;
71 /// use kube::runtime::{predicates, Predicate};
72 /// # fn blah<K>(a: impl Predicate<K>) {}
73 /// let pred = predicates::generation.fallback(predicates::resource_version);
74 /// blah::<Pod>(pred);
75 /// ```
76 fn fallback<F: Predicate<K>>(self, f: F) -> Fallback<Self, F>
77 where
78 Self: Sized,
79 {
80 Fallback(self, f)
81 }
82
83 /// Returns a `Predicate` that combines all available hashes
84 ///
85 /// # Usage
86 ///
87 /// ```
88 /// # use k8s_openapi::api::core::v1::Pod;
89 /// use kube::runtime::{predicates, Predicate};
90 /// # fn blah<K>(a: impl Predicate<K>) {}
91 /// let pred = predicates::labels.combine(predicates::annotations);
92 /// blah::<Pod>(pred);
93 /// ```
94 fn combine<F: Predicate<K>>(self, f: F) -> Combine<Self, F>
95 where
96 Self: Sized,
97 {
98 Combine(self, f)
99 }
100}
101
102impl<K, F: Fn(&K) -> Option<u64>> Predicate<K> for F {
103 fn hash_property(&self, obj: &K) -> Option<u64> {
104 (self)(obj)
105 }
106}
107
108/// See [`Predicate::fallback`]
109#[derive(Copy, Clone, Debug, PartialEq, Eq)]
110pub struct Fallback<A, B>(pub(super) A, pub(super) B);
111impl<A, B, K> Predicate<K> for Fallback<A, B>
112where
113 A: Predicate<K>,
114 B: Predicate<K>,
115{
116 fn hash_property(&self, obj: &K) -> Option<u64> {
117 self.0.hash_property(obj).or_else(|| self.1.hash_property(obj))
118 }
119}
120/// See [`Predicate::combine`]
121#[derive(Copy, Clone, Debug, PartialEq, Eq)]
122pub struct Combine<A, B>(pub(super) A, pub(super) B);
123impl<A, B, K> Predicate<K> for Combine<A, B>
124where
125 A: Predicate<K>,
126 B: Predicate<K>,
127{
128 fn hash_property(&self, obj: &K) -> Option<u64> {
129 match (self.0.hash_property(obj), self.1.hash_property(obj)) {
130 // pass on both missing properties so people can chain .fallback
131 (None, None) => None,
132 // but any other combination of properties are hashed together
133 (a, b) => Some(hash(&(a, b))),
134 }
135 }
136}
137
138/// Configuration for predicate filtering with cache TTL
139#[derive(Debug, Clone)]
140pub struct Config {
141 /// Time-to-live for cache entries
142 ///
143 /// Entries not seen for at least this long will be evicted from the cache.
144 /// Default is 1 hour.
145 ttl: Duration,
146}
147
148impl Config {
149 /// Set the time-to-live for cache entries
150 ///
151 /// Entries not seen for at least this long will be evicted from the cache.
152 #[must_use]
153 pub fn ttl(mut self, ttl: Duration) -> Self {
154 self.ttl = ttl;
155 self
156 }
157}
158
159impl Default for Config {
160 fn default() -> Self {
161 Self {
162 // Default to 1 hour TTL - long enough to avoid unnecessary reconciles
163 // but short enough to prevent unbounded memory growth
164 ttl: Duration::from_secs(3600),
165 }
166 }
167}
168
169/// Cache entry storing predicate hash and last access time
170#[derive(Debug, Clone)]
171struct CacheEntry {
172 hash: u64,
173 last_seen: Instant,
174}
175
176#[pin_project]
177/// Stream returned by the [`predicate_filter`](super::WatchStreamExt::predicate_filter) method.
178#[must_use = "streams do nothing unless polled"]
179pub struct PredicateFilter<St, K: Resource, P: Predicate<K>> {
180 #[pin]
181 stream: St,
182 predicate: P,
183 cache: HashMap<PredicateCacheKey, CacheEntry>,
184 config: Config,
185 last_evicted: Instant,
186 // K: Resource necessary to get .meta() of an object during polling
187 _phantom: PhantomData<K>,
188}
189impl<St, K, P> PredicateFilter<St, K, P>
190where
191 St: Stream<Item = Result<K, Error>>,
192 K: Resource,
193 P: Predicate<K>,
194{
195 pub(super) fn new(stream: St, predicate: P, config: Config) -> Self {
196 Self {
197 stream,
198 predicate,
199 cache: HashMap::new(),
200 config,
201 last_evicted: Instant::now(),
202 _phantom: PhantomData,
203 }
204 }
205}
206impl<St, K, P> Stream for PredicateFilter<St, K, P>
207where
208 St: Stream<Item = Result<K, Error>>,
209 K: Resource,
210 P: Predicate<K>,
211{
212 type Item = Result<K, Error>;
213
214 fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
215 let mut me = self.project();
216
217 let now = Instant::now();
218 let ttl = me.config.ttl;
219 // Reclaim expired entries periodically instead of on every poll. Per-entry
220 // freshness is enforced below, so this scan is only memory hygiene and does
221 // not affect which events are emitted.
222 if now.duration_since(*me.last_evicted) >= ttl {
223 me.cache
224 .retain(|_, entry| now.duration_since(entry.last_seen) < ttl);
225 *me.last_evicted = now;
226 }
227
228 Poll::Ready(loop {
229 break match ready!(me.stream.as_mut().poll_next(cx)) {
230 Some(Ok(obj)) => {
231 if let Some(val) = me.predicate.hash_property(&obj) {
232 let key = PredicateCacheKey::from(obj.meta());
233
234 // Upsert in a single lookup. An entry older than the TTL is
235 // treated as absent, matching the evict-before-every-poll
236 // semantics now that eviction is amortized.
237 let changed = match me.cache.entry(key) {
238 Entry::Occupied(mut e) => {
239 let stale = now.duration_since(e.get().last_seen) >= ttl;
240 let changed = stale || e.get().hash != val;
241 e.insert(CacheEntry {
242 hash: val,
243 last_seen: now,
244 });
245 changed
246 }
247 Entry::Vacant(e) => {
248 e.insert(CacheEntry {
249 hash: val,
250 last_seen: now,
251 });
252 true
253 }
254 };
255
256 if changed {
257 Some(Ok(obj))
258 } else {
259 continue;
260 }
261 } else {
262 // if we can't evaluate predicate, always emit K
263 Some(Ok(obj))
264 }
265 }
266 Some(Err(err)) => Some(Err(err)),
267 None => return Poll::Ready(None),
268 };
269 })
270 }
271}
272
273/// Predicate functions for [`WatchStreamExt::predicate_filter`](crate::WatchStreamExt::predicate_filter)
274///
275/// These functions just return a hash of commonly compared values,
276/// to help decide whether to pass a watch event along or not.
277///
278/// # Choosing a predicate
279///
280/// | Predicate | Use case | Deletion behavior |
281/// | --- | --- | --- |
282/// | [`generation`] | Observe desired-state changes while ignoring status-only updates, for resources supporting generation | Can suppress deletion-related updates and deleted objects when generation is unchanged |
283/// | [`resource_version`] | Observe object revisions, including status-only changes | Retains observed deletes whose resource version differs from the cached version |
284/// | [`labels`], [`annotations`], [`finalizers`] | Observe changes to those fields | Can suppress deletions when the selected fields are unchanged |
285/// | [`fallback`](crate::Predicate::fallback) | Use another predicate when the first has no value | See [`Predicate::fallback`](crate::Predicate::fallback) for the deletion caveat |
286///
287/// # Deletion handling
288///
289/// Predicates operate on decoded objects (versus Events).
290/// After [`touched_objects`](crate::WatchStreamExt::touched_objects), an object from a
291/// delete event is filtered using the same rules as any other object. Deletion does not
292/// necessarily change `metadata.generation` or populate `metadata.deletionTimestamp`,
293/// so predicates based on unchanged fields can suppress that object.
294///
295/// Use [`resource_version`] when observed deletions should trigger reconciliation, for
296/// example to recreate a missing owned resource. The Kubernetes apiserver stamps the
297/// delete revision onto the deleted object. This predicate also passes status-only
298/// changes, so it does not provide the same filtering as [`generation`].
299///
300/// No predicate guarantees delivery of every deletion: events can be missed while a
301/// watcher is unavailable. Reconcilers should check current desired and actual state,
302/// and use a recovery mechanism such as periodic requeues when missed triggers matter.
303/// Use [finalizers](crate::finalizer::finalizer) for cleanup that must complete before
304/// deletion. The initial deletion marking bumps a positive generation, so a generation-only
305/// predicate lets that update through to start cleanup. It can still suppress the final
306/// delete event and the update that adds the finalizer, since adding a finalizer leaves
307/// generation unchanged. See the [finalizer documentation](crate::finalizer::finalizer).
308///
309/// Functional rewrite of the [controller-runtime/predicate module](https://github.com/kubernetes-sigs/controller-runtime/blob/main/pkg/predicate/predicate.go).
310///
311/// [`generation`]: predicates::generation
312/// [`resource_version`]: predicates::resource_version
313/// [`labels`]: predicates::labels
314/// [`annotations`]: predicates::annotations
315/// [`finalizers`]: predicates::finalizers
316pub mod predicates {
317 use super::hash;
318 use kube_client::{Resource, ResourceExt};
319
320 /// Hash the generation of a Resource K
321 ///
322 /// Useful for ignoring status-only updates on resources that support generation.
323 ///
324 /// Note that the final delete event need not change generation, so this can suppress
325 /// objects from delete events. See the [module documentation](crate::predicates).
326 pub fn generation<K: Resource>(obj: &K) -> Option<u64> {
327 obj.meta().generation.map(|g| hash(&g))
328 }
329
330 /// Hash the resource version of a Resource K
331 ///
332 /// Use this when observed deletions should trigger reconciliation: the Kubernetes
333 /// apiserver stamps the delete revision onto the deleted object. Status-only changes
334 /// also change resource version and pass this filter. This does not guarantee that
335 /// every deletion is observed; see the [module documentation](crate::predicates).
336 pub fn resource_version<K: Resource>(obj: &K) -> Option<u64> {
337 obj.meta().resource_version.as_ref().map(hash)
338 }
339
340 /// Hash the labels of a Resource K
341 pub fn labels<K: Resource>(obj: &K) -> Option<u64> {
342 Some(hash(obj.labels()))
343 }
344
345 /// Hash the annotations of a Resource K
346 pub fn annotations<K: Resource>(obj: &K) -> Option<u64> {
347 Some(hash(obj.annotations()))
348 }
349
350 /// Hash the finalizers of a Resource K
351 pub fn finalizers<K: Resource>(obj: &K) -> Option<u64> {
352 Some(hash(obj.finalizers()))
353 }
354}
355
356#[cfg(test)]
357pub(crate) mod tests {
358 use std::{pin::pin, task::Poll};
359
360 use super::{Config, Error, PredicateFilter, predicates};
361 use futures::{FutureExt, StreamExt, poll, stream};
362 use kube_client::Resource;
363 use serde_json::json;
364
365 #[tokio::test]
366 async fn predicate_filtering_hides_equal_predicate_values() {
367 use k8s_openapi::api::core::v1::Pod;
368 let mkobj = |g: i32| {
369 let p: Pod = serde_json::from_value(json!({
370 "apiVersion": "v1",
371 "kind": "Pod",
372 "metadata": {
373 "name": "blog",
374 "generation": Some(g),
375 },
376 "spec": {
377 "containers": [{
378 "name": "blog",
379 "image": "clux/blog:0.1.0"
380 }],
381 }
382 }))
383 .unwrap();
384 p
385 };
386 let data = stream::iter([
387 Ok(mkobj(1)),
388 Err(Error::NoResourceVersion),
389 Ok(mkobj(1)),
390 Ok(mkobj(2)),
391 ]);
392 let mut rx = pin!(PredicateFilter::new(
393 data,
394 predicates::generation,
395 Config::default()
396 ));
397
398 // mkobj(1) passed through
399 let first = rx.next().now_or_never().unwrap().unwrap().unwrap();
400 assert_eq!(first.meta().generation, Some(1));
401
402 // Error passed through
403 assert!(matches!(
404 poll!(rx.next()),
405 Poll::Ready(Some(Err(Error::NoResourceVersion)))
406 ));
407 // (no repeat mkobj(1) - same generation)
408 // mkobj(2) next
409 let second = rx.next().now_or_never().unwrap().unwrap().unwrap();
410 assert_eq!(second.meta().generation, Some(2));
411 assert!(matches!(poll!(rx.next()), Poll::Ready(None)));
412 }
413
414 #[tokio::test]
415 async fn predicate_filtering_should_handle_recreated_resources_with_same_generation() {
416 use k8s_openapi::api::core::v1::Pod;
417
418 let mkobj = |g: i32, uid: &str| {
419 let p: Pod = serde_json::from_value(json!({
420 "apiVersion": "v1",
421 "kind": "Pod",
422 "metadata": {
423 "name": "blog",
424 "namespace": "default",
425 "generation": Some(g),
426 "uid": uid,
427 },
428 "spec": {
429 "containers": [{
430 "name": "blog",
431 "image": "clux/blog:0.1.0"
432 }],
433 }
434 }))
435 .unwrap();
436 p
437 };
438
439 // Simulate: create (gen=1, uid=1) -> update (gen=1, uid=1) -> delete ->
440 // create (gen=1, uid=2) -> delete -> create (gen=2, uid=3)
441 let data = stream::iter([
442 Ok(mkobj(1, "uid-1")),
443 Ok(mkobj(1, "uid-1")),
444 Ok(mkobj(1, "uid-2")),
445 Ok(mkobj(2, "uid-3")),
446 ]);
447 let mut rx = pin!(PredicateFilter::new(
448 data,
449 predicates::generation,
450 Config::default()
451 ));
452
453 // mkobj(1, uid-1) passed through
454 let first = rx.next().now_or_never().unwrap().unwrap().unwrap();
455 assert_eq!(first.meta().generation, Some(1));
456 assert_eq!(first.meta().uid.as_deref(), Some("uid-1"));
457
458 // (no repeat mkobj(1, uid-1) - same UID and generation)
459 // mkobj(1, uid-2) next - different UID detected
460 let second = rx.next().now_or_never().unwrap().unwrap().unwrap();
461 assert_eq!(second.meta().generation, Some(1));
462 assert_eq!(second.meta().uid.as_deref(), Some("uid-2"));
463
464 // mkobj(2, uid-3) next
465 let third = rx.next().now_or_never().unwrap().unwrap().unwrap();
466 assert_eq!(third.meta().generation, Some(2));
467 assert_eq!(third.meta().uid.as_deref(), Some("uid-3"));
468
469 assert!(matches!(poll!(rx.next()), Poll::Ready(None)));
470 }
471
472 #[tokio::test(start_paused = true)]
473 async fn predicate_cache_ttl_evicts_expired_entries() {
474 use futures::{SinkExt, channel::mpsc};
475 use k8s_openapi::api::core::v1::Pod;
476 use std::time::Duration;
477
478 let mkobj = |g: i32, uid: &str| {
479 let p: Pod = serde_json::from_value(json!({
480 "apiVersion": "v1",
481 "kind": "Pod",
482 "metadata": {
483 "name": "blog",
484 "namespace": "default",
485 "generation": Some(g),
486 "uid": uid,
487 },
488 "spec": {
489 "containers": [{
490 "name": "blog",
491 "image": "clux/blog:0.1.0"
492 }],
493 }
494 }))
495 .unwrap();
496 p
497 };
498
499 // Time is paused, so the TTL only expires via tokio::time::advance below
500 let config = Config::default().ttl(Duration::from_secs(10));
501
502 // Use a channel so we can send items with delays
503 let (mut tx, rx) = mpsc::unbounded();
504 let mut filtered = pin!(PredicateFilter::new(
505 rx.map(Ok::<_, Error>),
506 predicates::generation,
507 config
508 ));
509
510 // Send first object
511 tx.send(mkobj(1, "uid-1")).await.unwrap();
512 let first = filtered.next().now_or_never().unwrap().unwrap().unwrap();
513 assert_eq!(first.meta().generation, Some(1));
514
515 // Send same object immediately - should be filtered
516 tx.send(mkobj(1, "uid-1")).await.unwrap();
517 assert!(matches!(poll!(filtered.next()), Poll::Pending));
518
519 // Wait for TTL to expire
520 tokio::time::advance(Duration::from_secs(20)).await;
521
522 // Send same object after TTL - should pass through due to eviction
523 tx.send(mkobj(1, "uid-1")).await.unwrap();
524 let second = filtered.next().now_or_never().unwrap().unwrap().unwrap();
525 assert_eq!(second.meta().generation, Some(1));
526 }
527
528 #[tokio::test]
529 async fn predicate_filter_compiles_with_dynamic_resource() {
530 use kube::api::DynamicObject;
531
532 let obj: DynamicObject = serde_json::from_value(json!({
533 "apiVersion": "v1",
534 "kind": "Pod",
535 "metadata": {
536 "name": "blog",
537 "generation": Some(1),
538 },
539 }))
540 .unwrap();
541 let data = stream::iter([Ok(obj)]);
542 let mut rx = pin!(PredicateFilter::new(
543 data,
544 predicates::generation,
545 Config::default()
546 ));
547
548 let first = rx.next().now_or_never().unwrap().unwrap().unwrap();
549 assert_eq!(first.meta().generation, Some(1));
550
551 // Mostly, this check is ensuring that predicate filters compile with
552 // `DynamicObject`, not testing any behaviour.
553 }
554}