1use serde_json::{Map, Value, json};
2use std::collections::BTreeSet;
3use std::time::{SystemTime, UNIX_EPOCH};
4
5const LAST_APPLIED: &str = "kubectl.kubernetes.io/last-applied-configuration";
6const MANAGED: &str = "managedFields";
7
8pub fn last_applied_annotation_key() -> &'static str {
9 LAST_APPLIED
10}
11
12fn same(a: &Value, b: &Value) -> bool {
13 a == b || matches!((a, b), (Value::Number(x), Value::Number(y)) if x.as_f64() == y.as_f64())
14}
15
16pub fn json_merge_patch(target: &mut Value, patch: &Value) {
17 let Value::Object(p) = patch else {
18 *target = patch.clone();
19 return;
20 };
21 if !target.is_object() {
22 *target = Value::Object(Map::new());
23 }
24 if let Value::Object(t) = target {
25 for (k, v) in p {
26 if v.is_null() {
27 t.remove(k);
28 } else {
29 json_merge_patch(t.entry(k.clone()).or_insert(Value::Null), v);
30 }
31 }
32 }
33}
34
35fn unescape(token: &str) -> String {
36 token.replace("~1", "/").replace("~0", "~")
37}
38
39fn split_pointer(path: &str) -> Result<(&str, String), String> {
40 let i = path
41 .rfind('/')
42 .filter(|_| path.starts_with('/'))
43 .ok_or_else(|| format!("invalid JSON pointer: {path:?}"))?;
44 Ok((&path[..i], unescape(&path[i + 1..])))
45}
46
47fn array_index(token: &str) -> Option<usize> {
48 if token.is_empty()
49 || (token.len() > 1 && token.starts_with('0'))
50 || !token.bytes().all(|b| b.is_ascii_digit())
51 {
52 return None;
53 }
54 token.parse().ok()
55}
56
57fn op_add(doc: &mut Value, path: &str, value: Value) -> Result<(), String> {
58 if path.is_empty() {
59 *doc = value;
60 return Ok(());
61 }
62 let (parent, last) = split_pointer(path)?;
63 match doc.pointer_mut(parent) {
64 Some(Value::Object(m)) => {
65 m.insert(last, value);
66 Ok(())
67 }
68 Some(Value::Array(a)) => {
69 if last == "-" {
70 a.push(value);
71 return Ok(());
72 }
73 let i = array_index(&last)
74 .filter(|i| *i <= a.len())
75 .ok_or_else(|| format!("invalid array index in {path}"))?;
76 a.insert(i, value);
77 Ok(())
78 }
79 _ => Err(format!("add target parent does not exist: {path}")),
80 }
81}
82
83fn op_remove(doc: &mut Value, path: &str) -> Result<Value, String> {
84 if path.is_empty() {
85 return Err("cannot remove the document root".into());
86 }
87 let (parent, last) = split_pointer(path)?;
88 match doc.pointer_mut(parent) {
89 Some(Value::Object(m)) => m
90 .remove(&last)
91 .ok_or_else(|| format!("path does not exist: {path}")),
92 Some(Value::Array(a)) => {
93 let i = array_index(&last)
94 .filter(|i| *i < a.len())
95 .ok_or_else(|| format!("invalid array index in {path}"))?;
96 Ok(a.remove(i))
97 }
98 _ => Err(format!("path does not exist: {path}")),
99 }
100}
101
102const MAX_OPS: usize = 10_000;
103const MAX_DEPTH: usize = 100;
104const MAX_COPY_BYTES: usize = 8 << 20;
105
106fn measure(v: &Value) -> (usize, usize) {
107 let mut stack = vec![(v, 1usize)];
108 let (mut depth, mut size) = (0, 0);
109 while let Some((v, d)) = stack.pop() {
110 depth = depth.max(d);
111 size += 8;
112 match v {
113 Value::String(s) => size += s.len(),
114 Value::Array(a) => stack.extend(a.iter().map(|x| (x, d + 1))),
115 Value::Object(m) => {
116 for (k, x) in m {
117 size += k.len();
118 stack.push((x, d + 1));
119 }
120 }
121 _ => {}
122 }
123 }
124 (depth, size)
125}
126
127fn ptr_depth(p: &str) -> usize {
128 p.matches('/').count()
129}
130
131struct Budget {
132 depth: usize,
133 copied: usize,
134}
135
136impl Budget {
137 fn place(&mut self, path: &str, value_depth: usize) -> Result<(), String> {
138 let d = ptr_depth(path) + value_depth;
139 if d > MAX_DEPTH {
140 return Err(format!(
141 "resulting document is nested deeper than {MAX_DEPTH} levels"
142 ));
143 }
144 self.depth = self.depth.max(d);
145 Ok(())
146 }
147}
148
149fn guard(doc: &Value, op: &Value, b: &mut Budget) -> Result<(), String> {
150 let name = op.get("op").and_then(Value::as_str).unwrap_or("");
151 let path = op.get("path").and_then(Value::as_str).unwrap_or("");
152 match name {
153 "add" | "replace" => {
154 let vd = op.get("value").map(|v| measure(v).0).unwrap_or(0);
155 b.place(path, vd)
156 }
157 "move" => {
158 let from = op.get("from").and_then(Value::as_str).unwrap_or("");
159 let vd = b.depth.saturating_sub(ptr_depth(from));
160 b.place(path, vd)
161 }
162 "copy" => {
163 let from = op.get("from").and_then(Value::as_str).unwrap_or("");
164 let (vd, size) = doc.pointer(from).map(measure).unwrap_or((0, 0));
165 b.copied += size;
166 if b.copied > MAX_COPY_BYTES {
167 return Err("copy operations exceed the size limit".into());
168 }
169 b.place(path, vd)
170 }
171 _ => Ok(()),
172 }
173}
174
175fn apply_op(doc: &mut Value, op: &Value) -> Result<(), String> {
176 let name = op
177 .get("op")
178 .and_then(Value::as_str)
179 .ok_or("missing \"op\"")?;
180 let path = op
181 .get("path")
182 .and_then(Value::as_str)
183 .ok_or("missing \"path\"")?;
184 let value = || {
185 op.get("value")
186 .cloned()
187 .ok_or_else(|| "missing \"value\"".to_string())
188 };
189 let from = || {
190 op.get("from")
191 .and_then(Value::as_str)
192 .ok_or_else(|| "missing \"from\"".to_string())
193 };
194 match name {
195 "add" => op_add(doc, path, value()?),
196 "remove" => op_remove(doc, path).map(|_| ()),
197 "replace" => {
198 let v = value()?;
199 if path.is_empty() {
200 *doc = v;
201 return Ok(());
202 }
203 let slot = doc
204 .pointer_mut(path)
205 .ok_or_else(|| format!("path does not exist: {path}"))?;
206 *slot = v;
207 Ok(())
208 }
209 "move" => {
210 let from = from()?;
211 if from == path {
212 return doc
213 .pointer(from)
214 .map(|_| ())
215 .ok_or_else(|| format!("path does not exist: {from}"));
216 }
217 if path.starts_with(&format!("{from}/")) {
218 return Err("cannot move a value into one of its children".into());
219 }
220 let v = op_remove(doc, from)?;
221 op_add(doc, path, v)
222 }
223 "copy" => {
224 let from = from()?;
225 let v = doc
226 .pointer(from)
227 .cloned()
228 .ok_or_else(|| format!("path does not exist: {from}"))?;
229 op_add(doc, path, v)
230 }
231 "test" => {
232 let want = value()?;
233 match doc.pointer(path) {
234 Some(have) if same(have, &want) => Ok(()),
235 Some(_) => Err(format!("test failed at {path}")),
236 None => Err(format!("path does not exist: {path}")),
237 }
238 }
239 other => Err(format!("unknown operation: {other}")),
240 }
241}
242
243pub fn json_patch(target: &mut Value, ops: &Value) -> Result<(), String> {
244 let Value::Array(list) = ops else {
245 return Err("JSON patch must be an array".into());
246 };
247 if list.len() > MAX_OPS {
248 return Err(format!("JSON patch has more than {MAX_OPS} operations"));
249 }
250 let mut work = target.clone();
251 let mut b = Budget {
252 depth: measure(&work).0,
253 copied: 0,
254 };
255 for (i, op) in list.iter().enumerate() {
256 guard(&work, op, &mut b).map_err(|e| format!("operation {i}: {e}"))?;
257 apply_op(&mut work, op).map_err(|e| format!("operation {i}: {e}"))?;
258 }
259 *target = work;
260 Ok(())
261}
262
263#[derive(Clone, Copy)]
264enum List {
265 Key(&'static str),
266 Set,
267}
268
269struct Field {
270 parent: &'static str,
271 name: &'static str,
272 list: Option<List>,
273 child: &'static str,
274}
275
276const fn obj(parent: &'static str, name: &'static str, child: &'static str) -> Field {
277 Field {
278 parent,
279 name,
280 list: None,
281 child,
282 }
283}
284
285const fn keyed(
286 parent: &'static str,
287 name: &'static str,
288 key: &'static str,
289 child: &'static str,
290) -> Field {
291 Field {
292 parent,
293 name,
294 list: Some(List::Key(key)),
295 child,
296 }
297}
298
299const fn set(parent: &'static str, name: &'static str) -> Field {
300 Field {
301 parent,
302 name,
303 list: Some(List::Set),
304 child: "",
305 }
306}
307
308const ROOTS: &[&str] = &[
309 "Object",
310 "Pod",
311 "PodTemplate",
312 "Workload",
313 "CronJob",
314 "Service",
315];
316
317static ROOT_FIELDS: &[Field] = &[
318 obj("", "metadata", "ObjectMeta"),
319 obj("", "status", "Status"),
320];
321
322static FIELDS: &[Field] = &[
323 obj("Pod", "spec", "PodSpec"),
324 obj("Workload", "spec", "WorkloadSpec"),
325 obj("PodTemplate", "template", "PodTemplateSpec"),
326 obj("CronJob", "spec", "CronJobSpec"),
327 obj("Service", "spec", "ServiceSpec"),
328 obj("CronJobSpec", "jobTemplate", "JobTemplateSpec"),
329 obj("JobTemplateSpec", "metadata", "ObjectMeta"),
330 obj("JobTemplateSpec", "spec", "WorkloadSpec"),
331 obj("WorkloadSpec", "template", "PodTemplateSpec"),
332 obj("PodTemplateSpec", "metadata", "ObjectMeta"),
333 obj("PodTemplateSpec", "spec", "PodSpec"),
334 keyed("ObjectMeta", "ownerReferences", "uid", ""),
335 set("ObjectMeta", "finalizers"),
336 keyed("Status", "conditions", "type", ""),
337 keyed("PodSpec", "containers", "name", "Container"),
338 keyed("PodSpec", "initContainers", "name", "Container"),
339 keyed("PodSpec", "ephemeralContainers", "name", "Container"),
340 keyed("PodSpec", "volumes", "name", ""),
341 keyed("PodSpec", "imagePullSecrets", "name", ""),
342 keyed("PodSpec", "hostAliases", "ip", ""),
343 keyed("Container", "env", "name", ""),
344 keyed("Container", "ports", "containerPort", ""),
345 keyed("Container", "volumeMounts", "mountPath", ""),
346 keyed("Container", "volumeDevices", "devicePath", ""),
347 keyed("ServiceSpec", "ports", "port", ""),
348];
349
350fn lookup(parent: &str, name: &str) -> Option<&'static Field> {
351 FIELDS
352 .iter()
353 .find(|f| f.parent == parent && f.name == name)
354 .or_else(|| {
355 ROOTS
356 .contains(&parent)
357 .then(|| ROOT_FIELDS.iter().find(|f| f.name == name))
358 .flatten()
359 })
360}
361
362fn root_type(kind: &str) -> &'static str {
363 match kind {
364 "Pod" => "Pod",
365 "PodTemplate" => "PodTemplate",
366 "Deployment"
367 | "ReplicaSet"
368 | "StatefulSet"
369 | "DaemonSet"
370 | "Job"
371 | "ReplicationController" => "Workload",
372 "CronJob" => "CronJob",
373 "Service" => "Service",
374 _ => "Object",
375 }
376}
377
378fn is_directive(key: &str) -> bool {
379 key == "$patch"
380 || key == "$retainKeys"
381 || key.starts_with("$setElementOrder/")
382 || key.starts_with("$deleteFromPrimitiveList/")
383}
384
385fn directive(v: &Value) -> Option<&str> {
386 v.get("$patch").and_then(Value::as_str)
387}
388
389fn element_id(v: &Value, key: Option<&str>) -> Value {
390 match key {
391 Some(k) => v.get(k).cloned().unwrap_or(Value::Null),
392 None => v.clone(),
393 }
394}
395
396fn reorder(arr: &mut Vec<Value>, order: &[Value], key: Option<&str>) {
397 let mut pool = std::mem::take(arr);
398 let mut out = Vec::with_capacity(pool.len());
399 for o in order {
400 let want = element_id(o, key);
401 if let Some(i) = pool.iter().position(|x| element_id(x, key) == want) {
402 out.push(pool.remove(i));
403 }
404 }
405 out.extend(pool);
406 *arr = out;
407}
408
409fn merge_keyed(
410 child: &str,
411 key: &str,
412 target: &mut Vec<Value>,
413 patch: &[Value],
414) -> Result<(), String> {
415 let is_marker =
416 |e: &Value| directive(e) == Some("replace") && e.as_object().is_some_and(|o| o.len() == 1);
417 if patch.iter().any(is_marker) {
418 *target = patch.iter().filter(|e| !is_marker(e)).cloned().collect();
419 return Ok(());
420 }
421 for e in patch {
422 let Value::Object(eo) = e else {
423 return Err(format!("list element is not an object: {e}"));
424 };
425 let kv = eo
426 .get(key)
427 .ok_or_else(|| format!("map: {e} does not contain declared merge key: {key}"))?;
428 let pos = target.iter().position(|x| x.get(key) == Some(kv));
429 match (directive(e), pos) {
430 (Some("delete"), Some(i)) => {
431 target.remove(i);
432 }
433 (Some("delete"), None) => {}
434 (_, Some(i)) => {
435 if let Value::Object(tm) = &mut target[i] {
436 merge_obj(child, tm, eo)?;
437 }
438 }
439 (_, None) => {
440 let mut m = Map::new();
441 merge_obj(child, &mut m, eo)?;
442 target.push(Value::Object(m));
443 }
444 }
445 }
446 Ok(())
447}
448
449fn merge_obj(ty: &str, t: &mut Map<String, Value>, p: &Map<String, Value>) -> Result<(), String> {
450 match p.get("$patch").and_then(Value::as_str) {
451 Some("replace") => {
452 *t = p
453 .iter()
454 .filter(|(k, _)| k.as_str() != "$patch")
455 .map(|(k, v)| (k.clone(), v.clone()))
456 .collect();
457 return Ok(());
458 }
459 Some("delete") => {
460 t.clear();
461 return Ok(());
462 }
463 Some("merge") | None => {}
464 Some(other) => return Err(format!("unknown patch strategy: {other}")),
465 }
466 for (k, v) in p {
467 if is_directive(k) {
468 continue;
469 }
470 if v.is_null() {
471 t.remove(k);
472 continue;
473 }
474 let info = lookup(ty, k);
475 let child = info.map_or("", |i| i.child);
476 match v {
477 Value::Object(po) => {
478 if directive(v) == Some("delete") {
479 t.remove(k);
480 continue;
481 }
482 let e = t
483 .entry(k.clone())
484 .or_insert_with(|| Value::Object(Map::new()));
485 if !e.is_object() {
486 *e = Value::Object(Map::new());
487 }
488 if let Value::Object(tm) = e {
489 merge_obj(child, tm, po)?;
490 }
491 }
492 Value::Array(pa) => match info.and_then(|i| i.list) {
493 Some(List::Key(mk)) => {
494 let e = t
495 .entry(k.clone())
496 .or_insert_with(|| Value::Array(Vec::new()));
497 if !e.is_array() {
498 *e = Value::Array(Vec::new());
499 }
500 if let Value::Array(ta) = e {
501 merge_keyed(child, mk, ta, pa)?;
502 }
503 }
504 Some(List::Set) => {
505 let e = t
506 .entry(k.clone())
507 .or_insert_with(|| Value::Array(Vec::new()));
508 if !e.is_array() {
509 *e = Value::Array(Vec::new());
510 }
511 if let Value::Array(ta) = e {
512 for x in pa {
513 if !ta.contains(x) {
514 ta.push(x.clone());
515 }
516 }
517 }
518 }
519 None => {
520 t.insert(k.clone(), v.clone());
521 }
522 },
523 _ => {
524 t.insert(k.clone(), v.clone());
525 }
526 }
527 }
528 for (k, v) in p {
529 if let Some(f) = k.strip_prefix("$deleteFromPrimitiveList/") {
530 if let (Some(Value::Array(ta)), Value::Array(del)) = (t.get_mut(f), v) {
531 ta.retain(|x| !del.contains(x));
532 }
533 } else if let Some(f) = k.strip_prefix("$setElementOrder/")
534 && let (Some(Value::Array(ta)), Value::Array(order)) = (t.get_mut(f), v)
535 {
536 match lookup(ty, f).and_then(|i| i.list) {
537 Some(List::Key(mk)) => reorder(ta, order, Some(mk)),
538 Some(List::Set) => reorder(ta, order, None),
539 None => {}
540 }
541 }
542 }
543 if let Some(Value::Array(keep)) = p.get("$retainKeys") {
544 t.retain(|k, _| keep.iter().any(|x| x.as_str() == Some(k)));
545 }
546 Ok(())
547}
548
549pub fn strategic_merge_patch(kind: &str, target: &mut Value, patch: &Value) -> Result<(), String> {
550 match (target, patch) {
551 (Value::Object(t), Value::Object(p)) => merge_obj(root_type(kind), t, p),
552 _ => Err("strategic merge patch and target must be objects".into()),
553 }
554}
555
556fn walk(ty: &str, m: &Map<String, Value>, top: bool) -> Map<String, Value> {
557 let mut out = Map::new();
558 for (k, v) in m {
559 if top && (k == "apiVersion" || k == "kind") {
560 continue;
561 }
562 if ty == "ObjectMeta"
563 && matches!(
564 k.as_str(),
565 "name"
566 | "namespace"
567 | "uid"
568 | "resourceVersion"
569 | "generation"
570 | "creationTimestamp"
571 | "selfLink"
572 | "managedFields"
573 )
574 {
575 continue;
576 }
577 let info = lookup(ty, k);
578 let child = info.map_or("", |i| i.child);
579 let node = match v {
580 Value::Object(o) if !o.is_empty() => {
581 let w = walk(child, o, false);
582 if w.is_empty() {
583 continue;
584 }
585 Value::Object(w)
586 }
587 Value::Array(a) => match info.and_then(|i| i.list) {
588 Some(List::Key(mk)) => {
589 let mut n = Map::new();
590 for e in a {
591 let (Some(kv), Value::Object(eo)) = (e.get(mk), e) else {
592 continue;
593 };
594 let mut item = walk(child, eo, false);
595 item.insert(".".into(), json!({}));
596 n.insert(format!("k:{}", json!({ mk: kv })), Value::Object(item));
597 }
598 Value::Object(n)
599 }
600 Some(List::Set) => Value::Object(
601 a.iter()
602 .map(|x| (format!("v:{x}"), json!({})))
603 .collect::<Map<_, _>>(),
604 ),
605 None => json!({}),
606 },
607 _ => json!({}),
608 };
609 out.insert(format!("f:{k}"), node);
610 }
611 out
612}
613
614type Paths = BTreeSet<Vec<String>>;
615
616fn flatten(set: &Map<String, Value>, prefix: &mut Vec<String>, out: &mut Paths) {
617 for (k, v) in set {
618 if k == "." {
619 continue;
620 }
621 prefix.push(k.clone());
622 let children = v.as_object().filter(|c| c.keys().any(|x| x != "."));
623 if children.is_none() || k.starts_with("k:") {
624 out.insert(prefix.clone());
625 }
626 if let Some(c) = children {
627 flatten(c, prefix, out);
628 }
629 prefix.pop();
630 }
631}
632
633fn build(paths: &Paths) -> Map<String, Value> {
634 let mut root = Map::new();
635 for p in paths {
636 let mut cur = &mut root;
637 for t in p {
638 let e = cur.entry(t.clone()).or_insert_with(|| {
639 if t.starts_with("k:") {
640 json!({".": {}})
641 } else {
642 json!({})
643 }
644 });
645 cur = match e.as_object_mut() {
646 Some(m) => m,
647 None => break,
648 };
649 }
650 }
651 root
652}
653
654fn key_matches(e: &Value, key: &Value) -> bool {
655 key.as_object()
656 .is_some_and(|k| k.iter().all(|(n, v)| e.get(n) == Some(v)))
657}
658
659fn step<'a>(v: &'a Value, token: &str) -> Option<&'a Value> {
660 if let Some(n) = token.strip_prefix("f:") {
661 v.get(n)
662 } else if let Some(k) = token.strip_prefix("k:") {
663 let key: Value = serde_json::from_str(k).ok()?;
664 v.as_array()?.iter().find(|e| key_matches(e, &key))
665 } else if let Some(x) = token.strip_prefix("v:") {
666 let val: Value = serde_json::from_str(x).ok()?;
667 v.as_array()?.iter().find(|e| **e == val)
668 } else {
669 None
670 }
671}
672
673fn step_mut<'a>(v: &'a mut Value, token: &str) -> Option<&'a mut Value> {
674 if let Some(n) = token.strip_prefix("f:") {
675 v.get_mut(n)
676 } else if let Some(k) = token.strip_prefix("k:") {
677 let key: Value = serde_json::from_str(k).ok()?;
678 v.as_array_mut()?.iter_mut().find(|e| key_matches(e, &key))
679 } else {
680 None
681 }
682}
683
684fn get_path<'a>(root: &'a Value, tokens: &[String]) -> Option<&'a Value> {
685 let mut cur = root;
686 for t in tokens {
687 cur = step(cur, t)?;
688 }
689 Some(cur)
690}
691
692fn remove_path(root: &mut Value, tokens: &[String]) {
693 let Some((last, init)) = tokens.split_last() else {
694 return;
695 };
696 let mut cur = root;
697 for t in init {
698 cur = match step_mut(cur, t) {
699 Some(n) => n,
700 None => return,
701 };
702 }
703 if let Some(n) = last.strip_prefix("f:") {
704 if let Value::Object(m) = cur {
705 m.remove(n);
706 }
707 } else if let Some(k) = last.strip_prefix("k:") {
708 if let (Value::Array(a), Ok(key)) = (cur, serde_json::from_str::<Value>(k)) {
709 a.retain(|e| !key_matches(e, &key));
710 }
711 } else if let Some(x) = last.strip_prefix("v:")
712 && let (Value::Array(a), Ok(val)) = (cur, serde_json::from_str::<Value>(x))
713 {
714 a.retain(|e| *e != val);
715 }
716}
717
718fn format_path(tokens: &[String]) -> String {
719 tokens
720 .iter()
721 .map(|t| {
722 if let Some(n) = t.strip_prefix("f:") {
723 format!(".{n}")
724 } else if let Some(k) = t.strip_prefix("k:") {
725 let pairs = serde_json::from_str::<Map<String, Value>>(k)
726 .map(|m| {
727 m.iter()
728 .map(|(n, v)| format!("{n}={v}"))
729 .collect::<Vec<_>>()
730 .join(",")
731 })
732 .unwrap_or_default();
733 format!("[{pairs}]")
734 } else if let Some(v) = t.strip_prefix("v:") {
735 format!("[={v}]")
736 } else {
737 t.clone()
738 }
739 })
740 .collect()
741}
742
743fn now_rfc3339() -> String {
744 let secs = SystemTime::now()
745 .duration_since(UNIX_EPOCH)
746 .map(|d| d.as_secs() as i64)
747 .unwrap_or(0);
748 let days = secs.div_euclid(86_400);
749 let rem = secs.rem_euclid(86_400);
750 let z = days + 719_468;
751 let era = z.div_euclid(146_097);
752 let doe = z - era * 146_097;
753 let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365;
754 let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
755 let mp = (5 * doy + 2) / 153;
756 let d = doy - (153 * mp + 2) / 5 + 1;
757 let m = if mp < 10 { mp + 3 } else { mp - 9 };
758 let y = yoe + era * 400 + i64::from(m <= 2);
759 format!(
760 "{y:04}-{m:02}-{d:02}T{:02}:{:02}:{:02}Z",
761 rem / 3600,
762 rem % 3600 / 60,
763 rem % 60
764 )
765}
766
767fn read_entries(obj: &Value) -> Vec<(Value, Paths)> {
768 obj.pointer("/metadata/managedFields")
769 .and_then(Value::as_array)
770 .map(|a| {
771 a.iter()
772 .map(|e| {
773 let mut paths = Paths::new();
774 if let Some(f) = e.get("fieldsV1").and_then(Value::as_object) {
775 flatten(f, &mut Vec::new(), &mut paths);
776 }
777 (e.clone(), paths)
778 })
779 .collect()
780 })
781 .unwrap_or_default()
782}
783
784fn apply_inner(
785 kind: &str,
786 manager: &str,
787 live: Option<&Value>,
788 applied: &Value,
789 force: bool,
790) -> Result<Value, String> {
791 let Value::Object(am) = applied else {
792 return Err("applied configuration must be an object".into());
793 };
794 if live.is_some_and(|l| !l.is_object()) {
795 return Err("live object must be an object".into());
796 }
797 let ty = root_type(kind);
798 let mut cm = am.clone();
799 if let Some(Value::Object(meta)) = cm.get_mut("metadata") {
800 meta.remove(MANAGED);
801 }
802 let mut new_paths = Paths::new();
803 flatten(&walk(ty, &cm, true), &mut Vec::new(), &mut new_paths);
804 let api = am
805 .get("apiVersion")
806 .and_then(Value::as_str)
807 .unwrap_or("v1")
808 .to_string();
809 let clean = Value::Object(cm);
810 let mut result = live.cloned().unwrap_or_else(|| Value::Object(Map::new()));
811 let mut entries = read_entries(&result);
812 let mut touched = vec![false; entries.len()];
813 let ours = entries.iter().position(|(e, _)| {
814 e.get("manager").and_then(Value::as_str) == Some(manager)
815 && e.get("operation").and_then(Value::as_str) == Some("Apply")
816 });
817 let prev = ours.map(|i| entries[i].1.clone()).unwrap_or_default();
818
819 let mut conflicts: Vec<(usize, Vec<String>)> = Vec::new();
820 for (i, (_, ps)) in entries.iter().enumerate() {
821 if Some(i) == ours {
822 continue;
823 }
824 for p in ps.intersection(&new_paths) {
825 if p.last().is_some_and(|t| t.starts_with("k:")) {
826 continue;
827 }
828 if let (Some(a), Some(b)) = (get_path(&result, p), get_path(&clean, p))
829 && !same(a, b)
830 {
831 conflicts.push((i, p.clone()));
832 }
833 }
834 }
835 if !conflicts.is_empty() && !force {
836 let lines: Vec<String> = conflicts
837 .iter()
838 .map(|(i, p)| {
839 let who = entries[*i]
840 .0
841 .get("manager")
842 .and_then(Value::as_str)
843 .unwrap_or("");
844 format!("conflict with \"{who}\": {}", format_path(p))
845 })
846 .collect();
847 let n = lines.len();
848 return Err(format!(
849 "Apply failed with {n} conflict{}: {}",
850 if n == 1 { "" } else { "s" },
851 lines.join("\n")
852 ));
853 }
854 for (i, p) in &conflicts {
855 entries[*i].1.remove(p);
856 touched[*i] = true;
857 }
858
859 for p in prev.difference(&new_paths) {
860 let kept_by_new = new_paths.iter().any(|q| q.starts_with(p));
861 let kept_by_other = entries
862 .iter()
863 .enumerate()
864 .any(|(i, (_, ps))| Some(i) != ours && ps.iter().any(|q| q.starts_with(p)));
865 if !kept_by_new && !kept_by_other {
866 remove_path(&mut result, p);
867 }
868 }
869
870 strategic_merge_patch(kind, &mut result, &clean)?;
871
872 let mine = json!({
873 "manager": manager,
874 "operation": "Apply",
875 "apiVersion": api,
876 "time": now_rfc3339(),
877 "fieldsType": "FieldsV1",
878 "fieldsV1": Value::Object(build(&new_paths)),
879 });
880 let mut out = Vec::with_capacity(entries.len() + 1);
881 for (i, (mut e, ps)) in entries.into_iter().enumerate() {
882 if Some(i) == ours {
883 out.push(mine.clone());
884 continue;
885 }
886 if touched[i] {
887 if ps.is_empty() {
888 continue;
889 }
890 e["fieldsV1"] = Value::Object(build(&ps));
891 }
892 out.push(e);
893 }
894 if ours.is_none() {
895 out.push(mine);
896 }
897 if let Value::Object(r) = &mut result
898 && let Value::Object(meta) = r.entry("metadata").or_insert_with(|| json!({}))
899 {
900 meta.insert(MANAGED.into(), Value::Array(out));
901 }
902 Ok(result)
903}
904
905pub fn apply_patch(
906 kind: &str,
907 manager: &str,
908 live: Option<&Value>,
909 applied: &Value,
910) -> Result<Value, String> {
911 apply_inner(kind, manager, live, applied, false)
912}
913
914pub fn apply_patch_force(
915 kind: &str,
916 manager: &str,
917 live: Option<&Value>,
918 applied: &Value,
919) -> Result<Value, String> {
920 apply_inner(kind, manager, live, applied, true)
921}
922
923#[cfg(test)]
924mod tests {
925 use super::*;
926
927 macro_rules! mp_case {
928 ($name:ident, $target:expr, $patch:expr, $expected:expr) => {
929 #[test]
930 fn $name() {
931 let mut t: Value = $target;
932 json_merge_patch(&mut t, &$patch);
933 assert_eq!(t, $expected);
934 }
935 };
936 }
937
938 macro_rules! jp_ok {
939 ($name:ident, $doc:expr, $ops:expr, $expected:expr) => {
940 #[test]
941 fn $name() {
942 let mut d: Value = $doc;
943 json_patch(&mut d, &$ops).unwrap();
944 assert_eq!(d, $expected);
945 }
946 };
947 }
948
949 macro_rules! jp_err {
950 ($name:ident, $doc:expr, $ops:expr) => {
951 #[test]
952 fn $name() {
953 let mut d: Value = $doc;
954 let before = d.clone();
955 assert!(json_patch(&mut d, &$ops).is_err());
956 assert_eq!(d, before);
957 }
958 };
959 }
960
961 mp_case!(mp_01, json!({"a":"b"}), json!({"a":"c"}), json!({"a":"c"}));
962 mp_case!(
963 mp_02,
964 json!({"a":"b"}),
965 json!({"b":"c"}),
966 json!({"a":"b","b":"c"})
967 );
968 mp_case!(mp_03, json!({"a":"b"}), json!({"a":null}), json!({}));
969 mp_case!(
970 mp_04,
971 json!({"a":"b","b":"c"}),
972 json!({"a":null}),
973 json!({"b":"c"})
974 );
975 mp_case!(
976 mp_05,
977 json!({"a":["b"]}),
978 json!({"a":"c"}),
979 json!({"a":"c"})
980 );
981 mp_case!(
982 mp_06,
983 json!({"a":"c"}),
984 json!({"a":["b"]}),
985 json!({"a":["b"]})
986 );
987 mp_case!(
988 mp_07,
989 json!({"a":{"b":"c"}}),
990 json!({"a":{"b":"d","c":null}}),
991 json!({"a":{"b":"d"}})
992 );
993 mp_case!(
994 mp_08,
995 json!({"a":[{"b":"c"}]}),
996 json!({"a":[1]}),
997 json!({"a":[1]})
998 );
999 mp_case!(
1000 mp_09,
1001 json!(["a", "b"]),
1002 json!(["c", "d"]),
1003 json!(["c", "d"])
1004 );
1005 mp_case!(mp_10, json!({"a":"b"}), json!(["c"]), json!(["c"]));
1006 mp_case!(mp_11, json!({"a":"foo"}), json!(null), json!(null));
1007 mp_case!(mp_12, json!({"a":"foo"}), json!("bar"), json!("bar"));
1008 mp_case!(
1009 mp_13,
1010 json!({"e":null}),
1011 json!({"a":1}),
1012 json!({"e":null,"a":1})
1013 );
1014 mp_case!(
1015 mp_14,
1016 json!([1, 2]),
1017 json!({"a":"b","c":null}),
1018 json!({"a":"b"})
1019 );
1020 mp_case!(
1021 mp_15,
1022 json!({}),
1023 json!({"a":{"bb":{"ccc":null}}}),
1024 json!({"a":{"bb":{}}})
1025 );
1026
1027 jp_ok!(
1028 jp_a1,
1029 json!({"foo":"bar"}),
1030 json!([{"op":"add","path":"/baz","value":"qux"}]),
1031 json!({"baz":"qux","foo":"bar"})
1032 );
1033 jp_ok!(
1034 jp_a2,
1035 json!({"foo":["bar","baz"]}),
1036 json!([{"op":"add","path":"/foo/1","value":"qux"}]),
1037 json!({"foo":["bar","qux","baz"]})
1038 );
1039 jp_ok!(
1040 jp_a3,
1041 json!({"baz":"qux","foo":"bar"}),
1042 json!([{"op":"remove","path":"/baz"}]),
1043 json!({"foo":"bar"})
1044 );
1045 jp_ok!(
1046 jp_a4,
1047 json!({"foo":["bar","qux","baz"]}),
1048 json!([{"op":"remove","path":"/foo/1"}]),
1049 json!({"foo":["bar","baz"]})
1050 );
1051 jp_ok!(
1052 jp_a5,
1053 json!({"baz":"qux","foo":"bar"}),
1054 json!([{"op":"replace","path":"/baz","value":"boo"}]),
1055 json!({"baz":"boo","foo":"bar"})
1056 );
1057 jp_ok!(
1058 jp_a6,
1059 json!({"foo":{"bar":"baz","waldo":"fred"},"qux":{"corge":"grault"}}),
1060 json!([{"op":"move","from":"/foo/waldo","path":"/qux/thud"}]),
1061 json!({"foo":{"bar":"baz"},"qux":{"corge":"grault","thud":"fred"}})
1062 );
1063 jp_ok!(
1064 jp_a7,
1065 json!({"foo":["all","grass","cows","eat"]}),
1066 json!([{"op":"move","from":"/foo/1","path":"/foo/3"}]),
1067 json!({"foo":["all","cows","eat","grass"]})
1068 );
1069 jp_ok!(
1070 jp_a8,
1071 json!({"baz":"qux","foo":["a",2,"c"]}),
1072 json!([{"op":"test","path":"/baz","value":"qux"},{"op":"test","path":"/foo/1","value":2}]),
1073 json!({"baz":"qux","foo":["a",2,"c"]})
1074 );
1075 jp_err!(
1076 jp_a9,
1077 json!({"baz":"qux"}),
1078 json!([{"op":"test","path":"/baz","value":"bar"}])
1079 );
1080 jp_ok!(
1081 jp_a10,
1082 json!({"foo":"bar"}),
1083 json!([{"op":"add","path":"/child","value":{"grandchild":{}}}]),
1084 json!({"foo":"bar","child":{"grandchild":{}}})
1085 );
1086 jp_ok!(
1087 jp_a11,
1088 json!({"foo":"bar"}),
1089 json!([{"op":"add","path":"/baz","value":"qux","xyz":123}]),
1090 json!({"foo":"bar","baz":"qux"})
1091 );
1092 jp_err!(
1093 jp_a12,
1094 json!({"foo":"bar"}),
1095 json!([{"op":"add","path":"/baz/bat","value":"qux"}])
1096 );
1097 jp_ok!(
1098 jp_a14,
1099 json!({"/":9,"~1":10}),
1100 json!([{"op":"test","path":"/~01","value":10}]),
1101 json!({"/":9,"~1":10})
1102 );
1103 jp_err!(
1104 jp_a15,
1105 json!({"/":9,"~1":10}),
1106 json!([{"op":"test","path":"/~01","value":"10"}])
1107 );
1108 jp_ok!(
1109 jp_a16,
1110 json!({"foo":["bar"]}),
1111 json!([{"op":"add","path":"/foo/-","value":["abc","def"]}]),
1112 json!({"foo":["bar",["abc","def"]]})
1113 );
1114 jp_ok!(
1115 jp_copy,
1116 json!({"a":{"b":1}}),
1117 json!([{"op":"copy","from":"/a","path":"/c"}]),
1118 json!({"a":{"b":1},"c":{"b":1}})
1119 );
1120 jp_ok!(
1121 jp_escaped_slash,
1122 json!({"a/b":1}),
1123 json!([{"op":"replace","path":"/a~1b","value":2}]),
1124 json!({"a/b":2})
1125 );
1126 jp_ok!(
1127 jp_replace_root,
1128 json!({"a":1}),
1129 json!([{"op":"replace","path":"","value":[1]}]),
1130 json!([1])
1131 );
1132 jp_err!(
1133 jp_remove_missing,
1134 json!({"a":1}),
1135 json!([{"op":"remove","path":"/b"}])
1136 );
1137 jp_err!(
1138 jp_index_out_of_range,
1139 json!({"a":[1]}),
1140 json!([{"op":"add","path":"/a/3","value":0}])
1141 );
1142 jp_err!(
1143 jp_atomic,
1144 json!({"a":1}),
1145 json!([{"op":"add","path":"/b","value":2},{"op":"test","path":"/a","value":9}])
1146 );
1147 jp_err!(
1148 jp_unknown_op,
1149 json!({"a":1}),
1150 json!([{"op":"bogus","path":"/a"}])
1151 );
1152 jp_err!(
1153 jp_move_into_child,
1154 json!({"a":{"b":1}}),
1155 json!([{"op":"move","from":"/a","path":"/a/c"}])
1156 );
1157
1158 fn smp(kind: &str, target: Value, patch: Value) -> Value {
1159 let mut t = target;
1160 strategic_merge_patch(kind, &mut t, &patch).unwrap();
1161 t
1162 }
1163
1164 #[test]
1165 fn smp_containers_merge_by_name() {
1166 let r = smp(
1167 "Pod",
1168 json!({"spec":{"containers":[{"name":"a","image":"x"},{"name":"b","image":"y"}]}}),
1169 json!({"spec":{"containers":[{"name":"a","image":"z"}]}}),
1170 );
1171 assert_eq!(
1172 r,
1173 json!({"spec":{"containers":[{"name":"a","image":"z"},{"name":"b","image":"y"}]}})
1174 );
1175 }
1176
1177 #[test]
1178 fn smp_container_appended() {
1179 let r = smp(
1180 "Pod",
1181 json!({"spec":{"containers":[{"name":"a"}]}}),
1182 json!({"spec":{"containers":[{"name":"c","image":"i"}]}}),
1183 );
1184 assert_eq!(
1185 r["spec"]["containers"],
1186 json!([{"name":"a"},{"name":"c","image":"i"}])
1187 );
1188 }
1189
1190 #[test]
1191 fn smp_delete_container_directive() {
1192 let r = smp(
1193 "Pod",
1194 json!({"spec":{"containers":[{"name":"a"},{"name":"b"}]}}),
1195 json!({"spec":{"containers":[{"name":"a","$patch":"delete"}]}}),
1196 );
1197 assert_eq!(r["spec"]["containers"], json!([{"name":"b"}]));
1198 }
1199
1200 #[test]
1201 fn smp_env_merge_and_duplicate_names() {
1202 let r = smp(
1203 "Pod",
1204 json!({"spec":{"containers":[{"name":"a","env":[{"name":"X","value":"1"}]}]}}),
1205 json!({"spec":{"containers":[{"name":"a","env":[
1206 {"name":"X","value":"2"},{"name":"Y","value":"a"},{"name":"Y","value":"b"}
1207 ]}]}}),
1208 );
1209 assert_eq!(
1210 r["spec"]["containers"][0]["env"],
1211 json!([{"name":"X","value":"2"},{"name":"Y","value":"b"}])
1212 );
1213 }
1214
1215 #[test]
1216 fn smp_null_removes_field() {
1217 let r = smp(
1218 "Deployment",
1219 json!({"spec":{"replicas":3,"paused":true}}),
1220 json!({"spec":{"replicas":null}}),
1221 );
1222 assert_eq!(r, json!({"spec":{"paused":true}}));
1223 }
1224
1225 #[test]
1226 fn smp_retain_keys() {
1227 let r = smp(
1228 "Deployment",
1229 json!({"spec":{"strategy":{"type":"RollingUpdate","rollingUpdate":{"maxSurge":1}}}}),
1230 json!({"spec":{"strategy":{"$retainKeys":["type"],"type":"Recreate"}}}),
1231 );
1232 assert_eq!(r["spec"]["strategy"], json!({"type":"Recreate"}));
1233 }
1234
1235 #[test]
1236 fn smp_replace_element() {
1237 let r = smp(
1238 "Pod",
1239 json!({"spec":{"containers":[{"name":"a","image":"x","args":["1"]}]}}),
1240 json!({"spec":{"containers":[{"name":"a","image":"q","$patch":"replace"}]}}),
1241 );
1242 assert_eq!(r["spec"]["containers"], json!([{"name":"a","image":"q"}]));
1243 }
1244
1245 #[test]
1246 fn smp_replace_whole_list() {
1247 let r = smp(
1248 "Pod",
1249 json!({"spec":{"containers":[{"name":"a"},{"name":"b"}]}}),
1250 json!({"spec":{"containers":[{"$patch":"replace"},{"name":"c"}]}}),
1251 );
1252 assert_eq!(r["spec"]["containers"], json!([{"name":"c"}]));
1253 }
1254
1255 #[test]
1256 fn smp_delete_from_primitive_list() {
1257 let r = smp(
1258 "Pod",
1259 json!({"metadata":{"finalizers":["a","b","c"]}}),
1260 json!({"metadata":{"$deleteFromPrimitiveList/finalizers":["b"]}}),
1261 );
1262 assert_eq!(r["metadata"]["finalizers"], json!(["a", "c"]));
1263 }
1264
1265 #[test]
1266 fn smp_finalizers_union() {
1267 let r = smp(
1268 "Pod",
1269 json!({"metadata":{"finalizers":["a"]}}),
1270 json!({"metadata":{"finalizers":["a","b"]}}),
1271 );
1272 assert_eq!(r["metadata"]["finalizers"], json!(["a", "b"]));
1273 }
1274
1275 #[test]
1276 fn smp_ports_merge_key_and_order() {
1277 let r = smp(
1278 "Pod",
1279 json!({"spec":{"containers":[{"name":"a","ports":[
1280 {"containerPort":80,"name":"http"},{"containerPort":443,"name":"https"}
1281 ]}]}}),
1282 json!({"spec":{"containers":[{"name":"a",
1283 "$setElementOrder/ports":[{"containerPort":8080},{"containerPort":443},{"containerPort":80}],
1284 "ports":[{"containerPort":8080,"name":"alt"},{"containerPort":80,"protocol":"TCP"}]
1285 }]}}),
1286 );
1287 assert_eq!(
1288 r["spec"]["containers"][0]["ports"],
1289 json!([
1290 {"containerPort":8080,"name":"alt"},
1291 {"containerPort":443,"name":"https"},
1292 {"containerPort":80,"name":"http","protocol":"TCP"}
1293 ])
1294 );
1295 }
1296
1297 #[test]
1298 fn smp_tolerations_replaced() {
1299 let r = smp(
1300 "Pod",
1301 json!({"spec":{"tolerations":[{"key":"a"},{"key":"b"}]}}),
1302 json!({"spec":{"tolerations":[{"key":"c"}]}}),
1303 );
1304 assert_eq!(r["spec"]["tolerations"], json!([{"key":"c"}]));
1305 }
1306
1307 #[test]
1308 fn smp_service_ports_by_port() {
1309 let r = smp(
1310 "Service",
1311 json!({"spec":{"ports":[{"port":80,"targetPort":8080},{"port":443}]}}),
1312 json!({"spec":{"ports":[{"port":80,"targetPort":9090}]}}),
1313 );
1314 assert_eq!(
1315 r["spec"]["ports"],
1316 json!([{"port":80,"targetPort":9090},{"port":443}])
1317 );
1318 }
1319
1320 #[test]
1321 fn smp_status_conditions_by_type() {
1322 let r = smp(
1323 "Pod",
1324 json!({"status":{"conditions":[{"type":"Ready","status":"False"},{"type":"Init","status":"True"}]}}),
1325 json!({"status":{"conditions":[{"type":"Ready","status":"True"}]}}),
1326 );
1327 assert_eq!(
1328 r["status"]["conditions"],
1329 json!([{"type":"Ready","status":"True"},{"type":"Init","status":"True"}])
1330 );
1331 }
1332
1333 #[test]
1334 fn smp_deployment_template_containers() {
1335 let r = smp(
1336 "Deployment",
1337 json!({"spec":{"template":{"spec":{"containers":[{"name":"a","image":"x"}],
1338 "volumes":[{"name":"v","emptyDir":{}}]}}}}),
1339 json!({"spec":{"template":{"spec":{"containers":[{"name":"a","image":"y",
1340 "volumeMounts":[{"mountPath":"/d","name":"v"}]}],
1341 "volumes":[{"name":"w","emptyDir":{}}]}}}}),
1342 );
1343 let s = &r["spec"]["template"]["spec"];
1344 assert_eq!(s["containers"][0]["image"], json!("y"));
1345 assert_eq!(
1346 s["containers"][0]["volumeMounts"][0]["mountPath"],
1347 json!("/d")
1348 );
1349 assert_eq!(s["volumes"].as_array().unwrap().len(), 2);
1350 }
1351
1352 #[test]
1353 fn smp_cronjob_nested_containers() {
1354 let r = smp(
1355 "CronJob",
1356 json!({"spec":{"jobTemplate":{"spec":{"template":{"spec":{"containers":[{"name":"a","image":"x"}]}}}}}}),
1357 json!({"spec":{"jobTemplate":{"spec":{"template":{"spec":{"containers":[{"name":"b"}]}}}}}}),
1358 );
1359 assert_eq!(
1360 r["spec"]["jobTemplate"]["spec"]["template"]["spec"]["containers"]
1361 .as_array()
1362 .unwrap()
1363 .len(),
1364 2
1365 );
1366 }
1367
1368 #[test]
1369 fn smp_missing_merge_key_errors() {
1370 let mut t = json!({"spec":{"containers":[{"name":"a"}]}});
1371 let e = strategic_merge_patch(
1372 "Pod",
1373 &mut t,
1374 &json!({"spec":{"containers":[{"image":"x"}]}}),
1375 );
1376 assert!(e.unwrap_err().contains("merge key"));
1377 }
1378
1379 #[test]
1380 fn smp_unknown_strategy_errors() {
1381 let mut t = json!({"spec":{}});
1382 let e = strategic_merge_patch("Pod", &mut t, &json!({"spec":{"$patch":"zzz"}}));
1383 assert!(e.is_err());
1384 }
1385
1386 #[test]
1387 fn smp_unknown_kind_replaces_lists() {
1388 let r = smp(
1389 "Widget",
1390 json!({"spec":{"containers":[{"name":"a"},{"name":"b"}]}}),
1391 json!({"spec":{"containers":[{"name":"c"}]}}),
1392 );
1393 assert_eq!(r["spec"]["containers"], json!([{"name":"c"}]));
1394 }
1395
1396 #[test]
1397 fn smp_preserves_last_applied_annotation() {
1398 let value = r#"{"kind":"Pod"}"#;
1399 let r = smp(
1400 "Pod",
1401 json!({"metadata":{"annotations":{"keep":"1"}}}),
1402 json!({"metadata":{"annotations":{ last_applied_annotation_key(): value }}}),
1403 );
1404 assert_eq!(r["metadata"]["annotations"][LAST_APPLIED], json!(value));
1405 assert_eq!(r["metadata"]["annotations"]["keep"], json!("1"));
1406 assert_eq!(
1407 last_applied_annotation_key(),
1408 "kubectl.kubernetes.io/last-applied-configuration"
1409 );
1410 }
1411
1412 #[test]
1413 fn smp_delete_map_field() {
1414 let r = smp(
1415 "Pod",
1416 json!({"metadata":{"labels":{"a":"1"},"name":"p"}}),
1417 json!({"metadata":{"labels":{"$patch":"delete"}}}),
1418 );
1419 assert_eq!(r, json!({"metadata":{"name":"p"}}));
1420 }
1421
1422 #[test]
1423 fn smp_owner_refs_and_pull_secrets() {
1424 let r = smp(
1425 "Pod",
1426 json!({"metadata":{"ownerReferences":[{"uid":"1","name":"a"}]},
1427 "spec":{"imagePullSecrets":[{"name":"s1"}]}}),
1428 json!({"metadata":{"ownerReferences":[{"uid":"1","name":"b"},{"uid":"2","name":"c"}]},
1429 "spec":{"imagePullSecrets":[{"name":"s2"}]}}),
1430 );
1431 assert_eq!(
1432 r["metadata"]["ownerReferences"],
1433 json!([{"uid":"1","name":"b"},{"uid":"2","name":"c"}])
1434 );
1435 assert_eq!(
1436 r["spec"]["imagePullSecrets"],
1437 json!([{"name":"s1"},{"name":"s2"}])
1438 );
1439 }
1440
1441 struct Rng(u64);
1442
1443 impl Rng {
1444 fn next(&mut self) -> u64 {
1445 self.0 ^= self.0 << 13;
1446 self.0 ^= self.0 >> 7;
1447 self.0 ^= self.0 << 17;
1448 self.0
1449 }
1450 }
1451
1452 fn gen_value(r: &mut Rng, depth: u32, nulls: bool) -> Value {
1453 match r.next() % 6 {
1454 0 if nulls => Value::Null,
1455 1 => json!(r.next() % 10),
1456 2 => json!(format!("s{}", r.next() % 3)),
1457 3 => json!([r.next() % 3, r.next() % 3]),
1458 4 if depth > 0 => gen_object(r, depth - 1, nulls),
1459 _ => json!(true),
1460 }
1461 }
1462
1463 fn gen_object(r: &mut Rng, depth: u32, nulls: bool) -> Value {
1464 let mut m = Map::new();
1465 for _ in 0..(r.next() % 4) {
1466 let k = ["a", "b", "c"][(r.next() % 3) as usize];
1467 m.insert(k.to_string(), gen_value(r, depth, nulls));
1468 }
1469 Value::Object(m)
1470 }
1471
1472 #[test]
1473 fn merge_patch_is_idempotent() {
1474 let mut r = Rng(0x9E37_79B9_7F4A_7C15);
1475 for _ in 0..500 {
1476 let target = gen_object(&mut r, 3, false);
1477 let patch = gen_object(&mut r, 3, true);
1478 let mut once = target.clone();
1479 json_merge_patch(&mut once, &patch);
1480 let mut twice = once.clone();
1481 json_merge_patch(&mut twice, &patch);
1482 assert_eq!(once, twice);
1483 }
1484 }
1485
1486 #[test]
1487 fn strategic_patch_is_idempotent() {
1488 let mut r = Rng(0xD1B5_4A32_D192_ED03);
1489 for _ in 0..500 {
1490 let target = gen_object(&mut r, 3, false);
1491 let patch = gen_object(&mut r, 3, true);
1492 let mut once = target.clone();
1493 strategic_merge_patch("Widget", &mut once, &patch).unwrap();
1494 let mut twice = once.clone();
1495 strategic_merge_patch("Widget", &mut twice, &patch).unwrap();
1496 assert_eq!(once, twice);
1497 }
1498 }
1499
1500 #[test]
1501 fn strategic_patch_lists_are_idempotent() {
1502 let target = json!({
1503 "metadata":{"finalizers":["x"]},
1504 "spec":{"containers":[{"name":"a","image":"1","env":[{"name":"E","value":"1"}]},{"name":"z"}]}
1505 });
1506 let patches = [
1507 json!({"spec":{"containers":[{"name":"a","env":[{"name":"E","value":"2"},{"name":"F","value":"3"}]},{"name":"n"}]}}),
1508 json!({"spec":{"containers":[{"name":"z","$patch":"delete"}]}}),
1509 json!({"spec":{"containers":[{"$patch":"replace"},{"name":"only"}]}}),
1510 json!({"metadata":{"finalizers":["y"],"$deleteFromPrimitiveList/finalizers":["x"]}}),
1511 json!({"spec":{"containers":[{"name":"a","$patch":"replace","image":"9"}]}}),
1512 ];
1513 for p in &patches {
1514 let once = smp("Pod", target.clone(), p.clone());
1515 let twice = smp("Pod", once.clone(), p.clone());
1516 assert_eq!(once, twice);
1517 }
1518 }
1519
1520 fn deploy(replicas: i64, extra: Value) -> Value {
1521 let mut d = json!({
1522 "apiVersion":"apps/v1","kind":"Deployment",
1523 "metadata":{"name":"d","labels":{"app":"x"}},
1524 "spec":{"replicas":replicas}
1525 });
1526 json_merge_patch(&mut d, &extra);
1527 d
1528 }
1529
1530 fn entry<'a>(o: &'a Value, manager: &str) -> Option<&'a Value> {
1531 o["metadata"]["managedFields"]
1532 .as_array()?
1533 .iter()
1534 .find(|e| e["manager"] == manager)
1535 }
1536
1537 #[test]
1538 fn ssa_create_records_managed_fields() {
1539 let applied = json!({
1540 "apiVersion":"apps/v1","kind":"Deployment",
1541 "metadata":{"name":"d","labels":{"a":"1"}},
1542 "spec":{"replicas":3,"template":{"spec":{"containers":[{"name":"x","image":"i"}]}}}
1543 });
1544 let r = apply_patch("Deployment", "m1", None, &applied).unwrap();
1545 let e = entry(&r, "m1").unwrap();
1546 assert_eq!(e["operation"], "Apply");
1547 assert_eq!(e["apiVersion"], "apps/v1");
1548 assert_eq!(e["fieldsType"], "FieldsV1");
1549 assert!(e["time"].as_str().unwrap().ends_with('Z'));
1550 assert_eq!(
1551 e["fieldsV1"],
1552 json!({
1553 "f:metadata":{"f:labels":{"f:a":{}}},
1554 "f:spec":{
1555 "f:replicas":{},
1556 "f:template":{"f:spec":{"f:containers":{
1557 "k:{\"name\":\"x\"}":{".":{},"f:image":{},"f:name":{}}
1558 }}}
1559 }
1560 })
1561 );
1562 assert_eq!(r["spec"]["replicas"], 3);
1563 }
1564
1565 #[test]
1566 fn ssa_two_managers_disjoint_fields() {
1567 let a = apply_patch("Deployment", "A", None, &deploy(3, json!({}))).unwrap();
1568 let b_cfg = json!({"apiVersion":"apps/v1","kind":"Deployment",
1569 "spec":{"paused":true}});
1570 let r = apply_patch("Deployment", "B", Some(&a), &b_cfg).unwrap();
1571 assert_eq!(r["spec"]["replicas"], 3);
1572 assert_eq!(r["spec"]["paused"], true);
1573 assert_eq!(r["metadata"]["managedFields"].as_array().unwrap().len(), 2);
1574 assert!(entry(&r, "A").unwrap()["fieldsV1"]["f:spec"]["f:replicas"].is_object());
1575 assert!(entry(&r, "B").unwrap()["fieldsV1"]["f:spec"]["f:paused"].is_object());
1576 }
1577
1578 #[test]
1579 fn ssa_conflict_message() {
1580 let a = apply_patch("Deployment", "A", None, &deploy(3, json!({}))).unwrap();
1581 let e = apply_patch("Deployment", "B", Some(&a), &deploy(5, json!({}))).unwrap_err();
1582 assert_eq!(
1583 e,
1584 "Apply failed with 1 conflict: conflict with \"A\": .spec.replicas"
1585 );
1586 }
1587
1588 #[test]
1589 fn ssa_same_value_shares_ownership() {
1590 let a = apply_patch("Deployment", "A", None, &deploy(3, json!({}))).unwrap();
1591 let r = apply_patch("Deployment", "B", Some(&a), &deploy(3, json!({}))).unwrap();
1592 assert!(entry(&r, "A").unwrap()["fieldsV1"]["f:spec"]["f:replicas"].is_object());
1593 assert!(entry(&r, "B").unwrap()["fieldsV1"]["f:spec"]["f:replicas"].is_object());
1594 }
1595
1596 #[test]
1597 fn ssa_force_transfers_ownership() {
1598 let a = apply_patch("Deployment", "A", None, &deploy(3, json!({}))).unwrap();
1599 let r = apply_patch_force("Deployment", "B", Some(&a), &deploy(5, json!({}))).unwrap();
1600 assert_eq!(r["spec"]["replicas"], 5);
1601 let fa = &entry(&r, "A").unwrap()["fieldsV1"];
1602 assert!(fa["f:spec"].is_null());
1603 assert!(fa["f:metadata"]["f:labels"]["f:app"].is_object() || fa["f:metadata"].is_null());
1604 assert!(entry(&r, "B").unwrap()["fieldsV1"]["f:spec"]["f:replicas"].is_object());
1605 }
1606
1607 #[test]
1608 fn ssa_removes_own_dropped_fields() {
1609 let first = deploy(1, json!({"metadata":{"labels":{"b":"2"}}}));
1610 let a = apply_patch("Deployment", "A", None, &first).unwrap();
1611 assert_eq!(a["metadata"]["labels"]["b"], "2");
1612 let r = apply_patch("Deployment", "A", Some(&a), &deploy(1, json!({}))).unwrap();
1613 assert!(r["metadata"]["labels"].get("b").is_none());
1614 assert_eq!(r["metadata"]["labels"]["app"], "x");
1615 }
1616
1617 #[test]
1618 fn ssa_keeps_fields_owned_by_others() {
1619 let first = deploy(1, json!({"metadata":{"labels":{"b":"2"}}}));
1620 let a = apply_patch("Deployment", "A", None, &first).unwrap();
1621 let b_cfg = json!({"apiVersion":"apps/v1","kind":"Deployment",
1622 "metadata":{"labels":{"b":"2"}}});
1623 let both = apply_patch("Deployment", "B", Some(&a), &b_cfg).unwrap();
1624 let r = apply_patch("Deployment", "A", Some(&both), &deploy(1, json!({}))).unwrap();
1625 assert_eq!(r["metadata"]["labels"]["b"], "2");
1626 }
1627
1628 #[test]
1629 fn ssa_update_operation_conflicts() {
1630 let mut live = deploy(3, json!({}));
1631 live["metadata"]["managedFields"] = json!([{
1632 "manager":"kubectl-edit","operation":"Update","apiVersion":"apps/v1",
1633 "fieldsType":"FieldsV1","fieldsV1":{"f:spec":{"f:replicas":{}}}
1634 }]);
1635 let e = apply_patch("Deployment", "A", Some(&live), &deploy(4, json!({}))).unwrap_err();
1636 assert!(e.contains("conflict with \"kubectl-edit\": .spec.replicas"));
1637 }
1638
1639 #[test]
1640 fn ssa_removes_dropped_list_item() {
1641 let cfg = |names: &[&str]| {
1642 json!({"apiVersion":"v1","kind":"Pod","metadata":{"name":"p"},
1643 "spec":{"containers":names.iter().map(|n| json!({"name":n,"image":"i"})).collect::<Vec<_>>()}})
1644 };
1645 let a = apply_patch("Pod", "A", None, &cfg(&["x", "y"])).unwrap();
1646 assert_eq!(a["spec"]["containers"].as_array().unwrap().len(), 2);
1647 let r = apply_patch("Pod", "A", Some(&a), &cfg(&["x"])).unwrap();
1648 assert_eq!(r["spec"]["containers"], json!([{"name":"x","image":"i"}]));
1649 }
1650
1651 #[test]
1652 fn ssa_leaves_unowned_live_fields() {
1653 let live = json!({"apiVersion":"apps/v1","kind":"Deployment",
1654 "metadata":{"name":"d"},"spec":{"paused":true,"replicas":1}});
1655 let r = apply_patch("Deployment", "A", Some(&live), &deploy(2, json!({}))).unwrap();
1656 assert_eq!(r["spec"]["paused"], true);
1657 assert_eq!(r["spec"]["replicas"], 2);
1658 }
1659
1660 #[test]
1661 fn ssa_rejects_non_object() {
1662 assert!(apply_patch("Pod", "A", None, &json!([1])).is_err());
1663 }
1664
1665 #[test]
1666 fn rfc3339_shape() {
1667 let t = now_rfc3339();
1668 assert_eq!(t.len(), 20);
1669 assert!(t.starts_with("20") && t.ends_with('Z'));
1670 }
1671}