1use std::fmt;
33
34use serde_json::{Map, Value, json};
35
36use crate::meta::{ShapeError, array_mut, object_mut};
37
38crate::closed_enum! {
39 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
41 pub enum ConditionStatus {
42 True,
43 False,
44 Unknown,
45 }
46}
47
48impl ConditionStatus {
49 #[must_use]
51 pub const fn as_str(self) -> &'static str {
52 match self {
53 Self::True => "True",
54 Self::False => "False",
55 Self::Unknown => "Unknown",
56 }
57 }
58}
59
60impl fmt::Display for ConditionStatus {
61 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
62 f.write_str(self.as_str())
63 }
64}
65
66#[derive(Debug, Clone, PartialEq, Eq)]
72pub struct DesiredCondition {
73 pub condition_type: &'static str,
76 pub status: ConditionStatus,
77 pub reason: &'static str,
79 pub message: String,
81}
82
83impl DesiredCondition {
84 fn is_recorded_by(&self, recorded: &Value) -> bool {
91 text(recorded, "status") == self.status.as_str()
92 && text(recorded, "reason") == self.reason
93 && text(recorded, "message") == self.message
94 }
95
96 fn is_type_of(&self, condition: &Value) -> bool {
98 condition.get("type").and_then(Value::as_str) == Some(self.condition_type)
99 }
100
101 fn write_into(&self, slot: &mut Map<String, Value>, transition: String) {
104 slot.insert("type".to_owned(), json!(self.condition_type));
105 slot.insert("status".to_owned(), json!(self.status.as_str()));
106 slot.insert("reason".to_owned(), json!(self.reason));
107 slot.insert("message".to_owned(), json!(self.message));
108 slot.insert("lastTransitionTime".to_owned(), Value::String(transition));
109 }
110}
111
112fn text<'v>(condition: &'v Value, field: &str) -> &'v str {
114 condition.get(field).and_then(Value::as_str).unwrap_or("")
115}
116
117#[derive(Debug, Clone, PartialEq)]
119pub enum ConditionUpsert {
120 Unchanged,
122 Changed(Vec<Value>),
124}
125
126impl ConditionUpsert {
127 #[must_use]
131 pub fn into_status_fields(self) -> Option<Map<String, Value>> {
132 match self {
133 Self::Unchanged => None,
134 Self::Changed(conditions) => {
135 let mut fields = Map::new();
136 fields.insert("conditions".to_owned(), Value::Array(conditions));
137 Some(fields)
138 }
139 }
140 }
141}
142
143pub fn upsert_condition(
155 object: &Value,
156 desired: &DesiredCondition,
157 now: &str,
158) -> Result<ConditionUpsert, ShapeError> {
159 let mut status = object.get("status").cloned().unwrap_or(Value::Null);
160 let conditions = array_mut(&mut status, &["conditions"]).map_err(|e| e.under(&["status"]))?;
161
162 let before = conditions.len();
164 let mut seen = false;
165 conditions.retain(|c| {
166 let duplicate = desired.is_type_of(c) && seen;
167 seen |= desired.is_type_of(c);
168 !duplicate
169 });
170 let collapsed = conditions.len() != before;
171
172 let Some(recorded) = conditions.iter_mut().find(|c| desired.is_type_of(c)) else {
173 let mut appended = Map::new();
174 desired.write_into(&mut appended, now.to_owned());
175 conditions.push(Value::Object(appended));
176 return Ok(ConditionUpsert::Changed(std::mem::take(conditions)));
177 };
178 if !collapsed && desired.is_recorded_by(recorded) {
179 return Ok(ConditionUpsert::Unchanged);
180 }
181
182 let transition = match recorded.get("lastTransitionTime").and_then(Value::as_str) {
183 Some(at) if text(recorded, "status") == desired.status.as_str() => at.to_owned(),
184 _ => now.to_owned(),
185 };
186 let slot = object_mut(recorded, &[]).map_err(|e| e.under(&["status", "conditions"]))?;
189 desired.write_into(slot, transition);
190 Ok(ConditionUpsert::Changed(std::mem::take(conditions)))
191}
192
193#[cfg(test)]
194mod tests {
195 use super::*;
196
197 const T0: &str = "2026-09-19T10:00:00Z";
198 const NOW: &str = "2026-09-19T12:00:00Z";
199
200 fn unschedulable(message: &str) -> DesiredCondition {
201 DesiredCondition {
202 condition_type: "PodScheduled",
203 status: ConditionStatus::False,
204 reason: "Unschedulable",
205 message: message.to_owned(),
206 }
207 }
208
209 fn recorded(status: &str, message: &str, at: &str) -> Value {
210 json!({"type": "PodScheduled", "status": status, "reason": "Unschedulable",
211 "message": message, "lastTransitionTime": at})
212 }
213
214 fn changed(upsert: ConditionUpsert) -> Vec<Value> {
215 match upsert {
216 ConditionUpsert::Changed(list) => list,
217 ConditionUpsert::Unchanged => panic!("expected a change"),
218 }
219 }
220
221 #[test]
222 fn every_status_renders_its_wire_string() {
223 let rendered: Vec<&str> = ConditionStatus::ALL.iter().map(|s| s.as_str()).collect();
224 assert_eq!(rendered, ["True", "False", "Unknown"]);
225 }
226
227 #[test]
228 fn a_missing_condition_is_appended_stamped_now() {
229 let pod = json!({"status": {"conditions": [{"type": "Initialized", "status": "True"}]}});
230 let list = changed(upsert_condition(&pod, &unschedulable("0/1 nodes"), NOW).unwrap());
231 assert_eq!(
232 list,
233 vec![
234 json!({"type": "Initialized", "status": "True"}),
235 recorded("False", "0/1 nodes", NOW),
236 ]
237 );
238 }
239
240 #[test]
241 fn an_object_with_no_status_gets_its_first_condition() {
242 let list = changed(upsert_condition(&json!({}), &unschedulable("m"), NOW).unwrap());
243 assert_eq!(list, vec![recorded("False", "m", NOW)]);
244 }
245
246 #[test]
250 fn the_same_condition_is_unchanged_at_any_later_now() {
251 let mut carried = recorded("False", "0/1 nodes", T0);
252 carried["lastProbeTime"] = json!(T0);
253 let pod = json!({"status": {"conditions": [carried]}});
254 assert_eq!(
255 upsert_condition(&pod, &unschedulable("0/1 nodes"), NOW).unwrap(),
256 ConditionUpsert::Unchanged
257 );
258 }
259
260 #[test]
263 fn a_new_message_keeps_the_transition_time_and_the_position() {
264 let pod = json!({"status": {"conditions": [
265 recorded("False", "0/1 nodes", T0),
266 {"type": "Initialized", "status": "True"},
267 ]}});
268 let list = changed(upsert_condition(&pod, &unschedulable("0/2 nodes"), NOW).unwrap());
269 assert_eq!(
270 list,
271 vec![
272 recorded("False", "0/2 nodes", T0),
273 json!({"type": "Initialized", "status": "True"}),
274 ]
275 );
276 }
277
278 #[test]
279 fn a_status_flip_stamps_now() {
280 let pod = json!({"status": {"conditions": [recorded("True", "", T0)]}});
281 let list = changed(upsert_condition(&pod, &unschedulable("m"), NOW).unwrap());
282 assert_eq!(list, vec![recorded("False", "m", NOW)]);
283 }
284
285 #[test]
288 fn a_rewrite_with_no_recorded_time_stamps_now() {
289 let pod = json!({"status": {"conditions": [
290 {"type": "PodScheduled", "status": "False", "reason": "Unschedulable", "message": "old"}
291 ]}});
292 let list = changed(upsert_condition(&pod, &unschedulable("new"), NOW).unwrap());
293 assert_eq!(list, vec![recorded("False", "new", NOW)]);
294 }
295
296 #[test]
298 fn a_rewrite_keeps_fields_the_author_does_not_assert() {
299 let mut carried = recorded("False", "old", T0);
300 carried["lastProbeTime"] = json!(T0);
301 let pod = json!({"status": {"conditions": [carried]}});
302 let list = changed(upsert_condition(&pod, &unschedulable("new"), NOW).unwrap());
303 assert_eq!(list[0]["lastProbeTime"], T0);
304 assert_eq!(list[0]["message"], "new");
305 }
306
307 #[test]
308 fn duplicates_of_the_type_collapse_into_the_first() {
309 let pod = json!({"status": {"conditions": [
310 recorded("False", "m", T0),
311 {"type": "Initialized", "status": "True"},
312 recorded("False", "stale", T0),
313 ]}});
314 let list = changed(upsert_condition(&pod, &unschedulable("m"), NOW).unwrap());
315 assert_eq!(
316 list,
317 vec![
318 recorded("False", "m", T0),
319 json!({"type": "Initialized", "status": "True"}),
320 ]
321 );
322 }
323
324 #[test]
325 fn a_malformed_list_is_an_error_naming_it() {
326 for (pod, path) in [
327 (json!({"status": "Pending"}), "status"),
328 (json!({"status": {"conditions": {}}}), "status.conditions"),
329 ] {
330 let err = upsert_condition(&pod, &unschedulable("m"), NOW).unwrap_err();
331 assert_eq!(err.path().to_string(), path, "{pod}");
332 }
333 }
334
335 #[test]
336 fn only_a_change_carries_status_fields() {
337 assert_eq!(ConditionUpsert::Unchanged.into_status_fields(), None);
338 let fields = ConditionUpsert::Changed(vec![json!(1)])
339 .into_status_fields()
340 .unwrap();
341 assert_eq!(Value::Object(fields), json!({"conditions": [1]}));
342 }
343}