helm-rs 0.1.2

Typed Rust API for Helm 4: swappable backends, native chart, values and release reading
Documentation
//! `Schema.Validate` of helm-schema's `pkg/schema/schema.go`: the constraint checks run on every
//! annotated key. Errors are Go's message texts.

use serde_json::Value;

use super::model::Schema;
use super::schema_decode::parse_schema;

const TYPES: [&str; 7] = [
    "object", "string", "integer", "number", "array", "null", "boolean",
];

/// Go's `%T` of a decoded YAML value.
fn go_type(value: &Value) -> &'static str {
    match value {
        Value::Null => "<nil>",
        Value::Bool(_) => "bool",
        Value::Number(n) if n.is_f64() => "float64",
        Value::Number(_) => "int",
        Value::String(_) => "string",
        Value::Array(_) => "[]interface {}",
        Value::Object(_) => "map[string]interface {}",
    }
}

fn compile(pattern: &str) -> Result<(), String> {
    regex::Regex::new(pattern)
        .map(|_| ())
        .map_err(|e| e.to_string())
}

impl Schema {
    fn types_display(&self) -> String {
        format!("[{}]", self.types.join(" "))
    }

    fn type_empty(&self) -> bool {
        self.types.is_empty() || self.types.iter().any(String::is_empty)
    }

    fn type_matches(&self, name: &str) -> bool {
        self.types.iter().any(|t| t == name)
    }

    /// Fails with `{what} can only be used with {want} type` unless the type allows it.
    fn only_with(&self, what: &str, want: &str) -> Result<(), String> {
        if self.type_empty() || self.type_matches(want) {
            return Ok(());
        }

        Err(format!(
            "{what} can only be used with {want} type, got {}",
            self.types_display()
        ))
    }

    /// `Validate`: the first problem found, in Go's order.
    pub(super) fn validate(&self) -> Result<(), String> {
        for t in &self.types {
            if !t.is_empty() && !TYPES.contains(&t.as_str()) {
                return Err(format!("unsupported type {t}"));
            }
        }

        self.validate_numeric()?;
        self.validate_string()?;
        self.validate_array()?;
        self.validate_object()?;
        self.validate_nested()
    }

    fn validate_numeric(&self) -> Result<(), String> {
        let f = |n| self.float_of(n);
        let (min, max, emin, emax, multiple) = (
            f("minimum"),
            f("maximum"),
            f("exclusiveMinimum"),
            f("exclusiveMaximum"),
            f("multipleOf"),
        );

        if min.is_none() && max.is_none() && emin.is_none() && emax.is_none() && multiple.is_none()
        {
            return Ok(());
        }

        if !self.type_empty() && !self.type_matches("number") && !self.type_matches("integer") {
            return Err(format!(
                "numeric constraints can only be used with number or integer types, got {}",
                self.types_display()
            ));
        }

        if multiple.is_some_and(|m| m <= 0.0) {
            return Err("multipleOf must be greater than 0".to_owned());
        }

        if min.is_some() && emin.is_some() {
            return Err("cannot use both minimum and exclusiveMinimum".to_owned());
        }

        if max.is_some() && emax.is_some() {
            return Err("cannot use both maximum and exclusiveMaximum".to_owned());
        }

        if let (Some(a), Some(b)) = (min, max)
            && a > b
        {
            return Err(format!(
                "minimum ({}) cannot be greater than maximum ({})",
                go_float(a),
                go_float(b)
            ));
        }

        if let (Some(a), Some(b)) = (emin, emax)
            && a >= b
        {
            return Err(format!(
                "exclusiveMinimum ({}) must be less than exclusiveMaximum ({})",
                go_float(a),
                go_float(b)
            ));
        }

        Ok(())
    }

    fn validate_string(&self) -> Result<(), String> {
        let pattern = self.str_of("pattern");

        if !pattern.is_empty() {
            self.only_with("pattern", "string")?;
            compile(pattern).map_err(|e| format!("invalid pattern regex: {e}"))?;
        }

        let (min, max) = (self.int_of("minLength"), self.int_of("maxLength"));

        if min.is_some() || max.is_some() {
            self.only_with("minLength/maxLength", "string")?;
        }

        if let (Some(a), Some(b)) = (min, max)
            && a > b
        {
            return Err(format!(
                "minLength ({a}) cannot be greater than maxLength ({b})"
            ));
        }

        if min.is_some_and(|v| v < 0) {
            return Err("minLength must be non-negative".to_owned());
        }

        if max.is_some_and(|v| v < 0) {
            return Err("maxLength must be non-negative".to_owned());
        }

        if !self.str_of("contentEncoding").is_empty() || !self.str_of("contentMediaType").is_empty()
        {
            self.only_with("contentEncoding/contentMediaType", "string")?;
        }

        Ok(())
    }

