engenho_controllers/
pod_template.rs1use std::fmt;
57use std::io;
58
59use serde_json::{Map, Value};
60
61pub const POD_TEMPLATE_HASH_LABEL: &str = "pod-template-hash";
64
65#[derive(Debug, Clone, PartialEq, Eq)]
71pub struct NormalizedTemplate(Value);
72
73impl NormalizedTemplate {
74 #[must_use]
79 pub fn of(template: &Value) -> Self {
80 let mut t = template.clone();
81 if let Some(labels) = t
82 .get_mut("metadata")
83 .and_then(|m| m.get_mut("labels"))
84 .and_then(Value::as_object_mut)
85 {
86 labels.remove(POD_TEMPLATE_HASH_LABEL);
87 }
88 normalize(None, &mut t);
89 Self(t)
90 }
91
92 #[must_use]
96 pub fn of_spec_template(owner: &Value) -> Option<Self> {
97 owner
98 .get("spec")
99 .and_then(|s| s.get("template"))
100 .filter(|t| !t.is_null())
101 .map(Self::of)
102 }
103
104 #[must_use]
113 pub fn naming_hash(&self) -> Option<TemplateHash> {
114 let mut fnv = Fnv1a::new();
115 serde_json::to_writer(&mut fnv, &self.0).ok()?;
116 Some(TemplateHash(fnv.0))
117 }
118}
119
120#[derive(Debug, Clone, Copy, PartialEq, Eq)]
123pub struct TemplateHash(u64);
124
125impl fmt::Display for TemplateHash {
126 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
127 write!(f, "{:010x}", self.0 >> 24)
130 }
131}
132
133struct Fnv1a(u64);
136
137impl Fnv1a {
138 const OFFSET: u64 = 0xcbf2_9ce4_8422_2325;
139 const PRIME: u64 = 0x0100_0000_01b3;
140
141 fn new() -> Self {
142 Self(Self::OFFSET)
143 }
144}
145
146impl io::Write for Fnv1a {
147 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
148 for b in buf {
149 self.0 ^= u64::from(*b);
150 self.0 = self.0.wrapping_mul(Self::PRIME);
151 }
152 Ok(buf.len())
153 }
154
155 fn flush(&mut self) -> io::Result<()> {
156 Ok(())
157 }
158}
159
160pub const MAP_FIELDS: &[&str] = &[
170 "labels",
171 "annotations",
172 "nodeSelector",
173 "overhead",
174 "limits",
175 "requests",
176 "matchLabels",
177 "volumeAttributes",
178 "options",
179];
180
181fn is_map_field(field: &str) -> bool {
182 MAP_FIELDS.contains(&field)
183}
184
185fn normalize(field: Option<&str>, v: &mut Value) {
191 match v {
192 Value::Object(_) if field.is_some_and(is_map_field) => {}
193 Value::Object(fields) => fields.retain(|name, member| {
194 normalize(Some(name.as_str()), member);
195 !is_absent_field(name, member)
196 }),
197 Value::Array(items) => items.iter_mut().for_each(|item| normalize(None, item)),
198 _ => {}
199 }
200}
201
202fn is_absent_field(name: &str, v: &Value) -> bool {
205 v.is_null()
206 || v.as_array().is_some_and(Vec::is_empty)
207 || (v.as_object().is_some_and(Map::is_empty) && (is_map_field(name) || name == "metadata"))
208}
209
210#[cfg(test)]
211mod tests {
212 use super::*;
213 use serde_json::json;
214
215 fn web() -> Value {
216 json!({
217 "metadata": {"labels": {"app": "web"}},
218 "spec": {
219 "containers": [{"name": "c", "image": "web:1"}]
220 }
221 })
222 }
223
224 fn same(a: &Value, b: &Value) -> bool {
225 NormalizedTemplate::of(a) == NormalizedTemplate::of(b)
226 }
227
228 #[test]
229 fn the_pod_template_hash_label_is_ignored() {
230 let mut hashed = web();
231 hashed["metadata"]["labels"]["pod-template-hash"] = json!("0123456789");
232 assert!(same(&web(), &hashed));
233 }
234
235 #[test]
236 fn a_label_set_holding_only_the_hash_is_no_label_set() {
237 let bare = json!({"spec": {"containers": [{"name": "c"}]}});
238 let hashed = json!({
239 "metadata": {"labels": {"pod-template-hash": "0123456789"}},
240 "spec": {"containers": [{"name": "c"}]}
241 });
242 assert!(same(&bare, &hashed));
243 }
244
245 #[test]
246 fn a_null_member_is_an_absent_member_at_any_depth() {
247 let mut nulls = web();
248 nulls["metadata"]["annotations"] = Value::Null;
249 nulls["metadata"]["creationTimestamp"] = Value::Null;
250 nulls["spec"]["nodeSelector"] = Value::Null;
251 nulls["spec"]["containers"][0]["resources"] = Value::Null;
252 assert!(same(&web(), &nulls));
253 }
254
255 #[test]
256 fn an_empty_list_is_an_absent_list_at_any_depth() {
257 let mut empties = web();
258 empties["spec"]["volumes"] = json!([]);
259 empties["spec"]["containers"][0]["env"] = json!([]);
260 empties["spec"]["containers"][0]["args"] = json!([]);
261 assert!(same(&web(), &empties));
262 }
263
264 #[test]
265 fn empty_template_labels_annotations_and_metadata_are_absent() {
266 let bare = json!({"spec": {"containers": [{"name": "c"}]}});
267 let empty_maps = json!({
268 "metadata": {"labels": {}, "annotations": {}},
269 "spec": {"containers": [{"name": "c"}]}
270 });
271 let empty_meta = json!({"metadata": {}, "spec": {"containers": [{"name": "c"}]}});
272 assert!(same(&bare, &empty_maps));
273 assert!(same(&bare, &empty_meta));
274 }
275
276 #[test]
277 fn an_empty_map_field_is_absent_at_any_depth() {
278 let mut empties = web();
279 empties["spec"]["nodeSelector"] = json!({});
280 empties["spec"]["containers"][0]["resources"] = json!({"limits": {}, "requests": {}});
281 let mut bare_resources = web();
282 bare_resources["spec"]["containers"][0]["resources"] = json!({});
283 assert!(same(&bare_resources, &empties));
284 }
285
286 #[test]
287 fn a_null_map_entry_is_an_empty_string_not_an_absent_key() {
288 let mut null_entry = web();
292 null_entry["metadata"]["labels"]["tier"] = Value::Null;
293 assert!(!same(&web(), &null_entry));
294
295 let mut null_selector = web();
296 null_selector["spec"]["nodeSelector"] = json!({"disk": null});
297 assert!(!same(&web(), &null_selector));
298 }
299
300 #[test]
301 fn a_changed_image_is_a_different_template() {
302 let mut v2 = web();
303 v2["spec"]["containers"][0]["image"] = json!("web:2");
304 assert!(!same(&web(), &v2));
305 }
306
307 #[test]
308 fn a_restart_annotation_is_a_different_template() {
309 let mut restarted = web();
311 restarted["metadata"]["annotations"] =
312 json!({"kubectl.kubernetes.io/restartedAt": "2026-09-19T00:00:00Z"});
313 assert!(!same(&web(), &restarted));
314 }
315
316 #[test]
317 fn a_label_other_than_the_hash_is_part_of_the_template() {
318 let mut relabelled = web();
319 relabelled["metadata"]["labels"]["tier"] = json!("front");
320 assert!(!same(&web(), &relabelled));
321 }
322
323 #[test]
324 fn an_empty_object_that_is_a_pointer_upstream_is_kept() {
325 let mut with_source = web();
328 with_source["spec"]["volumes"] = json!([{"name": "scratch", "emptyDir": {}}]);
329 let mut without_source = web();
330 without_source["spec"]["volumes"] = json!([{"name": "scratch"}]);
331 assert!(!same(&with_source, &without_source));
332
333 let mut sc = web();
334 sc["spec"]["securityContext"] = json!({});
335 assert!(!same(&web(), &sc));
336 }
337
338 #[test]
339 fn list_order_and_length_are_part_of_the_template() {
340 let two = json!({"spec": {"containers": [{"name": "a"}, {"name": "b"}]}});
341 let swapped = json!({"spec": {"containers": [{"name": "b"}, {"name": "a"}]}});
342 let with_null = json!({"spec": {"containers": [{"name": "a"}, {"name": "b"}, null]}});
343 assert!(!same(&two, &swapped));
344 assert!(!same(&two, &with_null));
345 }
346
347 #[test]
348 fn normalizing_twice_changes_nothing() {
349 let messy = json!({
350 "metadata": {"labels": {"pod-template-hash": "x"}, "annotations": null},
351 "spec": {"containers": [{"name": "c", "env": [], "resources": null}]}
352 });
353 let once = NormalizedTemplate::of(&messy);
354 assert_eq!(NormalizedTemplate::of(&once.0), once);
355 }
356
357 #[test]
358 fn of_spec_template_reads_absent_and_null_as_no_template() {
359 assert!(NormalizedTemplate::of_spec_template(&json!({"spec": {}})).is_none());
360 assert!(
361 NormalizedTemplate::of_spec_template(&json!({"spec": {"template": null}})).is_none()
362 );
363 assert!(
364 NormalizedTemplate::of_spec_template(&json!({"spec": {"template": web()}})).is_some()
365 );
366 }
367
368 #[test]
369 fn the_naming_hash_is_ten_hex_digits_and_follows_the_template() {
370 let h1 = NormalizedTemplate::of(&web())
371 .naming_hash()
372 .map(|h| h.to_string());
373 let mut v2 = web();
374 v2["spec"]["containers"][0]["image"] = json!("web:2");
375 let h2 = NormalizedTemplate::of(&v2)
376 .naming_hash()
377 .map(|h| h.to_string());
378 let h1 = h1.expect("hashable");
379 assert_eq!(h1.len(), 10);
380 assert!(
381 h1.chars()
382 .all(|c| c.is_ascii_hexdigit() && !c.is_ascii_uppercase())
383 );
384 assert_ne!(Some(h1), h2);
385 }
386
387 #[test]
388 fn equal_templates_get_equal_names() {
389 let mut nulls = web();
390 nulls["metadata"]["annotations"] = Value::Null;
391 nulls["spec"]["volumes"] = json!([]);
392 assert_eq!(
393 NormalizedTemplate::of(&web()).naming_hash(),
394 NormalizedTemplate::of(&nulls).naming_hash()
395 );
396 }
397
398 #[test]
399 fn the_naming_hash_keeps_the_names_it_always_gave() {
400 let t = json!({"spec": {}});
404 let bytes = serde_json::to_vec(&t).expect("serializable");
405 let mut h: u64 = 0xcbf2_9ce4_8422_2325;
406 for b in &bytes {
407 h ^= u64::from(*b);
408 h = h.wrapping_mul(0x0100_0000_01b3);
409 }
410 let old: String = format!("{h:016x}").chars().take(10).collect();
411 assert_eq!(
412 NormalizedTemplate::of(&t)
413 .naming_hash()
414 .map(|h| h.to_string()),
415 Some(old)
416 );
417 }
418}