helm-schema-k8s 0.0.4

Generate an accurate JSON schema for any helm chart
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
use std::collections::{HashMap, HashSet};

use helm_schema_json_schema_walk::{SchemaTraversalContext, schema_child_context_for_keyword};
use serde_json::{Map, Value};

use crate::schema_doc::{SchemaDoc, strip_ref};

/// `$ref` resolution context. Holds previously-loaded documents and a
/// stack of (filename, json-pointer) pairs to break cycles.
///
/// The context is short-lived: one per top-level provider fragment lookup.
/// The provider supplies a loader that knows how to fetch a
/// neighboring schema file by relative filename (typically by mapping
/// the filename through the same provider fetch/cache path the
/// resource doc came from).
pub(crate) struct ResolveCtx<F: FnMut(&str) -> Option<SchemaDoc>> {
    loader: F,
    docs: HashMap<String, SchemaDoc>,
    stack: HashSet<(String, String)>,
}

/// Source location of a schema node inside the provider document graph.
#[derive(Clone, Debug, Eq, PartialEq)]
pub(crate) struct SchemaNodeLocation {
    filename: String,
    pointer: String,
}

impl SchemaNodeLocation {
    fn root(filename: impl Into<String>) -> Self {
        Self {
            filename: filename.into(),
            pointer: String::new(),
        }
    }

    fn child(&self, segment: impl AsRef<str>) -> Self {
        Self {
            filename: self.filename.clone(),
            pointer: append_json_pointer_segment(&self.pointer, segment.as_ref()),
        }
    }

    #[must_use]
    pub fn filename(&self) -> &str {
        &self.filename
    }

    #[must_use]
    pub fn pointer(&self) -> &str {
        &self.pointer
    }
}

/// Schema node plus the provider-document location it was read from.
#[derive(Clone, Debug, PartialEq)]
pub(crate) struct ResolvedSchemaNode {
    location: SchemaNodeLocation,
    schema: Value,
}

impl ResolvedSchemaNode {
    fn root(filename: impl Into<String>, schema: Value) -> Self {
        Self {
            location: SchemaNodeLocation::root(filename),
            schema,
        }
    }

    fn child(&self, segment: impl AsRef<str>, schema: Value) -> Self {
        Self {
            location: self.location.child(segment),
            schema,
        }
    }

    fn nested_child(
        &self,
        first_segment: impl AsRef<str>,
        second_segment: impl AsRef<str>,
        schema: Value,
    ) -> Self {
        Self {
            location: self.location.child(first_segment).child(second_segment),
            schema,
        }
    }

    fn at(location: SchemaNodeLocation, schema: Value) -> Self {
        Self { location, schema }
    }

    #[must_use]
    pub fn into_schema(self) -> Value {
        self.schema
    }

    #[must_use]
    pub fn location(&self) -> &SchemaNodeLocation {
        &self.location
    }
}

/// Path lookup result with both the materialized leaf and original source leaf.
#[derive(Clone, Debug, PartialEq)]
pub(crate) struct ResolvedSchemaLeaf {
    location: SchemaNodeLocation,
    source_schema: Value,
    schema: Value,
    required_in_parent: bool,
}

impl ResolvedSchemaLeaf {
    fn new(
        location: SchemaNodeLocation,
        source_schema: Value,
        schema: Value,
        required_in_parent: bool,
    ) -> Self {
        Self {
            location,
            source_schema,
            schema,
            required_in_parent,
        }
    }

    /// Whether the resolved path's final segment is listed in its parent
    /// object's `required` array.
    #[must_use]
    pub fn required_in_parent(&self) -> bool {
        self.required_in_parent
    }

    #[must_use]
    pub fn location(&self) -> &SchemaNodeLocation {
        &self.location
    }

    #[must_use]
    pub fn source_schema(&self) -> &Value {
        &self.source_schema
    }

    #[must_use]
    pub fn schema(&self) -> &Value {
        &self.schema
    }
}

