Skip to main content

engenho_controllers/
create_stamp.rs

1//! `creationTimestamp` boundary stamp for controller-created objects.
2//!
3//! ## The compat gap this closes
4//!
5//! The apiserver HTTP boundary stamps `metadata.creationTimestamp` on
6//! every kubectl-created object (`engenho_types::birth::stamp_born`),
7//! so `kubectl get <kind>` renders a real `AGE`. But objects a
8//! CONTROLLER creates — `ReplicaSets` (from the Deployment controller),
9//! Pods (from the ReplicaSet/StatefulSet/Job controllers), Endpoints
10//! (from the Endpoints controller) — never crossed that HTTP boundary;
11//! they are born inside a reconcile via [`engenho_store::command::ResourceCommand::Put`].
12//! Without this stamp they carried NO `creationTimestamp` → `kubectl get
13//! rs/pods` showed `AGE <unknown>`.
14//!
15//! ## The determinism contract (★★ — mirror the apiserver boundary clock)
16//!
17//! `creationTimestamp` is the ONE non-deterministic input on a create.
18//! It MUST be read ONCE, at the LEADER, BEFORE the Raft propose, and
19//! frozen into the single replicated `Put` value — so every Raft replica
20//! replays identical bytes. It MUST NOT be read inside the deterministic
21//! store-apply path (which runs per-node on replay and would diverge
22//! replicas — the exact law `engenho_types::time` documents, and the
23//! reason the store stamps uid/resourceVersion from REPLICATED inputs but
24//! never reads a clock).
25//!
26//! The controller-side reconcile (where [`stamp_create_timestamp`] runs)
27//! IS that leader boundary: a reconcile proposes through the leader's
28//! `StoreMesh::propose`, exactly once per delta, BEFORE the command is
29//! replicated. So the clock read here is the controller-family analogue
30//! of the apiserver's `engenho_types::birth::stamp_born`. Since 2026-10-15
31//! `StoreMesh::propose` also runs that stamp on every `Put` of an absent key,
32//! so a controller that skips this one still writes a born object.
33//!
34//! ## The `Clock` seam (unit-test determinism)
35//!
36//! The wall-clock read is injected as a [`CreateClock`] (`fn() -> String`) so
37//! unit tests pin a FIXED timestamp and assert exact bytes, while
38//! production uses [`wall_clock`] (`engenho_types::time::now_rfc3339_utc`).
39//! Reconcile determinism tests stay deterministic — the clock is never
40//! called inline.
41//!
42//! ## Idempotency
43//!
44//! The stamp is applied ONLY when the object does not already carry a
45//! `creationTimestamp` AND only on a CREATE (a `Put` of a key absent from
46//! the store this tick). An update-shaped `Put` of an existing key is left
47//! untouched — the timestamp is never bumped (matching k8s: a create-time
48//! field, immutable thereafter).
49
50use serde_json::Value;
51
52/// The boundary clock read: a function yielding the RFC3339-UTC wire
53/// timestamp. Injected so unit tests pin a fixed instant; production
54/// passes [`wall_clock`].
55///
56/// Distinct from `engenho_substrate::relogio::Clock` (a monotonic /
57/// causal `Instant`/`unix_secs` clock used for lease/HLC ordering): this
58/// is purpose-built for the `metadata.creationTimestamp` RFC3339 WIRE
59/// string, mirroring the apiserver boundary's `chrono`-rendered stamp.
60pub type CreateClock = fn() -> String;
61
62/// Production clock — the same typed RFC3339 render surface the apiserver
63/// boundary uses (`engenho_types::time::now_rfc3339_utc`). NEVER `format!()`
64/// of the wire string (★★ TYPED EMISSION).
65#[must_use]
66pub fn wall_clock() -> String {
67    engenho_types::time::now_rfc3339_utc()
68}
69
70pub use engenho_types::birth::creation_timestamp_is_unset;
71
72/// Inject `metadata.creationTimestamp` from `clock()` into `value`, IFF the
73/// slot is currently unset. Idempotent: an object that already carries a
74/// non-empty creationTimestamp is left untouched (never bumped). Pure JSON
75/// mutation of the (about-to-be-replicated) value — the frozen string then
76/// travels inside the single replicated `Put`.
77///
78/// Returns `true` iff a stamp was applied (a fresh create), `false` iff the
79/// slot was already set (no-op).
80pub fn stamp_create_timestamp(value: &mut Value, clock: CreateClock) -> bool {
81    value.is_object()
82        && creation_timestamp_is_unset(value.pointer("/metadata/creationTimestamp"))
83        && engenho_types::birth::stamp_creation_timestamp(value, &clock())
84}
85
86#[cfg(test)]
87mod tests {
88    use super::*;
89    use serde_json::json;
90
91    const FIXED: &str = "2026-06-14T00:00:00Z";
92    fn fixed_clock() -> String {
93        FIXED.to_string()
94    }
95
96    #[test]
97    fn stamps_when_absent() {
98        let mut v = json!({"metadata": {"name": "rs1"}});
99        let stamped = stamp_create_timestamp(&mut v, fixed_clock);
100        assert!(stamped, "an absent timestamp must be stamped");
101        assert_eq!(
102            v.get("metadata").unwrap().get("creationTimestamp").unwrap(),
103            FIXED
104        );
105    }
106
107    #[test]
108    fn creates_metadata_when_missing() {
109        let mut v = json!({"kind": "Pod"});
110        assert!(stamp_create_timestamp(&mut v, fixed_clock));
111        assert_eq!(
112            v.get("metadata").unwrap().get("creationTimestamp").unwrap(),
113            FIXED
114        );
115    }
116
117    #[test]
118    fn idempotent_does_not_bump_existing() {
119        let mut v = json!({"metadata": {"creationTimestamp": "2020-01-01T00:00:00Z"}});
120        let stamped = stamp_create_timestamp(&mut v, fixed_clock);
121        assert!(!stamped, "an existing timestamp must NOT be re-stamped");
122        assert_eq!(
123            v.get("metadata").unwrap().get("creationTimestamp").unwrap(),
124            "2020-01-01T00:00:00Z",
125            "the existing timestamp must be preserved, never bumped"
126        );
127    }
128
129    #[test]
130    fn treats_empty_string_as_unset() {
131        let mut v = json!({"metadata": {"creationTimestamp": ""}});
132        assert!(stamp_create_timestamp(&mut v, fixed_clock));
133        assert_eq!(
134            v.get("metadata").unwrap().get("creationTimestamp").unwrap(),
135            FIXED
136        );
137    }
138
139    #[test]
140    fn treats_empty_object_as_unset() {
141        // protobuf-decoded zero metav1.Time → {}
142        let mut v = json!({"metadata": {"creationTimestamp": {}}});
143        assert!(stamp_create_timestamp(&mut v, fixed_clock));
144        assert_eq!(
145            v.get("metadata").unwrap().get("creationTimestamp").unwrap(),
146            FIXED
147        );
148    }
149
150    #[test]
151    fn treats_null_as_unset() {
152        let mut v = json!({"metadata": {"creationTimestamp": null}});
153        assert!(stamp_create_timestamp(&mut v, fixed_clock));
154        assert_eq!(
155            v.get("metadata").unwrap().get("creationTimestamp").unwrap(),
156            FIXED
157        );
158    }
159
160    #[test]
161    fn unset_predicate_matches_apiserver() {
162        assert!(creation_timestamp_is_unset(None));
163        assert!(creation_timestamp_is_unset(Some(&Value::Null)));
164        assert!(creation_timestamp_is_unset(Some(&json!(""))));
165        assert!(creation_timestamp_is_unset(Some(&json!({}))));
166        assert!(!creation_timestamp_is_unset(Some(&json!(
167            "2026-01-01T00:00:00Z"
168        ))));
169    }
170
171    #[test]
172    fn wall_clock_renders_zulu_rfc3339() {
173        let s = wall_clock();
174        assert!(s.ends_with('Z'), "wire timestamp must be Zulu: {s}");
175        assert!(!s.contains('.'), "second precision: {s}");
176    }
177}