Skip to main content

kube_runtime/reflector/
object_ref.rs

1#[cfg(feature = "unstable-runtime-subscribe")]
2use super::subscriber::SubscriberId;
3use educe::Educe;
4use k8s_openapi::{api::core::v1::ObjectReference, apimachinery::pkg::apis::meta::v1::OwnerReference};
5#[cfg(doc)] use kube_client::core::ObjectMeta;
6use kube_client::{
7    api::{DynamicObject, Resource},
8    core::api_version_from_group_version,
9};
10#[cfg(feature = "unstable-runtime-subscribe")] use std::collections::BTreeSet;
11use std::{
12    borrow::Cow,
13    fmt::{Debug, Display},
14    hash::Hash,
15};
16
17/// Minimal lookup behaviour needed by a [reflector store](super::Store).
18///
19/// This trait is blanket-implemented for all [`Resource`] objects.
20pub trait Lookup {
21    /// Type information for types that do not know their resource information at compile time.
22    /// This is equivalent to [`Resource::DynamicType`].
23    type DynamicType;
24
25    /// The [kind](Resource::kind) for this object.
26    fn kind(dyntype: &Self::DynamicType) -> Cow<'_, str>;
27
28    /// The [group](Resource::group) for this object.
29    fn group(dyntype: &Self::DynamicType) -> Cow<'_, str>;
30
31    /// The [version](Resource::version) for this object.
32    fn version(dyntype: &Self::DynamicType) -> Cow<'_, str>;
33
34    /// The [apiVersion](Resource::api_version) for this object.
35    fn api_version(dyntype: &Self::DynamicType) -> Cow<'_, str> {
36        api_version_from_group_version(Self::group(dyntype), Self::version(dyntype))
37    }
38
39    /// The [plural](Resource::plural) for this object.
40    fn plural(dyntype: &Self::DynamicType) -> Cow<'_, str>;
41
42    /// The [name](ObjectMeta#structfield.name) of the object.
43    fn name(&self) -> Option<Cow<'_, str>>;
44
45    /// The [namespace](ObjectMeta#structfield.namespace) of the object.
46    fn namespace(&self) -> Option<Cow<'_, str>>;
47
48    /// The [resource version](ObjectMeta#structfield.resource_version) of the object.
49    fn resource_version(&self) -> Option<Cow<'_, str>>;
50
51    /// The [UID](ObjectMeta#structfield.uid) of the object.
52    fn uid(&self) -> Option<Cow<'_, str>>;
53
54    /// Constructs an [`ObjectRef`] for this object.
55    fn to_object_ref(&self, dyntype: Self::DynamicType) -> ObjectRef<Self> {
56        ObjectRef {
57            dyntype,
58            name: self.name().expect(".metadata.name missing").into_owned(),
59            namespace: self.namespace().map(Cow::into_owned),
60            extra: Extra {
61                resource_version: self.resource_version().map(Cow::into_owned),
62                uid: self.uid().map(Cow::into_owned),
63                #[cfg(feature = "unstable-runtime-subscribe")]
64                pending_lookups: None,
65            },
66        }
67    }
68}
69
70impl<K: Resource> Lookup for K {
71    type DynamicType = K::DynamicType;
72
73    fn kind(dyntype: &Self::DynamicType) -> Cow<'_, str> {
74        K::kind(dyntype)
75    }
76
77    fn version(dyntype: &Self::DynamicType) -> Cow<'_, str> {
78        K::version(dyntype)
79    }
80
81    fn group(dyntype: &Self::DynamicType) -> Cow<'_, str> {
82        K::group(dyntype)
83    }
84
85    fn plural(dyntype: &Self::DynamicType) -> Cow<'_, str> {
86        K::plural(dyntype)
87    }
88
89    fn name(&self) -> Option<Cow<'_, str>> {
90        self.meta().name.as_deref().map(Cow::Borrowed)
91    }
92
93    fn namespace(&self) -> Option<Cow<'_, str>> {
94        self.meta().namespace.as_deref().map(Cow::Borrowed)
95    }
96
97    fn resource_version(&self) -> Option<Cow<'_, str>> {
98        self.meta().resource_version.as_deref().map(Cow::Borrowed)
99    }
100
101    fn uid(&self) -> Option<Cow<'_, str>> {
102        self.meta().uid.as_deref().map(Cow::Borrowed)
103    }
104}
105
106#[derive(Educe)]
107#[educe(
108    Debug(bound("K::DynamicType: Debug")),
109    PartialEq(bound("K::DynamicType: PartialEq")),
110    Hash(bound("K::DynamicType: Hash")),
111    Clone(bound("K::DynamicType: Clone"))
112)]
113/// A typed and namedspaced (if relevant) reference to a Kubernetes object
114///
115/// `K` may be either the object type or `DynamicObject`, in which case the
116/// type is stored at runtime. Erased `ObjectRef`s pointing to different types
117/// are still considered different.
118///
119/// ```
120/// use kube_runtime::reflector::ObjectRef;
121/// use k8s_openapi::api::core::v1::{ConfigMap, Secret};
122/// assert_ne!(
123///     ObjectRef::<ConfigMap>::new("a").erase(),
124///     ObjectRef::<Secret>::new("a").erase(),
125/// );
126/// ```
127#[non_exhaustive]
128pub struct ObjectRef<K: Lookup + ?Sized> {
129    /// Resource information for the object K
130    pub dyntype: K::DynamicType,
131    /// The name of the object
132    pub name: String,
133    /// The namespace of the object
134    ///
135    /// May only be `None` if the kind is cluster-scoped (not located in a namespace).
136    /// Note that it *is* acceptable for an `ObjectRef` to a cluster-scoped resource to
137    /// have a namespace. These are, however, not considered equal:
138    ///
139    /// ```
140    /// # use kube_runtime::reflector::ObjectRef;
141    /// # use k8s_openapi::api::core::v1::ConfigMap;
142    /// assert_ne!(ObjectRef::<ConfigMap>::new("foo"), ObjectRef::new("foo").within("bar"));
143    /// ```
144    pub namespace: Option<String>,
145    /// Extra information about the object being referred to
146    ///
147    /// This is *not* considered when comparing objects, but may be used when converting to and from other representations,
148    /// such as [`OwnerReference`] or [`ObjectReference`].
149    #[educe(Hash(ignore), PartialEq(ignore))]
150    pub extra: Extra,
151}
152
153impl<K: Lookup + ?Sized> Eq for ObjectRef<K> where K::DynamicType: Eq {}
154
155/// Non-vital information about an object being referred to
156///
157/// See [`ObjectRef::extra`].
158#[derive(Default, Debug, Clone)]
159#[non_exhaustive]
160pub struct Extra {
161    /// The version of the resource at the time of reference
162    pub resource_version: Option<String>,
163    /// The uid of the object
164    pub uid: Option<String>,
165    /// Subscriber IDs pending a lookup on this reference
166    #[cfg(feature = "unstable-runtime-subscribe")]
167    pub pending_lookups: Option<BTreeSet<SubscriberId>>,
168}
169
170impl<K: Lookup> ObjectRef<K>
171where
172    K::DynamicType: Default,
173{
174    /// Create a default object ref with a name
175    #[must_use]
176    pub fn new(name: &str) -> Self {
177        Self::new_with(name, Default::default())
178    }
179
180    /// Create an object ref from an object `K`
181    ///
182    /// This object is assumed to be valid and will expect a .metadata.name.
183    #[must_use]
184    pub fn from_obj(obj: &K) -> Self {
185        obj.to_object_ref(Default::default())
186    }
187}
188
189impl<K: Lookup> From<&K> for ObjectRef<K>
190where
191    K::DynamicType: Default,
192{
193    fn from(obj: &K) -> Self {
194        Self::from_obj(obj)
195    }
196}
197
198impl<K: Lookup> ObjectRef<K> {
199    /// Create an object ref with a name and a dynamic resource type
200    #[must_use]
201    pub fn new_with(name: &str, dyntype: K::DynamicType) -> Self {
202        Self {
203            dyntype,
204            name: name.into(),
205            namespace: None,
206            extra: Extra::default(),
207        }
208    }
209
210    /// Set the namespace on an object ref
211    #[must_use]
212    pub fn within(mut self, namespace: &str) -> Self {
213        self.namespace = Some(namespace.to_string());
214        self
215    }
216
217    /// Creates `ObjectRef` from the resource and dynamic type.
218    #[must_use]
219    pub fn from_obj_with(obj: &K, dyntype: K::DynamicType) -> Self
220    where
221        K: Lookup,
222    {
223        obj.to_object_ref(dyntype)
224    }
225
226    /// Create an `ObjectRef` from an `OwnerReference`
227    ///
228    /// Returns `None` if the types do not match.
229    #[must_use]
230    pub fn from_owner_ref(
231        namespace: Option<&str>,
232        owner: &OwnerReference,
233        dyntype: K::DynamicType,
234    ) -> Option<Self> {
235        if owner.api_version == K::api_version(&dyntype) && owner.kind == K::kind(&dyntype) {
236            Some(Self {
237                dyntype,
238                name: owner.name.clone(),
239                namespace: namespace.map(String::from),
240                extra: Extra {
241                    resource_version: None,
242                    uid: Some(owner.uid.clone()),
243                    #[cfg(feature = "unstable-runtime-subscribe")]
244                    pending_lookups: None,
245                },
246            })
247        } else {
248            None
249        }
250    }
251
252    /// Convert into a reference to `K2`
253    ///
254    /// Note that no checking is done on whether this conversion makes sense. For example, every `Service`
255    /// has a corresponding `Endpoints`, but it wouldn't make sense to convert a `Pod` into a `Deployment`.
256    #[must_use]
257    pub fn into_kind_unchecked<K2: Lookup>(self, dt2: K2::DynamicType) -> ObjectRef<K2> {
258        ObjectRef {
259            dyntype: dt2,
260            name: self.name,
261            namespace: self.namespace,
262            extra: self.extra,
263        }
264    }
265
266    /// Create a object ref for a type erased dynamic object (using a static impl)
267    pub fn erase(self) -> ObjectRef<DynamicObject> {
268        ObjectRef {
269            dyntype: kube_client::api::ApiResource {
270                group: K::group(&self.dyntype).to_string(),
271                version: K::version(&self.dyntype).to_string(),
272                api_version: K::api_version(&self.dyntype).to_string(),
273                kind: K::kind(&self.dyntype).to_string(),
274                plural: K::plural(&self.dyntype).to_string(),
275            },
276            name: self.name,
277            namespace: self.namespace,
278            extra: self.extra,
279        }
280    }
281}
282
283impl<K: Lookup> From<ObjectRef<K>> for ObjectReference {
284    fn from(val: ObjectRef<K>) -> Self {
285        let ObjectRef {
286            dyntype: dt,
287            name,
288            namespace,
289            extra:
290                Extra {
291                    resource_version,
292                    uid,
293                    ..
294                },
295        } = val;
296        ObjectReference {
297            api_version: Some(K::api_version(&dt).into_owned()),
298            kind: Some(K::kind(&dt).into_owned()),
299            field_path: None,
300            name: Some(name),
301            namespace,
302            resource_version,
303            uid,
304        }
305    }
306}
307
308impl<K: Lookup> Display for ObjectRef<K> {
309    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
310        write!(
311            f,
312            "{}.{}.{}/{}",
313            K::kind(&self.dyntype),
314            K::version(&self.dyntype),
315            K::group(&self.dyntype),
316            self.name
317        )?;
318        if let Some(namespace) = &self.namespace {
319            write!(f, ".{namespace}")?;
320        }
321        Ok(())
322    }
323}
324
325#[cfg(test)]
326mod tests {
327    use std::{
328        collections::hash_map::DefaultHasher,
329        hash::{Hash, Hasher},
330    };
331
332    use super::{Extra, ObjectRef};
333    use k8s_openapi::api::{
334        apps::v1::Deployment,
335        core::v1::{Node, Pod},
336    };
337
338    #[test]
339    fn display_should_follow_expected_format() {
340        assert_eq!(
341            format!("{}", ObjectRef::<Pod>::new("my-pod").within("my-namespace")),
342            "Pod.v1./my-pod.my-namespace"
343        );
344        assert_eq!(
345            format!(
346                "{}",
347                ObjectRef::<Deployment>::new("my-deploy").within("my-namespace")
348            ),
349            "Deployment.v1.apps/my-deploy.my-namespace"
350        );
351        assert_eq!(
352            format!("{}", ObjectRef::<Node>::new("my-node")),
353            "Node.v1./my-node"
354        );
355    }
356
357    #[test]
358    fn display_should_be_transparent_to_representation() {
359        let pod_ref = ObjectRef::<Pod>::new("my-pod").within("my-namespace");
360        assert_eq!(format!("{pod_ref}"), format!("{}", pod_ref.erase()));
361        let deploy_ref = ObjectRef::<Deployment>::new("my-deploy").within("my-namespace");
362        assert_eq!(format!("{deploy_ref}"), format!("{}", deploy_ref.erase()));
363        let node_ref = ObjectRef::<Node>::new("my-node");
364        assert_eq!(format!("{node_ref}"), format!("{}", node_ref.erase()));
365    }
366
367    #[test]
368    fn comparison_should_ignore_extra() {
369        let minimal = ObjectRef::<Pod>::new("my-pod").within("my-namespace");
370        let with_extra = ObjectRef {
371            extra: Extra {
372                resource_version: Some("123".to_string()),
373                uid: Some("638ffacd-f666-4402-ba10-7848c66ef576".to_string()),
374                #[cfg(feature = "unstable-runtime-subscribe")]
375                pending_lookups: None,
376            },
377            ..minimal.clone()
378        };
379
380        // Eq and PartialEq should be unaffected by the contents of `extra`
381        assert_eq!(minimal, with_extra);
382
383        // Hash should be unaffected by the contents of `extra`
384        let hash_value = |value: &ObjectRef<Pod>| {
385            let mut hasher = DefaultHasher::new();
386            value.hash(&mut hasher);
387            hasher.finish()
388        };
389        assert_eq!(hash_value(&minimal), hash_value(&with_extra));
390    }
391}