impl<F: FnMut(&str) -> Option<SchemaDoc>> ResolveCtx<F> {
    pub fn new(loader: F, root_filename: String, root_doc: SchemaDoc) -> Self {
        let mut docs = HashMap::new();
        docs.insert(root_filename, root_doc);
        Self {
            loader,
            docs,
            stack: HashSet::new(),
        }
    }

    pub fn doc(&self, filename: &str) -> Option<&Value> {
        self.docs.get(filename).map(SchemaDoc::root)
    }

    fn load_doc(&mut self, filename: &str) -> Option<&Value> {
        if self.docs.contains_key(filename) {
            return self.doc(filename);
        }
        let doc = (self.loader)(filename)?;
        self.docs.insert(filename.to_string(), doc);
        self.doc(filename)
    }

    pub(crate) fn resolve_ref(
        &mut self,
        current_filename: &str,
        reference: &str,
    ) -> Option<ResolvedSchemaNode> {
        let (filename, pointer) = split_reference(current_filename, reference);
        let doc = self.load_doc(&filename)?;
        let schema = if pointer.is_empty() {
            doc.clone()
        } else {
            doc.pointer(&pointer)?.clone()
        };
        Some(ResolvedSchemaNode::at(
            SchemaNodeLocation { filename, pointer },
            schema,
        ))
    }
}

/// Split a `$ref` into the `(filename, json-pointer)` pair it targets,
/// resolving same-document references against `current_filename`. The pair is
/// also the cycle-stack key for that reference.
fn split_reference(current_filename: &str, reference: &str) -> (String, String) {
    if let Some(pointer) = reference.strip_prefix('#') {
        return (current_filename.to_string(), pointer.to_string());
    }
    let (file, pointer) = reference.split_once('#').unwrap_or((reference, ""));
    (
        normalize_ref_filename(current_filename, file),
        pointer.to_string(),
    )
}

fn normalize_ref_filename(current_filename: &str, file: &str) -> String {
    if file.is_empty() {
        return current_filename.to_string();
    }
    let trimmed = file.trim().trim_start_matches("./");
    trimmed.rsplit('/').next().unwrap_or(trimmed).to_string()
}

fn append_json_pointer_segment(pointer: &str, segment: &str) -> String {
    let escaped = helm_schema_json_schema_walk::escape_json_pointer_segment(segment);
    if pointer.is_empty() {
        format!("/{escaped}")
    } else {
        format!("{pointer}/{escaped}")
    }
}

fn expand_schema_node_at<F: FnMut(&str) -> Option<SchemaDoc>>(
    ctx: &mut ResolveCtx<F>,
    node: ResolvedSchemaNode,
    depth: usize,
) -> ResolvedSchemaNode {
    if depth > 64 {
        return node;
    }

    if let Some(reference) = node.schema.get("$ref").and_then(|v| v.as_str()) {
        let key = split_reference(node.location.filename(), reference);

        if ctx.stack.contains(&key) {
            return ResolvedSchemaNode::at(node.location, strip_ref(&node.schema));
        }
        ctx.stack.insert(key.clone());

        let out = if let Some(target) = ctx.resolve_ref(node.location.filename(), reference) {
            expand_schema_node_at(ctx, target, depth + 1)
        } else {
            ResolvedSchemaNode::at(node.location, strip_ref(&node.schema))
        };

        ctx.stack.remove(&key);
        return out;
    }

    for keyword in ["allOf", "anyOf", "oneOf"] {
        if let Some(branches) = node.schema.get(keyword).and_then(Value::as_array) {
            let expanded = expand_schema_array_at(ctx, &node, keyword, branches, depth + 1);
            let mut obj = node.schema.as_object().cloned().unwrap_or_default();
            obj.insert(keyword.to_string(), expanded);
            return ResolvedSchemaNode::at(node.location, Value::Object(obj));
        }
    }

    let mut obj = match node.schema.as_object() {
        Some(o) => o.clone(),
        None => return node,
    };

    for (key, value) in node.schema.as_object().into_iter().flat_map(Map::iter) {
        let expanded = match schema_child_context_for_keyword(key) {
            SchemaTraversalContext::Schema if value.is_boolean() => continue,
            SchemaTraversalContext::Schema => match value {
                Value::Array(values) => expand_schema_array_at(ctx, &node, key, values, depth + 1),
                _ => expand_schema_node_at(ctx, node.child(key, value.clone()), depth + 1)
                    .into_schema(),
            },
            SchemaTraversalContext::SchemaArray => {
                let Some(values) = value.as_array() else {
                    continue;
                };
                expand_schema_array_at(ctx, &node, key, values, depth + 1)
            }
            SchemaTraversalContext::SchemaMapValues => {
                let Some(values) = value.as_object() else {
                    continue;
                };
                Value::Object(
                    values
                        .iter()
                        .map(|(entry_key, schema)| {
                            (
                                entry_key.clone(),
                                expand_schema_node_at(
                                    ctx,
                                    node.nested_child(key, entry_key, schema.clone()),
                                    depth + 1,
                                )
                                .into_schema(),
                            )
                        })
                        .collect(),
                )
            }
            SchemaTraversalContext::Data | SchemaTraversalContext::Ref => continue,
        };
        obj.insert(key.clone(), expanded);
    }

    ResolvedSchemaNode::at(node.location, Value::Object(obj))
}

