helm-rs 0.1.2

Typed Rust API for Helm 4: swappable backends, native chart, values and release reading
Documentation
//! `$ref` resolution for values schemas.
//!
//! Helm resolves `file://`, `http://` and `https://` references and answers `urn:` references with
//! a permissive `true` schema (`pkg/chart/common/util/jsonschema.go`). This crate always does the
//! `urn:` part; `file`, `http` and `https` are refused with a clear error unless the
//! `schema-remote-refs` feature is enabled.

use std::sync::{Arc, Mutex};

use jsonschema::{Retrieve, Uri};
use serde_json::Value;

/// A `$ref` retriever that records the first reference it refused.
pub(super) struct Resolver {
    refused: Arc<Mutex<Option<String>>>,
    #[cfg(feature = "schema-remote-refs")]
    http: jsonschema::HttpRetriever,
}

impl Resolver {
    /// Creates a resolver and the handle through which a refused reference can be read back.
    pub(super) fn new() -> (Self, Arc<Mutex<Option<String>>>) {
        let refused = Arc::new(Mutex::new(None));
        let resolver = Self {
            refused: Arc::clone(&refused),
            #[cfg(feature = "schema-remote-refs")]
            http: jsonschema::HttpRetriever::new(
                &jsonschema::HttpOptions::new().timeout(std::time::Duration::from_secs(15)),
            )
            .expect("an HTTP client with a timeout builds"),
        };

        (resolver, refused)
    }
}

impl Retrieve for Resolver {
    fn retrieve(
        &self,
        uri: &Uri<String>,
    ) -> Result<Value, Box<dyn std::error::Error + Send + Sync>> {
        match uri.scheme().as_str() {
            "urn" => Ok(Value::Bool(true)),
            #[cfg(feature = "schema-remote-refs")]
            "http" | "https" => self.http.retrieve(uri),
            #[cfg(feature = "schema-remote-refs")]
            "file" => Ok(serde_json::from_slice(&std::fs::read(
                uri.path().as_str(),
            )?)?),
            _ => {
                *self.refused.lock().expect("lock is not poisoned") = Some(uri.to_string());

                Err(format!(
                    "remote $ref {uri} is not resolved (enable the `schema-remote-refs` feature)"
                )
                .into())
            }
        }
    }
}