Skip to main content

engenho_controllers/
meta.rs

1//! `ObjectMeta` accessor extension trait.
2//!
3//! Every workload controller (`ReplicaSet` / Deployment / `StatefulSet` /
4//! Endpoints / Job / GC) reads the same handful of fields off the
5//! opaque `serde_json::Value` it lists from the store:
6//!
7//!   * `metadata.uid`  — the object's stable identity (owner refs)
8//!   * `metadata.name` — the object's name (child naming, owner refs)
9//!   * `metadata.namespace` — scope
10//!
11//! Before this trait each controller hand-copied byte-identical
12//! `*_uid` / `*_name` accessors. Per the Prime Directive the shape is
13//! solved ONCE here: [`ObjectMeta`] is the single accessor surface every
14//! controller consumes. Adding a new controller no longer re-derives
15//! these accessors.
16//!
17//! The trait is implemented for [`serde_json::Value`] (so it is also
18//! available through any `&Value` deref); call sites read
19//! `obj.uid()` / `obj.name()` / `obj.namespace()` directly.
20//!
21//! ## Reading an integer: [`DefaultedInt`] and [`int_at`] (T1.6)
22//!
23//! A count (`spec.replicas`, `spec.completions`, `metadata.generation`)
24//! has three states — absent, an integer, or something else — and the
25//! old `spec_i64(key, default)` read the third as the first: a Deployment
26//! declaring `replicas: "3"` was scaled to one pod. Both readers go
27//! through [`engenho_types::SpecInt`] and keep the third state an error:
28//!
29//!   * [`int_at`] — `Ok(None)` absent, `Ok(Some(n))` an integer,
30//!     `Err(`[`ShapeError::NotAnInteger`]`)` anything else. For a field
31//!     whose absence means "off" (`startingDeadlineSeconds`).
32//!   * [`DefaultedInt::read`] — the same, with absence replaced by the
33//!     field's API default, declared once next to the field's path
34//!     ([`REPLICAS`]). For a count the apiserver would have defaulted.
35//!
36//! A malformed integer is a Declarative, Item-scoped [`ShapeError`]: the
37//! object it belongs to gets nothing written for it this pass and a
38//! Warning (an Event through the sweep, or [`warn_unreadable`] where
39//! there is no sweep), and every other object is reconciled as usual.
40//!
41//! ## Writing: [`object_mut`] and [`array_mut`] are total
42//!
43//! Reading an opaque object is already total (`get` returns `Option`).
44//! Writing was not: a controller reached a nested map through
45//! `.as_object_mut().expect(..)` or `serde_json`'s `IndexMut`, and both
46//! PANIC on a value of the wrong JSON type. Stored objects are declared by
47//! users, so the wrong type is ordinary input, not a broken invariant. The
48//! owner-reference writer was the worked case: a `ReplicaSet` whose
49//! `spec.template.metadata.ownerReferences` was `null` panicked the whole
50//! controller task on its first pod, and every `ReplicaSet` after it in the
51//! list stopped converging.
52//!
53//! The two accessors decide every shape in one place:
54//!
55//!   * absent, or `null` — treated as empty: `{}` or `[]` is inserted and
56//!     returned. Upstream's Go types decode `null` to a nil map or slice,
57//!     and every upstream writer initializes a nil one before writing, so
58//!     this is the same answer, not a new leniency;
59//!   * the expected container — returned as-is;
60//!   * anything else — [`ShapeError::Wrong`], naming the dotted path and the
61//!     JSON type found there. Nothing is written.
62//!
63//! [`JsonKind`] has no `Null` arm, because null is never reported: it is the
64//! empty case.
65
66use std::fmt;
67
68use engenho_types::SpecInt;
69use serde_json::{Map, Value};
70
71/// Borrowed accessors over a K8s object's `metadata` + `spec`.
72///
73/// Implemented for [`serde_json::Value`]. The returned `&str` borrows
74/// from the object, matching the byte-for-byte behavior of the
75/// per-controller accessors this trait replaces.
76pub trait ObjectMeta {
77    /// `metadata.uid` — the object's stable identity. `None` when the
78    /// field is absent or empty (a freshly minted object the apiserver has
79    /// not stamped yet; an empty uid is no uid).
80    fn uid(&self) -> Option<&str>;
81
82    /// `metadata.name` — the object's name. `None` when absent.
83    fn name(&self) -> Option<&str>;
84
85    /// `metadata.namespace` — the object's namespace scope. `None`
86    /// for cluster-scoped objects or before the field is set.
87    fn namespace(&self) -> Option<&str>;
88
89    /// `metadata.deletionTimestamp` — present once a delete was accepted
90    /// for an object that finalizers still hold (Terminating). `None` when
91    /// absent, `null` or empty: an empty stamp is no stamp.
92    fn deletion_timestamp(&self) -> Option<&str>;
93
94    /// Whether the object is Terminating: a delete was accepted and its
95    /// finalizers hold it (a [`Self::deletion_timestamp`] is present).
96    ///
97    /// A Terminating object is on its way out. A controller never writes
98    /// it again as a child: re-creating over it would clear a
99    /// `deletionTimestamp` nothing may clear, and deleting it again is the
100    /// store's `NoOp`, one Raft entry per tick.
101    fn is_terminating(&self) -> bool {
102        self.deletion_timestamp().is_some()
103    }
104
105    /// Whether `metadata.finalizers` names `finalizer`. An absent, `null`
106    /// or non-list field names none.
107    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
145/// `apps/v1` `spec.replicas` (Deployment, `ReplicaSet`, `StatefulSet`):
146/// the apiserver defaults an absent count to 1.
147pub const REPLICAS: DefaultedInt = DefaultedInt::new(&["spec", "replicas"], 1);
148
149/// An integer field whose absence means its API default.
150///
151/// The default is declared once, beside the path, so every controller
152/// reading the field applies the same one; the old `spec_i64(key,
153/// default)` took the default at each call site.
154#[derive(Debug, Clone, Copy, PartialEq, Eq)]
155pub struct DefaultedInt {
156    path: &'static [&'static str],
157    absent: i64,
158}
159
160impl DefaultedInt {
161    /// The field at `path`, reading as `absent` when missing or `null`.
162    #[must_use]
163    pub const fn new(path: &'static [&'static str], absent: i64) -> Self {
164        Self { path, absent }
165    }
166
167    /// The field's path, outermost first.
168    #[must_use]
169    pub const fn path(self) -> &'static [&'static str] {
170        self.path
171    }
172
173    /// The field's value in `object`: the integer it holds, or the API
174    /// default when it is missing or `null`.
175    ///
176    /// # Errors
177    ///
178    /// [`ShapeError::NotAnInteger`] when the field holds anything else —
179    /// never the default.
180    pub fn read(self, object: &Value) -> Result<i64, ShapeError> {
181        Ok(int_at(object, self.path)?.unwrap_or(self.absent))
182    }
183
184    /// # Errors
185    ///
186    /// [`ShapeError::NotAnInteger`] when the field holds anything else.
187    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
193/// The integer at `path` in `object`, in its three states: `Ok(None)`
194/// when missing or `null`, `Ok(Some(n))` when it holds an integer.
195///
196/// # Errors
197///
198/// [`ShapeError::NotAnInteger`] naming `path` when the field — or a step
199/// above it that is not an object — holds anything else.
200pub 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::at` reads `null` as Absent, so a `null` here is a
205        // `SpecInt` built by hand; it means what Absent means.
206        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
215/// Say that a field `object` declares cannot be read (`error` names it),
216/// so nothing is written from it this pass — the structured warning where
217/// there is no [`crate::sweep::Sweep`] to raise an Event on the object.
218pub 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/// The container a write needs at a path.
229#[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/// The JSON type found where a [`Container`] was needed.
245///
246/// There is no `Null` arm: the accessors treat null as empty and never
247/// report it.
248#[derive(Debug, Clone, Copy, PartialEq, Eq)]
249pub enum JsonKind {
250    Bool,
251    Number,
252    String,
253    Array,
254    Object,
255}
256
257impl JsonKind {
258    /// The kind of `value`; `None` for `null`, which is never reported.
259    #[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/// A dotted path into an object, as the operator reads it.
285///
286/// Segments are static field names. A value a controller built by cloning
287/// part of its parent (a Pod from `spec.template`) reports its paths
288/// relative to that parent through [`ShapeError::under`], so the message
289/// names the field the operator actually has to fix.
290#[derive(Debug, Clone, PartialEq, Eq)]
291pub struct FieldPath(Vec<&'static str>);
292
293impl FieldPath {
294    /// The path's segments, outermost first. Empty for the object itself.
295    #[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/// A stored object does not have the shape a controller needs: a write
317/// needs a container, or a read needs an integer.
318#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
319pub enum ShapeError {
320    /// `path` holds `found` where `expected` is required.
321    #[error("{path} is {found}, expected {expected}")]
322    Wrong {
323        path: FieldPath,
324        expected: Container,
325        found: JsonKind,
326    },
327    /// `path` cannot be read as an integer: `found` stands there, or at a
328    /// step above it that is not an object. `a number` here is one with a
329    /// fraction or beyond the `i64` range.
330    #[error("{path} is not an integer (found {found})")]
331    NotAnInteger { path: FieldPath, found: JsonKind },
332}
333
334impl ShapeError {
335    /// Re-anchor this error under `prefix`: the value it was found in is
336    /// the one at `prefix` in the object the operator declared.
337    #[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    /// The path the error names.
359    #[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
375/// The map at `path` inside `value`, creating every absent or null step as
376/// `{}`.
377///
378/// `path` is relative to `value`; the empty path is `value` itself.
379///
380/// # Errors
381///
382/// [`ShapeError::Wrong`] naming the first step (or `value` itself) that
383/// holds something other than an object or null. Nothing is written at or
384/// below that step.
385pub 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
400/// The array at `path` inside `value`, creating it as `[]` when absent or
401/// null, and every absent or null step above it as `{}`.
402///
403/// # Errors
404///
405/// [`ShapeError::Wrong`] naming the first step that holds something other
406/// than an object (above the leaf) or an array (at the leaf), or null.
407pub 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
422/// `slot` as a map; null becomes `{}`.
423fn 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
441/// `slot` as an array; null becomes `[]`.
442fn 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    /// T1.6 — `"3"` is not absent and is not 1. The old `spec_i64` read it
674    /// as the default and a Deployment declaring it was scaled to one pod.
675    #[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        // The returned &str borrows from the object (no allocation) —
745        // call sites that need an owned String do `.map(String::from)`.
746        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}