fn expand_schema_array_at<F: FnMut(&str) -> Option<SchemaDoc>>(
    ctx: &mut ResolveCtx<F>,
    node: &ResolvedSchemaNode,
    key: &str,
    values: &[Value],
    depth: usize,
) -> Value {
    Value::Array(
        values
            .iter()
            .enumerate()
            .map(|(index, schema)| {
                expand_schema_node_at(
                    ctx,
                    node.nested_child(key, index.to_string(), schema.clone()),
                    depth,
                )
                .into_schema()
            })
            .collect(),
    )
}

pub(crate) fn descend_schema_path_expanding_leaf_with_location<
    F: FnMut(&str) -> Option<SchemaDoc>,
>(
    ctx: &mut ResolveCtx<F>,
    current_filename: &str,
    schema: &Value,
    path: &[String],
) -> Option<ResolvedSchemaLeaf> {
    let root = ResolvedSchemaNode::root(current_filename.to_string(), schema.clone());
    let leaf = descend_schema_path_node(ctx, root, path)?;
    let location = leaf.location.clone();
    let source_schema = leaf.schema.clone();
    let expanded = expand_schema_node_at(ctx, leaf, 0).into_schema();
    let required_in_parent = final_segment_required_in_parent(ctx, current_filename, schema, path);
    Some(ResolvedSchemaLeaf::new(
        location,
        source_schema,
        expanded,
        required_in_parent,
    ))
}

/// Whether the path's final segment is a plain property the parent object
/// schema lists in `required`. Item segments (`x[*]`), dynamic mapping
/// values, and paths the parent resolves through `additionalProperties`
/// are never provider-required, and a parent that cannot be re-descended
/// abstains to `false`.
fn final_segment_required_in_parent<F: FnMut(&str) -> Option<SchemaDoc>>(
    ctx: &mut ResolveCtx<F>,
    current_filename: &str,
    schema: &Value,
    path: &[String],
) -> bool {
    let Some((leaf_segment, parents)) = path.split_last() else {
        return false;
    };
    if leaf_segment.ends_with("[*]")
        || leaf_segment == helm_schema_core::DYNAMIC_MAPPING_VALUE_SEGMENT
    {
        return false;
    }
    let root = ResolvedSchemaNode::root(current_filename.to_string(), schema.clone());
    let Some(parent) = descend_schema_path_node(ctx, root, parents) else {
        return false;
    };
    let Some(parent) = resolve_direct_ref(ctx, parent, 0) else {
        return false;
    };
    parent
        .schema
        .get("required")
        .and_then(Value::as_array)
        .is_some_and(|required| {
            required
                .iter()
                .any(|member| member.as_str() == Some(leaf_segment))
        })
}

