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
17pub trait Lookup {
21 type DynamicType;
24
25 fn kind(dyntype: &Self::DynamicType) -> Cow<'_, str>;
27
28 fn group(dyntype: &Self::DynamicType) -> Cow<'_, str>;
30
31 fn version(dyntype: &Self::DynamicType) -> Cow<'_, str>;
33
34 fn api_version(dyntype: &Self::DynamicType) -> Cow<'_, str> {
36 api_version_from_group_version(Self::group(dyntype), Self::version(dyntype))
37 }
38
39 fn plural(dyntype: &Self::DynamicType) -> Cow<'_, str>;
41
42 fn name(&self) -> Option<Cow<'_, str>>;
44
45 fn namespace(&self) -> Option<Cow<'_, str>>;
47
48 fn resource_version(&self) -> Option<Cow<'_, str>>;
50
51 fn uid(&self) -> Option<Cow<'_, str>>;
53
54 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#[non_exhaustive]
128pub struct ObjectRef<K: Lookup + ?Sized> {
129 pub dyntype: K::DynamicType,
131 pub name: String,
133 pub namespace: Option<String>,
145 #[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#[derive(Default, Debug, Clone)]
159#[non_exhaustive]
160pub struct Extra {
161 pub resource_version: Option<String>,
163 pub uid: Option<String>,
165 #[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 #[must_use]
176 pub fn new(name: &str) -> Self {
177 Self::new_with(name, Default::default())
178 }
179
180 #[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 #[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 #[must_use]
212 pub fn within(mut self, namespace: &str) -> Self {
213 self.namespace = Some(namespace.to_string());
214 self
215 }
216
217 #[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 #[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 #[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 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 assert_eq!(minimal, with_extra);
382
383 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}