    fn validate_array(&self) -> Result<(), String> {
        if let Some(items) = &self.items {
            self.only_with("items", "array")?;
            items
                .validate()
                .map_err(|e| format!("invalid items schema: {e}"))?;
        }

        let (min, max) = (self.int_of("minItems"), self.int_of("maxItems"));

        if min.is_some() || max.is_some() {
            self.only_with("minItems/maxItems", "array")?;

            if let (Some(a), Some(b)) = (min, max)
                && b < a
            {
                return Err(format!("maxItems ({b}) cannot be less than minItems ({a})"));
            }
        }

        if min.is_some_and(|v| v < 0) {
            return Err("minItems must be non-negative".to_owned());
        }

        if max.is_some_and(|v| v < 0) {
            return Err("maxItems must be non-negative".to_owned());
        }

        if let Some(contains) = &self.contains {
            self.only_with("contains", "array")?;
            contains
                .validate()
                .map_err(|e| format!("invalid contains schema: {e}"))?;
        }

        if let Some(value) = &self.additional_items {
            self.only_with("additionalItems", "array")?;
            validate_schema_value(value, "additionalItems")?;
        }

        Ok(())
    }

    fn validate_object(&self) -> Result<(), String> {
        let (min, max) = (self.int_of("minProperties"), self.int_of("maxProperties"));

        if min.is_some() || max.is_some() {
            self.only_with("minProperties/maxProperties", "object")?;

            if min.is_some_and(|v| v < 0) {
                return Err("minProperties must be non-negative".to_owned());
            }

            if max.is_some_and(|v| v < 0) {
                return Err("maxProperties must be non-negative".to_owned());
            }

            if let (Some(a), Some(b)) = (min, max)
                && b < a
            {
                return Err(format!(
                    "maxProperties ({b}) cannot be less than minProperties ({a})"
                ));
            }
        }

        if let Some(names) = &self.property_names {
            self.only_with("propertyNames", "object")?;
            names
                .validate()
                .map_err(|e| format!("invalid propertyNames schema: {e}"))?;
        }

        if let Some(value) = &self.additional_properties {
            self.only_with("additionalProperties", "object")?;
            validate_schema_value(value, "additionalProperties")?;
        }

        for (pattern, schema) in self.pattern_properties.iter().flatten() {
            compile(pattern)
                .map_err(|e| format!("invalid pattern in patternProperties '{pattern}': {e}"))?;
            schema
                .validate()
                .map_err(|e| format!("invalid schema in patternProperties[{pattern}]: {e}"))?;
        }

        for (key, value) in self.dependencies.iter().flatten() {
            match value {
                Value::Array(items) => {
                    for (i, item) in items.iter().enumerate() {
                        if !item.is_string() {
                            return Err(format!(
                                "dependencies[{key}][{i}] must be a string, got {}",
                                go_type(item)
                            ));
                        }
                    }
                }
                Value::Object(_) => {
                    let text = value.to_string();

                    parse_schema(&text, true)
                        .and_then(|s| s.validate())
                        .map_err(|e| format!("invalid schema in dependencies[{key}]: {e}"))?;
                }
                other => {
                    return Err(format!(
                        "dependencies[{key}] must be an array of strings or a schema, got {}",
                        go_type(other)
                    ));
                }
            }
        }

        Ok(())
    }

    fn validate_nested(&self) -> Result<(), String> {
        for schema in self.all_of.iter().chain(&self.any_of).chain(&self.one_of) {
            schema.validate()?;
        }

        for schema in [&self.if_, &self.then, &self.else_, &self.not]
            .into_iter()
            .flatten()
        {
            schema.validate()?;
        }

        for (name, schema) in self.definitions.iter().flatten() {
            schema
                .validate()
                .map_err(|e| format!("invalid schema in definitions[{name}]: {e}"))?;
        }

        for (name, schema) in self.properties.iter().flatten() {
            schema
                .validate()
                .map_err(|e| format!("invalid schema in properties[{name}]: {e}"))?;
        }

        Ok(())
    }
}

/// An `additionalProperties` / `additionalItems` value: a bool or a schema object.
fn validate_schema_value(value: &Value, keyword: &str) -> Result<(), String> {
    match value {
        Value::Bool(_) => Ok(()),
        Value::Object(_) => parse_schema(&value.to_string(), true)
            .and_then(|s| s.validate())
            .map_err(|e| format!("invalid {keyword} schema: {e}")),
        other => Err(format!(
            "{keyword} must be a boolean or schema, got {}",
            go_type(other)
        )),
    }
}

/// Go's `%v` of a float64.
fn go_float(f: f64) -> String {
    if f.fract() == 0.0 && f.abs() < 1e21 {
        return format!("{f:.0}");
    }

    format!("{f}")
}