fn descend_schema_path_node<F: FnMut(&str) -> Option<SchemaDoc>>(
    ctx: &mut ResolveCtx<F>,
    mut node: ResolvedSchemaNode,
    path: &[String],
) -> Option<ResolvedSchemaNode> {
    for (depth, segment) in path.iter().enumerate() {
        if depth > 64 {
            return Some(node);
        }
        node = descend_one_schema_path_segment(ctx, node, segment, depth)?;
    }
    Some(node)
}

fn descend_one_schema_path_segment<F: FnMut(&str) -> Option<SchemaDoc>>(
    ctx: &mut ResolveCtx<F>,
    node: ResolvedSchemaNode,
    segment: &str,
    depth: usize,
) -> Option<ResolvedSchemaNode> {
    let node = resolve_direct_ref(ctx, node, depth)?;

    for keyword in ["allOf", "anyOf", "oneOf"] {
        if let Some(branches) = node.schema.get(keyword).and_then(Value::as_array) {
            for (index, branch) in branches.iter().enumerate() {
                let branch = node.nested_child(keyword, index.to_string(), branch.clone());
                if let Some(next) = descend_one_schema_path_segment(ctx, branch, segment, depth + 1)
                {
                    return Some(next);
                }
            }
        }
    }

    let is_dynamic_mapping_value = segment == helm_schema_core::DYNAMIC_MAPPING_VALUE_SEGMENT;
    let (key, is_array_item) = segment
        .strip_suffix("[*]")
        .map_or((segment, false), |key| (key, true));

    let mut next = (!is_dynamic_mapping_value)
        .then(|| {
            node.schema
                .get("properties")
                .and_then(Value::as_object)
                .and_then(|properties| {
                    properties
                        .get(key)
                        .map(|schema| node.nested_child("properties", key, schema.clone()))
                })
        })
        .flatten()
        .or_else(|| {
            node.schema
                .get("additionalProperties")
                .and_then(|additional_properties| {
                    if additional_properties.is_boolean() {
                        None
                    } else {
                        Some(node.child("additionalProperties", additional_properties.clone()))
                    }
                })
        })?;

    if is_array_item {
        next = resolve_direct_ref(ctx, next, depth + 1)?;
        let array_schema = next;
        next = if let Some(items) = array_schema.schema.get("items") {
            array_schema.child("items", items.clone())
        } else {
            let first_prefix_item = array_schema
                .schema
                .get("prefixItems")
                .and_then(Value::as_array)
                .and_then(|items| items.first())?;
            array_schema.nested_child("prefixItems", "0", first_prefix_item.clone())
        };
    }

    Some(next)
}

fn resolve_direct_ref<F: FnMut(&str) -> Option<SchemaDoc>>(
    ctx: &mut ResolveCtx<F>,
    node: ResolvedSchemaNode,
    depth: usize,
) -> Option<ResolvedSchemaNode> {
    if depth > 64 {
        return Some(node);
    }
    let Some(reference) = node.schema.get("$ref").and_then(Value::as_str) else {
        return Some(node);
    };

    let key = split_reference(node.location.filename(), reference);
    if ctx.stack.contains(&key) {
        return Some(ResolvedSchemaNode::at(
            node.location,
            strip_ref(&node.schema),
        ));
    }
    ctx.stack.insert(key.clone());

    let resolved = ctx
        .resolve_ref(node.location.filename(), reference)
        .and_then(|target| resolve_direct_ref(ctx, target, depth + 1));

    ctx.stack.remove(&key);
    resolved.or_else(|| {
        Some(ResolvedSchemaNode::at(
            node.location,
            strip_ref(&node.schema),
        ))
    })
}

#[cfg(test)]
#[path = "tests/resolve_ctx.rs"]
mod tests;