1use std::fmt;
67
68use engenho_types::SpecInt;
69use serde_json::{Map, Value};
70
71pub trait ObjectMeta {
77 fn uid(&self) -> Option<&str>;
81
82 fn name(&self) -> Option<&str>;
84
85 fn namespace(&self) -> Option<&str>;
88
89 fn deletion_timestamp(&self) -> Option<&str>;
93
94 fn is_terminating(&self) -> bool {
102 self.deletion_timestamp().is_some()
103 }
104
105 fn has_finalizer(&self, finalizer: &str) -> bool;
108}
109
110impl ObjectMeta for Value {
111 fn uid(&self) -> Option<&str> {
112 self.get("metadata")
113 .and_then(|m| m.get("uid"))
114 .and_then(|u| u.as_str())
115 .filter(|u| !u.is_empty())
116 }
117
118 fn name(&self) -> Option<&str> {
119 self.get("metadata")
120 .and_then(|m| m.get("name"))
121 .and_then(|n| n.as_str())
122 }
123
124 fn namespace(&self) -> Option<&str> {
125 self.get("metadata")
126 .and_then(|m| m.get("namespace"))
127 .and_then(|n| n.as_str())
128 }
129
130 fn deletion_timestamp(&self) -> Option<&str> {
131 self.get("metadata")
132 .and_then(|m| m.get("deletionTimestamp"))
133 .and_then(Value::as_str)
134 .filter(|ts| !ts.is_empty())
135 }
136
137 fn has_finalizer(&self, finalizer: &str) -> bool {
138 self.get("metadata")
139 .and_then(|m| m.get("finalizers"))
140 .and_then(Value::as_array)
141 .is_some_and(|all| all.iter().any(|f| f.as_str() == Some(finalizer)))
142 }
143}
144
145pub const REPLICAS: DefaultedInt = DefaultedInt::new(&["spec", "replicas"], 1);
148
149#[derive(Debug, Clone, Copy, PartialEq, Eq)]
155pub struct DefaultedInt {
156 path: &'static [&'static str],
157 absent: i64,
158}
159
160impl DefaultedInt {
161 #[must_use]
163 pub const fn new(path: &'static [&'static str], absent: i64) -> Self {
164 Self { path, absent }
165 }
166
167 #[must_use]
169 pub const fn path(self) -> &'static [&'static str] {
170 self.path
171 }
172
173 pub fn read(self, object: &Value) -> Result<i64, ShapeError> {
181 Ok(int_at(object, self.path)?.unwrap_or(self.absent))
182 }
183
184 pub fn read_count(self, object: &Value) -> Result<usize, ShapeError> {
188 self.read(object)
189 .map(|n| usize::try_from(n.max(0)).unwrap_or(usize::MAX))
190 }
191}
192
193pub fn int_at(object: &Value, path: &'static [&'static str]) -> Result<Option<i64>, ShapeError> {
201 match SpecInt::at(object, path) {
202 SpecInt::Absent => Ok(None),
203 SpecInt::Int(n) => Ok(Some(n)),
204 SpecInt::Malformed(found) => JsonKind::of(found).map_or(Ok(None), |found| {
207 Err(ShapeError::NotAnInteger {
208 path: FieldPath(path.to_vec()),
209 found,
210 })
211 }),
212 }
213}
214
215pub fn warn_unreadable(controller: &'static str, object: &dyn fmt::Display, error: &ShapeError) {
219 tracing::warn!(
220 controller,
221 object = %object,
222 field = %error.path(),
223 error = %error,
224 "a field this object declares cannot be read; nothing is written from it this pass"
225 );
226}
227
228#[derive(Debug, Clone, Copy, PartialEq, Eq)]
230pub enum Container {
231 Object,
232 Array,
233}
234
235impl fmt::Display for Container {
236 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
237 f.write_str(match self {
238 Self::Object => "an object",
239 Self::Array => "an array",
240 })
241 }
242}
243
244#[derive(Debug, Clone, Copy, PartialEq, Eq)]
249pub enum JsonKind {
250 Bool,
251 Number,
252 String,
253 Array,
254 Object,
255}
256
257impl JsonKind {
258 #[must_use]
260 pub const fn of(value: &Value) -> Option<Self> {
261 match value {
262 Value::Null => None,
263 Value::Bool(_) => Some(Self::Bool),
264 Value::Number(_) => Some(Self::Number),
265 Value::String(_) => Some(Self::String),
266 Value::Array(_) => Some(Self::Array),
267 Value::Object(_) => Some(Self::Object),
268 }
269 }
270}
271
272impl fmt::Display for JsonKind {
273 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
274 f.write_str(match self {
275 Self::Bool => "a boolean",
276 Self::Number => "a number",
277 Self::String => "a string",
278 Self::Array => "an array",
279 Self::Object => "an object",
280 })
281 }
282}
283
284#[derive(Debug, Clone, PartialEq, Eq)]
291pub struct FieldPath(Vec<&'static str>);
292
293impl FieldPath {
294 #[must_use]
296 pub fn segments(&self) -> &[&'static str] {
297 &self.0
298 }
299}
300
301impl fmt::Display for FieldPath {
302 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
303 let mut segments = self.0.iter();
304 let Some(first) = segments.next() else {
305 return f.write_str("the object itself");
306 };
307 f.write_str(first)?;
308 for segment in segments {
309 f.write_str(".")?;
310 f.write_str(segment)?;
311 }
312 Ok(())
313 }
314}
315
316#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
319pub enum ShapeError {
320 #[error("{path} is {found}, expected {expected}")]
322 Wrong {
323 path: FieldPath,
324 expected: Container,
325 found: JsonKind,
326 },
327 #[error("{path} is not an integer (found {found})")]
331 NotAnInteger { path: FieldPath, found: JsonKind },
332}
333
334impl ShapeError {
335 #[must_use]
338 pub fn under(self, prefix: &'static [&'static str]) -> Self {
339 let anchor =
340 |path: FieldPath| FieldPath(prefix.iter().chain(path.segments()).copied().collect());
341 match self {
342 Self::Wrong {
343 path,
344 expected,
345 found,
346 } => Self::Wrong {
347 path: anchor(path),
348 expected,
349 found,
350 },
351 Self::NotAnInteger { path, found } => Self::NotAnInteger {
352 path: anchor(path),
353 found,
354 },
355 }
356 }
357
358 #[must_use]
360 pub fn path(&self) -> &FieldPath {
361 match self {
362 Self::Wrong { path, .. } | Self::NotAnInteger { path, .. } => path,
363 }
364 }
365
366 fn wrong(path: &'static [&'static str], expected: Container, found: JsonKind) -> Self {
367 Self::Wrong {
368 path: FieldPath(path.to_vec()),
369 expected,
370 found,
371 }
372 }
373}
374
375pub fn object_mut<'v>(
386 value: &'v mut Value,
387 path: &'static [&'static str],
388) -> Result<&'v mut Map<String, Value>, ShapeError> {
389 match path.split_last() {
390 None => object_slot(value, path),
391 Some((last, parent)) => object_slot(
392 object_mut(value, parent)?
393 .entry(*last)
394 .or_insert(Value::Null),
395 path,
396 ),
397 }
398}
399
400pub fn array_mut<'v>(
408 value: &'v mut Value,
409 path: &'static [&'static str],
410) -> Result<&'v mut Vec<Value>, ShapeError> {
411 match path.split_last() {
412 None => array_slot(value, path),
413 Some((last, parent)) => array_slot(
414 object_mut(value, parent)?
415 .entry(*last)
416 .or_insert(Value::Null),
417 path,
418 ),
419 }
420}
421
422fn object_slot<'v>(
424 slot: &'v mut Value,
425 path: &'static [&'static str],
426) -> Result<&'v mut Map<String, Value>, ShapeError> {
427 let found = match slot {
428 Value::Object(map) => return Ok(map),
429 Value::Null => {
430 *slot = Value::Object(Map::new());
431 return object_slot(slot, path);
432 }
433 Value::Bool(_) => JsonKind::Bool,
434 Value::Number(_) => JsonKind::Number,
435 Value::String(_) => JsonKind::String,
436 Value::Array(_) => JsonKind::Array,
437 };
438 Err(ShapeError::wrong(path, Container::Object, found))
439}
440
441fn array_slot<'v>(
443 slot: &'v mut Value,
444 path: &'static [&'static str],
445) -> Result<&'v mut Vec<Value>, ShapeError> {
446 let found = match slot {
447 Value::Array(items) => return Ok(items),
448 Value::Null => {
449 *slot = Value::Array(Vec::new());
450 return array_slot(slot, path);
451 }
452 Value::Bool(_) => JsonKind::Bool,
453 Value::Number(_) => JsonKind::Number,
454 Value::String(_) => JsonKind::String,
455 Value::Object(_) => JsonKind::Object,
456 };
457 Err(ShapeError::wrong(path, Container::Array, found))
458}
459
460#[cfg(test)]
461mod tests {
462 use super::*;
463 use serde_json::json;
464
465 const OWNER_REFS: &[&str] = &["metadata", "ownerReferences"];
466 const ANNOTATIONS: &[&str] = &["metadata", "annotations"];
467
468 #[test]
469 fn absent_steps_are_created_empty() {
470 let mut obj = json!({"kind": "Pod"});
471 array_mut(&mut obj, OWNER_REFS).unwrap().push(json!(1));
472 assert_eq!(
473 obj,
474 json!({"kind": "Pod", "metadata": {"ownerReferences": [1]}})
475 );
476 }
477
478 #[test]
479 fn null_is_empty_at_every_step() {
480 let mut obj = json!({"metadata": null});
481 object_mut(&mut obj, ANNOTATIONS)
482 .unwrap()
483 .insert("a".into(), json!("b"));
484 assert_eq!(obj, json!({"metadata": {"annotations": {"a": "b"}}}));
485
486 let mut obj = json!({"metadata": {"ownerReferences": null}});
487 assert!(array_mut(&mut obj, OWNER_REFS).unwrap().is_empty());
488 assert_eq!(obj, json!({"metadata": {"ownerReferences": []}}));
489
490 let mut root = Value::Null;
491 object_mut(&mut root, &[]).unwrap();
492 assert_eq!(root, json!({}));
493 }
494
495 #[test]
496 fn an_existing_container_is_returned_untouched() {
497 let mut obj = json!({"metadata": {"annotations": {"keep": "me"}}});
498 let anns = object_mut(&mut obj, ANNOTATIONS).unwrap();
499 assert_eq!(anns.get("keep"), Some(&json!("me")));
500 }
501
502 #[test]
503 fn the_wrong_type_at_the_leaf_is_named_and_left_alone() {
504 let mut obj = json!({"metadata": {"ownerReferences": "x"}});
505 let err = array_mut(&mut obj, OWNER_REFS).unwrap_err();
506 assert_eq!(
507 err,
508 ShapeError::Wrong {
509 path: FieldPath(vec!["metadata", "ownerReferences"]),
510 expected: Container::Array,
511 found: JsonKind::String,
512 }
513 );
514 assert_eq!(
515 err.to_string(),
516 "metadata.ownerReferences is a string, expected an array"
517 );
518 assert_eq!(obj, json!({"metadata": {"ownerReferences": "x"}}));
519 }
520
521 #[test]
522 fn the_wrong_type_above_the_leaf_is_named_at_that_step() {
523 let mut obj = json!({"metadata": [1]});
524 let err = object_mut(&mut obj, ANNOTATIONS).unwrap_err();
525 assert_eq!(err.path().segments(), ["metadata"]);
526 assert_eq!(err.to_string(), "metadata is an array, expected an object");
527 assert_eq!(obj, json!({"metadata": [1]}));
528
529 let mut not_an_object = json!("scalar");
530 assert_eq!(
531 object_mut(&mut not_an_object, ANNOTATIONS)
532 .unwrap_err()
533 .to_string(),
534 "the object itself is a string, expected an object"
535 );
536 }
537
538 #[test]
539 fn every_non_null_kind_is_reported_as_itself() {
540 for (value, found) in [
541 (json!(true), JsonKind::Bool),
542 (json!(1), JsonKind::Number),
543 (json!("s"), JsonKind::String),
544 (json!([]), JsonKind::Array),
545 ] {
546 let mut obj = json!({"metadata": {"annotations": value}});
547 assert!(
548 matches!(
549 object_mut(&mut obj, ANNOTATIONS),
550 Err(ShapeError::Wrong { found: f, expected: Container::Object, .. }) if f == found
551 ),
552 "{found:?}"
553 );
554 }
555 let mut obj = json!({"metadata": {"ownerReferences": {}}});
556 assert!(matches!(
557 array_mut(&mut obj, OWNER_REFS),
558 Err(ShapeError::Wrong {
559 found: JsonKind::Object,
560 expected: Container::Array,
561 ..
562 })
563 ));
564 }
565
566 #[test]
567 fn under_re_anchors_the_path_in_the_parent() {
568 let mut pod = json!({"metadata": {"ownerReferences": 7}});
569 let err = array_mut(&mut pod, OWNER_REFS)
570 .unwrap_err()
571 .under(&["spec", "template"]);
572 assert_eq!(
573 err.to_string(),
574 "spec.template.metadata.ownerReferences is a number, expected an array"
575 );
576 }
577
578 #[test]
579 fn uid_reads_metadata_uid() {
580 let obj = json!({"metadata": {"uid": "u-1"}});
581 assert_eq!(obj.uid(), Some("u-1"));
582 }
583
584 #[test]
585 fn uid_none_when_absent() {
586 let obj = json!({"metadata": {"name": "x"}});
587 assert_eq!(obj.uid(), None);
588 let obj = json!({"spec": {}});
589 assert_eq!(obj.uid(), None);
590 }
591
592 #[test]
593 fn name_reads_metadata_name() {
594 let obj = json!({"metadata": {"name": "podinfo"}});
595 assert_eq!(obj.name(), Some("podinfo"));
596 }
597
598 #[test]
599 fn name_none_when_absent() {
600 let obj = json!({"metadata": {"uid": "u"}});
601 assert_eq!(obj.name(), None);
602 }
603
604 #[test]
605 fn namespace_reads_metadata_namespace() {
606 let obj = json!({"metadata": {"namespace": "kube-system"}});
607 assert_eq!(obj.namespace(), Some("kube-system"));
608 }
609
610 #[test]
611 fn namespace_none_when_absent() {
612 let obj = json!({"metadata": {"name": "x"}});
613 assert_eq!(obj.namespace(), None);
614 }
615
616 #[test]
617 fn deletion_timestamp_reads_a_stamp_and_nothing_else() {
618 let ts = "2026-01-01T00:00:00Z";
619 assert_eq!(
620 json!({"metadata": {"deletionTimestamp": ts}}).deletion_timestamp(),
621 Some(ts)
622 );
623 for unstamped in [
624 json!({"metadata": {}}),
625 json!({"metadata": {"deletionTimestamp": null}}),
626 json!({"metadata": {"deletionTimestamp": ""}}),
627 json!({}),
628 ] {
629 assert_eq!(unstamped.deletion_timestamp(), None, "{unstamped}");
630 assert!(!unstamped.is_terminating(), "{unstamped}");
631 }
632 assert!(json!({"metadata": {"deletionTimestamp": ts}}).is_terminating());
633 }
634
635 #[test]
636 fn has_finalizer_matches_a_named_entry_only() {
637 let obj = json!({"metadata": {"finalizers": ["orphan", "foregroundDeletion"]}});
638 assert!(obj.has_finalizer("foregroundDeletion"));
639 assert!(obj.has_finalizer("orphan"));
640 assert!(!obj.has_finalizer("kubernetes"));
641 for none in [
642 json!({"metadata": {}}),
643 json!({"metadata": {"finalizers": null}}),
644 json!({"metadata": {"finalizers": "foregroundDeletion"}}),
645 ] {
646 assert!(!none.has_finalizer("foregroundDeletion"), "{none}");
647 }
648 }
649
650 #[test]
651 fn a_declared_integer_is_read() {
652 let obj = json!({"spec": {"replicas": 3}});
653 assert_eq!(REPLICAS.read(&obj), Ok(3));
654 assert_eq!(int_at(&obj, &["spec", "replicas"]), Ok(Some(3)));
655 assert_eq!(REPLICAS.read(&json!({"spec": {"replicas": 0}})), Ok(0));
656 }
657
658 #[test]
659 fn an_absent_or_null_integer_is_the_api_default() {
660 for obj in [
661 json!({"spec": {}}),
662 json!({"spec": {"replicas": null}}),
663 json!({"spec": null}),
664 json!({"metadata": {}}),
665 ] {
666 assert_eq!(REPLICAS.read(&obj), Ok(1), "{obj}");
667 assert_eq!(int_at(&obj, REPLICAS.path()), Ok(None), "{obj}");
668 }
669 let seven = DefaultedInt::new(&["spec", "completions"], 7);
670 assert_eq!(seven.read(&json!({"spec": {}})), Ok(7));
671 }
672
673 #[test]
676 fn a_quoted_integer_is_an_error_naming_the_field_not_the_default() {
677 let obj = json!({"spec": {"replicas": "3"}});
678 let err = REPLICAS.read(&obj).unwrap_err();
679 assert_eq!(
680 err,
681 ShapeError::NotAnInteger {
682 path: FieldPath(vec!["spec", "replicas"]),
683 found: JsonKind::String,
684 }
685 );
686 assert_eq!(
687 err.to_string(),
688 "spec.replicas is not an integer (found a string)"
689 );
690 assert_eq!(int_at(&obj, REPLICAS.path()), Err(err));
691 }
692
693 #[test]
694 fn every_non_integer_is_an_error_never_a_value() {
695 for (value, found) in [
696 (json!("two"), JsonKind::String),
697 (json!(2.5), JsonKind::Number),
698 (json!(3.0), JsonKind::Number),
699 (json!(u64::MAX), JsonKind::Number),
700 (json!(true), JsonKind::Bool),
701 (json!([3]), JsonKind::Array),
702 (json!({"n": 3}), JsonKind::Object),
703 ] {
704 let obj = json!({"spec": {"replicas": value}});
705 assert!(
706 matches!(
707 REPLICAS.read(&obj),
708 Err(ShapeError::NotAnInteger { found: f, .. }) if f == found
709 ),
710 "{obj}"
711 );
712 }
713 }
714
715 #[test]
716 fn a_non_object_above_the_integer_is_an_error_too() {
717 let obj = json!({"spec": "oops"});
718 assert_eq!(
719 REPLICAS.read(&obj).unwrap_err().to_string(),
720 "spec.replicas is not an integer (found a string)"
721 );
722 }
723
724 #[test]
725 fn null_has_no_reported_kind() {
726 assert_eq!(JsonKind::of(&Value::Null), None);
727 assert_eq!(JsonKind::of(&json!(1)), Some(JsonKind::Number));
728 }
729
730 #[test]
731 fn not_an_integer_re_anchors_under_a_parent() {
732 let err = REPLICAS
733 .read(&json!({"spec": {"replicas": "3"}}))
734 .unwrap_err()
735 .under(&["spec", "template"]);
736 assert_eq!(
737 err.path().segments(),
738 ["spec", "template", "spec", "replicas"]
739 );
740 }
741
742 #[test]
743 fn accessors_return_borrowed_str() {
744 let obj = json!({"metadata": {"uid": "u", "name": "n", "namespace": "ns"}});
747 let _: Option<&str> = obj.uid();
748 let _: Option<&str> = obj.name();
749 let _: Option<&str> = obj.namespace();
750 }
751}