vector/kubernetes/
meta_cache.rs1use std::collections::HashSet;
2
3use kube::core::ObjectMeta;
4
5#[derive(Default)]
6pub struct MetaCache {
7 pub cache: HashSet<MetaDescribe>,
8}
9
10impl MetaCache {
11 pub fn new() -> Self {
12 Self {
13 cache: HashSet::new(),
14 }
15 }
16 pub fn store(&mut self, meta_desc: MetaDescribe) {
17 self.cache.insert(meta_desc);
18 }
19 pub fn delete(&mut self, meta_desc: &MetaDescribe) {
20 self.cache.remove(meta_desc);
21 }
22 pub fn contains(&self, meta_desc: &MetaDescribe) -> bool {
23 self.cache.contains(meta_desc)
24 }
25 pub fn clear(&mut self) {
26 self.cache.clear();
27 }
28}
29
30#[derive(PartialEq, Eq, Hash, Clone)]
31pub struct MetaDescribe {
32 name: String,
33 namespace: String,
34}
35
36impl MetaDescribe {
37 pub fn from_meta(meta: &ObjectMeta) -> Self {
38 let name = meta.name.clone().unwrap_or_default();
39 let namespace = meta.namespace.clone().unwrap_or_default();
40
41 Self { name, namespace }
42 }
43}
44
45#[cfg(test)]
46mod tests {
47 use kube::core::ObjectMeta;
48
49 use super::{MetaCache, MetaDescribe};
50
51 #[test]
52 fn cache_should_store_data() {
53 let mut meta_cache = MetaCache::new();
54
55 let obj_meta = ObjectMeta {
56 name: Some("a".to_string()),
57 namespace: Some("b".to_string()),
58 ..ObjectMeta::default()
59 };
60 let meta_desc = MetaDescribe::from_meta(&obj_meta);
61
62 meta_cache.store(meta_desc);
63 assert_eq!(1, meta_cache.cache.len());
64 }
65
66 #[test]
67 fn cache_should_delete_data() {
68 let mut meta_cache = MetaCache::new();
69
70 let obj_meta = ObjectMeta {
71 name: Some("a".to_string()),
72 namespace: Some("b".to_string()),
73 ..ObjectMeta::default()
74 };
75 let meta_desc = MetaDescribe::from_meta(&obj_meta);
76
77 meta_cache.store(meta_desc.clone());
78 assert_eq!(1, meta_cache.cache.len());
79 meta_cache.delete(&meta_desc);
80 assert_eq!(0, meta_cache.cache.len());
81 }
82
83 #[test]
84 fn cache_should_check_active() {
85 let mut meta_cache = MetaCache::new();
86
87 let obj_meta = ObjectMeta {
88 name: Some("a".to_string()),
89 namespace: Some("b".to_string()),
90 ..ObjectMeta::default()
91 };
92 let meta_desc = MetaDescribe::from_meta(&obj_meta);
93
94 meta_cache.store(meta_desc.clone());
95 assert!(meta_cache.contains(&meta_desc));
96 }
97}