Skip to main content

kube_runtime/reflector/
store.rs

1//! A reader/writer split store for reflectors
2#[cfg(feature = "unstable-runtime-subscribe")]
3use super::subscriber::{SubscriberId, fresh_subscriber_id};
4use super::{Lookup, ObjectRef, dispatcher::Dispatcher};
5#[cfg(feature = "unstable-runtime-subscribe")]
6use crate::reflector::ReflectHandle;
7use crate::{
8    utils::delayed_init::{self, DelayedInit},
9    watcher,
10};
11use ahash::AHashMap;
12use educe::Educe;
13use kube_client::{
14    ResourceExt,
15    core::{Selector, SelectorExt},
16};
17#[cfg(feature = "unstable-runtime-subscribe")] use parking_lot::Mutex;
18use parking_lot::RwLock;
19#[cfg(feature = "unstable-runtime-subscribe")] use std::collections::BTreeSet;
20use std::{fmt::Debug, hash::Hash, sync::Arc};
21use thiserror::Error;
22
23type Cache<K> = Arc<RwLock<AHashMap<ObjectRef<K>, Arc<K>>>>;
24
25/// A writable Store handle
26///
27/// This is exclusive since it's not safe to share a single `Store` between multiple reflectors.
28/// In particular, `Restarted` events will clobber the state of other connected reflectors.
29#[derive(Debug)]
30pub struct Writer<K: 'static + Lookup + Clone>
31where
32    K::DynamicType: Eq + Hash + Clone,
33{
34    store: Cache<K>,
35    buffer: AHashMap<ObjectRef<K>, Arc<K>>,
36    dyntype: K::DynamicType,
37    ready_tx: Option<delayed_init::Initializer<()>>,
38    ready_rx: Arc<DelayedInit<()>>,
39    dispatcher: Option<Dispatcher<K>>,
40    #[cfg(feature = "unstable-runtime-subscribe")]
41    subscribers: Arc<Mutex<BTreeSet<SubscriberId>>>,
42}
43
44impl<K: 'static + Lookup + Clone> Writer<K>
45where
46    K::DynamicType: Eq + Hash + Clone,
47{
48    /// Creates a new Writer with the specified dynamic type.
49    ///
50    /// If the dynamic type is default-able (for example when writer is used with
51    /// `k8s_openapi` types) you can use `Default` instead.
52    pub fn new(dyntype: K::DynamicType) -> Self {
53        let (ready_tx, ready_rx) = DelayedInit::new();
54        Writer {
55            store: Default::default(),
56            buffer: Default::default(),
57            dyntype,
58            ready_tx: Some(ready_tx),
59            ready_rx: Arc::new(ready_rx),
60            dispatcher: None,
61            #[cfg(feature = "unstable-runtime-subscribe")]
62            subscribers: Default::default(),
63        }
64    }
65
66    /// Creates a new Writer with the specified dynamic type and buffer size.
67    ///
68    /// When the Writer is created through `new_shared`, it will be able to
69    /// be subscribed. Stored objects will be propagated to all subscribers. The
70    /// buffer size is used for the underlying channel. An object is cleared
71    /// from the buffer only when all subscribers have seen it.
72    ///
73    /// If the dynamic type is default-able (for example when writer is used with
74    /// `k8s_openapi` types) you can use `Default` instead.
75    #[cfg(feature = "unstable-runtime-subscribe")]
76    pub fn new_shared(buf_size: usize, dyntype: K::DynamicType) -> Self {
77        let (ready_tx, ready_rx) = DelayedInit::new();
78        Writer {
79            store: Default::default(),
80            buffer: Default::default(),
81            dyntype,
82            ready_tx: Some(ready_tx),
83            ready_rx: Arc::new(ready_rx),
84            dispatcher: Some(Dispatcher::new(buf_size)),
85            subscribers: Default::default(),
86        }
87    }
88
89    /// Return a read handle to the store
90    ///
91    /// Multiple read handles may be obtained, by either calling `as_reader` multiple times,
92    /// or by calling `Store::clone()` afterwards.
93    #[must_use]
94    pub fn as_reader(&self) -> Store<K> {
95        Store {
96            store: self.store.clone(),
97            ready_rx: self.ready_rx.clone(),
98            #[cfg(feature = "unstable-runtime-subscribe")]
99            subscribers: self.subscribers.clone(),
100        }
101    }
102
103    /// Return a handle to a subscriber
104    ///
105    /// Multiple subscribe handles may be obtained, by either calling
106    /// `subscribe` multiple times, or by calling `clone()`
107    ///
108    /// This function returns a `Some` when the [`Writer`] is constructed through
109    /// [`Writer::new_shared`] or [`store_shared`], and a `None` otherwise.
110    #[cfg(feature = "unstable-runtime-subscribe")]
111    pub fn subscribe(&self) -> Option<ReflectHandle<K>> {
112        self.dispatcher
113            .as_ref()
114            .map(|dispatcher| dispatcher.subscribe(self.as_reader()))
115    }
116
117    /// Return the current subscriber IDs, or `None` if there are no subscribers
118    #[cfg(feature = "unstable-runtime-subscribe")]
119    pub(crate) fn subscriber_ids(&self) -> Option<BTreeSet<SubscriberId>> {
120        let set = self.subscribers.lock().clone();
121        (!set.is_empty()).then_some(set)
122    }
123
124    /// Applies a single watcher event to the store
125    pub fn apply_watcher_event(&mut self, event: &watcher::Event<K>) {
126        match event {
127            watcher::Event::Apply(obj) => {
128                let key = obj.to_object_ref(self.dyntype.clone());
129                let obj = Arc::new(obj.clone());
130                let mut store = self.store.write();
131                #[cfg(feature = "unstable-runtime-subscribe")]
132                if self.dispatcher.is_some()
133                    && let Some((stored, _)) = store.get_key_value(&key)
134                    && stored.extra.pending_lookups.is_some()
135                {
136                    store.remove(&key);
137                }
138                store.insert(key, obj);
139            }
140            watcher::Event::Delete(obj) => {
141                let key = obj.to_object_ref(self.dyntype.clone());
142                let mut store = self.store.write();
143                #[cfg(not(feature = "unstable-runtime-subscribe"))]
144                store.remove(&key);
145
146                #[cfg(feature = "unstable-runtime-subscribe")]
147                if let Some((original_key, existing)) = store.remove_entry(&key)
148                    && let Some(ids) = self.subscriber_ids()
149                {
150                    if existing.uid().as_deref() == key.extra.uid.as_deref() {
151                        // Re-insert the entry with updated key, as insert on its own doesnt modify the key
152                        let mut key = key;
153                        key.extra.pending_lookups = Some(ids);
154                        store.insert(key, existing);
155                    } else {
156                        store.insert(original_key, existing);
157                    }
158                }
159            }
160            watcher::Event::Init => {
161                self.buffer = AHashMap::new();
162            }
163            watcher::Event::InitApply(obj) => {
164                let key = obj.to_object_ref(self.dyntype.clone());
165                let obj = Arc::new(obj.clone());
166                self.buffer.insert(key, obj);
167            }
168            watcher::Event::InitDone => {
169                let mut store = self.store.write();
170
171                // Swap the buffer into the store
172                std::mem::swap(&mut *store, &mut self.buffer);
173
174                // Clear the buffer
175                // This is preferred over self.buffer.clear(), as clear() will keep the allocated memory for reuse.
176                // This way, the old buffer is dropped.
177                self.buffer = AHashMap::new();
178
179                // Mark as ready after the Restart, "releasing" any calls to Store::wait_until_ready()
180                if let Some(ready_tx) = self.ready_tx.take() {
181                    ready_tx.init(())
182                }
183            }
184        }
185    }
186
187    /// Broadcast an event to any downstream listeners subscribed on the store
188    pub(crate) async fn dispatch_event(&mut self, event: &watcher::Event<K>) {
189        if let Some(ref mut dispatcher) = self.dispatcher {
190            match event {
191                watcher::Event::Apply(obj) => {
192                    let obj_ref = obj.to_object_ref(self.dyntype.clone());
193                    // TODO (matei): should this take a timeout to log when backpressure has
194                    // been applied for too long, e.g. 10s
195                    dispatcher.broadcast(obj_ref).await;
196                }
197
198                watcher::Event::InitDone => {
199                    let obj_refs: Vec<_> = {
200                        let store = self.store.read();
201                        store.keys().cloned().collect()
202                    };
203
204                    for obj_ref in obj_refs {
205                        dispatcher.broadcast(obj_ref).await;
206                    }
207                }
208
209                #[cfg(feature = "unstable-runtime-subscribe")]
210                watcher::Event::Delete(obj) => {
211                    let obj_ref = {
212                        let obj_ref = obj.to_object_ref(self.dyntype.clone());
213                        let store = self.store.read();
214                        store
215                            .get_key_value(&obj_ref)
216                            .map(|(obj_ref, _)| obj_ref.clone())
217                            .unwrap_or(obj_ref)
218                    };
219                    dispatcher.broadcast(obj_ref).await;
220                }
221
222                _ => {}
223            }
224        }
225    }
226}
227
228impl<K> Default for Writer<K>
229where
230    K: Lookup + Clone + 'static,
231    K::DynamicType: Default + Eq + Hash + Clone,
232{
233    fn default() -> Self {
234        Self::new(K::DynamicType::default())
235    }
236}
237
238/// A readable cache of Kubernetes objects of kind `K`
239///
240/// Cloning will produce a new reference to the same backing store.
241///
242/// Cannot be constructed directly since one writer handle is required,
243/// use `Writer::as_reader()` instead.
244#[derive(Educe)]
245#[educe(Debug(bound("K: Debug, K::DynamicType: Debug")), Clone)]
246pub struct Store<K: 'static + Lookup>
247where
248    K::DynamicType: Hash + Eq,
249{
250    #[allow(clippy::struct_field_names)]
251    store: Cache<K>,
252    ready_rx: Arc<DelayedInit<()>>,
253    #[cfg(feature = "unstable-runtime-subscribe")]
254    subscribers: Arc<Mutex<BTreeSet<SubscriberId>>>,
255}
256
257/// The error returned by `Store::wait_until_ready`
258#[derive(Debug, Error)]
259#[error("writer was dropped before store became ready")]
260pub struct WriterDropped(delayed_init::InitDropped);
261
262impl<K: 'static + Clone + Lookup> Store<K>
263where
264    K::DynamicType: Eq + Hash + Clone,
265{
266    /// Wait for the store to be populated by Kubernetes.
267    ///
268    /// Note that polling this will _not_ await the source of the stream that populates the [`Writer`].
269    /// The [`reflector`](crate::reflector()) stream must be awaited separately.
270    ///
271    /// # Errors
272    /// Returns an error if the [`Writer`] was dropped before any value was written.
273    pub async fn wait_until_ready(&self) -> Result<(), WriterDropped> {
274        self.ready_rx.get().await.map_err(WriterDropped)
275    }
276
277    /// Register a new subscriber and return its ID
278    #[cfg(feature = "unstable-runtime-subscribe")]
279    pub(crate) fn add_subscriber(&self) -> SubscriberId {
280        let id = fresh_subscriber_id();
281        self.subscribers.lock().insert(id);
282        id
283    }
284
285    /// Retrieve a `clone()` of the entry referred to by `key`, if it is in the cache.
286    ///
287    /// `key.namespace` is ignored for cluster-scoped resources.
288    ///
289    /// Note that this is a cache and may be stale. Deleted objects may still exist in the cache
290    /// despite having been deleted in the cluster, and new objects may not yet exist in the cache.
291    /// If any of these are a problem for you then you should abort your reconciler and retry later.
292    /// If you use `kube_rt::controller` then you can do this by returning an error and specifying a
293    /// reasonable `error_policy`.
294    #[must_use]
295    pub fn get(&self, key: &ObjectRef<K>) -> Option<Arc<K>> {
296        let store = self.store.read();
297        store
298            .get(key)
299            // Try to erase the namespace and try again, in case the object is cluster-scoped
300            .or_else(|| {
301                store.get(&{
302                    let mut cluster_key = key.clone();
303                    cluster_key.namespace = None;
304                    cluster_key
305                })
306            })
307            // Clone to let go of the entry lock ASAP
308            .cloned()
309    }
310
311    /// Return the cached object for `key`, removing it once the given subscriber
312    /// acknowledges its pending lookup.
313    #[cfg(feature = "unstable-runtime-subscribe")]
314    #[must_use]
315    pub(crate) fn remove(&self, key: &ObjectRef<K>, id: SubscriberId) -> Option<Arc<K>> {
316        Self::remove_from_store(&mut self.store.write(), key, id)
317    }
318
319    /// Perform atomic removal from store based on the subscriber set
320    #[cfg(feature = "unstable-runtime-subscribe")]
321    #[must_use]
322    fn remove_from_store(
323        store: &mut AHashMap<ObjectRef<K>, Arc<K>>,
324        key: &ObjectRef<K>,
325        id: SubscriberId,
326    ) -> Option<Arc<K>> {
327        let (mut stored_key, obj) = store.remove_entry(key)?;
328
329        if key.extra.uid.as_deref() != obj.uid().as_deref()
330            || stored_key.extra.pending_lookups.as_mut().is_none_or(|set| {
331                set.remove(&id);
332                !set.is_empty()
333            })
334        {
335            store.insert(stored_key, obj.clone());
336        }
337
338        Some(obj)
339    }
340
341    /// Perform cleanup of retained cache items in the middle of deletion.
342    ///
343    /// This does not guarantee deletion event delivery to the dropped subscriber
344    /// (or to subscribers added after the delete),
345    /// but avoids leaving unconsumed deleted objects in cache, and is consistent
346    /// with handling of apply events always reading latest cache state, potentially
347    /// missing individual edges.
348    #[cfg(feature = "unstable-runtime-subscribe")]
349    pub(crate) fn drop_subscriber(&self, id: SubscriberId) {
350        self.subscribers.lock().remove(&id);
351        let mut store = self.store.write();
352        let keys: Vec<ObjectRef<K>> = store
353            .keys()
354            .filter(|k| k.extra.pending_lookups.as_ref().is_some_and(|s| s.contains(&id)))
355            .cloned()
356            .collect();
357
358        for k in keys {
359            let _ = Self::remove_from_store(&mut store, &k, id);
360        }
361    }
362
363    /// Return a full snapshot of the current values
364    #[must_use]
365    pub fn state(&self) -> Vec<Arc<K>> {
366        let s = self.store.read();
367        s.values().cloned().collect()
368    }
369
370    /// Retrieve a `clone()` of the entry found by the given predicate
371    #[must_use]
372    pub fn find<P>(&self, predicate: P) -> Option<Arc<K>>
373    where
374        P: Fn(&K) -> bool,
375    {
376        self.store
377            .read()
378            .values()
379            .find(|k| predicate(k.as_ref()))
380            .cloned()
381    }
382
383    /// Return a filtered snapshot of the current values, retaining only objects matching `predicate`
384    ///
385    /// Note: the store read lock is held for the entire duration of predicate evaluation.
386    /// Avoid blocking or expensive operations inside the predicate.
387    #[must_use]
388    pub fn state_filter<P>(&self, predicate: P) -> Vec<Arc<K>>
389    where
390        P: Fn(&K) -> bool,
391    {
392        self.store
393            .read()
394            .values()
395            .filter(|k| predicate(k.as_ref()))
396            .cloned()
397            .collect()
398    }
399
400    /// Return a filtered snapshot of the current values, retaining only objects whose labels match `selector`
401    ///
402    /// # Example
403    ///
404    /// ```
405    /// # use k8s_openapi::api::core::v1::ConfigMap;
406    /// # use kube_client::core::{Expression, Selector};
407    /// # let (reader, _writer) = kube_runtime::reflector::store::<ConfigMap>();
408    /// let selector: Selector = Expression::Equal("app".into(), "nginx".into()).into();
409    /// let result = reader.state_filter_selector(&selector);
410    /// ```
411    #[must_use]
412    pub fn state_filter_selector(&self, selector: &Selector) -> Vec<Arc<K>>
413    where
414        K: ResourceExt,
415    {
416        self.state_filter(|k| selector.matches(k.labels()))
417    }
418
419    /// Return the number of elements in the store
420    #[must_use]
421    pub fn len(&self) -> usize {
422        self.store.read().len()
423    }
424
425    /// Return whether the store is empty
426    #[must_use]
427    pub fn is_empty(&self) -> bool {
428        self.store.read().is_empty()
429    }
430}
431
432/// Create a (Reader, Writer) for a `Store<K>` for a typed resource `K`
433///
434/// The `Writer` should be passed to a [`reflector`](crate::reflector()),
435/// and the [`Store`] is a read-only handle.
436#[must_use]
437pub fn store<K>() -> (Store<K>, Writer<K>)
438where
439    K: Lookup + Clone + 'static,
440    K::DynamicType: Eq + Hash + Clone + Default,
441{
442    let w = Writer::<K>::default();
443    let r = w.as_reader();
444    (r, w)
445}
446
447/// Create a (Reader, Writer) for a `Store<K>` for a typed resource `K`
448///
449/// The resulting `Writer` can be subscribed on in order to fan out events from
450/// a watcher. The `Writer` should be passed to a [`reflector`](crate::reflector()),
451/// and the [`Store`] is a read-only handle.
452///
453/// A buffer size is used for the underlying message channel. When the buffer is
454/// full, backpressure will be applied by waiting for capacity.
455#[must_use]
456#[cfg(feature = "unstable-runtime-subscribe")]
457pub fn store_shared<K>(buf_size: usize) -> (Store<K>, Writer<K>)
458where
459    K: Lookup + Clone + 'static,
460    K::DynamicType: Eq + Hash + Clone + Default,
461{
462    let w = Writer::<K>::new_shared(buf_size, Default::default());
463    let r = w.as_reader();
464    (r, w)
465}
466
467#[cfg(test)]
468mod tests {
469    use super::{Writer, store};
470    use crate::{reflector::ObjectRef, watcher};
471    use k8s_openapi::api::core::v1::ConfigMap;
472    use kube_client::api::ObjectMeta;
473
474    #[test]
475    fn should_allow_getting_namespaced_object_by_namespaced_ref() {
476        let cm = ConfigMap {
477            metadata: ObjectMeta {
478                name: Some("obj".to_string()),
479                namespace: Some("ns".to_string()),
480                ..ObjectMeta::default()
481            },
482            ..ConfigMap::default()
483        };
484        let mut store_w = Writer::default();
485        store_w.apply_watcher_event(&watcher::Event::Apply(cm.clone()));
486        let store = store_w.as_reader();
487        assert_eq!(store.get(&ObjectRef::from_obj(&cm)).as_deref(), Some(&cm));
488    }
489
490    #[test]
491    fn should_not_allow_getting_namespaced_object_by_clusterscoped_ref() {
492        let cm = ConfigMap {
493            metadata: ObjectMeta {
494                name: Some("obj".to_string()),
495                namespace: Some("ns".to_string()),
496                ..ObjectMeta::default()
497            },
498            ..ConfigMap::default()
499        };
500        let mut cluster_cm = cm.clone();
501        cluster_cm.metadata.namespace = None;
502        let mut store_w = Writer::default();
503        store_w.apply_watcher_event(&watcher::Event::Apply(cm));
504        let store = store_w.as_reader();
505        assert_eq!(store.get(&ObjectRef::from_obj(&cluster_cm)), None);
506    }
507
508    #[test]
509    fn should_allow_getting_clusterscoped_object_by_clusterscoped_ref() {
510        let cm = ConfigMap {
511            metadata: ObjectMeta {
512                name: Some("obj".to_string()),
513                namespace: None,
514                ..ObjectMeta::default()
515            },
516            ..ConfigMap::default()
517        };
518        let (store, mut writer) = store();
519        writer.apply_watcher_event(&watcher::Event::Apply(cm.clone()));
520        assert_eq!(store.get(&ObjectRef::from_obj(&cm)).as_deref(), Some(&cm));
521    }
522
523    #[test]
524    fn should_allow_getting_clusterscoped_object_by_namespaced_ref() {
525        let cm = ConfigMap {
526            metadata: ObjectMeta {
527                name: Some("obj".to_string()),
528                namespace: None,
529                ..ObjectMeta::default()
530            },
531            ..ConfigMap::default()
532        };
533        let mut nsed_cm = cm.clone();
534        nsed_cm.metadata.namespace = Some("ns".to_string());
535        let mut store_w = Writer::default();
536        store_w.apply_watcher_event(&watcher::Event::Apply(cm.clone()));
537        let store = store_w.as_reader();
538        assert_eq!(store.get(&ObjectRef::from_obj(&nsed_cm)).as_deref(), Some(&cm));
539    }
540
541    #[test]
542    fn state_filter_filters_by_predicate() {
543        let (reader, mut writer) = store::<ConfigMap>();
544
545        let cm1 = ConfigMap {
546            metadata: ObjectMeta {
547                name: Some("cm1".to_string()),
548                namespace: Some("ns".to_string()),
549                labels: Some([("app".to_string(), "nginx".to_string())].into()),
550                ..ObjectMeta::default()
551            },
552            ..ConfigMap::default()
553        };
554        let cm2 = ConfigMap {
555            metadata: ObjectMeta {
556                name: Some("cm2".to_string()),
557                namespace: Some("ns".to_string()),
558                labels: Some([("app".to_string(), "postgres".to_string())].into()),
559                ..ObjectMeta::default()
560            },
561            ..ConfigMap::default()
562        };
563
564        writer.apply_watcher_event(&watcher::Event::Apply(cm1.clone()));
565        writer.apply_watcher_event(&watcher::Event::Apply(cm2));
566
567        let result = reader.state_filter(|k| {
568            k.metadata
569                .labels
570                .as_ref()
571                .and_then(|l| l.get("app"))
572                .is_some_and(|v| v == "nginx")
573        });
574        assert_eq!(result.len(), 1);
575        assert_eq!(result[0].as_ref(), &cm1);
576    }
577
578    #[test]
579    fn state_filter_selector_filters_by_label_selector() {
580        use kube_client::core::{Expression, Selector};
581
582        let (reader, mut writer) = store::<ConfigMap>();
583
584        let cm1 = ConfigMap {
585            metadata: ObjectMeta {
586                name: Some("cm1".to_string()),
587                namespace: Some("ns".to_string()),
588                labels: Some([("app".to_string(), "nginx".to_string())].into()),
589                ..ObjectMeta::default()
590            },
591            ..ConfigMap::default()
592        };
593        let cm2 = ConfigMap {
594            metadata: ObjectMeta {
595                name: Some("cm2".to_string()),
596                namespace: Some("ns".to_string()),
597                labels: Some([("app".to_string(), "postgres".to_string())].into()),
598                ..ObjectMeta::default()
599            },
600            ..ConfigMap::default()
601        };
602
603        writer.apply_watcher_event(&watcher::Event::Apply(cm1.clone()));
604        writer.apply_watcher_event(&watcher::Event::Apply(cm2));
605
606        let selector: Selector = Expression::Equal("app".into(), "nginx".into()).into();
607        let result = reader.state_filter_selector(&selector);
608        assert_eq!(result.len(), 1);
609        assert_eq!(result[0].as_ref(), &cm1);
610    }
611
612    #[test]
613    fn find_element_in_store() {
614        let cm = ConfigMap {
615            metadata: ObjectMeta {
616                name: Some("obj".to_string()),
617                namespace: None,
618                ..ObjectMeta::default()
619            },
620            ..ConfigMap::default()
621        };
622        let mut target_cm = cm.clone();
623
624        let (reader, mut writer) = store::<ConfigMap>();
625        assert!(reader.is_empty());
626        writer.apply_watcher_event(&watcher::Event::Apply(cm));
627
628        assert_eq!(reader.len(), 1);
629        assert!(reader.find(|k| k.metadata.generation == Some(1234)).is_none());
630
631        target_cm.metadata.name = Some("obj1".to_string());
632        target_cm.metadata.generation = Some(1234);
633        writer.apply_watcher_event(&watcher::Event::Apply(target_cm.clone()));
634        assert!(!reader.is_empty());
635        assert_eq!(reader.len(), 2);
636        let found = reader.find(|k| k.metadata.generation == Some(1234));
637        assert_eq!(found.as_deref(), Some(&target_cm));
638    }
639}