kube_core/schema.rs
1//! Utilities for managing [`CustomResourceDefinition`] schemas
2//!
3//! [`CustomResourceDefinition`]: `k8s_openapi::apiextensions_apiserver::pkg::apis::apiextensions::v1::CustomResourceDefinition`
4
5// Used in docs
6#[allow(unused_imports)] use schemars::generate::SchemaSettings;
7
8use schemars::{
9 JsonSchema,
10 transform::{Transform, transform_subschemas},
11};
12use serde::{Deserialize, Serialize};
13use serde_json::{Value, json};
14use std::collections::{BTreeMap, BTreeSet, btree_map::Entry};
15
16/// schemars [`Transform`] that rewrites a [`Schema`](schemars::Schema) to conform to Kubernetes' "structural schema" rules
17///
18/// The following two transformations are applied
19/// * Rewrite enums from `oneOf` to `object`s with multiple variants ([schemars#84](https://github.com/GREsau/schemars/issues/84))
20/// * Rewrite untagged enums from `anyOf` to `object`s with multiple variants ([kube#1028](https://github.com/kube-rs/kube/pull/1028))
21/// * Merge untagged enums of plain enums from `anyOf` into a single `enum` ([kube#1622](https://github.com/kube-rs/kube/issues/1622))
22/// * Rewrite `additionalProperties` from `#[serde(flatten)]` to `x-kubernetes-preserve-unknown-fields` ([kube#844](https://github.com/kube-rs/kube/issues/844))
23///
24/// This is used automatically by `kube::derive`'s `#[derive(CustomResource)]`,
25/// but it can also be used manually with [`SchemaSettings::with_transform`].
26///
27/// # Panics
28///
29/// The [`Transform`] functions may panic if the transform could not be applied. For example,
30/// there must not be any overlapping properties between `oneOf` branches.
31#[derive(Debug, Clone)]
32pub struct StructuralSchemaRewriter;
33
34/// Recursively restructures JSON Schema objects so that the Option<Enum> object
35/// is returned per k8s CRD schema expectations.
36///
37/// In kube 2.x the schema output behavior for `Option<Enum>` types changed.
38///
39/// Previously given an enum like:
40///
41/// ```rust
42/// enum LogLevel {
43/// Debug,
44/// Info,
45/// Error,
46/// }
47/// ```
48///
49/// The following would be generated for Optional<LogLevel>:
50///
51/// ```json
52/// { "enum": ["Debug", "Info", "Error"], "type": "string", "nullable": true }
53/// ```
54///
55/// Now, schemars generates `anyOf` for `Option<LogLevel>` like:
56///
57/// ```json
58/// {
59/// "anyOf": [
60/// { "enum": ["Debug", "Info", "Error"], "type": "string" },
61/// { "enum": [null], "nullable": true }
62/// ]
63/// }
64/// ```
65///
66/// This transform implementation prevents this specific case from happening.
67#[derive(Debug, Clone, Default)]
68pub struct OptionalEnum;
69
70/// Recursively restructures JSON Schema objects so that the `Option<T>` object
71/// where `T` uses `x-kubernetes-int-or-string` is returned per k8s CRD schema expectations.
72///
73/// In kube 2.x with k8s-openapi 0.26.x, the schema output behavior for `Option<Quantity>`
74/// and similar `x-kubernetes-int-or-string` types changed.
75///
76/// Previously given an optional Quantity field:
77///
78/// ```json
79/// { "nullable": true, "type": "string" }
80/// ```
81///
82/// Now, schemars generates `anyOf` for `Option<Quantity>` like:
83///
84/// ```json
85/// {
86/// "anyOf": [
87/// { "x-kubernetes-int-or-string": true },
88/// { "enum": [null], "nullable": true }
89/// ]
90/// }
91/// ```
92///
93/// This transform converts it to:
94///
95/// ```json
96/// { "x-kubernetes-int-or-string": true, "nullable": true }
97/// ```
98#[derive(Debug, Clone, Default)]
99pub struct OptionalIntOrString;
100
101/// A JSON Schema.
102#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema)]
103#[serde(untagged)]
104enum Schema {
105 /// A trivial boolean JSON Schema.
106 ///
107 /// The schema `true` matches everything (always passes validation), whereas the schema `false`
108 /// matches nothing (always fails validation).
109 Bool(bool),
110 /// A JSON Schema object.
111 Object(SchemaObject),
112}
113
114/// A JSON Schema object.
115#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Default, JsonSchema)]
116#[serde(rename_all = "camelCase", default)]
117struct SchemaObject {
118 /// Properties which annotate the [`SchemaObject`] which typically have no effect when an object is being validated against the schema.
119 #[serde(flatten, deserialize_with = "skip_if_default")]
120 metadata: Option<Box<Metadata>>,
121 /// The `type` keyword.
122 ///
123 /// See [JSON Schema Validation 6.1.1. "type"](https://tools.ietf.org/html/draft-handrews-json-schema-validation-02#section-6.1.1)
124 /// and [JSON Schema 4.2.1. Instance Data Model](https://tools.ietf.org/html/draft-handrews-json-schema-02#section-4.2.1).
125 #[serde(rename = "type", skip_serializing_if = "Option::is_none")]
126 instance_type: Option<SingleOrVec<InstanceType>>,
127 /// The `format` keyword.
128 ///
129 /// See [JSON Schema Validation 7. A Vocabulary for Semantic Content With "format"](https://tools.ietf.org/html/draft-handrews-json-schema-validation-02#section-7).
130 #[serde(skip_serializing_if = "Option::is_none")]
131 format: Option<String>,
132 /// The `enum` keyword.
133 ///
134 /// See [JSON Schema Validation 6.1.2. "enum"](https://tools.ietf.org/html/draft-handrews-json-schema-validation-02#section-6.1.2)
135 #[serde(rename = "enum", skip_serializing_if = "Option::is_none")]
136 enum_values: Option<Vec<Value>>,
137 /// Properties of the [`SchemaObject`] which define validation assertions in terms of other schemas.
138 #[serde(flatten, deserialize_with = "skip_if_default")]
139 subschemas: Option<Box<SubschemaValidation>>,
140 /// Properties of the [`SchemaObject`] which define validation assertions for arrays.
141 #[serde(flatten, deserialize_with = "skip_if_default")]
142 array: Option<Box<ArrayValidation>>,
143 /// Properties of the [`SchemaObject`] which define validation assertions for objects.
144 #[serde(flatten, deserialize_with = "skip_if_default")]
145 object: Option<Box<ObjectValidation>>,
146 /// Arbitrary extra properties which are not part of the JSON Schema specification, or which `schemars` does not support.
147 #[serde(flatten)]
148 extensions: BTreeMap<String, Value>,
149 /// Arbitrary data.
150 #[serde(flatten)]
151 other: Value,
152}
153
154// Deserializing "null" to `Option<Value>` directly results in `None`,
155// this function instead makes it deserialize to `Some(Value::Null)`.
156fn allow_null<'de, D>(de: D) -> Result<Option<Value>, D::Error>
157where
158 D: serde::Deserializer<'de>,
159{
160 Value::deserialize(de).map(Option::Some)
161}
162
163fn skip_if_default<'de, D, T>(deserializer: D) -> Result<Option<Box<T>>, D::Error>
164where
165 D: serde::Deserializer<'de>,
166 T: Deserialize<'de> + Default + PartialEq,
167{
168 let value = T::deserialize(deserializer)?;
169 if value == T::default() {
170 Ok(None)
171 } else {
172 Ok(Some(Box::new(value)))
173 }
174}
175
176/// Properties which annotate a [`SchemaObject`] which typically have no effect when an object is being validated against the schema.
177#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Default, JsonSchema)]
178#[serde(rename_all = "camelCase", default)]
179struct Metadata {
180 /// The `description` keyword.
181 ///
182 /// See [JSON Schema Validation 9.1. "title" and "description"](https://tools.ietf.org/html/draft-handrews-json-schema-validation-02#section-9.1).
183 #[serde(skip_serializing_if = "Option::is_none")]
184 description: Option<String>,
185 /// The `default` keyword.
186 ///
187 /// See [JSON Schema Validation 9.2. "default"](https://tools.ietf.org/html/draft-handrews-json-schema-validation-02#section-9.2).
188 #[serde(skip_serializing_if = "Option::is_none", deserialize_with = "allow_null")]
189 default: Option<Value>,
190}
191
192/// Properties of a [`SchemaObject`] which define validation assertions in terms of other schemas.
193#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Default, JsonSchema)]
194#[serde(rename_all = "camelCase", default)]
195struct SubschemaValidation {
196 /// The `anyOf` keyword.
197 ///
198 /// See [JSON Schema 9.2.1.2. "anyOf"](https://tools.ietf.org/html/draft-handrews-json-schema-02#section-9.2.1.2).
199 #[serde(skip_serializing_if = "Option::is_none")]
200 any_of: Option<Vec<Schema>>,
201 /// The `oneOf` keyword.
202 ///
203 /// See [JSON Schema 9.2.1.3. "oneOf"](https://tools.ietf.org/html/draft-handrews-json-schema-02#section-9.2.1.3).
204 #[serde(skip_serializing_if = "Option::is_none")]
205 one_of: Option<Vec<Schema>>,
206}
207
208/// Properties of a [`SchemaObject`] which define validation assertions for arrays.
209#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Default, JsonSchema)]
210#[serde(rename_all = "camelCase", default)]
211struct ArrayValidation {
212 /// The `items` keyword.
213 ///
214 /// See [JSON Schema 9.3.1.1. "items"](https://tools.ietf.org/html/draft-handrews-json-schema-02#section-9.3.1.1).
215 #[serde(skip_serializing_if = "Option::is_none")]
216 items: Option<SingleOrVec<Schema>>,
217 /// The `additionalItems` keyword.
218 ///
219 /// See [JSON Schema 9.3.1.2. "additionalItems"](https://tools.ietf.org/html/draft-handrews-json-schema-02#section-9.3.1.2).
220 #[serde(skip_serializing_if = "Option::is_none")]
221 additional_items: Option<Box<Schema>>,
222 /// The `maxItems` keyword.
223 ///
224 /// See [JSON Schema Validation 6.4.1. "maxItems"](https://tools.ietf.org/html/draft-handrews-json-schema-validation-02#section-6.4.1).
225 #[serde(skip_serializing_if = "Option::is_none")]
226 max_items: Option<u32>,
227 /// The `minItems` keyword.
228 ///
229 /// See [JSON Schema Validation 6.4.2. "minItems"](https://tools.ietf.org/html/draft-handrews-json-schema-validation-02#section-6.4.2).
230 #[serde(skip_serializing_if = "Option::is_none")]
231 min_items: Option<u32>,
232 /// The `uniqueItems` keyword.
233 ///
234 /// See [JSON Schema Validation 6.4.3. "uniqueItems"](https://tools.ietf.org/html/draft-handrews-json-schema-validation-02#section-6.4.3).
235 #[serde(skip_serializing_if = "Option::is_none")]
236 unique_items: Option<bool>,
237 /// The `contains` keyword.
238 ///
239 /// See [JSON Schema 9.3.1.4. "contains"](https://tools.ietf.org/html/draft-handrews-json-schema-02#section-9.3.1.4).
240 #[serde(skip_serializing_if = "Option::is_none")]
241 contains: Option<Box<Schema>>,
242}
243
244/// Properties of a [`SchemaObject`] which define validation assertions for objects.
245#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Default, JsonSchema)]
246#[serde(rename_all = "camelCase", default)]
247struct ObjectValidation {
248 /// The `maxProperties` keyword.
249 ///
250 /// See [JSON Schema Validation 6.5.1. "maxProperties"](https://tools.ietf.org/html/draft-handrews-json-schema-validation-02#section-6.5.1).
251 #[serde(skip_serializing_if = "Option::is_none")]
252 max_properties: Option<u32>,
253 /// The `minProperties` keyword.
254 ///
255 /// See [JSON Schema Validation 6.5.2. "minProperties"](https://tools.ietf.org/html/draft-handrews-json-schema-validation-02#section-6.5.2).
256 #[serde(skip_serializing_if = "Option::is_none")]
257 min_properties: Option<u32>,
258 /// The `required` keyword.
259 ///
260 /// See [JSON Schema Validation 6.5.3. "required"](https://tools.ietf.org/html/draft-handrews-json-schema-validation-02#section-6.5.3).
261 #[serde(skip_serializing_if = "BTreeSet::is_empty")]
262 required: BTreeSet<String>,
263 /// The `properties` keyword.
264 ///
265 /// See [JSON Schema 9.3.2.1. "properties"](https://tools.ietf.org/html/draft-handrews-json-schema-02#section-9.3.2.1).
266 #[serde(skip_serializing_if = "BTreeMap::is_empty")]
267 properties: BTreeMap<String, Schema>,
268 /// The `patternProperties` keyword.
269 ///
270 /// See [JSON Schema 9.3.2.2. "patternProperties"](https://tools.ietf.org/html/draft-handrews-json-schema-02#section-9.3.2.2).
271 #[serde(skip_serializing_if = "BTreeMap::is_empty")]
272 pattern_properties: BTreeMap<String, Schema>,
273 /// The `additionalProperties` keyword.
274 ///
275 /// See [JSON Schema 9.3.2.3. "additionalProperties"](https://tools.ietf.org/html/draft-handrews-json-schema-02#section-9.3.2.3).
276 #[serde(skip_serializing_if = "Option::is_none")]
277 additional_properties: Option<Box<Schema>>,
278 /// The `propertyNames` keyword.
279 ///
280 /// See [JSON Schema 9.3.2.5. "propertyNames"](https://tools.ietf.org/html/draft-handrews-json-schema-02#section-9.3.2.5).
281 #[serde(skip_serializing_if = "Option::is_none")]
282 property_names: Option<Box<Schema>>,
283}
284
285/// The possible types of values in JSON Schema documents.
286///
287/// See [JSON Schema 4.2.1. Instance Data Model](https://tools.ietf.org/html/draft-handrews-json-schema-02#section-4.2.1).
288#[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, JsonSchema)]
289#[serde(rename_all = "camelCase")]
290enum InstanceType {
291 /// Represents the JSON null type.
292 Null,
293 /// Represents the JSON boolean type.
294 Boolean,
295 /// Represents the JSON object type.
296 Object,
297 /// Represents the JSON array type.
298 Array,
299 /// Represents the JSON number type (floating point).
300 Number,
301 /// Represents the JSON string type.
302 String,
303 /// Represents the JSON integer type.
304 Integer,
305}
306
307/// A type which can be serialized as a single item, or multiple items.
308///
309/// In some contexts, a `Single` may be semantically distinct from a `Vec` containing only item.
310#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, PartialOrd, Ord, JsonSchema)]
311#[serde(untagged)]
312enum SingleOrVec<T> {
313 /// Represents a single item.
314 Single(Box<T>),
315 /// Represents a vector of items.
316 Vec(Vec<T>),
317}
318
319impl Transform for StructuralSchemaRewriter {
320 fn transform(&mut self, transform_schema: &mut schemars::Schema) {
321 schemars::transform::transform_subschemas(self, transform_schema);
322
323 // Untagged enums of plain enums are serialized using `any_of` with one enum per variant
324 merge_any_of_enum_values(transform_schema);
325
326 let mut schema: SchemaObject = match serde_json::from_value(transform_schema.clone().to_value()).ok()
327 {
328 Some(schema) => schema,
329 None => return,
330 };
331
332 if let Some(subschemas) = &mut schema.subschemas {
333 if let Some(one_of) = subschemas.one_of.as_mut() {
334 // Tagged enums are serialized using `one_of`
335 hoist_subschema_properties(one_of, &mut schema.object, &mut schema.instance_type, true);
336
337 // "Plain" enums are serialized using `one_of` if they have doc tags
338 hoist_subschema_enum_values(one_of, &mut schema.enum_values, &mut schema.instance_type);
339
340 if one_of.is_empty() {
341 subschemas.one_of = None;
342 }
343 }
344
345 if let Some(any_of) = &mut subschemas.any_of {
346 // Untagged enums are serialized using `any_of`
347 // Variant descriptions are not pushed into properties (because they are not for the field).
348 hoist_subschema_properties(any_of, &mut schema.object, &mut schema.instance_type, false);
349 }
350 }
351
352 if let Some(object) = &mut schema.object
353 && !object.properties.is_empty()
354 {
355 // check for maps without with properties (i.e. flattened maps)
356 // and allow these to persist dynamically
357 match object.additional_properties.as_deref() {
358 Some(&Schema::Bool(true)) => {
359 object.additional_properties = None;
360 schema
361 .extensions
362 .insert("x-kubernetes-preserve-unknown-fields".into(), true.into());
363 }
364 Some(&Schema::Bool(false)) => {
365 object.additional_properties = None;
366 }
367 _ => {}
368 }
369 }
370
371 // As of version 1.30 Kubernetes does not support setting `uniqueItems` to `true`,
372 // so we need to remove this fields.
373 // Users can still set `x-kubernetes-list-type=set` in case they want the apiserver
374 // to do validation, but we can't make an assumption about the Set contents here.
375 // See https://kubernetes.io/docs/reference/using-api/server-side-apply/ for details.
376 if let Some(array) = &mut schema.array {
377 array.unique_items = None;
378 }
379
380 if let Ok(schema) = serde_json::to_value(schema)
381 && let Ok(transformed) = serde_json::from_value(schema)
382 {
383 *transform_schema = transformed;
384 }
385 }
386}
387
388impl Transform for OptionalEnum {
389 fn transform(&mut self, schema: &mut schemars::Schema) {
390 transform_subschemas(self, schema);
391
392 let Some(obj) = schema.as_object_mut() else {
393 return;
394 };
395
396 let arr = obj
397 .get("anyOf")
398 .iter()
399 .flat_map(|any_of| any_of.as_array())
400 .last()
401 .cloned()
402 .unwrap_or_default();
403
404 let [first, second] = arr.as_slice() else {
405 return;
406 };
407 let (Some(first), Some(second)) = (first.as_object(), second.as_object()) else {
408 return;
409 };
410
411 // Check if this is an Option<T> pattern:
412 // anyOf with two elements where second is { "enum": [null], "nullable": true }
413 if !first.contains_key("nullable")
414 && second.get("enum") == Some(&json!([null]))
415 && second.get("nullable") == Some(&json!(true))
416 {
417 // Remove anyOf and hoist first element's properties to root
418 obj.remove("anyOf");
419 obj.append(&mut first.clone());
420 obj.insert("nullable".to_string(), Value::Bool(true));
421 }
422 }
423}
424
425impl Transform for OptionalIntOrString {
426 fn transform(&mut self, schema: &mut schemars::Schema) {
427 transform_subschemas(self, schema);
428
429 let Some(obj) = schema.as_object_mut() else {
430 return;
431 };
432
433 // Get required fields list
434 let required: BTreeSet<String> = obj
435 .get("required")
436 .and_then(|v| v.as_array())
437 .map(|arr| arr.iter().filter_map(|v| v.as_str().map(String::from)).collect())
438 .unwrap_or_default();
439
440 // Get mutable properties
441 let Some(properties) = obj.get_mut("properties").and_then(|v| v.as_object_mut()) else {
442 return;
443 };
444
445 // For each property that is NOT required and has x-kubernetes-int-or-string,
446 // add nullable: true if not already present
447 for (name, prop_schema) in properties.iter_mut() {
448 if required.contains(name) {
449 continue;
450 }
451
452 let Some(prop_obj) = prop_schema.as_object_mut() else {
453 continue;
454 };
455
456 if prop_obj.get("x-kubernetes-int-or-string") == Some(&json!(true))
457 && !prop_obj.contains_key("nullable")
458 {
459 prop_obj.insert("nullable".to_string(), Value::Bool(true));
460 }
461 }
462 }
463}
464
465/// Bring all plain enum values up to the root schema,
466/// since Kubernetes doesn't allow subschemas to define enum options.
467///
468/// (Enum here means a list of hard-coded values, not a tagged union.)
469fn hoist_subschema_enum_values(
470 subschemas: &mut Vec<Schema>,
471 common_enum_values: &mut Option<Vec<serde_json::Value>>,
472 instance_type: &mut Option<SingleOrVec<InstanceType>>,
473) {
474 subschemas.retain(|variant| {
475 if let Schema::Object(SchemaObject {
476 instance_type: variant_type,
477 enum_values: Some(variant_enum_values),
478 ..
479 }) = variant
480 {
481 if let Some(variant_type) = variant_type {
482 match instance_type {
483 None => *instance_type = Some(variant_type.clone()),
484 Some(tpe) => {
485 if tpe != variant_type {
486 panic!("Enum variant set {variant_enum_values:?} has type {variant_type:?} but was already defined as {instance_type:?}. The instance type must be equal for all subschema variants.")
487 }
488 }
489 }
490 }
491 common_enum_values
492 .get_or_insert_with(Vec::new)
493 .extend(variant_enum_values.iter().cloned());
494 false
495 } else {
496 true
497 }
498 })
499}
500
501/// Merge `anyOf` branches into a single enum when every branch is a plain enum of the same type.
502///
503/// A branch with only a `type` (e.g. `String` next to a unit enum) accepts any value of that type,
504/// so the merged schema keeps the `type` and drops the `enum`.
505///
506/// Branch descriptions are dropped, since Kubernetes can't attach them to individual values.
507/// Any other `anyOf` is left untouched.
508fn merge_any_of_enum_values(schema: &mut schemars::Schema) {
509 let Some(obj) = schema.as_object_mut() else {
510 return;
511 };
512 if obj.contains_key("type") || obj.contains_key("enum") {
513 return;
514 }
515 let Some(Value::Array(any_of)) = obj.get("anyOf") else {
516 return;
517 };
518
519 // `Option<T>` of a composite `T` is `anyOf: [T, null]`. Once `T` has collapsed to a bare scalar
520 // type, unwrap it like schemars does for plain types, before the rewriter strips the branch's type.
521 // Parents with other keywords are hand-written schemas, not an `Option` wrapper, so leave them.
522 if let [Value::Object(inner), null] = any_of.as_slice()
523 && null == &json!({ "enum": [null], "nullable": true })
524 && obj
525 .keys()
526 .all(|k| matches!(k.as_str(), "anyOf" | "description" | "default"))
527 && matches!(
528 inner.get("type").and_then(Value::as_str),
529 Some("string" | "integer" | "number" | "boolean")
530 )
531 && inner.keys().all(|k| matches!(k.as_str(), "type" | "description"))
532 {
533 let inner = inner.clone();
534 obj.remove("anyOf");
535 for (key, value) in inner {
536 obj.entry(key).or_insert(value);
537 }
538 obj.insert("nullable".into(), Value::Bool(true));
539 return;
540 }
541
542 let mut instance_type = None;
543 let mut enum_values = Vec::new();
544 let mut unrestricted = false;
545 for branch in any_of {
546 let Some(branch) = branch.as_object() else {
547 return;
548 };
549 if branch
550 .keys()
551 .any(|k| !matches!(k.as_str(), "type" | "enum" | "description"))
552 {
553 return;
554 }
555 let Some(variant_type @ Value::String(_)) = branch.get("type") else {
556 return;
557 };
558 if instance_type.get_or_insert(variant_type) != &variant_type {
559 return;
560 }
561 match branch.get("enum") {
562 Some(Value::Array(variant_values)) => {
563 for value in variant_values {
564 if !enum_values.contains(value) {
565 enum_values.push(value.clone());
566 }
567 }
568 }
569 None => unrestricted = true,
570 Some(_) => return,
571 }
572 }
573
574 // Only rewrite unions of enums; leave enum-free `anyOf`s to the existing rewrites
575 let Some(instance_type) = instance_type.cloned().filter(|_| !enum_values.is_empty()) else {
576 return;
577 };
578 obj.remove("anyOf");
579 obj.insert("type".into(), instance_type);
580 if !unrestricted {
581 obj.insert("enum".into(), enum_values.into());
582 }
583}
584
585/// Bring all property definitions from subschemas up to the root schema,
586/// since Kubernetes doesn't allow subschemas to define properties.
587fn hoist_subschema_properties(
588 subschemas: &mut Vec<Schema>,
589 common_obj: &mut Option<Box<ObjectValidation>>,
590 instance_type: &mut Option<SingleOrVec<InstanceType>>,
591 push_description_to_property: bool,
592) {
593 for variant in subschemas {
594 if let Schema::Object(SchemaObject {
595 instance_type: variant_type,
596 object: Some(variant_obj),
597 metadata: variant_metadata,
598 ..
599 }) = variant
600 {
601 let common_obj = common_obj.get_or_insert_with(Box::<ObjectValidation>::default);
602
603 // Move enum variant description from oneOf clause to its corresponding property
604 if let Some(variant_metadata) = variant_metadata
605 && let Some(description) = std::mem::take(&mut variant_metadata.description)
606 && let Some(Schema::Object(variant_object)) = only_item(variant_obj.properties.values_mut())
607 {
608 let metadata = variant_object
609 .metadata
610 .get_or_insert_with(Box::<Metadata>::default);
611 if push_description_to_property {
612 metadata.description = Some(description);
613 }
614 }
615
616 // Move all properties
617 let variant_properties = std::mem::take(&mut variant_obj.properties);
618 for (property_name, property) in variant_properties {
619 match common_obj.properties.entry(property_name) {
620 Entry::Vacant(entry) => {
621 entry.insert(property);
622 }
623 Entry::Occupied(entry) => {
624 if &property != entry.get() {
625 panic!(
626 "Property {:?} has the schema {:?} but was already defined as {:?} in another subschema. The schemas for a property used in multiple subschemas must be identical",
627 entry.key(),
628 property,
629 entry.get()
630 );
631 }
632 }
633 }
634 }
635
636 // Kubernetes doesn't allow variants to set additionalProperties
637 variant_obj.additional_properties = None;
638
639 merge_metadata(instance_type, variant_type.take());
640 }
641 // Removes the type/description from oneOf and anyOf subschemas
642 else if let Schema::Object(SchemaObject {
643 metadata: variant_metadata,
644 instance_type: variant_type,
645 enum_values: None,
646 subschemas: None,
647 array: None,
648 object: None,
649 ..
650 }) = variant
651 {
652 std::mem::take(&mut *variant_type);
653 std::mem::take(&mut *variant_metadata);
654 }
655 }
656}
657
658fn only_item<I: Iterator>(mut i: I) -> Option<I::Item> {
659 let item = i.next()?;
660 if i.next().is_some() {
661 return None;
662 }
663 Some(item)
664}
665
666fn merge_metadata(
667 instance_type: &mut Option<SingleOrVec<InstanceType>>,
668 variant_type: Option<SingleOrVec<InstanceType>>,
669) {
670 match (instance_type, variant_type) {
671 (_, None) => {}
672 (common_type @ None, variant_type) => {
673 *common_type = variant_type;
674 }
675 (Some(common_type), Some(variant_type)) => {
676 if *common_type != variant_type {
677 panic!(
678 "variant defined type {variant_type:?}, conflicting with existing type {common_type:?}"
679 );
680 }
681 }
682 }
683}
684
685#[cfg(test)]
686mod tests {
687 use super::*;
688
689 fn merged(schema: Value) -> Value {
690 let mut schema: schemars::Schema = serde_json::from_value(schema).unwrap();
691 merge_any_of_enum_values(&mut schema);
692 schema.to_value()
693 }
694
695 #[test]
696 fn merge_any_of_enum_values_merges_same_type_enums() {
697 assert_eq!(
698 merged(json!({
699 "description": "kept",
700 "anyOf": [
701 { "type": "integer", "enum": [1, 2], "description": "dropped" },
702 { "type": "integer", "enum": [2, 3] },
703 ],
704 })),
705 json!({ "description": "kept", "type": "integer", "enum": [1, 2, 3] })
706 );
707 }
708
709 #[test]
710 fn merge_any_of_enum_values_drops_enum_for_plain_type_branch() {
711 assert_eq!(
712 merged(json!({
713 "anyOf": [
714 { "type": "string", "enum": ["a", "b"] },
715 { "type": "string" },
716 ],
717 })),
718 json!({ "type": "string" })
719 );
720 }
721
722 #[test]
723 fn merge_any_of_enum_values_unwraps_optional_plain_type() {
724 assert_eq!(
725 merged(json!({
726 "description": "field",
727 "anyOf": [
728 { "type": "string", "description": "type" },
729 { "enum": [null], "nullable": true },
730 ],
731 })),
732 json!({ "description": "field", "type": "string", "nullable": true })
733 );
734 }
735
736 #[test]
737 fn merge_any_of_enum_values_skips_other_any_of() {
738 for schema in [
739 // mismatched types
740 json!({ "anyOf": [{ "type": "string", "enum": ["a"] }, { "type": "integer", "enum": [1] }] }),
741 // Option<Enum>, handled by OptionalEnum
742 json!({ "anyOf": [{ "type": "string", "enum": ["a"] }, { "enum": [null], "nullable": true }] }),
743 // extra keywords
744 json!({ "anyOf": [{ "type": "string", "enum": ["a"] }, { "type": "string", "enum": ["b"], "format": "x" }] }),
745 // no enum branch at all
746 json!({ "anyOf": [{ "type": "string" }, { "type": "string" }] }),
747 // nullable non-scalar
748 json!({ "anyOf": [{ "type": "array" }, { "enum": [null], "nullable": true }] }),
749 // nullable with other keywords on the parent
750 json!({
751 "x-kubernetes-preserve-unknown-fields": true,
752 "anyOf": [{ "type": "string" }, { "enum": [null], "nullable": true }],
753 }),
754 json!({ "anyOf": [] }),
755 ] {
756 assert_eq!(merged(schema.clone()), schema);
757 }
758 }
759}